自动调用函数
语义内核 SDK 支持强大的自动函数调用功能。 启用自动函数调用后,内核会自动选择要对某些提供的输入使用哪些函数和提示。 此功能可帮助你节省手动调用函数和提示的时间,并让你的应用程序更智能。
要使用自动函数调用,必须使用支持它的 OpenAI 模型。 目前,这些模型包含 GPT-3.5-turbo 和 GPT-4 模型版本 0613 或更高版本。
若要启用自动函数调用,必须将 OpenAIPromptExecutionSettings
对象的 ToolCallBehavior
属性设置为 AutoInvokeKernelFunctions
。
例如,假设你有一些支持以下函数的食材插件:
- `GetIngredients`: Gets a list of the user's available ingredients
- `GetRecipe`: Gets a list of ingredients for a given recipe
- `GetMissingIngredients`: Gets a list of ingredients that are missing from the user's kitchen for a given recipe
可运用 AutoInvokeKernelFunctions
行为根据提示自动运行函数。 例如:
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.OpenAI;
var builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
"your-deployment-name",
"your-endpoint",
"your-api-key",
"deployment-model");
kernel.ImportPluginFromType<IngredientsPlugin>();
kernel.ImportPluginFromPromptDirectory("Prompts/IngredientPrompts");
// Set the ToolCallBehavior property
OpenAIPromptExecutionSettings settings = new()
{
ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
};
string prompt = @"What ingredients am I missing from my current list of ingredients
to make a recipe for aloo jeera?";
// Use the settings to automatically invoke plugins based on the prompt
var result = await kernel.InvokePromptAsync(prompt, new(settings));
Console.WriteLine(result);
根据你的食材和函数详细信息,此代码的输出可能与以下响应类似:
Based on the list of ingredients for aloo jeera, you are missing the following items:
- Cumin seeds
- Green chilies
- Ginger
- Turmeric powder
- Red chili powder
- Coriander powder
- Fresh coriander leaves
- Salt
- Oil
函数调用允许 AI 按正确的顺序调用具有适当参数的函数。 LLM 可以迭代调用函数来满足用户的需求。 这是通过反馈环路完成的,在该过程中,AI 可以调用函数、检查结果,然后决定下一步要执行的操作。
AutoInvokeKernelFunctions
设置会自动调用所需的插件来运行提示,从而可以用更少的代码来实现应用程序的动态性和稳健性。 此功能可帮助你创建能够处理各种方案的复杂应用程序。