다음을 통해 공유


AI 함수의 데이터 액세스

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: IServiceProviderAIFunction를 통해 DI(종속성 주입) 컨테이너에서 임의의 상태를 해결할 수 있도록 합니다.

AIFunctionFactory.Create 대리자 내에서 AIFunctionArguments 또는 IServiceProvider에 액세스하려면 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 매개 변수가 있는 경우, 이는 AIFunction.InvokeAsync()에 전달된 CancellationToken에 바인딩됩니다.

FunctionInvokingChatClient를 통한 호출

FunctionInvokingChatClientChatOptions 및 호출 중인 함수가 전체 함수 중 어느 것인지에 대한 세부 정보를 포함하여, 현재 FunctionInvokingChatClient.CurrentContext에의 호출 상태를 게시합니다. 이는 모든 입력 ChatMessage 개체와 인수를 포함합니다. 원하는 데이터를 ChatOptions.AdditionalProperties에 추가하고, 이 데이터를 FunctionInvokingChatClient.CurrentContext.Options.AdditionalProperties에서 AIFunction 내에서 추출할 수 있습니다.

다음 코드는 예제를 보여줍니다.

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를 사용하고, 해당 클라이언트가 AIFunction에 전달할 AIFunctionArguments 객체를 구성합니다. 표준 DI 수단을 사용하여 클라이언트를 생성하는 경우, AIFunctionArgumentsIServiceProviderFunctionInvokingChatClient에 자체적으로 제공된 항목을 포함하므로, 그 IServiceProviderAIFunction로 완전히 전달됩니다. 이 시점에서 DI에서 원하는 모든 항목을 쿼리할 수 있습니다.

고급 기술

매개 변수가 바인딩되는 방식을 보다 세밀하게 제어하려면 각 매개 변수가 채워지는 방식을 제어하는 데 사용할 AIFunctionFactoryOptions.ConfigureParameterBinding수 있습니다. 예를 들어 MCP C# SDK는 이 기술을 사용하여 DI의 매개 변수를 자동으로 바인딩합니다.

오버로드를 AIFunctionFactory.Create(MethodInfo, Func<AIFunctionArguments,Object>, AIFunctionFactoryOptions) 사용하는 경우 매번 인스턴스 메서드가 호출될 대상 개체를 만들 때 고유한 임의 논리를 실행할 수도 있습니다. 또한 해당 인스턴스를 구성하려는 모든 작업을 수행할 수 있습니다.