Partilhar via


Configuração de agentes com plugins de núcleo semântico

Importante

Este recurso está na fase de candidato a lançamento. Os recursos neste estágio estão quase completos e geralmente estáveis, embora possam passar por pequenos refinamentos ou otimizações antes de atingir a disponibilidade geral total.

Funções e Plugins no Kernel Semântico

A chamada de função é uma ferramenta poderosa que permite aos desenvolvedores adicionar funcionalidades personalizadas e expandir as capacidades de aplicativos de IA. A arquitetura do plug-in do kernel semântico oferece uma estrutura flexível para suportar a chamada de função. Para um Agent, a integração de Plugins e Chamadas de Função é baseada neste recurso essencial conhecido como Kernel Semântico.

Uma vez configurado, um agente escolherá quando e como chamar uma função disponível, como faria em qualquer uso fora do Agent Framework.

Adicionando plug-ins a um agente

Qualquer plug-in disponível para um Agent é gerenciado dentro de sua respetiva Kernel instância. Esta configuração permite que cada um Agent aceda a funcionalidades distintas com base na sua função específica.

Plugins podem ser adicionados ao Kernel antes ou depois de a Agent ser criada. O processo de inicialização de Plugins segue os mesmos padrões usados para qualquer implementação de Kernel Semântico, permitindo consistência e facilidade de uso no gerenciamento de recursos de IA.

Observação

Para um ChatCompletionAgent, o modo de chamada de função deve ser explicitamente habilitado. OpenAIAssistant O agente baseia-se sempre na chamada automática de funções.

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

Há duas maneiras de criar um ChatCompletionAgent com plugins.

Método 1: Especificar plug-ins através do construtor

Você pode passar diretamente uma lista de plugins para o construtor:

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

Sugestão

Por padrão, a chamada de função automática está habilitada. Para desativá-lo, defina o argumento function_choice_behavior como function_choice_behavior=FunctionChoiceBehavior.Auto(auto_invoke=False) no construtor. Com essa configuração, os plug-ins são transmitidos para o modelo, mas não são invocados automaticamente. Se as configurações de execução especificarem o mesmo service_id ou ai_model_id como a configuração do serviço AI, o comportamento de chamada de função definido nas configurações de execução (via KernelArguments) terá precedência sobre o comportamento de escolha de função definido no construtor.

Método 2: Configurar o kernel manualmente

Se nenhum kernel é fornecido através do construtor, um é criado automaticamente durante a validação do modelo. Todos os plugins passados têm precedência e são adicionados ao kernel. Para obter um controle mais refinado sobre o estado do kernel, siga estas etapas:

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

Sugestão

Se a service_id não for especificado ao adicionar um serviço ao kernel, o padrão será default. Ao configurar vários serviços de IA no kernel, é recomendável diferenciá-los usando o service_id argumento. Isso permite que você recupere as configurações de execução para um específico service_id e vincule essas configurações ao serviço desejado.

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

Adicionando funções a um agente

Um plug-in é a abordagem mais comum para configurar chamadas de funções. No entanto, funções individuais também podem ser fornecidas independentemente, incluindo funções de solicitação.

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

Limitações para chamada de função de agente

Ao invocar diretamente aChatCompletionAgent, todos os Comportamentos de Escolha de Função são suportados. No entanto, quando se utiliza um OpenAIAssistant, apenas a chamada automática de função está disponível atualmente.

Procedimentos

Para obter um exemplo de ponta a ponta para usar a chamada de função, consulte:

Próximos passos