Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
Os comportamentos de escolha de função são bits de configuração que permitem que um desenvolvedor configure:
- Quais funções são anunciadas para modelos de IA.
- Como os modelos devem escolhê-los para invocação.
- Como o Kernel Semântico pode invocar essas funções.
A partir de hoje, os comportamentos de escolha de função são representados por três métodos estáticos da FunctionChoiceBehavior
classe:
- Auto: Permite que o modelo de IA escolha entre zero ou mais funções(ões) da(s) função(ões) fornecida(s) para invocação.
- Obrigatório: força o modelo de IA a escolher uma ou mais funções da(s) função(ões) fornecida(s) para invocação.
- Nenhuma: instrui o modelo de IA a não escolher nenhuma função(ões).
A partir de hoje, os comportamentos de escolha de função são representados por três métodos de classe da FunctionChoiceBehavior
classe:
- Auto: Permite que o modelo de IA escolha entre zero ou mais funções(ões) da(s) função(ões) fornecida(s) para invocação.
- Obrigatório: força o modelo de IA a escolher uma ou mais funções da(s) função(ões) fornecida(s) para invocação.
- NoneInvoke: instrui o modelo de IA a não escolher nenhuma função.
Nota
Você pode estar mais familiarizado com o None
comportamento em outras obras literárias. Usamos NoneInvoke
para evitar confusão com a palavra-chave Python None
.
- Auto: Permite que o modelo de IA escolha entre zero ou mais funções(ões) da(s) função(ões) fornecida(s) para invocação.
- Obrigatório: força o modelo de IA a escolher uma ou mais funções da(s) função(ões) fornecida(s) para invocação.
- Nenhuma: instrui o modelo de IA a não escolher nenhuma função(ões).
Nota
Se seu código usa os recursos de chamada de função representados pela classe ToolCallBehavior, consulte o guia de migração para atualizar o código para o modelo de chamada de função mais recente.
Nota
Os recursos de chamada de função são suportados apenas por alguns conectores AI até agora, consulte a seção Conectores AI suportados abaixo para obter mais detalhes.
Função Publicidade
O anúncio de funções é o processo de fornecer funções a modelos de IA para chamadas e invocações posteriores. Todos os três comportamentos de seleção de função aceitam uma lista de funções a anunciar como parâmetro functions
. Por padrão, é null, o que significa que todas as funções de plugins registrados no Kernel são fornecidas para o modelo de IA.
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));
Se uma lista de funções for fornecida, apenas essas funções serão enviadas para o modelo de IA:
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));
Uma lista vazia de funções significa que nenhuma função é fornecida ao modelo de IA, o que equivale a desativar a chamada de funções.
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));
O anúncio de funções é o processo de fornecer funções a modelos de IA para chamadas e invocações posteriores. Por padrão, todas as funções de plugins registrados no Kernel são fornecidas para o modelo de IA, a menos que os filtros sejam especificados.
Filtros é um dicionário com as seguintes chaves: excluded_plugins
, included_plugins
, excluded_functions
, included_functions
. Eles permitem especificar quais funções devem ser anunciadas para o modelo de IA.
Importante
Não é permitido especificar tanto excluded_plugins
e included_plugins
ou excluded_functions
e included_functions
ao mesmo tempo.
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)
Se um filtro for fornecido, apenas aqueles que passarem pelo filtro serão enviados para o modelo de IA:
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)
Importante
Fornecer uma lista vazia para included_plugins
ou included_functions
não tem qualquer efeito. Se você quiser desativar a chamada de função, você deve definir function_choice_behavior
como NoneInvoke
.
O anúncio de funções é o processo de fornecer funções a modelos de IA para chamadas e invocações posteriores. Todos os três comportamentos de seleção de função aceitam uma lista de funções a anunciar como parâmetro functions
. Por padrão, é null, o que significa que todas as funções de plugins registrados no Kernel são fornecidas para o modelo de IA.
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();
Se uma lista de funções for fornecida, apenas essas funções serão enviadas para o modelo de IA:
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();
Uma lista vazia de funções significa que nenhuma função é fornecida ao modelo de IA, o que equivale a desativar a chamada de funções.
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();
Usando o comportamento de escolha automática de função
O Auto
comportamento de escolha de função instrui o modelo de IA a escolher entre zero ou mais funções(ões) da(s) função(ões) fornecida(s) para invocação.
Neste exemplo, todas as funções dos plugins DateTimeUtils
e WeatherForecastUtils
serão fornecidas ao modelo de IA juntamente com o prompt.
O modelo primeiro escolherá GetCurrentTime
a função para invocação para obter a data e hora atuais, pois essas informações são necessárias como entrada para a GetWeatherForCity
função.
Em seguida, ele escolherá GetWeatherForCity
a função para invocação para obter a previsão do tempo para a cidade de Boston usando a data e hora obtidas.
Com essas informações, o modelo será capaz de determinar a cor provável do céu em Boston.
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));
O mesmo exemplo pode ser facilmente modelado em uma configuração de modelo de prompt 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));
Neste exemplo, todas as funções dos plugins WeatherPlugin
e DateTimePlugin
serão fornecidas ao modelo de IA juntamente com o prompt. O modelo irá primeiro escolher a função GetCurrentUtcDateTime
do plugin DateTimePlugin
para invocação, a fim de obter a data e hora atuais, pois esta informação é necessária como entrada para a função GetWeatherForCity
do plugin WeatherPlugin
. Em seguida, ele escolherá a GetWeatherForCity
função de invocação para obter a previsão do tempo para a cidade de Seattle usando a data e hora obtidas. Com essas informações, o modelo será capaz de responder à consulta do usuário em linguagem natural.
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)
O mesmo exemplo pode ser facilmente modelado em uma configuração de modelo de prompt 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();
Sugestão
Mais atualizações em breve para o Java SDK.
Utilização do comportamento obrigatório de escolha de função
O Required
comportamento força o modelo a escolher uma ou mais funções da(s) função(ões) fornecida(s) para invocação. Isso é útil para cenários em que o modelo de IA deve obter as informações necessárias das funções especificadas em vez de seu próprio conhecimento.
Nota
O comportamento anuncia funções na primeira solicitação apenas para o modelo de IA e para de enviá-las em solicitações subsequentes para evitar um loop infinito onde o modelo continua escolhendo as mesmas funções para invocação repetidamente.
Aqui, especificamos que o modelo de IA deve escolher a GetWeatherForCity
função de invocação para obter a previsão do tempo para a cidade de Boston, em vez de adivinhá-la com base em seu próprio conhecimento.
O modelo escolherá primeiro a GetWeatherForCity
função de invocação para recuperar a previsão do tempo.
Com essas informações, o modelo pode então determinar a cor provável do céu em Boston usando a resposta da chamada para 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));
Um exemplo idêntico em uma configuração de modelo 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));
Alternativamente, todas as funções registradas no kernel podem ser fornecidas ao modelo de IA, conforme necessário. No entanto, apenas os escolhidos pelo modelo de IA como resultado da primeira solicitação serão invocados pelo Kernel Semântico. As funções não serão enviadas para o modelo de IA em solicitações subsequentes para evitar um loop infinito, como mencionado acima.
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));
Aqui, fornecemos apenas uma função, get_weather_for_city
, para o modelo de IA e forçamo-lo a escolher esta função para invocação para obter a previsão do tempo.
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)
Um exemplo idêntico em uma configuração de modelo 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();
Sugestão
Mais atualizações em breve para o Java SDK.
Usar Comportamento de Escolha da Função Nenhuma
O None
comportamento instrui o modelo de IA a usar a(s) função(ões) fornecida(s) sem escolher nenhuma delas para invocação e, em vez disso, gerar uma resposta de mensagem. Isso é útil para execuções secas quando o chamador pode querer ver quais funções o modelo escolheria sem realmente invocá-las. Por exemplo, no exemplo abaixo, o modelo de IA lista corretamente as funções que escolheria para determinar a cor do céu em Boston.
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).
Um exemplo correspondente na configuração de um modelo de prompt em 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));
O NoneInvoke
comportamento instrui o modelo de IA a usar a(s) função(ões) fornecida(s) sem escolher nenhuma delas para invocação e, em vez disso, gerar uma resposta de mensagem. Isso é útil para execuções secas quando o chamador pode querer ver quais funções o modelo escolheria sem realmente invocá-las. Por exemplo, no exemplo abaixo, o modelo de IA lista corretamente as funções que escolheria para determinar a cor do céu em Boston.
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.
Um exemplo idêntico em uma configuração de modelo 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.
Aqui, anunciamos todas as funções dos plugins DateTimeUtils
e WeatherForecastUtils
para o modelo de IA, mas instruímos o modelo a não escolher nenhuma delas.
Em vez disso, o modelo fornecerá uma resposta descrevendo quais funções escolheria para determinar a cor do céu em Boston em uma data especificada.
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).
Sugestão
Mais atualizações em breve para o Java SDK.
Opções de comportamento de escolha de função
Certos aspetos dos comportamentos de escolha de função podem ser configurados através de opções que cada classe de comportamento de escolha de função aceita através do options
parâmetro construtor do FunctionChoiceBehaviorOptions
tipo. As seguintes opções estão disponíveis:
AllowConcurrentInvocation: Esta opção permite a invocação simultânea de funções pelo Kernel Semântico. Por padrão, ele é definido como false, o que significa que as funções são invocadas sequencialmente. A invocação simultânea só é possível se o modelo de IA puder escolher várias funções para invocação em uma única solicitação; caso contrário, não há distinção entre invocação sequencial e simultânea
AllowParallelCalls: Esta opção permite que o modelo de IA escolha várias funções em uma solicitação. Alguns modelos de IA podem não suportar esse recurso; Nesses casos, a opção não terá efeito. Por padrão, essa opção é definida como null, indicando que o comportamento padrão do modelo de IA será usado.
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
Certos aspetos dos comportamentos de escolha de função podem ser configurados através de opções que cada classe de comportamento de escolha de função aceita através do options
parâmetro construtor do FunctionChoiceBehaviorOptions
tipo. As seguintes opções estão disponíveis:
- AllowParallelCalls: Esta opção permite que o modelo de IA escolha várias funções em uma solicitação. Alguns modelos de IA podem não suportar esse recurso; Nesses casos, a opção não terá efeito. Por padrão, essa opção é definida como null, indicando que o comportamento padrão do modelo de IA será usado.
Invocação de função
A invocação de função é o processo pelo qual o Kernel Semântico invoca funções escolhidas pelo modelo de IA. Para obter mais detalhes sobre a invocação de função, consulte o artigo de invocação de função.
Conectores AI suportados
A partir de hoje, os seguintes conectores AI no Kernel Semântico suportam o modelo de chamada de função:
Conector AI | FunctionChoiceBehavior | ToolCallBehavior |
---|---|---|
Antrópico | Planeado | ❌ |
AzureAIInference | Brevemente | ❌ |
AzureOpenAI | ✔️ | ✔️ |
Gêmeos | Planeado | ✔️ |
HuggingFace | Planeado | ❌ |
Mistral | Planeado | ✔️ |
Ollama | Brevemente | ❌ |
Onnx | Brevemente | ❌ |
OpenAI | ✔️ | ✔️ |
A partir de hoje, os seguintes conectores AI no Kernel Semântico suportam o modelo de chamada de função:
Conector AI | ComportamentoDeEscolhaDeFunção | ToolCallBehavior |
---|---|---|
Antrópico | ✔️ | ❌ |
AzureAIInference | ✔️ | ❌ |
Substrato rochoso | ✔️ | ❌ |
IA do Google | ✔️ | ❌ |
IA Vertex | ✔️ | ❌ |
HuggingFace | Planeado | ❌ |
Mistral IA | ✔️ | ❌ |
Ollama | ✔️ | ❌ |
Onnx | ❌ | ❌ |
OpenAI | ✔️ | ✔️ |
Azure OpenAI | ✔️ | ✔️ |
Aviso
Nem todos os modelos suportam chamada de função, enquanto alguns modelos suportam apenas chamada de função no modo sem streaming. Por favor, entenda as limitações do modelo que você está usando antes de tentar usar a chamada de função.
A partir de hoje, os seguintes conectores AI no Kernel Semântico suportam o modelo de chamada de função:
Conector AI | FunctionChoiceBehavior | ToolCallBehavior |
---|---|---|
AzureOpenAI | ✔️ | ✔️ |
Gêmeos | Planeado | ✔️ |
OpenAI | ✔️ | ✔️ |