Sdílet prostřednictvím


Chování při výběru funkcí

Volby funkcí jsou konfigurační prvky, které umožňují vývojářům konfigurovat:

  1. Které funkce se inzerují do modelů AI.
  2. Jak by si modely měly vybrat pro vyvolání.
  3. Jak může sémantické jádro vyvolat tyto funkce.

Od dnešního dne jsou chování výběru funkce reprezentovány třemi statickými metodami FunctionChoiceBehavior třídy:

  • Automaticky: Umožňuje modelu AI vybrat z nuly nebo více funkcí ze zadaných funkcí pro vyvolání.
  • Povinné: Vynutí model AI zvolit jednu nebo více funkcí ze zadaných funkcí pro vyvolání.
  • Žádné: Dává modelu AI pokyn, aby nevybírej žádné funkce.

Od dnešního dne jsou chování výběru funkce reprezentovány třemi metodami FunctionChoiceBehavior třídy:

  • Automaticky: Umožňuje modelu AI vybrat z nuly nebo více funkcí ze zadaných funkcí pro vyvolání.
  • Povinné: Vynutí model AI zvolit jednu nebo více funkcí ze zadaných funkcí pro vyvolání.
  • NoneInvoke: Dává modelu AI pokyn, aby nevybízel žádné funkce.

Poznámka:

None Možná znáte chování z jiných literatur. Používáme NoneInvoke k tomu, abychom se vyhnuli nejasnostem s klíčovým slovem Pythonu None .

  • Automaticky: Umožňuje modelu AI vybrat z nuly nebo více funkcí ze zadaných funkcí pro vyvolání.
  • Povinné: Vynutí model AI zvolit jednu nebo více funkcí ze zadaných funkcí pro vyvolání.
  • Žádné: Dává modelu AI pokyn, aby nevybírej žádné funkce.

Poznámka:

Pokud váš kód používá funkce volání funkcí reprezentované ToolCallBehavior třídy, projděte si průvodce migrací a aktualizujte kód na nejnovější model volání funkcí.

Poznámka:

Funkce volání jsou zatím podporovány pouze několika konektory AI. Další podrobnosti najdete v části Podporované konektory AI níže.

Inzerce funkcí

Propagace funkcí je proces poskytování funkcí modelům AI pro jejich další volání a použití. Všechny tři chování výběru funkce přijímají seznam funkcí, které se mají inzerovat jako functions parametr. Ve výchozím nastavení má hodnotu null, což znamená, že všechny funkce z modulů plug-in zaregistrovaných v jádru jsou k dispozici modelu AI.

using Microsoft.SemanticKernel;

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

Kernel kernel = builder.Build();

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

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

Pokud je k dispozici seznam funkcí, odesílají se do modelu AI pouze tyto funkce:

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

Prázdný seznam funkcí znamená, že modelu AI nejsou k dispozici žádné funkce, což odpovídá zakázání volání funkcí.

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

Propagace funkcí je proces poskytování funkcí modelům AI pro jejich další volání a použití. Ve výchozím nastavení jsou všechny funkce z modulů plug-in zaregistrovaných v jádru k dispozici modelu AI, pokud nejsou zadány filtry . Filtry je slovník s následujícími klíči: excluded_plugins, included_plugins, excluded_functions, included_functions. Umožňují určit, které funkce se mají inzerovat do modelu AI.

Důležité

Není povoleno zadávat obojí excluded_plugins ani included_pluginsexcluded_functionsincluded_functions současně.

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)

Pokud je filtr zadaný, odesílají se do modelu AI pouze ty, které filtr předají:

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)

Důležité

Poskytnutí prázdného seznamu included_plugins nebo included_functions se neprojeví. Pokud chcete zakázat volání funkcí, měli byste nastavit function_choice_behavior hodnotu NoneInvoke.

Propagace funkcí je proces poskytování funkcí modelům AI pro jejich další volání a použití. Všechny tři chování výběru funkce přijímají seznam funkcí, které se mají inzerovat jako functions parametr. Ve výchozím nastavení má hodnotu null, což znamená, že všechny funkce z modulů plug-in zaregistrovaných v jádru jsou k dispozici modelu AI.

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

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

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

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

Pokud je k dispozici seznam funkcí, odesílají se do modelu AI pouze tyto funkce:

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

Prázdný seznam funkcí znamená, že modelu AI nejsou k dispozici žádné funkce, což odpovídá zakázání volání funkcí.

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

Používání funkce automatického výběru

Chování Auto při výběru funkce dává modelu AI pokyn, aby pro vyvolání zvolil z nuly nebo více funkcí.

V tomto příkladu budou všechny funkce z modulů DateTimeUtilsWeatherForecastUtils plug-in k modelu AI k dispozici společně s výzvou. Model nejprve zvolí GetCurrentTime funkci pro vyvolání, aby získal aktuální datum a čas, protože tyto informace jsou potřeba jako vstup pro GetWeatherForCity funkci. Dále zvolí GetWeatherForCity funkci pro vyvolání, aby získal předpověď počasí pro město Boston pomocí získaného data a času. Díky této informaci bude model schopen určit pravděpodobnou barvu oblohy v Bostonu.

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

Stejný příklad lze snadno modelovat v konfiguraci šablony výzvy 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));

V tomto příkladu budou všechny funkce z modulů WeatherPluginDateTimePlugin plug-in k modelu AI k dispozici společně s výzvou. Model nejprve zvolí funkci z GetCurrentUtcDateTime modulu plug-in pro vyvolání, aby získal aktuální datum a čas, protože tyto informace jsou potřeba jako vstup pro DateTimePlugin funkci z modulu plug-inGetWeatherForCity.WeatherPlugin V dalším kroku zvolí GetWeatherForCity funkci pro vyvolání a získá předpověď počasí pro město Seattle pomocí získaného data a času. Díky této informaci bude model schopen odpovědět na uživatelský dotaz v přirozeném jazyce.

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)

Stejný příklad lze snadno modelovat v konfiguraci šablony výzvy 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();

Návod

V sadě Java SDK budou brzy k dispozici další aktualizace.

Použití chování výběru požadované funkce

Chování Required vynutí model zvolit jednu nebo více funkcí ze zadaných funkcí pro vyvolání. To je užitečné pro scénáře, kdy model AI musí získávat požadované informace ze zadaných funkcí, a ne z vlastních znalostí.

Poznámka:

Chování inzeruje funkce pouze v prvním požadavku na model AI a přestane je odesílat v následných požadavcích, aby se zabránilo nekonečné smyčce, ve které model neustále vybírá stejné funkce pro opakované vyvolání.

Zde určíme, že model AI musí zvolit GetWeatherForCity funkci pro vyvolání, aby získal předpověď počasí pro město Boston, a nikoli odhad na základě vlastních znalostí. Model nejprve zvolí GetWeatherForCity funkci pro vyvolání a načte předpověď počasí. Pomocí těchto informací pak model může určit pravděpodobnou barvu oblohy v Bostonu pomocí odpovědi z volání na 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));

Stejný příklad v konfiguraci šablony 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));

Případně je možné všem funkcím registrovaným v jádru podle potřeby poskytnout model AI. V důsledku prvního požadavku však bude vyvoláno sémantické jádro pouze ty, které model AI zvolil. Funkce nebudou odeslány do modelu AI v následných požadavcích, aby se zabránilo nekonečné smyčce, jak je uvedeno výše.

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

Zde poskytujeme pouze jednu funkci, get_weather_for_city, modelu AI a nutíme ho zvolit tuto funkci k vyvolání předpovědi počasí.

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)

Stejný příklad v konfiguraci šablony 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();

Návod

V sadě Java SDK budou brzy k dispozici další aktualizace.

Použití chování volby funkce „Žádná“

Toto None chování dává modelu AI pokyn, aby používal poskytnuté funkce, aniž by se k vyvolání vybral některý z nich, a místo toho vygeneroval odpověď na zprávu. To je užitečné při testovacích spuštěních, když uživatel může chtít zjistit, které funkce by model zvolil, aniž by je skutečně spouštěl. Například v ukázce níže model umělé inteligence správně vypisuje funkce, které by zvolil pro určení barvy oblohy v Bostonu.


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

Odpovídající příklad v konfiguraci šablony výzvy 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));

Toto NoneInvoke chování dává modelu AI pokyn, aby používal poskytnuté funkce, aniž by se k vyvolání vybral některý z nich, a místo toho vygeneroval odpověď na zprávu. To je užitečné při testovacích spuštěních, když uživatel může chtít zjistit, které funkce by model zvolil, aniž by je skutečně spouštěl. Například v ukázce níže model umělé inteligence správně vypisuje funkce, které by zvolil pro určení barvy oblohy v Bostonu.

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.

Stejný příklad v konfiguraci šablony 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.

Zde inzerujeme všechny funkce z plug-inů DateTimeUtils a WeatherForecastUtils modelu AI, ale dáváme pokyn, aby nevybíral žádnou z nich. Místo toho model poskytne odpověď popisující funkce, které by vybral, aby určil barvu oblohy v Bostonu v zadaném datu.

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

Návod

V sadě Java SDK budou brzy k dispozici další aktualizace.

Možnosti volby chování funkce

Určité aspekty chování výběru funkce je možné nakonfigurovat prostřednictvím možností, které každá třída chování funkce přijímá prostřednictvím options parametru konstruktoru FunctionChoiceBehaviorOptions typu. K dispozici jsou následující možnosti:

  • AllowConcurrentInvocation: Tato možnost umožňuje souběžné vyvolání funkcí pomocí sémantického jádra. Ve výchozím nastavení je nastavená na false, což znamená, že se funkce vyvolávají postupně. Souběžné vyvolání je možné pouze v případě, že model AI může zvolit více funkcí pro vyvolání v jednom požadavku; jinak neexistuje žádný rozdíl mezi sekvenčním a souběžnými vyvoláním.

  • AllowParallelCalls: Tato možnost umožňuje modelu AI zvolit více funkcí v jednom požadavku. Některé modely AI nemusí tuto funkci podporovat; v takových případech nebude mít tato možnost žádný vliv. Ve výchozím nastavení je tato možnost nastavená na hodnotu null, což znamená, že se použije výchozí chování modelu AI.

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

Určité aspekty chování výběru funkce je možné nakonfigurovat prostřednictvím možností, které každá třída chování funkce přijímá prostřednictvím options parametru konstruktoru FunctionChoiceBehaviorOptions typu. K dispozici jsou následující možnosti:

  • AllowParallelCalls: Tato možnost umožňuje modelu AI zvolit více funkcí v jednom požadavku. Některé modely AI nemusí tuto funkci podporovat; v takových případech nebude mít tato možnost žádný vliv. Ve výchozím nastavení je tato možnost nastavená na hodnotu null, což znamená, že se použije výchozí chování modelu AI.

Vyvolání funkce

Vyvolání funkce je proces, kdy sémantické jádro vyvolá funkce vybrané modelem AI. Další podrobnosti o vyvolání funkce najdete v článku o vyvolání funkce.

Podporované konektory AI

Od dnešního dne podporují následující konektory AI v sémantickém jádru model volání funkcí:

Konektor AI Chování výběru funkce ToolCallBehavior
Antropický Naplánováno
AzureAIInference Již brzy
AzureOpenAI ✔️ ✔️
Blíženci Naplánováno ✔️
HuggingFace Naplánováno
Mistral Naplánováno ✔️
Ollama Již brzy
Onnx Již brzy
OpenAI ✔️ ✔️

Od dnešního dne podporují následující konektory AI v sémantickém jádru model volání funkcí:

Konektor AI Chování výběru funkce ToolCallBehavior
Antropický ✔️
AzureAIInference ✔️
Dno ✔️
Google AI ✔️
Vertex AI ✔️
HuggingFace Naplánováno
Mistral AI (umělá inteligence) ✔️
Ollama ✔️
Onnx
OpenAI ✔️ ✔️
Azure OpenAI ✔️ ✔️

Upozorňující

Ne všechny modely podporují volání funkcí, zatímco některé modely podporují pouze volání funkcí v režimu bez streamování. Než se pokusíte použít volání funkcí, seznamte se s omezeními modelu, který používáte.

Od dnešního dne podporují následující konektory AI v sémantickém jádru model volání funkcí:

Konektor AI Chování výběru funkce ToolCallBehavior
AzureOpenAI ✔️ ✔️
Blíženci Naplánováno ✔️
OpenAI ✔️ ✔️