Partager via


Guide pratique : ChatCompletionAgent

Important

Cette fonctionnalité est à l’étape expérimentale. Les fonctionnalités à ce stade sont en cours de développement et soumises à des modifications avant de passer à la phase de préversion ou de version candidate.

Vue d’ensemble

Dans cet exemple, nous allons explorer la configuration d’un plug-in pour accéder à l’API GitHub et fournir des instructions modélisées à un ChatCompletionAgent afin de répondre à des questions sur un dépôt GitHub. L’approche sera décomposée pas à pas pour éclairer les principales parties du processus de codage. Dans le cadre de la tâche, l’agent fournit des citations de document dans la réponse.

La diffusion en continu sera utilisée pour fournir les réponses de l’agent. Cela fournit des mises à jour en temps réel à mesure que la tâche progresse.

Mise en route

Avant de continuer avec l'implémentation des fonctionnalités, vérifiez que votre environnement de développement est entièrement installé et configuré.

Commencez par créer un projet console . Ensuite, incluez les références de package suivantes pour vous assurer que toutes les dépendances requises sont disponibles.

Pour ajouter des dépendances de package à partir de la ligne de commande, utilisez la dotnet commande :

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

Important

Si vous gérez des packages NuGet dans Visual Studio, assurez-vous que Include prerelease est coché.

Le fichier projet (.csproj) doit contenir les définitions suivantes 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>

Le Agent Framework est expérimental et nécessite la suppression des avertissements. Cela peut être traité en tant que propriété dans le fichier projet (.csproj) :

  <PropertyGroup>
    <NoWarn>$(NoWarn);CA2007;IDE1006;SKEXP0001;SKEXP0110;OPENAI001</NoWarn>
  </PropertyGroup>

En outre, copiez le plug-in GitHub et les modèles (GitHubPlugin.cs et GitHubModels.cs) à partir du projet de noyau LearnResources sémantique. Ajoutez ces fichiers dans votre dossier de projet.

Commencez par créer un dossier qui contiendra votre script (.py fichier) et les exemples de ressources. Incluez les importations suivantes en haut de votre .py fichier :

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

En outre, copiez le plug-in GitHub et les modèles (github.py) à partir du projet de noyau LearnResources sémantique. Ajoutez ces fichiers dans votre dossier de projet.

Commencez par créer un projet de console Maven. Ensuite, incluez les références de package suivantes pour vous assurer que toutes les dépendances requises sont disponibles.

Le projet pom.xml doit contenir les dépendances suivantes :

<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>

En outre, copiez le plug-in GitHub et les modèles (GitHubPlugin.java et GitHubModels.java) à partir du projet de noyau LearnResources sémantique. Ajoutez ces fichiers dans votre dossier de projet.

Paramétrage

Cet exemple nécessite un paramètre de configuration pour se connecter aux services distants. Vous devez définir des paramètres pour OpenAI ou Azure OpenAI et également pour GitHub.

Remarque

Pour plus d’informations sur les jetons d’accès personnel GitHub, consultez : Gestion de vos jetons d’accès personnels.

# 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 suivante est utilisée dans tous les exemples agent. Veillez à l’inclure dans votre projet pour garantir une fonctionnalité appropriée. Cette classe sert de composant fondamental pour les exemples qui suivent.

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();
    }
}

Le moyen le plus rapide de bien démarrer avec la configuration appropriée pour exécuter l’exemple de code consiste à créer un .env fichier à la racine de votre projet (où votre script est exécuté).

Configurez les paramètres suivants dans votre .env fichier pour Azure OpenAI ou 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=""

Une fois configurées, les classes de service IA respectives récupèrent les variables requises et les utilisent pendant l’instanciation.

Définissez les variables d’environnement suivantes dans votre système.

# 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=""

En haut du fichier, vous pouvez récupérer leurs valeurs comme suit.

// 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");

Codage

Le processus de codage de cet exemple implique :

  1. Configuration : initialisation des paramètres et du plug-in.
  2. Agent Définition : Créez le ChatCompletionAgent avec des instructions prédéfinies et un module d'extension.
  3. La boucle de conversation : écrivez la boucle qui pilote l’interaction utilisateur/agent.

L’exemple de code complet est fourni dans la section Finale . Reportez-vous à cette section pour l’implémentation complète.

Programme d’installation

Avant de créer un ChatCompletionAgent, les paramètres de configuration, les plug-ins et les Kernel doivent être initialisés.

Initialisez la Settings classe référencée dans la section Configuration précédente.

Settings settings = new();

Initialisez le plug-in à l’aide de ses paramètres.

Ici, un message s’affiche pour indiquer la progression.

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);

Initialisez maintenant une Kernel instance avec un IChatCompletionService et le GitHubPlugin précédemment créé.

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();

Définition de l’agent

Enfin, nous sommes prêts à instancier une ChatCompletionAgent avec ses Instructions, associée à un Kernel, et avec les arguments et paramètres d’exécution par défaut. Dans ce cas, nous souhaitons que les fonctions de plug-in s’exécutent automatiquement.

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();

Boucle de conversation

Enfin, nous sommes en mesure de coordonner l’interaction entre l’utilisateur et le Agent. Commencez par créer un objet ChatHistoryAgentThread pour maintenir l’état de la conversation et créer une boucle vide.

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
}

Nous allons maintenant capturer l’entrée utilisateur dans la boucle précédente. Dans ce cas, l’entrée vide est ignorée et le terme EXIT signale que la conversation est terminée.

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;
    }

}

Pour générer une réponse Agent à l’entrée utilisateur, appelez l’agent à l’aide de arguments pour fournir le paramètre de modèle final qui spécifie la date et l’heure actuelles.

La réponse Agent est ensuite affichée à l’utilisateur.

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

En rassemblant toutes les étapes, nous obtenons le code final de cet exemple. L’implémentation complète est fournie ci-dessous.

Essayez d’utiliser ces entrées suggérées :

  1. Qu’est-ce que mon nom d’utilisateur ?
  2. Décrivez le dépôt.
  3. Décrivez le problème le plus récent créé dans le dépôt.
  4. Répertoriez les 10 principaux problèmes fermés au cours de la semaine dernière.
  5. Comment ces problèmes ont-ils été étiquetés ?
  6. Répertorie les 5 problèmes ouverts récemment avec l’étiquette « 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())

Vous trouverez peut-être le code complet , comme indiqué ci-dessus, dans notre dépôt.

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();
            }
        }
    }
}

Étapes suivantes