在提示中使用函数

已完成

可以使用语义内核 SDK 的模板化语言创建动态提示。 该语言支持三个功能:

  • 使用变量。
  • 调用外部函数。
  • 将参数传递给函数。

为了在提示中嵌入表达式,模板化语言使用大括号 {{...}},变量用美元符号 $ 表示。 调用的函数必须是加载到内核中的插件的一部分。 例如,如果要在提示中调用函数,可以使用以下语法:

{{plugin.functionName $argument}}

在提示中调用函数之前,必须确保包含函数的插件加载到内核中。 提示中的嵌套函数有助于减少提示中使用的令牌数,或为模型提供其他上下文,以改进结果。

假设你有一个提示,它根据一些用户信息推荐食谱清单:

string history = @"In the heart of my bustling kitchen, I have embraced the challenge 
    of satisfying my family's diverse taste buds and navigating their unique tastes. 
    With a mix of picky eaters and allergies, my culinary journey revolves around 
    exploring a plethora of vegetarian recipes.

    One of my kids is a picky eater with an aversion to anything green, while another 
    has a peanut allergy that adds an extra layer of complexity to meal planning. 
    Armed with creativity and a passion for wholesome cooking, I've embarked on a 
    flavorful adventure, discovering plant-based dishes that not only please the 
    picky palates but are also heathy and delicious.";

string prompt = @"This is some information about the user's background: {{$history}}
    Given this user's background, provide a list of relevant recipes.";

var result = await kernel.InvokePromptAsync(suggestRecipes, new() { "history", history });
Console.WriteLine(result);

在提供食谱清单之前,你可以调用函数来汇总用户的冗长背景信息。 下面是有关如何在提示中使用该函数的示例:

 kernel.ImportPluginFromType<ConversationSummaryPlugin>();

string prompt = @"User information: 
    {{ConversationSummaryPlugin.SummarizeConversation $history}}

    Given this user's background information, provide a list of relevant recipes.";

var result = await kernel.InvokePromptAsync(suggestRecipes, new() { "history", history });
Console.WriteLine(result);

在此示例中,提示根据提供的 ConversationSummaryPlugin.SummarizeConversation 输入调用 $history。 该函数获取用户的背景信息并对其进行汇总,结果用于检索相关食谱清单。 必须将 ConversationSummaryPlugin 插件添加到内核生成器中,提示才能正常工作。

示例输出如下所示:

1. Lentil and vegetable soup - a hearty, filling soup that is perfect for a cold day. This recipe is vegetarian and can easily be adapted to accommodate allergies.

2. Cauliflower "steaks" - a delicious and healthy main course that is sure to satisfy even the pickiest of eaters. This recipe is vegetarian and can easily be made vegan.

3. Quinoa salad with roasted vegetables - a healthy and filling salad that is perfect for any occasion. This recipe is vegetarian and can easily be adapted to accommodate allergies.

4. Peanut-free pad Thai - a classic dish made without peanut sauce, perfect for those with peanut allergies. This recipe is vegetarian and can easily be made vegan.

5. Black bean and sweet potato enchiladas - a delicious and healthy twist on traditional enchiladas. This recipe is vegetarian and can easily be made vegan.

通过在提示中使用变量和函数,可以创建可动态填充不同输入的可重用模板。 需要使用不同的输入执行同一任务,或者为模型提供上下文以改进结果时,重用提示特别有用。