Compartilhar via


Comportamentos de escolha de função

Os comportamentos de escolha da função são bits de configuração que permitem que um desenvolvedor configure:

  1. Quais funções são anunciadas para modelos de IA.
  2. Como os modelos devem escolhê-los para invocação.
  3. Como o Kernel Semântico pode invocar essas funções.

A partir de hoje, os comportamentos de escolha da função são representados por três métodos estáticos da FunctionChoiceBehavior classe:

  • Automático: permite que o modelo de IA escolha entre zero ou mais funções nas funções fornecidas para invocação.
  • Obrigatório: força o modelo de IA a escolher uma ou mais funções das funções fornecidas para invocação.
  • Nenhum: instrui o modelo de IA a não escolher nenhuma função.

A partir de hoje, os comportamentos de escolha da função são representados por três métodos de classe da FunctionChoiceBehavior classe:

  • Automático: permite que o modelo de IA escolha entre zero ou mais funções nas funções fornecidas para invocação.
  • Obrigatório: força o modelo de IA a escolher uma ou mais funções das funções fornecidas para invocação.
  • NoneInvoke: instrui o modelo de IA a não escolher nenhuma função.

Observação

Você pode estar mais familiarizado com o None comportamento de outras literaturas. Usamos NoneInvoke para evitar confusão com a palavra-chave python None .

  • Automático: permite que o modelo de IA escolha entre zero ou mais funções nas funções fornecidas para invocação.
  • Obrigatório: força o modelo de IA a escolher uma ou mais funções das funções fornecidas para invocação.
  • Nenhum: instrui o modelo de IA a não escolher nenhuma função.

Observação

Se o código usar 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.

Observação

Os recursos de chamada de função só têm suporte para alguns conectores de IA até agora, consulte a seção Conectores de IA com suporte abaixo para obter mais detalhes.

Publicidade de funções

O anúncio de funções é o processo de fornecer funções a modelos de IA para chamadas ou invocações adicionais. Todos os três comportamentos de escolha de função aceitam uma lista de funções para serem anunciadas como parâmetro functions. Por padrão, ele é nulo, o que significa que todas as funções de plug-ins 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, somente 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 desabilitar a chamada de função.

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));

A publicidade de funções é o processo de fornecer funções a modelos de IA para chamadas e invocações adicionais. Por padrão, todas as funções de plug-ins 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 que você especifique quais funções devem ser anunciadas para o modelo de IA.

Importante

Não é permitido especificar tanto excluded_plugins quanto 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, somente aqueles que passam o 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 nenhum efeito. Se você quiser desabilitar a chamada de função, deverá 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 adicionais. Todos os três comportamentos de escolha de função aceitam uma lista de funções para anunciar como um functions parâmetro. Por padrão, ele é nulo, o que significa que todas as funções de plug-ins 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, somente 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 desabilitar a chamada de função.

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 de função automática

O Auto comportamento de escolha da função instrui o modelo de IA a escolher entre zero ou mais funções das funções fornecidas para invocação.

Neste exemplo, todas as funções dos plug-ins DateTimeUtils e WeatherForecastUtils serão fornecidas ao modelo de IA junto com o prompt. O modelo escolherá primeiro a função GetCurrentTime para invocar e obter a data e a hora atuais, pois essas informações são necessárias como entrada para a função GetWeatherForCity. Em seguida, ele escolherá GetWeatherForCity a função de invocação para obter a previsão do tempo para a cidade de Boston usando a data e a 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 plug-ins WeatherPlugin e DateTimePlugin serão fornecidas ao modelo de IA junto com o prompt. O modelo escolherá primeiro a função GetCurrentUtcDateTime do plugin DateTimePlugin para invocação, a fim de obter a data e hora atuais, já que essas informações são necessárias 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 a hora obtidas. Com essas informações, o modelo poderá 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();

Dica

Mais atualizações em breve para o SDK do Java.

Usando o comportamento de opção de função necessária

O Required comportamento força o modelo a escolher uma ou mais funções das funções fornecidas para invocação. Isso é útil para cenários em que o modelo de IA deve obter informações necessárias das funções especificadas em vez de seu próprio conhecimento.

Observação

O comportamento anuncia as 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 em que 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 para 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 para invocação para recuperar a previsão do tempo. Com essas informações, o modelo pode 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));

Como alternativa, todas as funções registradas no kernel podem ser fornecidas ao modelo de IA conforme necessário. No entanto, somente 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 impedir um loop infinito, conforme 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_citypara o modelo de IA e a forçamos a escolher essa 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();

Dica

Mais atualizações em breve para o SDK do Java.

Usando o comportamento de escolha da função None

O None comportamento instrui o modelo de IA a usar as funções fornecidas 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 do modelo de IA lista corretamente as funções que ele 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 em uma configuração de 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 as funções fornecidas sem escolher nenhuma delas para invocação e, em vez disso, gerar uma resposta de mensagem. Isso é útil para testes simulados quando o usuário pode querer ver quais funções o modelo escolheria sem realmente invocá-las. Por exemplo, no exemplo abaixo do modelo de IA lista corretamente as funções que ele 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 plug-ins DateTimeUtils e WeatherForecastUtils aos modelos de IA, mas instruímos a não escolher nenhuma delas. Em vez disso, o modelo fornecerá uma resposta descrevendo quais funções ele 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).

Dica

Mais atualizações em breve para o SDK do Java.

Opções de Comportamento de Escolha de Função

Determinados aspectos dos comportamentos de escolha da função podem ser configurados por meio de opções que cada classe de comportamento de escolha de função aceita por meio do options parâmetro construtor do FunctionChoiceBehaviorOptions tipo. As seguintes opções estão disponíveis:

  • AllowConcurrentInvocation: essa opção habilita 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. Invocação simultânea só será 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: essa opção permite que o modelo de IA escolha várias funções em uma solicitação. Alguns modelos de IA podem não dar suporte a esse recurso; nesses casos, a opção não terá efeito. Por padrão, essa opção é definida como nula, 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
    

Determinados aspectos dos comportamentos de escolha da função podem ser configurados por meio de opções que cada classe de comportamento de escolha de função aceita por meio do options parâmetro construtor do FunctionChoiceBehaviorOptions tipo. As seguintes opções estão disponíveis:

  • AllowParallelCalls: essa opção permite que o modelo de IA escolha várias funções em uma solicitação. Alguns modelos de IA podem não dar suporte a esse recurso; nesses casos, a opção não terá efeito. Por padrão, essa opção é definida como nula, indicando que o comportamento padrão do modelo de IA será usado.

Invocação de função

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 invocação de função, consulte o artigo de invocação de função.

Conectores de IA com suporte

A partir de hoje, os seguintes conectores de IA no Kernel Semântico dão suporte ao modelo de chamada de função:

Conector de IA FunctionChoiceBehavior ToolCallBehavior
Antrópico Planeado
AzureAIInference Em breve
AzureOpenAI ✔️ ✔️
Gemini Planeado ✔️
HuggingFace Planeado
Mistral Planeado ✔️
Ollama Em breve
ONNX Em breve
OpenAI ✔️ ✔️

A partir de hoje, os seguintes conectores de IA no Kernel Semântico dão suporte ao modelo de chamada de função:

Conector de IA Comportamento de Escolha de Função ToolCallBehavior
Antrópico ✔️
AzureAIInference ✔️
Rocha Matriz ✔️
IA do Google ✔️
Vertex AI ✔️
HuggingFace Planeado
Mistral AI ✔️
Ollama ✔️
ONNX
OpenAI ✔️ ✔️
Azure OpenAI ✔️ ✔️

Aviso

Nem todos os modelos dão suporte à chamada de função, enquanto alguns modelos só dão suporte à chamada de função no modo não streaming. 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 de IA no Kernel Semântico dão suporte ao modelo de chamada de função:

Conector de IA Comportamento de Escolha de Função ToolCallBehavior
AzureOpenAI ✔️ ✔️
Gemini Planeado ✔️
OpenAI ✔️ ✔️