篩選叫用的函式

已完成

Semantic Kernel 中的篩選可讓開發人員透過啟用精細的控制與可見度,來管理及保護函式執行。 它們有助於建置符合企業標準的負責任 AI 解決方案。 篩選會驗證動作,例如用戶權力或修改與 AI 模型的互動,以確保合規性和可靠性。

篩選類型

語意核心提供三種類型的篩選來增強控件和自定義:函式調用篩選 來管理函式執行,提示轉譯篩選 在提交前修改提示,以及 自動函數調用篩選 來引導多步驟工作流程。 每個篩選類型都解決了特定需求,可讓開發人員建置安全且可調整的 AI 解決方案。

函式叫用篩選

每次執行函式時,此篩選都會執行,無論是源自提示,還是是在C# 中實作。 其功能包括:

  • 存取函式及其自變數的相關元數據。
  • 在執行前後記錄或驗證動作。
  • 使用替代 AI 模型覆寫結果或重試作業。

以下是一個函式調用篩選器的範例,用於記錄已呼叫的外掛程式函式。

public sealed class LoggingFilter(ILogger logger) : IFunctionInvocationFilter
{
    public async Task OnFunctionInvocationAsync(FunctionInvocationContext context, Func<FunctionInvocationContext, Task> next)
    {
        logger.LogInformation("Invoking: {PluginName}.{FunctionName}", context.Function.PluginName, context.Function.Name);

        await next(context);

        logger.LogInformation("Executed: {PluginName}.{FunctionName}", context.Function.PluginName, context.Function.Name);
    }
}
# Python example: Function invocation filter using a decorator

from semantic_kernel.functions.kernel_function_decorator import kernel_function

def logging_filter(func):
    def wrapper(*args, **kwargs):
        print(f"Invoking: {func.__qualname__}")
        result = func(*args, **kwargs)
        print(f"Executed: {func.__qualname__}")
        return result
    return wrapper

class WeatherForecastUtils:
    @kernel_function(name="GetWeatherForCity", description="Gets the weather for a given city.")
    @logging_filter
    def get_weather_for_city(self, city: str) -> str:
        return "Sunny"

即時渲染篩選

在提示轉譯期間觸發,此篩選可控制提示格式化和提交至 AI 的方式。 它非常適合用於修改涉及敏感資訊的提示 (例如 PII 資訊的刪除) 或啟用語意快取等工作。

提示轉譯篩選的範例:

public class SafePromptFilter : IPromptRenderFilter
{
    public async Task OnPromptRenderAsync(PromptRenderContext context, Func<PromptRenderContext, Task> next)
    {
        await next(context);

        // Modify prompt before submission
        context.RenderedPrompt = "Safe and sanitized prompt.";
    }
}
# Python example: Prompt render filter using a decorator

def safe_prompt_filter(render_func):
    def wrapper(*args, **kwargs):
        prompt = render_func(*args, **kwargs)
        # Modify prompt before submission
        return "Safe and sanitized prompt."
    return wrapper

@safe_prompt_filter
def render_prompt(user_input):
    return f"User prompt: {user_input}"

# Example usage
print(render_prompt("Sensitive information here"))

自動函數調用篩選

只有在自動函式呼叫程式期間才會叫用此篩選。 它可以根據中繼結果來調整甚至終止工作流程。

以下是終止函式呼叫行程的函式調用篩選範例:

public sealed class EarlyTerminationFilter : IAutoFunctionInvocationFilter
{
    public async Task OnAutoFunctionInvocationAsync(AutoFunctionInvocationContext context, Func<AutoFunctionInvocationContext, Task> next)
    {
        await next(context);

        var result = context.Result.GetValue<string>();
        if (result == "desired result")
        {
            context.Terminate = true;
        }
    }
}
# Python example: Auto function invocation filter using a decorator

def early_termination_filter(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        # Simulate checking the result and terminating if needed
        if result == "desired result":
            print("Terminating workflow early.")
            return result
        return result
    return wrapper

@early_termination_filter
def auto_function():
    # Simulate function logic
    return "desired result"

# Example usage
auto_function()

整合函式篩選

若要整合任何函式篩選條件,您可以使用下列方法:

  • 相依性插入

將函式新增至 KernelBuilder 服務:

builder.Services.AddSingleton<IFunctionInvocationFilter, LoggingFilter>();
  • 核心屬性

將函式新增至核心 FunctionInvocationFilters 清單:

kernel.FunctionInvocationFilters.Add(new LoggingFilter(logger));

若要在 Python 中整合篩選,請將裝飾項目套用至外掛程式方法或提示轉譯函式,如上所示。
像往常一樣向核心註冊外掛程式類別:

kernel.add_plugin(WeatherForecastUtils(), "WeatherForecastUtils")

裝飾的方法會自動套用篩選邏輯。

請一律在函式篩選中叫用 next 委派,以允許後續篩選或主要作業執行。 略過此步驟會封鎖作業。

藉由整合提示轉譯篩選,您可以讓語意核心解決方案更安全且更可靠。 提示篩選可讓您在提示到達 AI 之前進行清理。 自動調用過濾器可讓您控制函式執行,以便根據結果提前終止或執行自定義邏輯。