Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
Importante
Esta funcionalidade está na fase de release candidate. Os recursos nesta fase são quase completos e geralmente estáveis, embora possam passar por pequenos refinamentos ou otimizações antes de atingir a disponibilidade geral completa.
Funções e plug-ins no kernel semântico
A chamada de função é uma ferramenta poderosa que permite aos desenvolvedores adicionar funcionalidades personalizadas e expandir os recursos dos aplicativos de IA. A arquitetura do Plug-in do Kernel Semântico oferece uma estrutura flexível para suportar Chamada de Funções. Para um Agent, a integração de plug-ins e Chamadas de Função é construída sobre esse recurso fundamental do 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.
Dica
Referência de API:
Adicionando plug-ins a um agente
Qualquer plugin disponível para um Agent é gerenciado dentro de sua respectiva Kernel instância. Essa configuração permite que cada um Agent acesse funcionalidades distintas com base em sua função específica.
Os plug-ins podem ser adicionados ao Kernel antes ou depois da Agent criação. O processo de inicialização de plug-ins 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 habilitado explicitamente.
OpenAIAssistant o agente sempre se baseia em chamadas automáticas 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 plug-ins.
Método 1: especificar plug-ins por meio do Construtor
Você pode passar diretamente uma lista de plug-ins 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()]
)
Dica
Por padrão, a chamada de função automática está habilitada. Para desabilitá-lo, coloque 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 que a configuração do serviço de IA, o comportamento de chamada de função definido nas configurações de execução (via KernelArguments) terá precedência sobre o comportamento de escolha da função definido no construtor.
Método 2: Configurar o Kernel manualmente
Se nenhum kernel for fornecido por meio do construtor, um será criado automaticamente durante a validação do modelo. Todos os plug-ins 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),
)
Dica
Se um service_id não for especificado ao adicionar um serviço ao kernel, ele usará como padrão 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 determinado 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 chamada de função. No entanto, funções individuais também podem ser fornecidas independentemente, incluindo funções de prompt.
// 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 umChatCompletionAgent, todos os comportamentos de escolha de função são suportados. No entanto, ao usar um OpenAIAssistant, apenas a função de chamada automática está disponível no momento.
Instruções
Para obter um exemplo de ponta a ponta para usar a chamada de função, consulte: