Partilhar via


Modos de invocação de função

Quando o modelo de IA recebe um prompt contendo uma lista de funções, ele pode escolher uma ou mais delas para invocação para concluir o prompt. Quando uma função é escolhida pelo modelo, ela precisa ser invocada pelo Kernel Semântico.

O subsistema de chamada de função no Kernel Semântico tem dois modos de invocação de função: automático e manual.

Dependendo do modo de invocação, o Kernel Semântico faz a invocação de função de ponta a ponta ou dá ao chamador controle sobre o processo de invocação de função.

Invocação automática de função

A invocação automática de função é o modo padrão do subsistema de chamada de função do Kernel Semântico. Quando o modelo de IA escolhe uma ou mais funções, o Kernel Semântico invoca automaticamente as funções escolhidas. Os resultados dessas invocações de função são adicionados ao histórico de bate-papo e enviados para o modelo automaticamente em solicitações subsequentes. O modelo então raciocina sobre o histórico de bate-papo, escolhe funções adicionais, se necessário, ou gera a resposta final. Esta abordagem é totalmente automatizada e não requer intervenção manual do chamador.

Este exemplo demonstra como usar a invocação de função automática no Semantic Kernel. O modelo AI decide quais funções chamar para concluir o prompt e o Semantic Kernel faz o resto e as invoca automaticamente.

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

// By default, functions are set to be automatically invoked.  
// If you want to explicitly enable this behavior, you can do so with the following code:  
// PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(autoInvoke: true) };  
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() }; 

await kernel.InvokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?", new(settings));

Alguns modelos de IA suportam chamada de função paralela, onde o modelo escolhe várias funções para invocação. Isso pode ser útil nos casos em que invocar as funções escolhidas leva muito tempo. Por exemplo, a IA pode optar por recuperar as últimas notícias e a hora atual simultaneamente, em vez de fazer uma viagem de ida e volta por função.

O Kernel Semântico pode invocar essas funções de duas maneiras diferentes:

  • Sequencialmente: As funções são invocadas uma após a outra. Este é o comportamento predefinido.
  • Simultaneamente: As funções são invocadas ao mesmo tempo. Isso pode ser ativado definindo a FunctionChoiceBehaviorOptions.AllowConcurrentInvocation propriedade como true, conforme mostrado no exemplo abaixo.
using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<NewsUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

// Enable concurrent invocation of functions to get the latest news and the current time.
FunctionChoiceBehaviorOptions options = new() { AllowConcurrentInvocation = true };

PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(options: options) }; 

await kernel.InvokePromptAsync("Good morning! What is the current time and latest news headlines?", new(settings));

Invocação Manual de Funções

Nos casos em que o chamador deseja ter mais controle sobre o processo de invocação de função, a invocação manual de função pode ser usada.

Quando a invocação manual de funções está ativada, o Semantic Kernel não invoca automaticamente as funções escolhidas pelo modelo de IA. Em vez disso, ele retorna uma lista de funções escolhidas para o chamador, que pode decidir quais funções invocar, invocá-las sequencialmente ou em paralelo, lidar com exceções e assim por diante. Os resultados da invocação da função precisam ser adicionados ao histórico de bate-papo e retornados ao modelo, que raciocina sobre eles e decide se deseja escolher funções adicionais ou gerar a resposta final.

O exemplo abaixo demonstra como usar a invocação manual de funções.

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

IChatCompletionService chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();

// Manual function invocation needs to be enabled explicitly by setting autoInvoke to false.
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = Microsoft.SemanticKernel.FunctionChoiceBehavior.Auto(autoInvoke: false) };

ChatHistory chatHistory = [];
chatHistory.AddUserMessage("Given the current time of day and weather, what is the likely color of the sky in Boston?");

while (true)
{
    ChatMessageContent result = await chatCompletionService.GetChatMessageContentAsync(chatHistory, settings, kernel);

    // Check if the AI model has generated a response.
    if (result.Content is not null)
    {
        Console.Write(result.Content);
        // Sample output: "Considering the current weather conditions in Boston with a tornado watch in effect resulting in potential severe thunderstorms,
        // the sky color is likely unusual such as green, yellow, or dark gray. Please stay safe and follow instructions from local authorities."
        break;
    }

    // Adding AI model response containing chosen functions to chat history as it's required by the models to preserve the context.
    chatHistory.Add(result); 

    // Check if the AI model has chosen any function for invocation.
    IEnumerable<FunctionCallContent> functionCalls = FunctionCallContent.GetFunctionCalls(result);
    if (!functionCalls.Any())
    {
        break;
    }

    // Sequentially iterating over each chosen function, invoke it, and add the result to the chat history.
    foreach (FunctionCallContent functionCall in functionCalls)
    {
        try
        {
            // Invoking the function
            FunctionResultContent resultContent = await functionCall.InvokeAsync(kernel);

            // Adding the function result to the chat history
            chatHistory.Add(resultContent.ToChatMessage());
        }
        catch (Exception ex)
        {
            // Adding function exception to the chat history.
            chatHistory.Add(new FunctionResultContent(functionCall, ex).ToChatMessage());
            // or
            //chatHistory.Add(new FunctionResultContent(functionCall, "Error details that the AI model can reason about.").ToChatMessage());
        }
    }
}

Nota

As classes FunctionCallContent e FunctionResultContent são usadas para representar chamadas de função de modelo de IA e resultados de invocação de função Kernel Semântico, respectivamente. Eles contêm informações sobre a função escolhida, como o ID da função, nome e argumentos, e resultados de invocação de função, como ID de chamada de função e resultado.

Brevemente

Mais informações em breve.

Brevemente

Mais informações em breve.