AI 関数を作成するときに、AI モデルによって提供されるパラメーターを超えてコンテキスト データにアクセスすることが必要になる場合があります。
Microsoft.Extensions.AI ライブラリには、関数デリゲートにデータを渡すメカニズムがいくつか用意されています。
AIFunction クラス
AIFunction型は、AI サービスに記述して呼び出すことができる関数を表します。
AIFunctionオーバーロードのいずれかを呼び出して、AIFunctionFactory.Createオブジェクトを作成できます。 ただし、 AIFunction も基底クラスであり、そこから派生して独自の AI 関数型を実装できます。
DelegatingAIFunction は、既存の AIFunction とレイヤーを追加機能でラップする簡単な方法を提供します。これには、使用する追加データのキャプチャが含まれます。
データを渡す
クロージャまたは AdditionalPropertiesを使用して、作成時にデータを関数に関連付けることができます。 独自の関数を作成する場合は、必要に応じて AdditionalProperties を設定できます。
AIFunctionFactoryを使用して関数を作成する場合は、AIFunctionFactoryOptions.AdditionalPropertiesを使用してデータを設定できます。
また、 AIFunctionFactoryに提供されるデリゲートの一部として、データへの参照をキャプチャすることもできます。 つまり、AIFunction 自体の一部として参照するものは何でも組み込むことができます。
関数デリゲート内のデータにアクセスする
AIFunctionを直接呼び出すか、FunctionInvokingChatClientを使用して間接的に呼び出す場合があります。 次のセクションでは、いずれかの方法を使用して引数データにアクセスする方法について説明します。
手動関数呼び出し
AIFunction.InvokeAsync(AIFunctionArguments, CancellationToken)を手動で使用してAIFunctionを呼び出す場合は、AIFunctionArgumentsを渡します。 AIFunctionArgumentsの種類には、次のものが含まれます。
- 名前付き引数のディクショナリ。
-
Context: 関数に追加のアンビエント データを渡すための任意の
IDictionary<object, object>。 -
Services: 任意の状態を依存関係注入 (DI) コンテナーから解決するIServiceProvider
AIFunction。
AIFunctionArguments デリゲート内からIServiceProviderまたはAIFunctionFactory.Createにアクセスする場合は、IServiceProviderまたはAIFunctionArgumentsとして型指定されたパラメーターを作成します。 そのパラメーターは、AIFunctionArgumentsに渡されるAIFunction.InvokeAsync()の関連データにバインドされます。
次のコードは例を示しています。
Delegate getWeatherDelegate = (AIFunctionArguments args) =>
{
// Access named parameters from the arguments dictionary.
string? location = args.TryGetValue("location", out object? loc) ? loc.ToString() : "Unknown";
string? units = args.TryGetValue("units", out object? u) ? u.ToString() : "celsius";
return $"Weather in {location}: 35°{units}";
};
// Create the AIFunction.
AIFunction getWeather = AIFunctionFactory.Create(getWeatherDelegate);
// Call the function manually.
var result = await getWeather.InvokeAsync(new AIFunctionArguments
{
{ "location", "Seattle" },
{ "units", "F" }
});
Console.WriteLine($"Function result: {result}");
CancellationTokenは特殊な場合もあります。AIFunctionFactory.Create デリゲートまたはラムダにCancellationTokenパラメーターがある場合、CancellationTokenに渡されたAIFunction.InvokeAsync()にバインドされます。
FunctionInvokingChatClientを通じての呼び出し
FunctionInvokingChatClient引数だけでなく、すべての入力FunctionInvokingChatClient.CurrentContextオブジェクト、ChatMessage、および呼び出されている関数の詳細 (数を含む) を含め、現在の呼び出しに関する状態をChatOptionsに発行します。 必要なデータをChatOptions.AdditionalPropertiesに追加し、AIFunctionからFunctionInvokingChatClient.CurrentContext.Options.AdditionalProperties内に抽出できます。
次のコードは例を示しています。
FunctionInvokingChatClient client = new FunctionInvokingChatClient(
new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(apiKey))
.GetChatClient(model).AsIChatClient());
AIFunction getWeather = AIFunctionFactory.Create(() =>
{
// Access named parameters from the arguments dictionary.
AdditionalPropertiesDictionary props =
FunctionInvokingChatClient.CurrentContext.Options.AdditionalProperties;
string location = props["location"].ToString();
string units = props["units"].ToString();
return $"Weather in {location}: 35°{units}";
});
var chatOptions = new ChatOptions
{
Tools = [getWeather],
AdditionalProperties = new AdditionalPropertiesDictionary {
["location"] = "Seattle",
["units"] = "F"
},
};
List<ChatMessage> chatHistory = [
new(ChatRole.System, "You're a helpful weather assistant.")
];
chatHistory.Add(new ChatMessage(ChatRole.User, "What's the weather like?"));
ChatResponse response = await client.GetResponseAsync(chatHistory, chatOptions);
Console.WriteLine($"Response: {response.Text}");
依存関係の挿入
FunctionInvokingChatClientを使用して関数を自動的に呼び出す場合、そのクライアントはAIFunctionArgumentsに渡すAIFunction オブジェクトを構成します。
AIFunctionArgumentsには、IServiceProvider自体が提供したFunctionInvokingChatClientが含まれているため、標準の DI 手段を使用してクライアントを構築すると、そのIServiceProviderはAIFunctionに渡されます。 その時点で、DI から必要なものに対してクエリを実行できます。
高度な手法
パラメーターのバインド方法をより細かく制御する場合は、 AIFunctionFactoryOptions.ConfigureParameterBindingを使用して、各パラメーターの設定方法を制御できます。 たとえば、 MCP C# SDK では、この手法を使用 して DI からパラメーターを自動的にバインドします。
AIFunctionFactory.Create(MethodInfo, Func<AIFunctionArguments,Object>, AIFunctionFactoryOptions)オーバーロードを使用する場合は、インスタンス メソッドが呼び出されるターゲット オブジェクトを毎回作成するときに、独自の任意のロジックを実行することもできます。 また、そのインスタンスを構成する任意の操作を実行できます。
.NET