Notatka
Dostęp do tej strony wymaga autoryzacji. Może spróbować zalogować się lub zmienić katalogi.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
Gdy model sztucznej inteligencji otrzymuje monit zawierający listę funkcji, może wybrać co najmniej jeden z nich do wywołania, aby ukończyć monit. Gdy funkcja jest wybierana przez model, musi być wywoływana przez jądro semantyczne.
Podsystem wywoływania funkcji w jądrze semantycznym ma dwa tryby wywołania funkcji: automatyczne i ręczne.
W zależności od trybu wywołania Semantic Kernel albo wykonuje kompleksowe wywołanie funkcji, albo oddaje elementowi wywołującemu kontrolę nad procesem wywoływania funkcji.
Automatyczne wywoływanie funkcji
Wywołanie funkcji automatycznej jest domyślnym trybem podsystemu wywoływania funkcji semantycznego jądra. Gdy model sztucznej inteligencji wybierze co najmniej jedną funkcję, semantyczne jądro automatycznie wywołuje wybrane funkcje. Wyniki tych wywołań funkcji są dodawane do historii czatu i wysyłane do modelu automatycznie w kolejnych żądaniach. Następnie model analizuje historię czatu, w razie potrzeby wybiera dodatkowe funkcje lub generuje ostateczną odpowiedź. Takie podejście jest w pełni zautomatyzowane i nie wymaga ręcznej interwencji obiektu wywołującego.
Wskazówka
Automatyczne wywoływanie funkcji różni się od zachowania automatycznego wyboru funkcji. Pierwszy określa, czy funkcje powinny być wywoływane automatycznie przez Semantic Kernel, podczas gdy ten ostatni określa, czy funkcje powinny być wybierane automatycznie przez model AI.
W tym przykładzie pokazano, jak używać automatycznego wywoływania funkcji w Semantic Kernel. Model sztucznej inteligencji decyduje, które funkcje mają być wywoływane w celu ukończenia monitu, a jądro semantyczne wykonuje resztę i wywołuje je automatycznie.
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)
Wskazówka
Wkrótce do zestawu SDK Java pojawi się więcej aktualizacji.
Niektóre modele sztucznej inteligencji obsługują wywołania funkcji równoległych, w których model wybiera wiele funkcji do wywołania. Może to być przydatne w przypadkach, gdy wywoływanie wybranych funkcji trwa długo. Na przykład SI może zdecydować się na jednoczesne pobranie najnowszych wiadomości i aktualnej godziny, zamiast wykonywać osobne wywołanie dla każdej funkcji.
Semantyczne jądro może wywoływać te funkcje na dwa różne sposoby:
- Sekwencyjnie: funkcje są wywoływane jeden po drugim. To jest zachowanie domyślne.
-
Jednocześnie: funkcje są wywoływane w tym samym czasie. Można to włączyć, ustawiając
FunctionChoiceBehaviorOptions.AllowConcurrentInvocationwłaściwość natrue, jak pokazano w poniższym przykładzie.
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));
Czasami model może wybrać wiele funkcji do wywołania. Jest to często nazywane wywołaniem funkcji równoległych . Gdy model sztucznej inteligencji wybiera wiele funkcji, Semantic Kernel będą wywoływać je współbieżnie.
Wskazówka
Za pomocą łącznika OpenAI lub Azure OpenAI można wyłączyć wywoływanie funkcji równoległych, wykonując następujące czynności:
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
)
Ręczne wywołanie funkcji
W przypadkach, gdy wywołujący chce mieć większą kontrolę nad procesem wywoływania funkcji, można użyć ręcznego wywołania funkcji.
Po włączeniu wywołania funkcji ręcznej semantyczne jądro nie wywołuje automatycznie funkcji wybranych przez model AI. Zamiast tego zwraca listę wybranych funkcji do obiektu wywołującego, który może następnie zdecydować, które funkcje mają być wywoływane, wywoływać je sekwencyjnie lub równolegle, obsługiwać wyjątki itd. Wyniki wywołania funkcji muszą zostać dodane do historii czatu i przekazane z powrotem do modelu, który przeanalizuje je i zdecyduje, czy wybrać dodatkowe funkcje, czy wygenerować ostateczną odpowiedź.
W poniższym przykładzie pokazano, jak używać wywołania funkcji ręcznej.
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());
}
}
}
Uwaga
Klasy FunctionCallContent i FunctionResultContent służą odpowiednio do reprezentowania wywołań funkcji modelu AI oraz wyników wywołania funkcji Semantic Kernel. Zawierają one informacje o wybranej funkcji, takie jak identyfikator funkcji, nazwa i argumenty oraz wyniki wywołania funkcji, takie jak identyfikator wywołania funkcji i wynik.
Poniższy przykład pokazuje, jak korzystać z ręcznego wywoływania funkcji za pomocą interfejsu API strumieniowego generowania odpowiedzi czatu. Zwróć uwagę na użycie klasy FunctionCallContentBuilder do tworzenia wywołań funkcji na podstawie treści strumieniowanej.
Ze względu na strumieniowy charakter interfejsu API wywołania funkcji są również przesyłane strumieniowo. Oznacza to, że obiekt wywołujący musi skompilować wywołania funkcji z zawartości przesyłania strumieniowego przed wywołaniem ich.
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].
Uwaga
Klasy FunctionCallContent i FunctionResultContent służą do reprezentowania odpowiednio wywołań funkcji modelu AI oraz wyników wywołania funkcji w systemie Semantic Kernel. Zawierają one informacje o wybranej funkcji, takie jak identyfikator funkcji, nazwa i argumenty oraz wyniki wywołania funkcji, takie jak identyfikator wywołania funkcji i wynik.
Wskazówka
Wkrótce do zestawu SDK Java pojawi się więcej aktualizacji.