Compartir a través de


Cómo Hacer: ChatCompletionAgent

Importante

Esta característica está en la fase experimental. Las características de esta fase están en desarrollo y están sujetas a cambios antes de avanzar a la fase de versión preliminar o candidata para lanzamiento.

Información general

En este ejemplo, exploraremos la configuración de un complemento para acceder a la API de GitHub y proporcionaremos instrucciones basadas en plantillas para ChatCompletionAgent para responder a preguntas sobre un repositorio de GitHub. El enfoque se desglosará paso a paso para iluminar las partes clave del proceso de codificación. Como parte de la tarea, el agente proporcionará citas de documentos dentro de la respuesta.

El streaming se usará para entregar las respuestas del agente. Esto proporcionará actualizaciones en tiempo real a medida que avanza la tarea.

Introducción

Antes de continuar con la codificación de características, asegúrese de que el entorno de desarrollo esté completamente preparado y configurado.

Empiece por crear un proyecto de consola . A continuación, incluya las siguientes referencias de paquete para asegurarse de que todas las dependencias necesarias están disponibles.

Para agregar dependencias de paquete desde la línea de comandos, use el 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

Si administra paquetes NuGet en Visual Studio, asegúrese de que Include prerelease está activado.

El archivo de proyecto (.csproj) debe contener las definiciones siguientes 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>

El Agent Framework es experimental y requiere la supresión de advertencias. Esto puede abordarse en como una propiedad en el archivo del proyecto (.csproj):

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

Además, copie el complemento y los modelos de GitHub (GitHubPlugin.cs y GitHubModels.cs) del proyecto Kernel SemánticoLearnResources. Agregue estos archivos en la carpeta del proyecto.

Empiece por crear una carpeta que contenga el script (.py archivo) y los recursos de ejemplo. Incluya las siguientes importaciones en la parte superior del .py archivo:

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

Además, copie el plugin y los modelos de GitHub (github.py) del Proyecto Semantic Kernel LearnResources. Agregue estos archivos en la carpeta del proyecto.

Empiece por crear un proyecto de consola de Maven. A continuación, incluya las siguientes referencias de paquete para asegurarse de que todas las dependencias necesarias están disponibles.

El proyecto pom.xml debe contener las siguientes dependencias:

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

Además, copie el complemento y los modelos de GitHub (GitHubPlugin.java y GitHubModels.java) del proyecto Kernel SemánticoLearnResources. Agregue estos archivos en la carpeta del proyecto.

Configuración

Este ejemplo requiere la configuración para conectarse a servicios remotos. Deberá definir la configuración de OpenAI o Azure OpenAI y también para GitHub.

Nota:

Para obtener información sobre los tokens de acceso personal de GitHub, consulte: Administración de los tokens de acceso personal.

# 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 siguiente clase se usa en todos los ejemplos del agente. Asegúrese de incluirlo en el proyecto para garantizar una funcionalidad adecuada. Esta clase actúa como un componente fundamental para los ejemplos siguientes.

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

La forma más rápida de empezar a trabajar con la configuración adecuada para ejecutar el código de ejemplo es crear un .env archivo en la raíz del proyecto (donde se ejecuta el script).

Configure los valores siguientes en el archivo .env para 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=""

Una vez configuradas, las clases de servicio de IA correspondientes recogerán las variables necesarias y las usarán durante la creación de instancias.

Defina las siguientes variables de entorno en el 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=""

En la parte superior del archivo puede recuperar sus valores como se indica a continuación.

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

Codificar

El proceso de codificación de este ejemplo implica:

  1. Configuración : inicialización de la configuración y el complemento.
  2. Agent definición - Cree el ChatCompletionAgent con instrucciones y plugins templatizados.
  3. El bucle de chat: elabora el bucle que impulsa la interacción usuario/agente.

El código de ejemplo completo se proporciona en la sección Final . Consulte esa sección para obtener la implementación completa.

Configuración

Antes de crear un ChatCompletionAgent, se deben inicializar los ajustes de configuración, los complementos y el Kernel.

Inicialice la clase Settings a la que se hace referencia en la sección anterior de Configuración.

Settings settings = new();

Inicialice el complemento con su configuración.

Aquí se muestra un mensaje para indicar el progreso.

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

Ahora inicialice una Kernel instancia con el IChatCompletionService y el GitHubPlugin creado anteriormente.

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

Definición del agente

Por último, estamos listos para realizar una instanciación de ChatCompletionAgent con sus instrucciones, Kernel asociadas, y los argumentos y la configuración de ejecución predeterminados. En este caso, queremos que las funciones del complemento se ejecuten automáticamente.

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

Bucle de chat

Por último, podemos coordinar la interacción entre el usuario y el Agent. Empiece por crear un objeto ChatHistoryAgentThread para mantener el estado de la conversación y crear un bucle vacío.

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
}

Ahora vamos a capturar la entrada del usuario dentro del bucle anterior. En este caso, se omitirá la entrada vacía y el término EXIT indicará que la conversación se ha completado.

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

}

Para generar una Agent respuesta a la entrada del usuario, invoque al agente usando Argumentos para proporcionar el parámetro de plantilla final que especifica la fecha y hora actuales.

La respuesta Agent se muestra a continuación al usuario.

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

Final

Al reunir todos los pasos, tenemos el código final de este ejemplo. A continuación se proporciona la implementación completa.

Pruebe a usar estas entradas sugeridas:

  1. ¿Cuál es mi nombre de usuario?
  2. Describir el repositorio.
  3. Describa el problema más reciente creado en el repositorio.
  4. Enumere los 10 principales problemas cerrados en la última semana.
  5. ¿Cómo se etiquetaron estos problemas?
  6. Enumerar las 5 incidencias abiertas más recientemente con la etiqueta "Agentes"
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())

Puede encontrar el código completo , como se muestra anteriormente, en nuestro repositorio.

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

Pasos siguientes