Compartir a través de


Guía de migración de Planner paso a paso

En esta guía de migración se muestra cómo migrar de FunctionCallingStepwisePlanner a un nuevo enfoque recomendado para la capacidad de planeación: llamada a funciones automáticas. El nuevo enfoque genera los resultados de forma más confiable y usa menos tokens en comparación con FunctionCallingStepwisePlanner.

Generación de planes

El código siguiente muestra cómo generar un nuevo plan con llamadas automáticas a funciones mediante FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(). Después de enviar una solicitud al modelo de IA, el plan se ubicará en el objeto donde ChatHistory un mensaje con Assistant rol contendrá una lista de funciones (pasos) a las que llamar.

Enfoque antiguo:

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;

Nuevo enfoque:

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;

Ejecución del nuevo plan

El código siguiente muestra cómo ejecutar un nuevo plan con llamadas automáticas a funciones mediante FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(). Este enfoque es útil cuando solo se necesita el resultado sin pasos de plan. En este caso, Kernel el objeto se puede usar para pasar un objetivo al InvokePromptAsync método . El resultado de la ejecución del plan se ubicará en el FunctionResult objeto .

Enfoque antiguo:

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;

Nuevo enfoque:

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();

Ejecución del plan existente

En el código siguiente se muestra cómo ejecutar un plan existente con llamadas automáticas a funciones mediante FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(). Este enfoque es útil cuando ChatHistory ya está presente (por ejemplo, almacenado en caché) y se debe volver a ejecutar y el resultado final debe proporcionarse mediante el modelo de IA.

Enfoque antiguo:

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;

Nuevo enfoque:

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;

En el código siguiente se muestra cómo generar un nuevo plan con llamadas automáticas a funciones mediante function_choice_behavior = FunctionChoiceBehavior.Auto(). Después de enviar una solicitud al modelo de IA, el plan se ubicará en el objeto donde ChatHistory un mensaje con Assistant rol contendrá una lista de funciones (pasos) a las que llamar.

Enfoque antiguo:

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

Nuevo enfoque:

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`.

Ejecución del nuevo plan

El código siguiente muestra cómo ejecutar un nuevo plan con llamadas automáticas a funciones mediante function_choice_behavior = FunctionChoiceBehavior.Auto(). Este enfoque es útil cuando solo se necesita el resultado sin pasos del plan. En este caso, el Kernel objeto se puede usar para pasar un objetivo al invoke_prompt método . El resultado de la ejecución del plan se ubicará en un FunctionResult objeto .

Enfoque antiguo:

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)

Nuevo enfoque:

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)

Los planificadores no estaban disponibles en SK Java. Use la llamada de función directamente.

Los fragmentos de código anteriores muestran cómo migrar el código que usa Stepwise Planner para usar llamadas automáticas a funciones. Obtenga más información sobre Las llamadas a funciones con finalización del chat.