Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Guida:
Importante
Questa funzionalità si trova nella fase sperimentale. Le funzionalità in questa fase sono in fase di sviluppo e soggette a cambiamenti prima di passare alla fase di anteprima o alla versione candidata al rilascio.
Panoramica
In questo esempio si esaminerà la configurazione di un plug-in per accedere all'API GitHub e verranno fornite istruzioni templatizzate per rispondere a domande ChatCompletionAgent su un repository GitHub. L'approccio verrà suddiviso passo dopo passo per evidenziare le parti chiave del processo di codifica. Nell'ambito dell'attività, l'agente fornirà citazioni di documenti all'interno della risposta.
Lo streaming verrà usato per recapitare le risposte dell'agente. In questo modo verranno forniti aggiornamenti in tempo reale man mano che l'attività procede.
Introduzione
Prima di procedere con lo sviluppo delle funzionalità, assicurati che l'ambiente di sviluppo sia completamente configurato e pronto per l'uso.
Per iniziare, creare un progetto console . Includere quindi i riferimenti al pacchetto seguenti per assicurarsi che tutte le dipendenze necessarie siano disponibili.
Per aggiungere le dipendenze dei pacchetti dalla riga di comando, usare il dotnet comando :
dotnet add package Azure.Identity
dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.Binder
dotnet add package Microsoft.Extensions.Configuration.UserSecrets
dotnet add package Microsoft.Extensions.Configuration.EnvironmentVariables
dotnet add package Microsoft.SemanticKernel.Connectors.AzureOpenAI
dotnet add package Microsoft.SemanticKernel.Agents.Core --prerelease
Importante
Se si gestiscono pacchetti NuGet in Visual Studio, verificare che Include prerelease sia selezionata.
Il file di progetto (.csproj) deve contenere le definizioni seguenti PackageReference :
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="<stable>" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="<stable>" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="<stable>" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="<stable>" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="<stable>" />
<PackageReference Include="Microsoft.SemanticKernel.Agents.Core" Version="<latest>" />
<PackageReference Include="Microsoft.SemanticKernel.Connectors.AzureOpenAI" Version="<latest>" />
</ItemGroup>
Il Agent Framework è sperimentale e richiede l'eliminazione degli avvisi. Ciò può essere risolto come proprietà nel file di progetto (.csproj):
<PropertyGroup>
<NoWarn>$(NoWarn);CA2007;IDE1006;SKEXP0001;SKEXP0110;OPENAI001</NoWarn>
</PropertyGroup>
Inoltre, copia il plug-in GitHub e i modelli (GitHubPlugin.cs e GitHubModels.cs) dal Semantic Kernel LearnResources Project. Aggiungere questi file nella cartella del progetto.
Per iniziare, creare una cartella che conterrà lo script (.py file) e le risorse di esempio. Includere le importazioni seguenti all'inizio del .py file:
import asyncio
import os
import sys
from datetime import datetime
from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.functions import KernelArguments
from semantic_kernel.kernel import Kernel
# Adjust the sys.path so we can use the GitHubPlugin and GitHubSettings classes
# This is so we can run the code from the samples/learn_resources/agent_docs directory
# If you are running code from your own project, you may not need need to do this.
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from plugins.GithubPlugin.github import GitHubPlugin, GitHubSettings # noqa: E402
Copiare il plug-in GitHub e i modelli (github.py) anche dal Semantic Kernel ProjectLearnResources. Aggiungere questi file nella cartella del progetto.
Per iniziare, creare un progetto console Maven. Includere quindi i riferimenti al pacchetto seguenti per assicurarsi che tutte le dipendenze necessarie siano disponibili.
Il progetto pom.xml deve contenere le dipendenze seguenti:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.microsoft.semantic-kernel</groupId>
<artifactId>semantickernel-bom</artifactId>
<version>[LATEST]</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.microsoft.semantic-kernel</groupId>
<artifactId>semantickernel-agents-core</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.semantic-kernel</groupId>
<artifactId>semantickernel-aiservices-openai</artifactId>
</dependency>
</dependencies>
Inoltre, copia il plug-in GitHub e i modelli (GitHubPlugin.java e GitHubModels.java) dal Semantic Kernel LearnResources Project. Aggiungere questi file nella cartella del progetto.
Impostazione
Questo esempio richiede l'impostazione di configurazione per connettersi ai servizi remoti. Sarà necessario definire le impostazioni per OpenAI o Azure OpenAI e anche per GitHub.
Annotazioni
Per informazioni sui token di accesso personale di GitHub, vedere Gestione dei token di accesso personali.
# OpenAI
dotnet user-secrets set "OpenAISettings:ApiKey" "<api-key>"
dotnet user-secrets set "OpenAISettings:ChatModel" "gpt-4o"
# Azure OpenAI
dotnet user-secrets set "AzureOpenAISettings:ApiKey" "<api-key>" # Not required if using token-credential
dotnet user-secrets set "AzureOpenAISettings:Endpoint" "<model-endpoint>"
dotnet user-secrets set "AzureOpenAISettings:ChatModelDeployment" "gpt-4o"
# GitHub
dotnet user-secrets set "GitHubSettings:BaseUrl" "https://api.github.com"
dotnet user-secrets set "GitHubSettings:Token" "<personal access token>"
La classe seguente viene usata in tutti gli esempi di Agent. Assicurarsi di includerlo nel progetto per garantire una funzionalità appropriata. Questa classe funge da componente di base per gli esempi seguenti.
using System.Reflection;
using Microsoft.Extensions.Configuration;
namespace AgentsSample;
public class Settings
{
private readonly IConfigurationRoot configRoot;
private AzureOpenAISettings azureOpenAI;
private OpenAISettings openAI;
public AzureOpenAISettings AzureOpenAI => this.azureOpenAI ??= this.GetSettings<Settings.AzureOpenAISettings>();
public OpenAISettings OpenAI => this.openAI ??= this.GetSettings<Settings.OpenAISettings>();
public class OpenAISettings
{
public string ChatModel { get; set; } = string.Empty;
public string ApiKey { get; set; } = string.Empty;
}
public class AzureOpenAISettings
{
public string ChatModelDeployment { get; set; } = string.Empty;
public string Endpoint { get; set; } = string.Empty;
public string ApiKey { get; set; } = string.Empty;
}
public TSettings GetSettings<TSettings>() =>
this.configRoot.GetRequiredSection(typeof(TSettings).Name).Get<TSettings>()!;
public Settings()
{
this.configRoot =
new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddUserSecrets(Assembly.GetExecutingAssembly(), optional: true)
.Build();
}
}
Il modo più rapido per iniziare a usare la configurazione corretta per eseguire il codice di esempio consiste nel creare un .env file nella radice del progetto (dove viene eseguito lo script).
Configurare le impostazioni seguenti nel .env file per Azure OpenAI o OpenAI:
AZURE_OPENAI_API_KEY="..."
AZURE_OPENAI_ENDPOINT="https://<resource-name>.openai.azure.com/"
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="..."
AZURE_OPENAI_API_VERSION="..."
OPENAI_API_KEY="sk-..."
OPENAI_ORG_ID=""
OPENAI_CHAT_MODEL_ID=""
Dopo la configurazione, le rispettive classi di servizi di intelligenza artificiale rileveranno le variabili necessarie e le useranno durante la creazione di istanze.
Definire le variabili di ambiente seguenti nel sistema.
# Azure OpenAI
AZURE_OPENAI_API_KEY=""
AZURE_OPENAI_ENDPOINT="https://<resource-name>.openai.azure.com/"
AZURE_CHAT_MODEL_DEPLOYMENT=""
# OpenAI
OPENAI_API_KEY=""
OPENAI_MODEL_ID=""
Nella parte superiore del file è possibile recuperare i relativi valori come indicato di seguito.
// Azure OpenAI
private static final String AZURE_OPENAI_API_KEY = System.getenv("AZURE_OPENAI_API_KEY");
private static final String AZURE_OPENAI_ENDPOINT = System.getenv("AZURE_OPENAI_ENDPOINT");
private static final String AZURE_CHAT_MODEL_DEPLOYMENT = System.getenv().getOrDefault("AZURE_CHAT_MODEL_DEPLOYMENT", "gpt-4o");
// OpenAI
private static final String OPENAI_API_KEY = System.getenv("OPENAI_API_KEY");
private static final String OPENAI_MODEL_ID = System.getenv().getOrDefault("OPENAI_MODEL_ID", "gpt-4o");
Scrittura del codice
Il processo di codifica per questo esempio prevede:
- Installazione : inizializzazione delle impostazioni e del plug-in.
-
AgentDefinizione: creare ilChatCompletionAgentcon istruzioni basate su template e plug-in. - Ciclo chat - Scrivere il ciclo che determina l'interazione utente/agente.
Il codice di esempio completo viene fornito nella sezione Finale . Fare riferimento a questa sezione per l'implementazione completa.
Configurazione
Prima di creare un ChatCompletionAgent, è necessario inizializzare le impostazioni di configurazione, i plug-in e Kernel.
Inizializzare la Settings classe a cui si fa riferimento nella sezione Configurazione precedente.
Settings settings = new();
Inizializzare il plug-in usando le relative impostazioni.
In questo caso viene visualizzato un messaggio per indicare lo stato di avanzamento.
Console.WriteLine("Initialize plugins...");
GitHubSettings githubSettings = settings.GetSettings<GitHubSettings>();
GitHubPlugin githubPlugin = new(githubSettings);
gh_settings = GitHubSettings(
token="<PAT value>"
)
kernel.add_plugin(GitHubPlugin(settings=gh_settings), plugin_name="github")
var githubPlugin = new GitHubPlugin(GITHUB_PAT);
Inizializza ora un'istanza Kernel con un IChatCompletionService e l'oggetto GitHubPlugin creato in precedenza.
Console.WriteLine("Creating kernel...");
IKernelBuilder builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
settings.AzureOpenAI.ChatModelDeployment,
settings.AzureOpenAI.Endpoint,
new AzureCliCredential());
builder.Plugins.AddFromObject(githubPlugin);
Kernel kernel = builder.Build();
kernel = Kernel()
# Add the AzureChatCompletion AI Service to the Kernel
service_id = "agent"
kernel.add_service(AzureChatCompletion(service_id=service_id))
settings = kernel.get_prompt_execution_settings_from_service_id(service_id=service_id)
# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()
OpenAIAsyncClient client = new OpenAIClientBuilder()
.credential(new AzureKeyCredential(AZURE_OPENAI_API_KEY))
.endpoint(AZURE_OPENAI_ENDPOINT)
.buildAsyncClient();
ChatCompletionService chatCompletion = OpenAIChatCompletion.builder()
.withModelId(AZURE_CHAT_MODEL_DEPLOYMENT)
.withOpenAIAsyncClient(client)
.build();
Kernel kernel = Kernel.builder()
.withAIService(ChatCompletionService.class, chatCompletion)
.withPlugin(KernelPluginFactory.createFromObject(githubPlugin, "GitHubPlugin"))
.build();
Definizione agente
Infine, siamo pronti a istanziare un ChatCompletionAgent con le sue istruzioni, il Kernel associato, gli argomenti predefiniti e le impostazioni di esecuzione. In questo caso, desideriamo che le funzioni del plug-in vengano eseguite automaticamente.
Console.WriteLine("Defining agent...");
ChatCompletionAgent agent =
new()
{
Name = "SampleAssistantAgent",
Instructions =
"""
You are an agent designed to query and retrieve information from a single GitHub repository in a read-only manner.
You are also able to access the profile of the active user.
Use the current date and time to provide up-to-date details or time-sensitive responses.
The repository you are querying is a public repository with the following name: {{$repository}}
The current date and time is: {{$now}}.
""",
Kernel = kernel,
Arguments =
new KernelArguments(new AzureOpenAIPromptExecutionSettings() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() })
{
{ "repository", "microsoft/semantic-kernel" }
}
};
Console.WriteLine("Ready!");
agent = ChatCompletionAgent(
kernel=kernel,
name="SampleAssistantAgent",
instructions=f"""
You are an agent designed to query and retrieve information from a single GitHub repository in a read-only
manner.
You are also able to access the profile of the active user.
Use the current date and time to provide up-to-date details or time-sensitive responses.
The repository you are querying is a public repository with the following name: microsoft/semantic-kernel
The current date and time is: {{$now}}.
""",
arguments=KernelArguments(
settings=settings,
),
)
// Invocation context for the agent
InvocationContext invocationContext = InvocationContext.builder()
.withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true))
.build()
ChatCompletionAgent agent = ChatCompletionAgent.builder()
.withName("SampleAssistantAgent")
.withKernel(kernel)
.withInvocationContext(invocationContext)
.withTemplate(
DefaultPromptTemplate.build(
PromptTemplateConfig.builder()
.withTemplate(
"""
You are an agent designed to query and retrieve information from a single GitHub repository in a read-only manner.
You are also able to access the profile of the active user.
Use the current date and time to provide up-to-date details or time-sensitive responses.
The repository you are querying is a public repository with the following name: {{$repository}}
The current date and time is: {{$now}}.
""")
.build()))
.withKernelArguments(
KernelArguments.builder()
.withVariable("repository", "microsoft/semantic-kernel-java")
.withExecutionSettings(PromptExecutionSettings.builder()
.build())
.build())
.build();
Ciclo chat
Infine, è possibile coordinare l'interazione tra l'utente e il Agent. Per iniziare, creare un oggetto ChatHistoryAgentThread per mantenere lo stato della conversazione e creare un ciclo vuoto.
ChatHistoryAgentThread agentThread = new();
bool isComplete = false;
do
{
// processing logic here
} while (!isComplete);
thread: ChatHistoryAgentThread = None
is_complete: bool = False
while not is_complete:
# processing logic here
AgentThread agentThread = new ChatHistoryAgentThread();
boolean isComplete = false;
while (!isComplete) {
// processing logic here
}
Acquisiamo ora l'input dell'utente all'interno del ciclo precedente. In questo caso, l'input vuoto verrà ignorato e il termine EXIT segnalerà che la conversazione è stata completata.
Console.WriteLine();
Console.Write("> ");
string input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
continue;
}
if (input.Trim().Equals("EXIT", StringComparison.OrdinalIgnoreCase))
{
isComplete = true;
break;
}
var message = new ChatMessageContent(AuthorRole.User, input);
Console.WriteLine();
user_input = input("User:> ")
if not user_input:
continue
if user_input.lower() == "exit":
is_complete = True
break
Scanner scanner = new Scanner(System.in);
while (!isComplete) {
System.out.print("> ");
String input = scanner.nextLine();
if (input.isEmpty()) {
continue;
}
if (input.equalsIgnoreCase("exit")) {
isComplete = true;
break;
}
}
Per generare una risposta Agent all'input dell'utente, richiamare l'agente usando Arguments per fornire il parametro di modello finale che specifica la data e l'ora correnti.
La risposta Agent viene quindi visualizzata all'utente.
DateTime now = DateTime.Now;
KernelArguments arguments =
new()
{
{ "now", $"{now.ToShortDateString()} {now.ToShortTimeString()}" }
};
await foreach (ChatMessageContent response in agent.InvokeAsync(message, agentThread, options: new() { KernelArguments = arguments }))
{
Console.WriteLine($"{response.Content}");
}
arguments = KernelArguments(
now=datetime.now().strftime("%Y-%m-%d %H:%M")
)
async for response in agent.invoke(messages=user_input, thread=thread, arguments=arguments):
print(f"{response.content}")
thread = response.thread
var options = AgentInvokeOptions.builder()
.withKernelArguments(KernelArguments.builder()
.withVariable("now", OffsetDateTime.now())
.build())
.build();
for (var response : agent.invokeAsync(message, agentThread, options).block()) {
System.out.println(response.getMessage());
agentThread = response.getThread();
}
Finale
Combinando tutti i passaggi, otteniamo il codice finale per questo esempio. Di seguito è riportata l'implementazione completa.
Provare a usare questi input suggeriti:
- Che cos'è il mio nome utente?
- Descrivi il repository.
- Descrivere il problema più recente creato nel repository.
- Elencare i primi 10 problemi chiusi nell'ultima settimana.
- Come sono stati etichettati questi problemi?
- Elenca le 5 questioni aperte più recenti con l'etichetta "Agents"
using System;
using System.Threading.Tasks;
using Azure.Identity;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.AzureOpenAI;
using Plugins;
namespace AgentsSample;
public static class Program
{
public static async Task Main()
{
// Load configuration from environment variables or user secrets.
Settings settings = new();
Console.WriteLine("Initialize plugins...");
GitHubSettings githubSettings = settings.GetSettings<GitHubSettings>();
GitHubPlugin githubPlugin = new(githubSettings);
Console.WriteLine("Creating kernel...");
IKernelBuilder builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
settings.AzureOpenAI.ChatModelDeployment,
settings.AzureOpenAI.Endpoint,
new AzureCliCredential());
builder.Plugins.AddFromObject(githubPlugin);
Kernel kernel = builder.Build();
Console.WriteLine("Defining agent...");
ChatCompletionAgent agent =
new()
{
Name = "SampleAssistantAgent",
Instructions =
"""
You are an agent designed to query and retrieve information from a single GitHub repository in a read-only manner.
You are also able to access the profile of the active user.
Use the current date and time to provide up-to-date details or time-sensitive responses.
The repository you are querying is a public repository with the following name: {{$repository}}
The current date and time is: {{$now}}.
""",
Kernel = kernel,
Arguments =
new KernelArguments(new AzureOpenAIPromptExecutionSettings() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() })
{
{ "repository", "microsoft/semantic-kernel" }
}
};
Console.WriteLine("Ready!");
ChatHistoryAgentThread agentThread = new();
bool isComplete = false;
do
{
Console.WriteLine();
Console.Write("> ");
string input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
continue;
}
if (input.Trim().Equals("EXIT", StringComparison.OrdinalIgnoreCase))
{
isComplete = true;
break;
}
var message = new ChatMessageContent(AuthorRole.User, input);
Console.WriteLine();
DateTime now = DateTime.Now;
KernelArguments arguments =
new()
{
{ "now", $"{now.ToShortDateString()} {now.ToShortTimeString()}" }
};
await foreach (ChatMessageContent response in agent.InvokeAsync(message, agentThread, options: new() { KernelArguments = arguments }))
{
// Display response.
Console.WriteLine($"{response.Content}");
}
} while (!isComplete);
}
}
import asyncio
import os
import sys
from datetime import datetime
from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.functions import KernelArguments
from semantic_kernel.kernel import Kernel
# Adjust the sys.path so we can use the GitHubPlugin and GitHubSettings classes
# This is so we can run the code from the samples/learn_resources/agent_docs directory
# If you are running code from your own project, you may not need need to do this.
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from plugins.GithubPlugin.github import GitHubPlugin, GitHubSettings # noqa: E402
async def main():
kernel = Kernel()
# Add the AzureChatCompletion AI Service to the Kernel
service_id = "agent"
kernel.add_service(AzureChatCompletion(service_id=service_id))
settings = kernel.get_prompt_execution_settings_from_service_id(service_id=service_id)
# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()
# Set your GitHub Personal Access Token (PAT) value here
gh_settings = GitHubSettings(token="") # nosec
kernel.add_plugin(plugin=GitHubPlugin(gh_settings), plugin_name="GithubPlugin")
current_time = datetime.now().isoformat()
# Create the agent
agent = ChatCompletionAgent(
kernel=kernel,
name="SampleAssistantAgent",
instructions=f"""
You are an agent designed to query and retrieve information from a single GitHub repository in a read-only
manner.
You are also able to access the profile of the active user.
Use the current date and time to provide up-to-date details or time-sensitive responses.
The repository you are querying is a public repository with the following name: microsoft/semantic-kernel
The current date and time is: {current_time}.
""",
arguments=KernelArguments(settings=settings),
)
thread: ChatHistoryAgentThread = None
is_complete: bool = False
while not is_complete:
user_input = input("User:> ")
if not user_input:
continue
if user_input.lower() == "exit":
is_complete = True
break
arguments = KernelArguments(now=datetime.now().strftime("%Y-%m-%d %H:%M"))
async for response in agent.invoke(messages=user_input, thread=thread, arguments=arguments):
print(f"{response.content}")
thread = response.thread
if __name__ == "__main__":
asyncio.run(main())
È possibile trovare il codice completo , come illustrato in precedenza, nel repository.
import com.microsoft.semantickernel.Kernel;
import com.microsoft.semantickernel.agents.AgentInvokeOptions;
import com.microsoft.semantickernel.agents.AgentThread;
import com.microsoft.semantickernel.agents.chatcompletion.ChatCompletionAgent;
import com.microsoft.semantickernel.agents.chatcompletion.ChatHistoryAgentThread;
import com.microsoft.semantickernel.aiservices.openai.chatcompletion.OpenAIChatCompletion;
import com.microsoft.semantickernel.contextvariables.ContextVariableTypeConverter;
import com.microsoft.semantickernel.functionchoice.FunctionChoiceBehavior;
import com.microsoft.semantickernel.implementation.templateengine.tokenizer.DefaultPromptTemplate;
import com.microsoft.semantickernel.orchestration.InvocationContext;
import com.microsoft.semantickernel.orchestration.PromptExecutionSettings;
import com.microsoft.semantickernel.plugin.KernelPluginFactory;
import com.microsoft.semantickernel.samples.plugins.github.GitHubModel;
import com.microsoft.semantickernel.samples.plugins.github.GitHubPlugin;
import com.microsoft.semantickernel.semanticfunctions.KernelArguments;
import com.microsoft.semantickernel.semanticfunctions.PromptTemplateConfig;
import com.microsoft.semantickernel.services.chatcompletion.AuthorRole;
import com.microsoft.semantickernel.services.chatcompletion.ChatCompletionService;
import com.microsoft.semantickernel.services.chatcompletion.ChatMessageContent;
import com.azure.ai.openai.OpenAIAsyncClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.azure.core.credential.AzureKeyCredential;
import java.time.OffsetDateTime;
import java.util.Scanner;
public class CompletionAgent {
// Azure OpenAI
private static final String AZURE_OPENAI_API_KEY = System.getenv("AZURE_OPENAI_API_KEY");
private static final String AZURE_OPENAI_ENDPOINT = System.getenv("AZURE_OPENAI_ENDPOINT");
private static final String AZURE_CHAT_MODEL_DEPLOYMENT = System.getenv().getOrDefault("AZURE_CHAT_MODEL_DEPLOYMENT", "gpt-4o");
// GitHub Personal Access Token
private static final String GITHUB_PAT = System.getenv("GITHUB_PAT");
public static void main(String[] args) {
System.out.println("======== ChatCompletion Agent ========");
OpenAIAsyncClient client = new OpenAIClientBuilder()
.credential(new AzureKeyCredential(AZURE_OPENAI_API_KEY))
.endpoint(AZURE_OPENAI_ENDPOINT)
.buildAsyncClient();
var githubPlugin = new GitHubPlugin(GITHUB_PAT);
ChatCompletionService chatCompletion = OpenAIChatCompletion.builder()
.withModelId(AZURE_CHAT_MODEL_DEPLOYMENT)
.withOpenAIAsyncClient(client)
.build();
Kernel kernel = Kernel.builder()
.withAIService(ChatCompletionService.class, chatCompletion)
.withPlugin(KernelPluginFactory.createFromObject(githubPlugin, "GitHubPlugin"))
.build();
InvocationContext invocationContext = InvocationContext.builder()
.withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true))
.withContextVariableConverter(new ContextVariableTypeConverter<>(
GitHubModel.Issue.class,
o -> (GitHubModel.Issue) o,
o -> o.toString(),
s -> null))
.build();
ChatCompletionAgent agent = ChatCompletionAgent.builder()
.withName("SampleAssistantAgent")
.withKernel(kernel)
.withInvocationContext(invocationContext)
.withTemplate(
DefaultPromptTemplate.build(
PromptTemplateConfig.builder()
.withTemplate(
"""
You are an agent designed to query and retrieve information from a single GitHub repository in a read-only manner.
You are also able to access the profile of the active user.
Use the current date and time to provide up-to-date details or time-sensitive responses.
The repository you are querying is a public repository with the following name: {{$repository}}
The current date and time is: {{$now}}.
""")
.build()))
.withKernelArguments(
KernelArguments.builder()
.withVariable("repository", "microsoft/semantic-kernel-java")
.withExecutionSettings(PromptExecutionSettings.builder()
.build())
.build())
.build();
AgentThread agentThread = new ChatHistoryAgentThread();
boolean isComplete = false;
Scanner scanner = new Scanner(System.in);
while (!isComplete) {
System.out.print("> ");
String input = scanner.nextLine();
if (input.isEmpty()) {
continue;
}
if (input.equalsIgnoreCase("EXIT")) {
isComplete = true;
break;
}
var message = new ChatMessageContent<>(AuthorRole.USER, input);
var options = AgentInvokeOptions.builder()
.withKernelArguments(KernelArguments.builder()
.withVariable("now", OffsetDateTime.now())
.build())
.build();
for (var response : agent.invokeAsync(message, agentThread, options).block()) {
System.out.println(response.getMessage());
agentThread = response.getThread();
}
}
}
}