在提示中使用函式
語意核心 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);
在此範例中,提示會在提供的 $history
輸入上呼叫 ConversationSummaryPlugin.SummarizeConversation
。 函式會取得使用者的背景資訊並加以摘要,而結果是用來擷取相關配方的清單。 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.
在提示中使用變數和函式可讓您建立可重複使用的範本,而這些範本可以動態填入不同的輸入。 當您需要使用不同的輸入來執行相同的工作,或為模型提供內容來改善結果時,重複使用提示特別有用。