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.
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ções
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 chat e enviados ao 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. Essa abordagem é totalmente automatizada e não requer intervenção manual do chamador.
Dica
A invocação de função automática é diferente do comportamento de escolha da função automática. O primeiro determina se as funções devem ser invocadas automaticamente por Kernel semântico, enquanto a última determina se as funções devem ser escolhidas automaticamente pelo modelo de IA.
Este exemplo demonstra como usar a invocação automática de função no Kernel Semântico. O modelo de IA decide quais funções chamar para concluir o prompt e o Kernel semântico 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));
from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.kernel import Kernel
kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())
# Assuming that WeatherPlugin and DateTimePlugin are already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
kernel.add_plugin(DateTimePlugin(), "DateTimePlugin")
query = "What is the weather in Seattle today?"
arguments = KernelArguments(
settings=PromptExecutionSettings(
# 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:
# function_choice_behavior=FunctionChoiceBehavior.Auto(auto_invoke=True),
function_choice_behavior=FunctionChoiceBehavior.Auto(),
)
)
response = await kernel.invoke_prompt(query, arguments=arguments)
Dica
Mais atualizações em breve para o SDK do Java.
Alguns modelos de IA dão suporte à chamada de função paralela, em que o modelo escolhe várias funções para invocação. Isso pode ser útil nos casos em que a invocação de 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. Esse é o comportamento padrão.
-
Simultaneamente: as funções são invocadas ao mesmo tempo. Isso pode ser habilitado definindo a
FunctionChoiceBehaviorOptions.AllowConcurrentInvocationpropriedade comotrue, 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));
Às vezes, um modelo pode escolher várias funções para invocação. Isso geralmente é chamado de chamada de função paralela . Quando várias funções forem escolhidas pelo modelo de IA, Kernel semântico as invocará simultaneamente.
Dica
Com o conector OpenAI ou Azure OpenAI, você pode desabilitar a chamada de função paralela fazendo o seguinte:
from semantic_kernel.connectors.ai.open_ai import OpenAIChatPromptExecutionSettings
from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
settings = OpenAIChatPromptExecutionSettings(
function_choice_behavior=FunctionChoiceBehavior.Auto(),
parallel_tool_calls=False
)
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ção está habilitada, o Kernel Semântico 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 de função precisam ser adicionados ao histórico de chat e retornados ao modelo, o que raciocinará sobre eles e decidirá se deseja escolher funções adicionais ou gerar uma resposta final.
O exemplo abaixo demonstra como usar a invocação manual de função.
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());
}
}
}
Observação
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 de kernel semântico, respectivamente. Eles contêm informações sobre a função escolhida, como o ID da função, o nome e os argumentos, e os resultados da invocação da função, como o ID da chamada da função e o resultado.
O exemplo a seguir demonstra como usar a invocação de função manual com a API de conclusão do chat de streaming. Observe o uso da FunctionCallContentBuilder classe para criar chamadas de função do conteúdo de streaming.
Devido à natureza de streaming da API, as chamadas de função também são transmitidas. Isso significa que o chamador deve montar as chamadas de função a partir do conteúdo de streaming antes de invocá-las.
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)
{
AuthorRole? authorRole = null;
FunctionCallContentBuilder fccBuilder = new ();
// Start or continue streaming chat based on the chat history
await foreach (StreamingChatMessageContent streamingContent in chatCompletionService.GetStreamingChatMessageContentsAsync(chatHistory, settings, kernel))
{
// Check if the AI model has generated a response.
if (streamingContent.Content is not null)
{
Console.Write(streamingContent.Content);
// Sample streamed output: "The color of the sky in Boston is likely to be gray due to the rainy weather."
}
authorRole ??= streamingContent.Role;
// Collect function calls details from the streaming content
fccBuilder.Append(streamingContent);
}
// Build the function calls from the streaming content and quit the chat loop if no function calls are found
IReadOnlyList<FunctionCallContent> functionCalls = fccBuilder.Build();
if (!functionCalls.Any())
{
break;
}
// Creating and adding chat message content to preserve the original function calls in the chat history.
// The function calls are added to the chat message a few lines below.
ChatMessageContent fcContent = new ChatMessageContent(role: authorRole ?? default, content: null);
chatHistory.Add(fcContent);
// Iterating over the requested function calls and invoking them.
// The code can easily be modified to invoke functions concurrently if needed.
foreach (FunctionCallContent functionCall in functionCalls)
{
// Adding the original function call to the chat message content
fcContent.Items.Add(functionCall);
// Invoking the function
FunctionResultContent functionResult = await functionCall.InvokeAsync(kernel);
// Adding the function result to the chat history
chatHistory.Add(functionResult.ToChatMessage());
}
}
from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.contents.chat_history import ChatHistory
from semantic_kernel.contents.function_call_content import FunctionCallContent
from semantic_kernel.contents.function_result_content import FunctionResultContent
from semantic_kernel.kernel import Kernel
kernel = Kernel()
chat_completion_service = OpenAIChatCompletion()
# Assuming that WeatherPlugin is already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
settings = PromptExecutionSettings(
function_choice_behavior=FunctionChoiceBehavior.Auto(auto_invoke=False),
)
chat_history = ChatHistory()
chat_history.add_user_message("What is the weather in Seattle on 10th of September 2024 at 11:29 AM?")
response = await chat_completion_service.get_chat_message_content(chat_history, settings, kernel=kernel)
function_call_content = response.items[0]
assert isinstance(function_call_content, FunctionCallContent)
# Need to add the response to the chat history to preserve the context
chat_history.add_message(response)
function = kernel.get_function(function_call_content.plugin_name, function_call_content.function_name)
function_result = await function(kernel, function_call_content.to_kernel_arguments())
function_result_content = FunctionResultContent.from_function_call_content_and_result(
function_call_content, function_result
)
# Adding the function result to the chat history
chat_history.add_message(function_result_content.to_chat_message_content())
# Invoke the model again with the function result
response = await chat_completion_service.get_chat_message_content(chat_history, settings, kernel=kernel)
print(response)
# The weather in Seattle on September 10th, 2024, is expected to be [weather condition].
Observação
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 de kernel semântico, respectivamente. Eles contêm informações sobre a função escolhida, como o ID, o nome e os argumentos da função, e sobre os resultados da invocação da função, como o ID da chamada da função e o resultado.
Dica
Mais atualizações em breve para o SDK do Java.