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 kernelplugin semántico ofrece un marco flexible para admitir llamadas a funciones. Para una Agent, la integración de complementos y llamadas a funciones se basa en esta característica semántica de el kernel .

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.

Los agentes no están disponibles actualmente en Java.

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 el ChatCompletionAgent, el modo de llamada de función debe estar habilitado explícitamente. El agente OpenAIAssistant siempre se basa en la llamada automática de funciones.

// Factory method to product 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()]
)

Propina

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 todavía 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 llamada de función definido en la configuración de ejecución (a través de KernelArguments) tendrá prioridad sobre el comportamiento de elección de función establecido 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),
)

Propina

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.

Los agentes no están disponibles actualmente en Java.

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, como las funciones de solicitud.

// 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),
)

Los agentes no están disponibles actualmente en Java.

Limitaciones de las llamadas a funciones del agente

Al invocar directamente unChatCompletionAgent, se admiten todos los comportamientos de elección de función . Sin embargo, cuando se usa un OpenAIAssistant o AgentChat, actualmente solo está disponible llamada automática de funciones de.

Procedimiento

Para obtener un ejemplo de un extremo a otro para usar la llamada a funciones, consulte: