Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
Este guia de migração mostra como migrar de uma nova abordagem recomendada para o recurso de FunctionCallingStepwisePlanner
planejamento - Auto Function Calling. A nova abordagem produz os resultados de forma mais confiável e usa menos tokens em comparação com o FunctionCallingStepwisePlanner
.
Geração de planos
O código a seguir mostra como gerar um novo plano com Auto Function Calling usando FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
. Depois de enviar uma solicitação para o modelo de IA, o plano será localizado no ChatHistory
objeto onde uma mensagem com Assistant
função conterá uma lista de funções (etapas) para chamar.
Abordagem antiga:
Kernel kernel = Kernel
.CreateBuilder()
.AddOpenAIChatCompletion("gpt-4", Environment.GetEnvironmentVariable("OpenAI__ApiKey"))
.Build();
FunctionCallingStepwisePlanner planner = new();
FunctionCallingStepwisePlannerResult result = await planner.ExecuteAsync(kernel, "Check current UTC time and return current weather in Boston city.");
ChatHistory generatedPlan = result.ChatHistory;
Nova abordagem:
Kernel kernel = Kernel
.CreateBuilder()
.AddOpenAIChatCompletion("gpt-4", Environment.GetEnvironmentVariable("OpenAI__ApiKey"))
.Build();
IChatCompletionService chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
ChatHistory chatHistory = [];
chatHistory.AddUserMessage("Check current UTC time and return current weather in Boston city.");
OpenAIPromptExecutionSettings executionSettings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() };
await chatCompletionService.GetChatMessageContentAsync(chatHistory, executionSettings, kernel);
ChatHistory generatedPlan = chatHistory;
Execução do novo plano
O código a seguir mostra como executar um novo plano com Auto Function Calling usando FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
. Esta abordagem é útil quando apenas o resultado é necessário sem etapas do plano. Nesse caso, Kernel
o objeto pode ser usado para passar um objetivo para o InvokePromptAsync
método. O resultado da execução do plano será localizado no FunctionResult
objeto.
Abordagem antiga:
Kernel kernel = Kernel
.CreateBuilder()
.AddOpenAIChatCompletion("gpt-4", Environment.GetEnvironmentVariable("OpenAI__ApiKey"))
.Build();
FunctionCallingStepwisePlanner planner = new();
FunctionCallingStepwisePlannerResult result = await planner.ExecuteAsync(kernel, "Check current UTC time and return current weather in Boston city.");
string planResult = result.FinalAnswer;
Nova abordagem:
Kernel kernel = Kernel
.CreateBuilder()
.AddOpenAIChatCompletion("gpt-4", Environment.GetEnvironmentVariable("OpenAI__ApiKey"))
.Build();
OpenAIPromptExecutionSettings executionSettings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() };
FunctionResult result = await kernel.InvokePromptAsync("Check current UTC time and return current weather in Boston city.", new(executionSettings));
string planResult = result.ToString();
Execução do plano existente
O código a seguir mostra como executar um plano existente com Auto Function Calling usando FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
o . Essa abordagem é útil quando ChatHistory
já está presente (por exemplo, armazenada em cache) e deve ser executada novamente e o resultado final deve ser fornecido pelo modelo de IA.
Abordagem antiga:
Kernel kernel = Kernel
.CreateBuilder()
.AddOpenAIChatCompletion("gpt-4", Environment.GetEnvironmentVariable("OpenAI__ApiKey"))
.Build();
FunctionCallingStepwisePlanner planner = new();
ChatHistory existingPlan = GetExistingPlan(); // plan can be stored in database or cache for reusability.
FunctionCallingStepwisePlannerResult result = await planner.ExecuteAsync(kernel, "Check current UTC time and return current weather in Boston city.", existingPlan);
string planResult = result.FinalAnswer;
Nova abordagem:
Kernel kernel = Kernel
.CreateBuilder()
.AddOpenAIChatCompletion("gpt-4", Environment.GetEnvironmentVariable("OpenAI__ApiKey"))
.Build();
IChatCompletionService chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
ChatHistory existingPlan = GetExistingPlan(); // plan can be stored in database or cache for reusability.
OpenAIPromptExecutionSettings executionSettings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() };
ChatMessageContent result = await chatCompletionService.GetChatMessageContentAsync(existingPlan, executionSettings, kernel);
string planResult = result.Content;
O código a seguir mostra como gerar um novo plano com Auto Function Calling usando function_choice_behavior = FunctionChoiceBehavior.Auto()
. Depois de enviar uma solicitação para o modelo de IA, o plano será localizado no ChatHistory
objeto onde uma mensagem com Assistant
função conterá uma lista de funções (etapas) para chamar.
Abordagem antiga:
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.planners.function_calling_stepwise_planner import (
FunctionCallingStepwisePlanner,
FunctionCallingStepwisePlannerResult,
)
kernel = Kernel()
kernel.add_service(AzureChatCompletion())
# Add any plugins to the kernel that the planner will leverage
kernel.add_plugins(...)
planner = FunctionCallingStepwisePlanner(service_id="service_id")
result: FunctionCallingStepwisePlannerResult = await planner.invoke(
kernel=kernel,
question="Check current UTC time and return current weather in Boston city.",
)
generated_plan = result.chat_history
Nova abordagem:
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.contents import ChatHistory
chat_completion_service = AzureChatCompletion()
chat_history = ChatHistory()
chat_hitory.add_user_message("Check current UTC time and return current weather in Boston city.")
request_settings = AzureChatPromptExecutionSettings(function_choice_behavior=FunctionChoiceBehavior.Auto())
# Add any plugins to the kernel that the planner will leverage
kernel = Kernel()
kernel.add_plugins(...)
response = await chat_completion_service.get_chat_message_content(
chat_history=chat_history,
settings=request_settings,
kernel=kernel,
)
print(response)
# The generated plan is now contained inside of `chat_history`.
Execução do novo plano
O código a seguir mostra como executar um novo plano com Auto Function Calling usando function_choice_behavior = FunctionChoiceBehavior.Auto()
. Esta abordagem é útil quando apenas o resultado é necessário sem etapas do plano. Nesse caso, o Kernel
objeto pode ser usado para passar uma meta para o invoke_prompt
método. O resultado da execução do plano estará localizado em um FunctionResult
objeto.
Abordagem antiga:
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.planners.function_calling_stepwise_planner import (
FunctionCallingStepwisePlanner,
FunctionCallingStepwisePlannerResult,
)
kernel = Kernel()
kernel.add_service(AzureChatCompletion())
# Add any plugins to the kernel that the planner will leverage
kernel.add_plugins(...)
planner = FunctionCallingStepwisePlanner(service_id="service_id")
result: FunctionCallingStepwisePlannerResult = await planner.invoke(
kernel=kernel,
question="Check current UTC time and return current weather in Boston city.",
)
print(result.final_answer)
Nova abordagem:
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.contents import ChatHistory
from semantic_kernel.functions import KernelArguments
kernel = Kernel()
kernel.add_service(AzureChatCompletion())
# Add any plugins to the kernel that the planner will leverage
kernel.add_plugins(...)
chat_history = ChatHistory()
chat_hitory.add_user_message("Check current UTC time and return current weather in Boston city.")
request_settings = AzureChatPromptExecutionSettings(function_choice_behavior=FunctionChoiceBehavior.Auto())
response = await kernel.invoke_prompt(
"Check current UTC time and return current weather in Boston city.",
arguments=KernelArguments(settings=request_settings),
)
print(response)
Os planejadores não estavam disponíveis no SK Java. Por favor, use a função chamando diretamente.
Os trechos de código acima demonstram como migrar seu código que usa o Stepwise Planner para usar a chamada de função automática. Saiba mais sobre a Chamada de função com a conclusão do chat.