上一篇的內容提到如何撰寫與掛載 Plugins(Tools) 到 Semantic Kernel 中,除了 Plugins(Tools) 的設計與實作之外,控制 AI Agent 如何選擇與呼叫這些 Plugins(Tools) 也是非常重要的一環。透過適當的配置,我們可以讓 AI Agent 在不同情境下表現出更精確、更可靠的行為。這其中的關鍵機制便是 Function Choice Behavior,決定了 AI Agent 如何選擇和呼叫函式,透過適當的配置,可以讓 AI Agent 在不同情境下表現出更精確、更可靠的行為。
簡單來說 Function Choice Behavior 是 Semantic Kernel 中控制函式調用機制的關鍵配置,開發者可透過三種模式精確控制 AI 模型與函數的互動行為:
不論是哪種模式,在程式碼裡需透過 OpenAIPromptExecutionSettings
的 FunctionChoiceBehavior
屬性來設定。
Auto Behavior 是最常用的模式,它讓 AI 模型根據對話上下文自動決定是否需要呼叫函式。
var executionSettings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
};
var result = _chatCompletion.GetStreamingChatMessageContentsAsync(
chatHistory,
executionSettings,
kernel: _kernel);
你也可以限制 AI 模型只能選擇特定的函式來呼叫,避免不必要或危險的函式被誤用,適合用於當一個 Plugin 擁有太多函式時,提供一種可選擇特定函式的彈性,而不一定需要把所有函式都暴露出來。
// 只允許模型選擇特定的函式
var customerFunctions = new[]
{
_kernel.Plugins.GetFunction("CustomerService", "GetCustomerInfo"), //plugin name, function name
_kernel.Plugins.GetFunction("CustomerService", "GetOrderStatus"),
_kernel.Plugins.GetFunction("CustomerService", "ProcessReturnRequest")
};
//配置自動決策使用必要工具
var executionSettings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(functions: customerFunctions)
};
Auto Behavior 適合用於:
Required Behavior 強制 AI 模型必須呼叫至少一個指定的函式,適用於需要確保特定函式會被執行的情境。通常用於需要嚴格控制流程的任務,不希望出現因LLM理解偏差而導致 function 未被呼叫的情況。
// 強制模型必須呼叫溫度查詢函式
kernel.Plugins.AddFromType<WeatherServicePlugin>("WeatherService");
var executionSettings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Required()
};
// 或者指定必須從特定函式中選擇
var requiredFunction = kernel.Plugins.GetFunction("WeatherService", "Get_Today_Temperature"); //plugin name, function name
var executionSettings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Required(functions: [requiredFunction])
};
Required Behavior 適合用於:
None Behavior 則是完全禁用函式呼叫,僅能依賴模型本身的知識來回答問題,適用於安全性要求高的場景。
var executionSettings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.None()
};
var response = await chatCompletion.GetChatMessageContentAsync(
chatHistory,
executionSettings: executionSettings,
kernel: kernel);
public class SecureChatAgent
{
public async Task<string> SafeChatMode(string userInput, Kernel kernel)
{
var chatHistory = new ChatHistory();
chatHistory.AddSystemMessage(
"""
你是一個安全模式的聊天助手。在此模式下:
1. 你不能執行任何外部操作
2. 只能基於已知資訊回答問題
3. 不能存取或修改任何系統資料
"""
);
chatHistory.AddUserMessage(userInput);
// 禁用所有函式呼叫
var safeSettings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.None()
};
var chatCompletion = kernel.GetRequiredService<IChatCompletionService>();
var response = await chatCompletion.GetChatMessageContentAsync(
chatHistory,
executionSettings: safeSettings,
kernel: kernel);
return response.Content ?? "無法在安全模式下處理此請求";
}
}
None Behavior 適合用於:
public class PermissionBasedAgent
{
public OpenAIPromptExecutionSettings GetSettingsForUser(
string userId,
Kernel kernel)
{
var userRole = GetUserRole(userId);
var requiredFunction = kernel.Plugins.GetFunction("WeatherService", "Get_Today_Temperature");
return userRole switch
{
"Admin" => new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() // 完全存取
},
"User" => new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Required(functions: [requiredFunction]) // 限定存取特定功能
},
"Guest" => new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.None() // 只能對話
},
_ => new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.None()
}
};
}
private string GetUserRole(string userId)
{
// 實際的使用者角色查詢邏輯
return "User";
}
}
在 Semantic Kernel 的函數調用配置中,提供另外二個選項 AllowConcurrentInvocation 和 AllowParallelCalls ,是控制並行處理的進階選項,允許開發者根據需求調整函式呼叫的並行行為。這兩個選項都可以在 FunctionChoiceBehaviorOptions 中設定,並與 Auto 或 Required 模式結合使用,能夠實現更靈活的函式呼叫策略。
二個參數的搭配組合使用,其效果為:
AllowConcurrentInvocation = false,AllowParallelCalls = false
AllowConcurrentInvocation = true,AllowParallelCalls = false
AllowConcurrentInvocation = false,AllowParallelCalls = true
AllowConcurrentInvocation = true,AllowParallelCalls = true
var options = new FunctionChoiceBehaviorOptions
{
AllowConcurrentInvocation = true, // 允許同時執行多個函式
AllowParallelCalls = true // 允許模型一次選擇多個函式
};
var executionSettings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(options: options)
};
public class DataAggregationAgent
{
public async Task<string> AggregateBusinessData(Kernel kernel)
{
var chatHistory = new ChatHistory();
chatHistory.AddUserMessage("產生本月業務報告,包含銷售數據、客戶滿意度和庫存狀況");
// 啟用平行呼叫以提高效率
var parallelOptions = new FunctionChoiceBehaviorOptions
{
AllowConcurrentInvocation = true,
AllowParallelCalls = true
};
var executionSettings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(options: parallelOptions)
};
var chatCompletion = kernel.GetRequiredService<IChatCompletionService>();
var response = await chatCompletion.GetChatMessageContentAsync(
chatHistory,
executionSettings: executionSettings,
kernel: kernel);
return response.Content ?? "無法產生業務報告";
}
}
Function Choice Behavior 是 Semantic Kernel 中控制 AI Agent 行為的關鍵機制。透過適當的配置,可以:
掌握這些配置技巧,可進一步提升 AI Agent 的可靠性和實用性。