Compartir a través de


Configuración de agentes con complementos de kernel semántico

Importante

Esta característica está en la fase candidata para lanzamiento. Las características de esta fase son casi completas y, por lo general, estables, aunque pueden someterse a pequeños refinamientos o optimizaciones antes de alcanzar la disponibilidad general completa.

Funciones y complementos en kernel semántico

La llamada a funciones es una herramienta eficaz que permite a los desarrolladores agregar funcionalidades personalizadas y expandir las funcionalidades de las aplicaciones de inteligencia artificial. La arquitectura del Plugin del núcleo semántico ofrece un marco flexible para admitir llamadas a funciones. En el caso de un Agent, la integración de Plugins y llamadas a funciones se basa en esta característica fundamental del Kernel Semántico.

Una vez configurado, un agente elegirá cuándo y cómo llamar a una función disponible, como lo haría en cualquier uso fuera del Agent Framework.

Adición de complementos a un agente

Cualquier plugin disponible para un Agent se administra dentro de su instancia de Kernel respectiva. Esta configuración permite que cada Agent acceda a funcionalidades distintas en función de su rol específico.

complementos pueden agregarse al Kernel antes o después de crear el Agent. El proceso de inicialización de complementos sigue los mismos patrones que se usan para cualquier implementación de kernel semántico, lo que permite la coherencia y facilidad de uso en la administración de funcionalidades de inteligencia artificial.

Nota:

Para un ChatCompletionAgent, el modo de llamada de funciones debe estar habilitado explícitamente. El agente OpenAIAssistant siempre se basa en la llamada automática de funciones.

// Factory method to produce an agent with a specific role.
// Could be incorporated into DI initialization.
ChatCompletionAgent CreateSpecificAgent(Kernel kernel, string credentials)
{
    // Clone kernel instance to allow for agent specific plug-in definition
    Kernel agentKernel = kernel.Clone();

    // Import plug-in from type
    agentKernel.ImportPluginFromType<StatelessPlugin>();

    // Import plug-in from object
    agentKernel.ImportPluginFromObject(new StatefulPlugin(credentials));

    // Create the agent
    return
        new ChatCompletionAgent()
        {
            Name = "<agent name>",
            Instructions = "<agent instructions>",
            Kernel = agentKernel,
            Arguments = new KernelArguments(
                new OpenAIPromptExecutionSettings()
                {
                    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
                })
        };
}

Hay dos maneras de crear una ChatCompletionAgent con complementos.

Método 1: Especificar complementos mediante el constructor

Puede pasar directamente una lista de complementos al constructor:

from semantic_kernel.agents import ChatCompletionAgent

# Create the Chat Completion Agent instance by specifying a list of plugins
agent = ChatCompletionAgent(
    service=AzureChatCompletion(),
    instructions="<instructions>",
    plugins=[SamplePlugin()]
)

Sugerencia

De forma predeterminada, la llamada a función automática está habilitada. Para deshabilitarlo, establezca el argumento function_choice_behavior en function_choice_behavior=FunctionChoiceBehavior.Auto(auto_invoke=False) en el constructor. Con esta configuración, los complementos se transmiten al modelo, pero no se invocan automáticamente. Si la configuración de ejecución especifica la misma service_id o ai_model_id que la configuración del servicio de IA, el comportamiento de invocación de función establecido en la configuración de ejecución (a través de KernelArguments) tendrá prioridad sobre el comportamiento de selección de función definido en el constructor.

Método 2: Configurar el kernel manualmente

Si no se proporciona ningún kernel a través del constructor, se crea automáticamente uno durante la validación del modelo. Los complementos proporcionados toman prioridad y se agregan al kernel. Para obtener un control más específico sobre el estado del kernel, siga estos pasos:

from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel

# Create the instance of the Kernel
kernel = Kernel()

# Add the chat completion service to the Kernel
kernel.add_service(AzureChatCompletion())

# Get the AI Service settings
settings = kernel.get_prompt_execution_settings_from_service_id()

# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()

# Add the Plugin to the Kernel
kernel.add_plugin(SamplePlugin(), plugin_name="<plugin name>")

# Create the agent
agent = ChatCompletionAgent(
    kernel=kernel,
    name=<agent name>,
    instructions=<agent instructions>,
    arguments=KernelArguments(settings=settings),
)

Sugerencia

Si no se especifica un service_id al agregar un servicio al kernel, el valor predeterminado es default. Al configurar varios servicios de IA en el kernel, se recomienda diferenciarlos mediante el argumento service_id. Esto le permite recuperar la configuración de ejecución de un service_id específico y vincular esa configuración al servicio deseado.

var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromObject(new SamplePlugin(), "<plugin name>"))
    .build();

var agent = ChatCompletionAgent.builder()
    .withKernel(kernel)
    .withName("<agent name>")
    .withInstructions("<agent instructions>")
    .build();

Agregar funciones a un agente

Un complemento es el enfoque más común para configurar las llamadas a funciones. Sin embargo, las funciones individuales también se pueden proporcionar de manera independiente, incluidas las funciones de aviso.

// Factory method to product an agent with a specific role.
// Could be incorporated into DI initialization.
ChatCompletionAgent CreateSpecificAgent(Kernel kernel)
{
    // Clone kernel instance to allow for agent specific plug-in definition
    Kernel agentKernel = kernel.Clone();

    // Create plug-in from a static function
    var functionFromMethod = agentKernel.CreateFunctionFromMethod(StatelessPlugin.AStaticMethod);

    // Create plug-in from a prompt
    var functionFromPrompt = agentKernel.CreateFunctionFromPrompt("<your prompt instructions>");

    // Add to the kernel
    agentKernel.ImportPluginFromFunctions("my_plugin", [functionFromMethod, functionFromPrompt]);

    // Create the agent
    return
        new ChatCompletionAgent()
        {
            Name = "<agent name>",
            Instructions = "<agent instructions>",
            Kernel = agentKernel,
            Arguments = new KernelArguments(
                new OpenAIPromptExecutionSettings()
                {
                    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
                })
        };
}
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel

# Create the instance of the Kernel
kernel = Kernel()

# Add the chat completion service to the Kernel
kernel.add_service(AzureChatCompletion())

# Create the AI Service settings
settings = AzureChatPromptExecutionSettings()

# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()

# Add the Plugin to the Kernel
kernel.add_function(
    plugin_name="<plugin_name>",
    function=KernelFunctionFromPrompt(
        function_name="<function_name>",
        prompt="<your prompt instructions>",
    )
)

# Create the agent
agent = ChatCompletionAgent(
    kernel=kernel,
    name=<agent name>,
    instructions=<agent instructions>,
    arguments=KernelArguments(settings=settings),
)
var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

// Create function from method
var functionFromMethod = KernelFunction.createFromMethod(SamplePlugin.class.getMethod("method"), new SamplePlugin());

// Create function from prompt
var functionFromPrompt = KernelFunction.createFromPrompt("<your prompt instructions>");

// Create the kernel with a plugin from the two functions
Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromFunctions("SamplePlugin", List.of(functionFromMethod, functionFromPrompt)))
    .build();

InvocationContext invocationContext = InvocationContext.builder()
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true))
    .build();

// Create the agent
var agent = ChatCompletionAgent.builder()
    .withKernel(kernel)
    .withName("<agent name>")
    .withInstructions("<agent instructions>")
    .withInvocationContext(invocationContext)
    .build();

Limitaciones en las llamadas a funciones del agente

Al invocar directamente ,ChatCompletionAgent se admiten todos los comportamientos de opción de función. Sin embargo, cuando se usa un OpenAIAssistant, solo la llamada automática a funciones está disponible actualmente.

Procedimiento

Para obtener un ejemplo completo para usar llamadas a funciones, consulte:

Pasos siguientes