Compartir a través de


Comportamientos de elección de función

Los comportamientos de elección de funciones son bits de configuración que permiten a un desarrollador configurar:

  1. Qué funciones se anuncian en los modelos de IA.
  2. Cómo deben seleccionarlos los modelos para la invocación.
  3. Cómo el kernel semántico podría invocar esas funciones.

A partir de hoy, los comportamientos de elección de función se representan mediante tres métodos estáticos de la FunctionChoiceBehavior clase :

  • Automático: permite que el modelo de IA elija entre cero o más funciones de las funciones proporcionadas para la invocación.
  • Obligatorio: obliga al modelo de IA a elegir una o varias funciones de las funciones proporcionadas para la invocación.
  • Ninguno: indica al modelo de IA que no elija ninguna función.

A partir de hoy, los comportamientos de elección de función se representan mediante tres métodos de clase de la FunctionChoiceBehavior clase :

  • Automático: permite que el modelo de IA elija entre cero o más funciones de las funciones proporcionadas para la invocación.
  • Obligatorio: obliga al modelo de IA a elegir una o varias funciones de las funciones proporcionadas para la invocación.
  • NoneInvoke: indica al modelo de IA que no elija ninguna función.

Nota:

Es posible que esté más familiarizado con el comportamiento de None en otras obras literarias. Se usa NoneInvoke para evitar confusiones con la palabra clave de Python None .

  • Automático: permite que el modelo de IA elija entre cero o más funciones de las funciones proporcionadas para la invocación.
  • Obligatorio: obliga al modelo de IA a elegir una o varias funciones de las funciones proporcionadas para la invocación.
  • Ninguno: indica al modelo de IA que no elija ninguna función.

Nota:

Si el código usa las funcionalidades de llamada a funciones representadas por la clase ToolCallBehavior, consulte la guía de migración para actualizar el código al modelo de llamada a funciones más reciente.

Nota:

Las funcionalidades de llamada a funciones solo son compatibles con algunos conectores de IA hasta ahora, consulte la sección Conectores de IA admitidos a continuación para obtener más detalles.

Publicidad de funciones

La divulgación de funciones es el proceso de proporcionar funciones a los modelos de IA para su utilización e invocación. Los tres comportamientos de elección de función aceptan una lista de funciones para anunciar como parámetro functions . De forma predeterminada, es null, lo que significa que todas las funciones de los complementos registrados en el kernel se proporcionan al 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));

Si se proporciona una lista de funciones, solo se envían esas funciones al 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));

Una lista vacía de funciones significa que no se proporciona ninguna función al modelo de IA, lo que equivale a deshabilitar la llamada a funciones.

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

La divulgación de funciones es el proceso de proporcionar funciones a los modelos de IA para su utilización e invocación. De forma predeterminada, todas las funciones de los complementos registrados en el kernel se proporcionan al modelo de IA a menos que se especifiquen filtros . Los filtros son un diccionario con las claves siguientes: excluded_plugins, included_plugins, excluded_functions, included_functions. Permiten especificar qué funciones se deben anunciar en el modelo de IA.

Importante

No se permite especificar ni excluded_plugins y included_plugins ni excluded_functions y included_functions al mismo tiempo.

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)

Si se proporciona un filtro, solo los que pasan el filtro se envían al 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

Proporcionar una lista vacía a included_plugins o included_functions no surte ningún efecto. Para deshabilitar la llamada a funciones, debe configurar function_choice_behavior a NoneInvoke.

La divulgación de funciones es el proceso de proporcionar funciones a los modelos de IA para su utilización e invocación. Los tres comportamientos de elección de función aceptan una lista de funciones para anunciar como parámetro functions . De forma predeterminada, es null, lo que significa que todas las funciones de los complementos registrados en el kernel se proporcionan al 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();

Si se proporciona una lista de funciones, solo se envían esas funciones al 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();

Una lista vacía de funciones significa que no se proporciona ninguna función al modelo de IA, lo que equivale a deshabilitar la llamada a funciones.

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

Uso del comportamiento de selección automática de funciones

El Auto comportamiento de elección de función indica al modelo de IA que elija entre cero o más funciones de las funciones proporcionadas para la invocación.

En este ejemplo, todas las funciones de los complementos DateTimeUtils y WeatherForecastUtils se proporcionarán al modelo de IA junto con la indicación. El modelo elegirá GetCurrentTime primero la función para la invocación para obtener la fecha y hora actuales, ya que esta información es necesaria como entrada para la GetWeatherForCity función. A continuación, elegirá GetWeatherForCity la función de invocación para obtener la previsión meteorológica de la ciudad de Boston con la fecha y hora obtenida. Con esta información, el modelo podrá determinar el color probable del cielo en 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));

El mismo ejemplo se puede modelar fácilmente en una configuración de plantilla de aviso de 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));

En este ejemplo, todas las funciones de los complementos WeatherPlugin y DateTimePlugin se proporcionarán al modelo de IA junto con la indicación. El modelo elegirá primero la GetCurrentUtcDateTime función del DateTimePlugin complemento para la invocación para obtener la fecha y hora actuales, ya que esta información es necesaria como entrada para la GetWeatherForCity función del WeatherPlugin complemento. A continuación, elegirá la GetWeatherForCity función de invocación para obtener la previsión meteorológica de la ciudad de Seattle con la fecha y hora obtenida. Con esta información, el modelo podrá responder a la consulta del usuario en lenguaje 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)

El mismo ejemplo se puede modelar fácilmente en una configuración de plantilla de aviso de 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();

Sugerencia

Próximamente se agregarán más actualizaciones al SDK de Java.

Uso del comportamiento de elección de función requerido

El Required comportamiento obliga al modelo a elegir una o varias funciones de las funciones proporcionadas para la invocación. Esto es útil para escenarios en los que el modelo de IA debe obtener información necesaria de las funciones especificadas en lugar de a partir de su propio conocimiento.

Nota:

El comportamiento anuncia las funciones de la primera solicitud al modelo de IA solo y deja de enviarlos en solicitudes posteriores para evitar un bucle infinito donde el modelo sigue eligiendo las mismas funciones para la invocación repetidamente.

Aquí, especificamos que el modelo de inteligencia artificial debe elegir la GetWeatherForCity función para invocar para obtener la previsión meteorológica de la ciudad de Boston, en lugar de adivinarla en función de su propio conocimiento. El modelo elegirá primero la GetWeatherForCity función para la invocación para recuperar la previsión meteorológica. Con esta información, el modelo puede determinar el color probable del cielo en Boston mediante la respuesta de la llamada a 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));

Un ejemplo idéntico en una configuración de plantilla 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 las funciones registradas en el kernel se pueden proporcionar al modelo de IA según sea necesario. Sin embargo, solo los elegidos por el modelo de IA como resultado de la primera solicitud se invocarán mediante el kernel semántico. Las funciones no se enviarán al modelo de IA en solicitudes posteriores para evitar un bucle infinito, como se mencionó anteriormente.

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

Aquí, solo se proporciona una función, get_weather_for_city, al modelo de IA y se obliga a elegir esta función para la invocación para obtener la previsión meteorológica.

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)

Un ejemplo idéntico en una configuración de plantilla 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();

Sugerencia

Próximamente se agregarán más actualizaciones al SDK de Java.

Uso del comportamiento de opción de función None

El None comportamiento indica al modelo de IA que use las funciones proporcionadas sin elegir ninguno de ellos para la invocación y, en su lugar, generar una respuesta de mensaje. Esto resulta útil para las ejecuciones secas cuando el autor de la llamada puede querer ver qué funciones elegiría el modelo sin invocarlas realmente. Por ejemplo, en el ejemplo siguiente, el modelo de IA muestra correctamente las funciones que elegiría determinar el color del cielo en 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).

Un ejemplo correspondiente en una configuración de plantilla para un prompt de 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));

El NoneInvoke comportamiento indica al modelo de IA que use las funciones proporcionadas sin elegir ninguno de ellos para la invocación y, en su lugar, generar una respuesta de mensaje. Esto resulta útil para las ejecuciones secas cuando el autor de la llamada puede querer ver qué funciones elegiría el modelo sin invocarlas realmente. Por ejemplo, en el ejemplo siguiente, el modelo de IA muestra correctamente las funciones que elegiría determinar el color del cielo en 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.

Un ejemplo idéntico en una configuración de plantilla 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.

Aquí anunciamos todas las funciones de los complementos DateTimeUtils y WeatherForecastUtils al modelo de IA, pero le indicamos que no elija ninguna de ellas. En su lugar, el modelo proporcionará una respuesta que describe qué funciones elegiría determinar el color del cielo en Boston en una fecha 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).

Sugerencia

Próximamente se agregarán más actualizaciones al SDK de Java.

Opciones de comportamiento de elección de función

Algunos aspectos de los comportamientos de elección de función se pueden configurar a través de opciones que cada clase de comportamiento de elección de función acepta a través del options parámetro constructor del FunctionChoiceBehaviorOptions tipo. Las siguientes opciones están disponibles:

  • AllowConcurrentInvocation: esta opción habilita la invocación simultánea de funciones mediante el kernel semántico. De forma predeterminada, se establece en false, lo que significa que las funciones se invocan secuencialmente. La invocación simultánea solo es posible si el modelo de IA puede elegir varias funciones para la invocación en una sola solicitud; de lo contrario, no hay distinción entre la invocación secuencial y simultánea.

  • AllowParallelCalls: esta opción permite que el modelo de IA elija varias funciones en una solicitud. Es posible que algunos modelos de IA no admitan esta característica; en tales casos, la opción no tendrá ningún efecto. De forma predeterminada, esta opción se establece en NULL, lo que indica que se usará el comportamiento predeterminado del modelo de IA.

    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
    

Algunos aspectos de los comportamientos de elección de función se pueden configurar a través de opciones que cada clase de comportamiento de elección de función acepta a través del options parámetro constructor del FunctionChoiceBehaviorOptions tipo. Las siguientes opciones están disponibles:

  • AllowParallelCalls: esta opción permite que el modelo de IA elija varias funciones en una solicitud. Es posible que algunos modelos de IA no admitan esta característica; en tales casos, la opción no tendrá ningún efecto. De forma predeterminada, esta opción se establece en NULL, lo que indica que se usará el comportamiento predeterminado del modelo de IA.

function_invocation

La invocación de funciones es el proceso por el que kernel semántico invoca las funciones elegidas por el modelo de IA. Para obtener más información sobre la invocación de funciones, consulte el artículo de invocación de funciones.

Conectores de IA compatibles

A partir de hoy, los siguientes conectores de IA en kernel semántico admiten el modelo de llamada de funciones:

Conector de IA Comportamiento de Elección de Función ToolCallBehavior
Antrópico Planeado
AzureAIInference Próximamente
AzureOpenAI ✔️ ✔️
Géminis Planeado ✔️
HuggingFace Planeado
Mistral Planeado ✔️
Ollama Próximamente
Onnx Próximamente
OpenAI ✔️ ✔️

A partir de hoy, los siguientes conectores de IA en kernel semántico admiten el modelo de llamada de funciones:

Conector de IA Comportamiento de Elección de Funciones ToolCallBehavior
Antrópico ✔️
AzureAIInference ✔️
Lecho de roca ✔️
Google AI ✔️
Inteligencia artificial de vértices ✔️
HuggingFace Planeado
Mistral AI ✔️
Ollama ✔️
Onnx
OpenAI ✔️ ✔️
Azure OpenAI ✔️ ✔️

Advertencia

No todos los modelos admiten llamadas a funciones, mientras que algunos modelos solo las admiten en modo no streaming. Comprenda las limitaciones del modelo que está usando antes de intentar usar la llamada a funciones.

A partir de hoy, los siguientes conectores de IA en kernel semántico admiten el modelo de llamada de funciones:

Conector de IA ComportamientoDeSelecciónDeFunción ToolCallBehavior
AzureOpenAI ✔️ ✔️
Géminis Planeado ✔️
OpenAI ✔️ ✔️