다음을 통해 공유


함수 선택 동작

함수 선택 동작은 개발자가 구성할 수 있는 구성 비트입니다.

  1. AI 모델에 보급되는 함수입니다.
  2. 모델에서 호출을 위해 모델을 선택하는 방법.
  3. 의미 체계 커널이 이러한 함수를 호출하는 방법

현재 함수 선택 동작은 클래스의 FunctionChoiceBehavior 세 가지 정적 메서드로 표시됩니다.

  • 자동: AI 모델이 제공된 함수에서 호출을 위해 0개 이상의 함수 중에서 선택할 수 있습니다.
  • 필수: AI 모델이 제공된 함수에서 호출을 위해 하나 이상의 함수를 선택하도록 합니다.
  • 없음: AI 모델에 함수를 선택하지 않도록 지시합니다.

현재 함수 선택 동작은 클래스의 FunctionChoiceBehavior 세 가지 클래스 메서드로 표시됩니다.

  • 자동: AI 모델이 제공된 함수에서 호출을 위해 0개 이상의 함수 중에서 선택할 수 있습니다.
  • 필수: AI 모델이 제공된 함수에서 호출을 위해 하나 이상의 함수를 선택하도록 합니다.
  • NoneInvoke: AI 모델에 함수를 선택하지 않도록 지시합니다.

참고 항목

다른 문헌에서 None의 동작에 더욱 익숙할 수 있습니다. Python None 키워드와의 혼동을 방지하는 데 사용합니다NoneInvoke.

  • 자동: AI 모델이 제공된 함수에서 호출을 위해 0개 이상의 함수 중에서 선택할 수 있습니다.
  • 필수: AI 모델이 제공된 함수에서 호출을 위해 하나 이상의 함수를 선택하도록 합니다.
  • 없음: AI 모델에 함수를 선택하지 않도록 지시합니다.

참고 항목

코드에서 ToolCallBehavior 클래스가 나타내는 함수 호출 기능을 사용하는 경우 마이그레이션 가이드 를 참조하여 코드를 최신 함수 호출 모델로 업데이트하세요.

참고 항목

함수 호출 기능은 지금까지 몇 가지 AI 커넥터에서만 지원됩니다. 자세한 내용은 아래의 지원되는 AI 커넥터 섹션을 참조하세요.

함수 광고

함수 광고는 추가 호출 및 호출을 위해 AI 모델에 함수를 제공하는 프로세스입니다. 세 가지 함수 선택 동작은 모두 매개 변수로 functions 보급할 함수 목록을 허용합니다. 기본적으로 Null입니다. 즉, 커널에 등록된 플러그 인의 모든 함수가 AI 모델에 제공됩니다.

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

// All functions from the DateTimeUtils and WeatherForecastUtils plugins will be sent to AI model together with the prompt.
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() }; 

await kernel.InvokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?", new(settings));

함수 목록이 제공되면 해당 함수만 AI 모델로 전송됩니다.

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

KernelFunction getWeatherForCity = kernel.Plugins.GetFunction("WeatherForecastUtils", "GetWeatherForCity");
KernelFunction getCurrentTime = kernel.Plugins.GetFunction("DateTimeUtils", "GetCurrentUtcDateTime");

// Only the specified getWeatherForCity and getCurrentTime functions will be sent to AI model alongside the prompt.
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(functions: [getWeatherForCity, getCurrentTime]) }; 

await kernel.InvokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?", new(settings));

함수의 빈 목록은 함수 호출을 사용하지 않도록 설정하는 것과 동일한 AI 모델에 함수가 제공되지 않음을 의미합니다.

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

// Disables function calling. Equivalent to var settings = new() { FunctionChoiceBehavior = null } or var settings = new() { }.
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(functions: []) }; 

await kernel.InvokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?", new(settings));

함수 광고는 추가 호출 및 호출을 위해 AI 모델에 함수를 제공하는 프로세스입니다. 기본적으로 필터 를 지정하지 않는 한 커널에 등록된 플러그 인의 모든 함수가 AI 모델에 제공됩니다. 필터는 다음 키가 있는 사전입니다. excluded_pluginsincluded_pluginsexcluded_functionsincluded_functions 이를 통해 AI 모델에 보급할 함수를 지정할 수 있습니다.

중요합니다

둘 다 excluded_plugins 또는 included_pluginsexcluded_functionsincluded_functions 동시에 지정할 수 없습니다.

from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.kernel import Kernel

kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())

# Assuming that WeatherPlugin, DateTimePlugin, and LocationPlugin are already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
kernel.add_plugin(DateTimePlugin(), "DateTimePlugin")
kernel.add_plugin(LocationPlugin(), "LocationPlugin")

query = "What is the weather in my current location today?"
arguments = KernelArguments(
    settings=PromptExecutionSettings(
        # Advertise all functions from the WeatherPlugin, DateTimePlugin, and LocationPlugin plugins to the AI model.
        function_choice_behavior=FunctionChoiceBehavior.Auto(),
    )
)

response = await kernel.invoke_prompt(query, arguments=arguments)

필터가 제공된 경우, 필터를 통과한 항목만 AI 모델로 전송됩니다.

from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.kernel import Kernel

kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())

# Assuming that WeatherPlugin, DateTimePlugin, and LocationPlugin are already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
kernel.add_plugin(DateTimePlugin(), "DateTimePlugin")
kernel.add_plugin(LocationPlugin(), "LocationPlugin")

query = "What is the weather in Seattle today?"
arguments = KernelArguments(
    settings=PromptExecutionSettings(
        # Advertise all functions from the WeatherPlugin and DateTimePlugin plugins to the AI model.
        function_choice_behavior=FunctionChoiceBehavior.Auto(filters={"included_plugins": ["WeatherPlugin", "DateTimePlugin"]}),
    )
)

response = await kernel.invoke_prompt(query, arguments=arguments)

중요합니다

included_plugins 또는 included_functions에 빈 목록을 제공해도 아무런 효과가 없습니다. 함수 호출을 비활성화하려면 function_choice_behaviorNoneInvoke로 설정해야 합니다.

함수 광고는 추가 호출 및 호출을 위해 AI 모델에 함수를 제공하는 프로세스입니다. 세 가지 함수 선택 동작은 모두 매개 변수로 functions 보급할 함수 목록을 허용합니다. 기본적으로 Null입니다. 즉, 커널에 등록된 플러그 인의 모든 함수가 AI 모델에 제공됩니다.

var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromObject(new WeatherForecastUtils(), "WeatherForecastUtils"))
    .withPlugin(KernelPluginFactory.createFromObject(new DateTimeUtils(), "DateTimeUtils"))
    .build();

InvocationContext invocationContext = InvocationContext.builder()
    // All functions from the DateTimeUtils and WeatherForecastUtils plugins will be sent to AI model together with the prompt.
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true))
    .build();

var response = kernel.invokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?",
    KernelArguments.builder().build(),
    invocationContext
).block();

함수 목록이 제공되면 해당 함수만 AI 모델로 전송됩니다.

var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromObject(new WeatherForecastUtils(), "WeatherForecastUtils"))
    .withPlugin(KernelPluginFactory.createFromObject(new DateTimeUtils(), "DateTimeUtils"))
    .build();

var getWeatherForCity = kernel.getFunction("WeatherPlugin", "getWeatherForCity");
var getCurrentTime = kernel.getFunction("WeatherPlugin", "getWeatherForCity");

InvocationContext invocationContext = InvocationContext.builder()
    // Only the specified getWeatherForCity and getCurrentTime functions will be sent to AI model alongside the prompt.
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true, List.of(getWeatherForCity, getCurrentTime)))
    .build();

var response = kernel.invokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?",
    KernelArguments.builder().build(),
    invocationContext
).block();

함수의 빈 목록은 함수 호출을 사용하지 않도록 설정하는 것과 동일한 AI 모델에 함수가 제공되지 않음을 의미합니다.

var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromObject(new WeatherForecastUtils(), "WeatherForecastUtils"))
    .withPlugin(KernelPluginFactory.createFromObject(new DateTimeUtils(), "DateTimeUtils"))
    .build();

InvocationContext invocationContext = InvocationContext.builder()
    // Disables function calling. Equivalent to .withFunctionChoiceBehavior(null)
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true, new ArrayList<>()))
    .build();

var response = kernel.invokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?",
    KernelArguments.builder().build(),
    invocationContext
).block();

자동 함수 선택 동작 사용

함수 선택 동작은 Auto 호출을 위해 제공된 함수에서 0개 이상의 함수 중에서 선택하도록 AI 모델에 지시합니다.

이 예제에서는 DateTimeUtilsWeatherForecastUtils 플러그인으로부터 모든 함수가 프롬프트와 함께 AI 모델에 제공됩니다. 이 정보는 함수에 대한 입력으로 필요하므로 모델은 먼저 호출을 위한 GetCurrentTime 함수를 선택하여 GetWeatherForCity 현재 날짜와 시간을 가져옵니다. 다음으로, 구한 날짜와 시간을 사용하여 보스턴 시의 일기 예보를 가져오기 위한 호출 함수를 선택합니다 GetWeatherForCity . 이 정보를 통해 모델은 보스턴에서 하늘의 가능성이 있는 색을 확인할 수 있습니다.

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

// All functions from the DateTimeUtils and WeatherForecastUtils plugins will be provided to AI model alongside the prompt.
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() }; 

await kernel.InvokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?", new(settings));

YAML 프롬프트 템플릿 구성에서 동일한 예제를 쉽게 모델링할 수 있습니다.

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

string promptTemplateConfig = """
    template_format: semantic-kernel
    template: Given the current time of day and weather, what is the likely color of the sky in Boston?
    execution_settings:
      default:
        function_choice_behavior:
          type: auto
    """;

KernelFunction promptFunction = KernelFunctionYaml.FromPromptYaml(promptTemplateConfig);

Console.WriteLine(await kernel.InvokeAsync(promptFunction));

이 예제에서는 WeatherPluginDateTimePlugin 플러그인의 모든 함수가 프롬프트와 함께 AI 모델에 제공됩니다. 모델은 시간이 필요한 정보를 얻기 위해 먼저 DateTimePlugin 플러그인에서 GetCurrentUtcDateTime 함수를 호출하여 현재 날짜와 시간을 얻고, 이 정보를 WeatherPlugin 플러그인에서 GetWeatherForCity 함수를 위한 입력으로 사용합니다. 다음으로, 구한 날짜 및 시간을 사용하여 시애틀 시의 일기 예보를 가져오는 호출 함수를 선택합니다 GetWeatherForCity . 이 정보를 통해 모델은 자연어로 사용자 쿼리에 응답할 수 있습니다.

from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.kernel import Kernel

kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())

# Assuming that WeatherPlugin and DateTimePlugin are already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
kernel.add_plugin(DateTimePlugin(), "DateTimePlugin")

query = "What is the weather in Seattle today?"
arguments = KernelArguments(
    settings=PromptExecutionSettings(
        # Advertise all functions from the WeatherPlugin and DateTimePlugin plugins to the AI model.
        function_choice_behavior=FunctionChoiceBehavior.Auto(),
    )
)

response = await kernel.invoke_prompt(query, arguments=arguments)

YAML 프롬프트 템플릿 구성에서 동일한 예제를 쉽게 모델링할 수 있습니다.

from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.functions.kernel_function_from_prompt import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel

kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())

# Assuming that WeatherPlugin and DateTimePlugin are already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
kernel.add_plugin(DateTimePlugin(), "DateTimePlugin")

prompt_template_config = """
    name: Weather
    template_format: semantic-kernel
    template: What is the weather in Seattle today?
    execution_settings:
      default:
        function_choice_behavior:
          type: auto
"""
prompt_function = KernelFunctionFromPrompt.from_yaml(prompt_template_config)

response = await kernel.invoke(prompt_function)
var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromObject(new WeatherForecastUtils(), "WeatherForecastUtils"))
    .withPlugin(KernelPluginFactory.createFromObject(new DateTimeUtils(), "DateTimeUtils"))
    .build();

InvocationContext invocationContext = InvocationContext.builder()
    // All functions from the DateTimeUtils and WeatherForecastUtils plugins will be sent to AI model together with the prompt.
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true))
    .build();

var response = kernel.invokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?",
    KernelArguments.builder().build(),
    invocationContext
).block();

팁 (조언)

Java SDK에 대한 추가 업데이트가 곧 제공될 예정입니다.

필수 함수 선택 동작 사용

이 동작은 Required 모델이 호출을 위해 제공된 함수에서 하나 이상의 함수를 선택하도록 강제합니다. 이는 AI 모델이 자체 지식이 아닌 지정된 함수에서 필요한 정보를 가져와야 하는 시나리오에 유용합니다.

참고 항목

동작은 AI 모델에 대한 첫 번째 요청의 함수만 보급하고 후속 요청에서 함수 전송을 중지하여 모델이 호출을 위해 동일한 함수를 계속 선택하는 무한 루프를 방지합니다.

여기서는 AI 모델이 자체 지식에 따라 추측하는 대신 보스턴 시의 일기 예보를 얻기 위해 호출 함수를 선택 GetWeatherForCity 해야 한다고 지정합니다. 모델은 먼저 호출 함수를 GetWeatherForCity 선택하여 일기 예보를 검색합니다. 이 정보를 사용하면 모델은 호출의 응답을 사용하여 보스턴에서 하늘의 가능성이 있는 색을 GetWeatherForCity확인할 수 있습니다.

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();

Kernel kernel = builder.Build();

KernelFunction getWeatherForCity = kernel.Plugins.GetFunction("WeatherForecastUtils", "GetWeatherForCity");

PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Required(functions: [getWeatherFunction]) };

await kernel.InvokePromptAsync("Given that it is now the 10th of September 2024, 11:29 AM, what is the likely color of the sky in Boston?", new(settings));

YAML 템플릿 구성의 동일한 예제:

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();

Kernel kernel = builder.Build();

string promptTemplateConfig = """
    template_format: semantic-kernel
    template: Given that it is now the 10th of September 2024, 11:29 AM, what is the likely color of the sky in Boston?
    execution_settings:
      default:
        function_choice_behavior:
          type: required
          functions:
            - WeatherForecastUtils.GetWeatherForCity
    """;

KernelFunction promptFunction = KernelFunctionYaml.FromPromptYaml(promptTemplateConfig);

Console.WriteLine(await kernel.InvokeAsync(promptFunction));

또는 필요에 따라 커널에 등록된 모든 함수를 AI 모델에 제공할 수 있습니다. 그러나 첫 번째 요청의 결과로 AI 모델에서 선택한 것만 의미 체계 커널에 의해 호출됩니다. 함수는 위에서 설명한 대로 무한 루프를 방지하기 위해 후속 요청에서 AI 모델로 전송되지 않습니다.

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();

Kernel kernel = builder.Build();

PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Required() };

await kernel.InvokePromptAsync("Given that it is now the 10th of September 2024, 11:29 AM, what is the likely color of the sky in Boston?", new(settings));

여기서는 AI 모델에 하나의 함수 get_weather_for_city만 제공하고 호출을 위해 이 함수를 강제로 선택하여 일기 예보를 얻습니다.

from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.kernel import Kernel

kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())

# Assuming that WeatherPlugin is already implemented with a
# get_weather_for_city function
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")

query = "What is the weather in Seattle on September 10, 2024, at 11:29 AM?"
arguments = KernelArguments(
    settings=PromptExecutionSettings(
        # Force the AI model to choose the get_weather_for_city function for invocation.
        function_choice_behavior=FunctionChoiceBehavior.Required(filters={"included_functions": ["get_weather_for_city"]}),
    )
)

response = await kernel.invoke_prompt(query, arguments=arguments)

YAML 템플릿 구성의 동일한 예제:

from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.functions.kernel_function_from_prompt import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel

kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())

# Assuming that WeatherPlugin is already implemented with a
# get_weather_for_city function
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")

prompt_template_config = """
    name: Weather
    template_format: semantic-kernel
    template: What is the weather in Seattle on September 10, 2024, at 11:29 AM?
    execution_settings:
      default:
        function_choice_behavior:
          type: auto
          filters:
            included_functions:
              - get_weather_for_city
"""
prompt_function = KernelFunctionFromPrompt.from_yaml(prompt_template_config)

response = await kernel.invoke(prompt_function)
var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromObject(new WeatherForecastUtils(), "WeatherForecastUtils"))
    .withPlugin(KernelPluginFactory.createFromObject(new DateTimeUtils(), "DateTimeUtils"))
    .build();

var getWeatherForCity = kernel.getFunction("WeatherPlugin", "getWeatherForCity");

InvocationContext invocationContext = InvocationContext.builder()
    // Force the AI model to choose the getWeatherForCity function for invocation.
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true, List.of(getWeatherForCity)))
    .build();

var response = kernel.invokePromptAsync("Given that it is now the 10th of September 2024, 11:29 AM, what is the likely color of the sky in Boston?",
    KernelArguments.builder().build(),
    invocationContext
).block();

팁 (조언)

Java SDK에 대한 추가 업데이트가 곧 제공될 예정입니다.

None 함수 선택 동작 사용

이 동작은 None AI 모델에 호출을 위해 해당 함수를 선택하지 않고 제공된 함수를 사용하도록 지시하고 대신 메시지 응답을 생성합니다. 이는 호출자가 실제로 호출하지 않고 모델에서 선택할 함수를 확인하려는 경우 드라이 실행에 유용합니다. 예를 들어 아래 샘플의 AI 모델은 보스턴에서 하늘의 색을 결정하기 위해 선택하는 함수를 올바르게 나열합니다.


Here, we advertise all functions from the `DateTimeUtils` and `WeatherForecastUtils` plugins to the AI model but instruct it not to choose any of them.
Instead, the model will provide a response describing which functions it would choose to determine the color of the sky in Boston on a specified date.

```csharp
using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

KernelFunction getWeatherForCity = kernel.Plugins.GetFunction("WeatherForecastUtils", "GetWeatherForCity");

PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.None() };

await kernel.InvokePromptAsync("Specify which provided functions are needed to determine the color of the sky in Boston on a specified date.", new(settings))

// Sample response: To determine the color of the sky in Boston on a specified date, first call the DateTimeUtils-GetCurrentUtcDateTime function to obtain the 
// current date and time in UTC. Next, use the WeatherForecastUtils-GetWeatherForCity function, providing 'Boston' as the city name and the retrieved UTC date and time. 
// These functions do not directly provide the sky's color, but the GetWeatherForCity function offers weather data, which can be used to infer the general sky condition (e.g., clear, cloudy, rainy).

YAML 프롬프트 템플릿 구성의 해당 예제:

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

string promptTemplateConfig = """
    template_format: semantic-kernel
    template: Specify which provided functions are needed to determine the color of the sky in Boston on a specified date.
    execution_settings:
      default:
        function_choice_behavior:
          type: none
    """;

KernelFunction promptFunction = KernelFunctionYaml.FromPromptYaml(promptTemplateConfig);

Console.WriteLine(await kernel.InvokeAsync(promptFunction));

이 동작은 NoneInvoke AI 모델에 호출을 위해 해당 함수를 선택하지 않고 제공된 함수를 사용하도록 지시하고 대신 메시지 응답을 생성합니다. 이는 호출자가 실제로 호출하지 않고 모델에서 선택할 함수를 확인하려는 경우 드라이 실행에 유용합니다. 예를 들어 아래 샘플의 AI 모델은 보스턴에서 하늘의 색을 결정하기 위해 선택하는 함수를 올바르게 나열합니다.

from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.kernel import Kernel

kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())

# Assuming that WeatherPlugin and DateTimePlugin are already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
kernel.add_plugin(DateTimePlugin(), "DateTimePlugin")

query = "Specify which provided functions are needed to determine the color of the sky in Boston on the current date."
arguments = KernelArguments(
    settings=PromptExecutionSettings(
        # Force the AI model to choose the get_weather_for_city function for invocation.
        function_choice_behavior=FunctionChoiceBehavior.NoneInvoke(),
    )
)

response = await kernel.invoke_prompt(query, arguments=arguments)
# To determine the color of the sky in Boston on the current date, you would need the following functions:
# 1. **functions.DateTimePlugin-get_current_date**: This function is needed to get the current date.
# 2. **functions.WeatherPlugin-get_weather_for_city**: After obtaining the current date,
#    this function will allow you to get the weather for Boston, which will indicate the sky conditions
#    such as clear, cloudy, etc., helping you infer the color of the sky.

YAML 템플릿 구성의 동일한 예제:

from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.functions.kernel_function_from_prompt import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel

kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())

# Assuming that WeatherPlugin and DateTimePlugin are already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
kernel.add_plugin(DateTimePlugin(), "DateTimePlugin")

prompt_template_config = """
    name: BostonSkyColor
    template_format: semantic-kernel
    template: Specify which provided functions are needed to determine the color of the sky in Boston on the current date.
    execution_settings:
      default:
        function_choice_behavior:
          type: none
"""
prompt_function = KernelFunctionFromPrompt.from_yaml(prompt_template_config)

response = await kernel.invoke(prompt_function)
# To determine the color of the sky in Boston on the current date, you would need the following functions:
# 1. **functions.DateTimePlugin-get_current_date**: This function is needed to get the current date.
# 2. **functions.WeatherPlugin-get_weather_for_city**: After obtaining the current date,
#    this function will allow you to get the weather for Boston, which will indicate the sky conditions
#    such as clear, cloudy, etc., helping you infer the color of the sky.

여기서는 모든 함수를 DateTimeUtils 보급하고 WeatherForecastUtils 플러그 인을 AI 모델에 보급하지만 그 중 하나를 선택하지 않도록 지시합니다. 대신, 모델은 지정된 날짜에 보스턴에서 하늘의 색상을 결정하기 위해 선택할 함수를 설명하는 응답을 제공합니다.

var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromObject(new WeatherForecastUtils(), "WeatherForecastUtils"))
    .withPlugin(KernelPluginFactory.createFromObject(new DateTimeUtils(), "DateTimeUtils"))
    .build();

InvocationContext invocationContext = InvocationContext.builder()
    // All functions from the WeatherForecastUtils and DateTimeUtils plugins will be sent to AI model together with the prompt.
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.none())
    .build();

var response = kernel.invokePromptAsync("Specify which provided functions are needed to determine the color of the sky in Boston on a specified date.",
    KernelArguments.builder().build(),
    invocationContext
).block();
// Sample response: To determine the color of the sky in Boston on a specified date, first call the DateTimeUtils-GetCurrentUtcDateTime function to obtain the 
// current date and time in UTC. Next, use the WeatherForecastUtils-GetWeatherForCity function, providing 'Boston' as the city name and the retrieved UTC date and time. 
// These functions do not directly provide the sky's color, but the GetWeatherForCity function offers weather data, which can be used to infer the general sky condition (e.g., clear, cloudy, rainy).

팁 (조언)

Java SDK에 대한 추가 업데이트가 곧 제공될 예정입니다.

함수 선택 동작 옵션

함수 선택 동작의 특정 측면은 options 형식의 생성자 매개 변수를 통해 각 함수 선택 동작 클래스가 허용하는 옵션을 통해 구성할 수 있습니다. 다음과 같은 옵션을 사용할 수 있습니다.

  • AllowConcurrentInvocation: 이 옵션을 사용하면 의미 체계 커널에서 함수를 동시에 호출할 수 있습니다. 기본적으로 false로 설정됩니다. 즉, 함수가 순차적으로 호출됩니다. 동시 호출은 AI 모델이 단일 요청에서 호출을 위해 여러 함수를 선택할 수 있는 경우에만 가능합니다. 그렇지 않으면 순차 호출과 동시 호출이 구분되지 않습니다.

  • AllowParallelCalls: 이 옵션을 사용하면 AI 모델이 한 요청에서 여러 함수를 선택할 수 있습니다. 일부 AI 모델은 이 기능을 지원하지 않을 수 있습니다. 이러한 경우 옵션은 아무런 영향을 주지 않습니다. 기본적으로 이 옵션은 Null로 설정되며, 이는 AI 모델의 기본 동작이 사용됨을 나타냅니다.

    The following table summarizes the effects of various combinations of the AllowParallelCalls and AllowConcurrentInvocation options:
    
    | AllowParallelCalls  | AllowConcurrentInvocation | # of functions chosen per AI roundtrip  | Concurrent Invocation by SK |
    |---------------------|---------------------------|-----------------------------------------|-----------------------|
    | false               | false                     | one                                     | false                 |
    | false               | true                      | one                                     | false*                |
    | true                | false                     | multiple                                | false                 |
    | true                | true                      | multiple                                | true                  |
    
    `*` There's only one function to invoke
    

함수 선택 동작의 특정 측면은 각 함수 선택 동작 클래스가 FunctionChoiceBehaviorOptions 유형의 options 생성자 매개변수를 통해 허용하는 옵션을 통해 설정할 수 있습니다. 다음과 같은 옵션을 사용할 수 있습니다.

  • AllowParallelCalls: 이 옵션을 사용하면 AI 모델이 한 요청에서 여러 함수를 선택할 수 있습니다. 일부 AI 모델은 이 기능을 지원하지 않을 수 있습니다. 이러한 경우 옵션은 아무런 영향을 주지 않습니다. 기본적으로 이 옵션은 Null로 설정되며, 이는 AI 모델의 기본 동작이 사용됨을 나타냅니다.

함수 호출

함수 호출은 의미 체계 커널이 AI 모델에서 선택한 함수를 호출하는 프로세스입니다. 함수 호출에 대한 자세한 내용은 함수 호출 문서를 참조 하세요.

지원되는 AI 커넥터

현재 의미 체계 커널의 다음 AI 커넥터는 함수 호출 모델을 지원합니다.

AI 커넥터 기능 선택 행동 ToolCallBehavior
인위적 예정
AzureAIInference 서비스 예정
AzureOpenAI ✔️ ✔️
쌍둥이자리 예정 ✔️
HuggingFace 예정
미스트랄 예정 ✔️
올라마 섬 서비스 예정
Onnx 서비스 예정
OpenAI ✔️ ✔️

현재 의미 체계 커널의 다음 AI 커넥터는 함수 호출 모델을 지원합니다.

AI 커넥터 함수선택행동 툴콜 동작
인위적 ✔️
AzureAIInference ✔️
암반 ✔️
Google AI ✔️
Vertex AI ✔️
HuggingFace 예정
미스트랄 인공지능 ✔️
올라마 섬 ✔️
Onnx
OpenAI ✔️ ✔️
Azure OpenAI ✔️ ✔️

경고

일부 모델은 비 스트리밍 모드에서 함수 호출만 지원하는 반면 일부 모델은 함수 호출을 지원하지 않습니다. 함수 호출을 사용하기 전에 사용 중인 모델의 제한 사항을 이해하세요.

현재 의미 체계 커널의 다음 AI 커넥터는 함수 호출 모델을 지원합니다.

AI 커넥터 기능 선택 행동 ToolCallBehavior
AzureOpenAI ✔️ ✔️
쌍둥이자리 예정 ✔️
OpenAI ✔️ ✔️