함수 선택 동작(Function Choice Behavior)
함수 선택 동작(Function Choice Behavior)
함수 선택 동작은 개발자가 다음을 구성할 수 있게 해 주는 설정 조각이에요.
- 어떤 함수를 AI 모델에 광고(advertise)할지.
- 모델이 호출을 위해 그것들을 어떻게 선택해야 할지.
- Semantic Kernel이 그 함수들을 어떻게 호출할지.
현재 함수 선택 동작은 FunctionChoiceBehavior 클래스의 정적 메서드 세 가지로 표현됩니다.
- Auto — AI 모델이 제공된 함수 중에서 0개 이상을 골라 호출하게 합니다.
- Required — AI 모델이 제공된 함수 중에서 하나 이상을 골라 호출하도록 강제합니다.
- None / NoneInvoke — AI 모델이 어떤 함수도 선택하지 말도록 지시합니다.
참고. Python에서는 NoneInvoke를 써요. 다른 문헌에서 익숙한 None 동작과 헷갈리기 쉬운데, Python의 None 키워드와의 혼동을 피하려고 NoneInvoke로 이름을 지었습니다.
참고. ToolCallBehavior 클래스로 표현되는 함수 호출 능력을 쓰는 코드가 있다면, 마이그레이션 가이드를 참고해 최신 함수 호출 모델로 코드를 업데이트하세요. 또 함수 호출 능력은 지금까지 몇몇 AI 커넥터만 지원합니다. 자세한 내용은 아래 지원되는 AI 커넥터 섹션을 확인하세요.
함수 광고(Function Advertising)
함수 광고는 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));
목록이 제공되면 그 함수들만 모델에 전송됩니다.
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));
Python의 함수 광고. 기본적으로 커널에 등록된 플러그인의 모든 함수가 AI 모델에 제공되지만, 필터(filters)를 지정할 수 있어요. 필터는 excluded_plugins, included_plugins, excluded_functions, included_functions 키를 가진 딕셔너리입니다. 이것들로 어떤 함수를 AI 모델에 광고할지 지정할 수 있어요.
중요. excluded_plugins와 included_plugins를 동시에, 또는 excluded_functions와 included_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_behavior를 NoneInvoke로 설정해야 합니다.
Auto 함수 선택 동작 사용하기
Auto 함수 선택 동작은 AI 모델이 제공된 함수 중에서 0개 이상을 골라 호출하도록 지시합니다.
C# 예시. 아래 예시에서 DateTimeUtils와 WeatherForecastUtils 플러그인의 모든 함수가 프롬프트와 함께 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));
Python 예시. WeatherPlugin과 DateTimePlugin 플러그인의 모든 함수가 프롬프트와 함께 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)
Required 함수 선택 동작 사용하기
Required 동작은 모델이 제공된 함수 중 하나 이상을 골라 호출하도록 강제합니다. AI 모델이 자신의 지식이 아니라 지정된 함수에서 필요한 정보를 얻어야 하는 시나리오에 유용해요.
참고. 이 동작은 첫 번째 요청에서만 함수를 AI 모델에 광고하고, 후속 요청에서는 보내지 않습니다. 모델이 같은 함수를 반복해서 고르는 무한 루프를 막기 위해서예요. 첫 번째 요청 결과로 AI 모델이 고른 함수만 Semantic Kernel이 호출합니다.
C# 예시. 여기서 AI 모델이 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: [getWeatherForCity]) };
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));
Python 예시. 여기서는 get_weather_for_city 함수 하나만 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 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)
None 함수 선택 동작 사용하기
None(Python에서는 NoneInvoke) 동작은 AI 모델이 제공된 함수를 선택하지 않고 메시지 응답을 생성하도록 지시합니다. 이는 드라이 런(dry run)에 유용해요. 호출자가 실제로 호출하지 않고 모델이 어떤 함수를 고를지 보고 싶을 때가 있으니까요. 예를 들어 아래 예시에서 AI 모델은 보스턴 하늘의 색을 결정하기 위해 자신이 고를 함수를 정확히 나열합니다.
C# 예시. 여기서는 DateTimeUtils와 WeatherForecastUtils 플러그인의 모든 함수를 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");
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).
Python 예시.
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.
함수 선택 동작 옵션
함수 선택 동작의 특정 측면은 각 함수 선택 동작 클래스가 FunctionChoiceBehaviorOptions 타입의 options 생성자 파라미터로 받는 옵션을 통해 구성할 수 있어요.
- AllowConcurrentInvocation — Semantic Kernel이 함수를 동시에 호출하게 활성화합니다. 기본값은 false로, 함수가 순차적으로 호출된다는 뜻이에요. 동시 호출은 AI 모델이 단일 요청에서 여러 함수를 골라 호출할 수 있을 때만 가능합니다. 그렇지 않으면 순차 호출과 동시 호출의 구분이 없어요.
- AllowParallelCalls — AI 모델이 한 요청에서 여러 함수를 고를 수 있게 합니다. 일부 AI 모델은 이 기능을 지원하지 않을 수 있는데, 그 경우 옵션이 효과가 없어요. 기본값은 null로, AI 모델의 기본 동작을 쓰겠다는 뜻입니다.
AllowParallelCalls와 AllowConcurrentInvocation 옵션 조합의 효과를 요약하면 다음과 같습니다.
| AllowParallelCalls | AllowConcurrentInvocation | AI 왕복당 선택된 함수 수 | SK의 동시 호출 |
|---|---|---|---|
| false | false | one | false |
| false | true | one | false* |
| true | false | multiple | false |
| true | true | multiple | true |
* 호출할 함수가 하나뿐인 경우
함수 호출
함수 호출은 Semantic Kernel이 AI 모델이 고른 함수를 호출하는 과정이에요. 자세한 내용은 함수 호출 문서를 참고하세요.
지원되는 AI 커넥터
현재 Semantic Kernel에서 함수 호출 모델을 지원하는 커넥터의 상태는 언어마다 차이가 있어요. (대표적으로 C#의 AzureOpenAI·OpenAI가 FunctionChoiceBehavior와 ToolCallBehavior를 모두 지원하고, 그 외 Anthropic·Gemini·Mistral 등은 계획 중이거나 일부 지원합니다. Python은 Anthropic·AzureAIInference·Bedrock·Google AI·Vertex AI·Mistral AI·Ollama·OpenAI·Azure OpenAI에서 FunctionChoiceBehavior를 지원합니다. 구체적인 표는 문서 원문의 "Supported AI Connectors" 표를 참고하세요.)
경고. 모든 모델이 함수 호출을 지원하는 건 아니며, 일부 모델은 비스트리밍 모드에서만 함수 호출을 지원합니다. 함수 호출을 쓰기 전에 사용하는 모델의 한계를 이해하세요.