呼び出された関数をフィルター処理する
セマンティック カーネルのフィルターを使用すると、開発者はきめ細かい制御と可視性を有効にすることで、関数の実行を管理およびセキュリティで保護できます。 これらは、エンタープライズ標準を満たす責任ある AI ソリューションを構築する上でインストルメント化されています。 フィルターは、ユーザーのアクセス許可などのアクションを検証したり、AI モデルとの対話を変更したりして、コンプライアンスと信頼性を確保します。
フィルターの種類
セマンティック カーネルには、制御とカスタマイズを強化するための 3 種類のフィルターが用意されています。関数の実行を管理するための 関数呼び出しフィルター 、送信前にプロンプトを変更するための プロンプト レンダリング フィルター 、マルチステップ ワークフローを指示するための 自動関数呼び出しフィルター です。 各フィルターの種類は、特定のニーズに対応し、開発者が安全で適応可能な 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 に到達する前にプロンプトをサニタイズできます。 自動呼び出しフィルターを使用すると、関数の実行を制御し、結果に基づいて早期終了またはカスタム ロジックを有効にできます。