iT邦幫忙

2025 iThome 鐵人賽

DAY 6
0
生成式 AI

當 .NET 遇見 AI Agents:用 Semantic Kernel × MCP 打造智慧協作應用系列 第 6

Day 6: Semantic Kernel Function Choice Behavior 深度解析:精確控制 AI Agent 的函式呼叫行為

  • 分享至 

  • xImage
  •  

上一篇的內容提到如何撰寫與掛載 Plugins(Tools) 到 Semantic Kernel 中,除了 Plugins(Tools) 的設計與實作之外,控制 AI Agent 如何選擇與呼叫這些 Plugins(Tools) 也是非常重要的一環。透過適當的配置,我們可以讓 AI Agent 在不同情境下表現出更精確、更可靠的行為。這其中的關鍵機制便是 Function Choice Behavior,決定了 AI Agent 如何選擇和呼叫函式,透過適當的配置,可以讓 AI Agent 在不同情境下表現出更精確、更可靠的行為。

Function Choice Behavior 概述

簡單來說 Function Choice Behavior 是 Semantic Kernel 中控制函式調用機制的關鍵配置,開發者可透過三種模式精確控制 AI 模型與函數的互動行為:

  • Auto 模式:允許 AI 模型從可用函數中自主選擇 0 至多個函式進行調用,適用於開放式任務場景。是預設值,透過 FunctionChoiceBehavior.Auto() 啟用,屬於最靈活的模式,完全由LLM根據上下文決定,但也可能帶來不可預測的行為。
  • Required 模式:強制 AI 模型必須從指定函式中選擇至少 1 個函式執行,適用於必須調用特定功能的場景。
  • None 模式:明確禁止 AI 模型呼叫任何函式,即便 Kernel 配置了 Plugins,也不允許呼叫,僅能依賴模型本身的知識來回答問題,適用於安全性要求高的場景。

不論是哪種模式,在程式碼裡需透過 OpenAIPromptExecutionSettingsFunctionChoiceBehavior 屬性來設定。

Auto Behavior:智慧型自動選擇

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 適合用於:

  • 一般對話 Agent:需要根據使用者問題靈活的選擇工具
  • 多功能助手:具備多種能力,需要智慧決策選擇
  • 探索性任務:不確定需要哪些工具完成任務

Required 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:禁用函式呼叫

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 適合用於:

  • 安全模式:完全不允許執行任何外部操作
  • 純對話模式:只需要純文本生成的情境
  • 測試和除錯:驗證 AI 模型在沒有工具時的行為

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";
    }
}

進階配置:FunctionChoiceBehaviorOptions

在 Semantic Kernel 的函數調用配置中,提供另外二個選項 AllowConcurrentInvocation 和 AllowParallelCalls ,是控制並行處理的進階選項,允許開發者根據需求調整函式呼叫的並行行為。這兩個選項都可以在 FunctionChoiceBehaviorOptions 中設定,並與 Auto 或 Required 模式結合使用,能夠實現更靈活的函式呼叫策略。

  • AllowConcurrentInvocation:允許同時執行多個函式呼叫,適用於函式之間沒有相互依賴關係的情境,當 AI 模型單次選擇多個函式時,此設定可以提升整體處理效率。
  • AllowParallelCalls:允許模型一次選擇多個函式進行呼叫,預設值為 null(遵循 AI 模型預設行為),但部份模型可能不支援此功能。啟用此選項後,AI 模型可以在單次回應中選擇多個函式,適合需要同時處理多個任務的場景。

二個參數的搭配組合使用,其效果為:

  1. AllowConcurrentInvocation = false,AllowParallelCalls = false

    • 函式選擇/調用模式:單次選擇 1 個函式
    • 實際行為:順序執行(無並行)
  2. AllowConcurrentInvocation = true,AllowParallelCalls = false

    • 函式選擇/調用模式:單次選擇 1 個函式
    • 實際行為:順序執行,無並行效果
  3. AllowConcurrentInvocation = false,AllowParallelCalls = true

    • 函式選擇/調用模式:單次選擇多個函式
    • 實際行為:順序執行多函式
  4. 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 ?? "無法產生業務報告";
    }
}

實務上使用建議

  1. 以安全性優先,明確限制可用函式,避免不必要的風險。
  2. 效能考量,對於需要快速回應的場景,避免使用過多函式,提升效能。
  3. 對於複雜任務,考慮使用 Required 模式確保函式被執行。
  4. 對於簡單任務,使用 Auto 模式提供最大的靈活性,使用情境必須具備可容錯性。

結語

Function Choice Behavior 是 Semantic Kernel 中控制 AI Agent 行為的關鍵機制。透過適當的配置,可以:

  • 確保 AI Agent 在適當的時機呼叫正確的函式
  • 提供安全性保障,防止不當的函式呼叫
  • 根據不同情境和使用者權限動態調整行為
  • 最佳化效能和使用者體驗

掌握這些配置技巧,可進一步提升 AI Agent 的可靠性和實用性。


上一篇
Day 5: Semantic Kernel 實戰:詳解 Tools 的撰寫與掛載技巧
下一篇
Day 7: Semantic Kernel Plugins 複雜性參數支援度
系列文
當 .NET 遇見 AI Agents:用 Semantic Kernel × MCP 打造智慧協作應用8
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言