Függvényválasztási viselkedések

A függvényválasztási viselkedések olyan konfigurációs bitek, amelyek lehetővé teszik a fejlesztők számára a konfigurálást:

  1. Mely függvényeket hirdetik meg az AI-modellek.
  2. Hogyan választják ki a modellek azokat a meghíváshoz.
  3. Hogyan hívhatja meg a Szemantikus Kernel ezeket a függvényeket.

A függvényválasztási viselkedéseket a mai naptól az osztály három statikus metódusa FunctionChoiceBehavior képviseli:

  • Automatikus: Lehetővé teszi, hogy az AI-modell nulla vagy több függvény(ek) közül válasszon a megadott függvény(ek) közül a meghíváshoz.
  • Kötelező: Kényszeríti az AI-modellt, hogy válasszon ki egy vagy több függvényt a megadott függvény(ek)ből a meghíváshoz.
  • Nincs: Utasítja az AI-modellt, hogy ne válasszon függvény(ek)et.

A függvényválasztási viselkedéseket jelenleg az FunctionChoiceBehavior osztály három metódusa képviseli.

  • Automatikus: Lehetővé teszi, hogy az AI-modell nulla vagy több függvény(ek) közül válasszon a megadott függvény(ek) közül a meghíváshoz.
  • Kötelező: Kényszeríti az AI-modellt, hogy válasszon ki egy vagy több függvényt a megadott függvény(ek)ből a meghíváshoz.
  • NoneInvoke: Utasítja az AI-modellt, hogy ne válasszon függvény(ek)et.

Megjegyzés:

Lehet, hogy jobban ismeri a viselkedést más None irodalomból. A Python-kulcsszóval NoneInvoke való összetévesztés elkerülése érdekében használjukNone.

  • Automatikus: Lehetővé teszi, hogy az AI-modell nulla vagy több függvény(ek) közül válasszon a megadott függvény(ek) közül a meghíváshoz.
  • Kötelező: Kényszeríti az AI-modellt, hogy válasszon ki egy vagy több függvényt a megadott függvény(ek)ből a meghíváshoz.
  • Nincs: Utasítja az AI-modellt, hogy ne válasszon függvény(ek)et.

Megjegyzés:

Ha a kód a ToolCallBehavior osztály által képviselt függvényhívási képességeket használja, tekintse meg a migrálási útmutatót a kód legújabb függvényhívási modellre való frissítéséhez.

Megjegyzés:

A függvényhívási képességeket eddig csak néhány AI-összekötő támogatja, további részletekért lásd az alábbi Támogatott AI-összekötők szakaszt.

Funkció reklámozás

Az AI-modellek funkcióinak publikálása a további hívásokhoz és meghívásokhoz való elérhetővé tétel folyamata. Mindhárom függvényválasztási viselkedés elfogadja a paraméterként functions meghirdetendő függvények listáját. Alapértelmezés szerint null értékű, ami azt jelenti, hogy a Kernelben regisztrált beépülő modulokból származó összes függvényt az AI-modell biztosítja.

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

Ha a függvények listája meg van adva, a rendszer csak ezeket a függvényeket küldi el az AI-modellnek:

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

A függvények üres listája azt jelenti, hogy az AI-modell nem biztosít függvényeket, ami egyenértékű a függvényhívás letiltásával.

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

Az AI-modellek funkcióinak publikálása a további hívásokhoz és meghívásokhoz való elérhetővé tétel folyamata. Alapértelmezés szerint a Kernelben regisztrált beépülő modulok összes függvénye az AI-modellnek lesz megadva, kivéve, ha szűrők vannak megadva. Szűrő egy szótár a következő kulcsokkal: excluded_plugins, included_plugins, excluded_functions, included_functions. Lehetővé teszik annak megadását, hogy mely függvényeket kell meghirdetni az AI-modellben.

Fontos

Nem engedélyezett egyszerre megadni a excluded_plugins és included_plugins vagy a excluded_functions és included_functions értékeket.

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)

Ha egy szűrő van megadva, a rendszer csak azokat küldi el az AI-modellnek, akik átjutnak a szűrőn:

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)

Fontos

Az üres lista megadása included_plugins vagy included_functions számára nem jár hatással. Ha le szeretné tiltani a függvényhívást, állítsa be a következőt function_choice_behaviorNoneInvoke: .

Az AI-modellek funkcióinak publikálása a további hívásokhoz és meghívásokhoz való elérhetővé tétel folyamata. Mindhárom függvényválasztási viselkedés elfogadja a paraméterként functions meghirdetendő függvények listáját. Alapértelmezés szerint null értékű, ami azt jelenti, hogy a Kernelben regisztrált beépülő modulokból származó összes függvényt az AI-modell biztosítja.

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

Ha a függvények listája meg van adva, a rendszer csak ezeket a függvényeket küldi el az AI-modellnek:

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

A függvények üres listája azt jelenti, hogy az AI-modell nem biztosít függvényeket, ami egyenértékű a függvényhívás letiltásával.

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

Automatikus függvényválasztási viselkedés használata

A Auto függvényválasztási viselkedés arra utasítja az AI-modellt, hogy a megadott függvény(ek) közül nulla vagy több függvény közül válasszon a meghíváshoz.

Ebben a példában az összes függvény az DateTimeUtils és WeatherForecastUtils beépülő modulokból a felszólítással együtt az AI-modellhez kerül. A modell először a függvényt választja GetCurrentTime a meghíváshoz az aktuális dátum és idő lekéréséhez, mivel ez az információ szükséges a GetWeatherForCity függvény bemeneteként. A következő lépésben a meghívás függvényt választja GetWeatherForCity , hogy a kapott dátum és idő alapján lekérje Boston város időjárás-előrejelzését. Ezzel az információval a modell képes lesz meghatározni az ég várható színét Bostonban.

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

Ugyanez a példa könnyen modellezhető egy YAML prompt sablonkonfigurációban.

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

Ebben a példában az összes függvény az WeatherPlugin és DateTimePlugin beépülő modulokból a felszólítással együtt az AI-modellhez kerül. A modell először kiválasztja a GetCurrentUtcDateTime függvényt a beépülő modulból az DateTimePlugin aktuális dátum és idő lekéréséhez, mivel ez az információ szükséges a GetWeatherForCity függvény bemeneteként a WeatherPlugin beépülő modulból. Ezután kiválasztja a GetWeatherForCity meghívás függvényt, hogy a kapott dátum és idő alapján lekérje Seattle város időjárás-előrejelzését. Ezekkel az információkkal a modell természetes nyelven válaszolhat a felhasználói lekérdezésre.

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)

Ugyanez a példa könnyen modellezhető egy YAML prompt sablonkonfigurációban.

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

Jótanács

Hamarosan további frissítések érkeznek a Java SDK-ba.

A szükséges függvényválasztás viselkedésének használata

A Required viselkedés arra kényszeríti a modellt, hogy válasszon ki egy vagy több függvényt a megadott függvény(ek)ből a meghíváshoz. Ez olyan helyzetekben hasznos, amikor az AI-modellnek nem a saját tudásából, hanem a megadott függvényekből kell beszereznie a szükséges információkat.

Megjegyzés:

A viselkedés csak az AI-modellnek küldött első kérésben hirdeti meg a függvényeket, és nem küldi el őket a következő kérésekben, hogy megakadályozza a végtelen ciklust, amelyben a modell folyamatosan ugyanazokat a függvényeket választja a meghíváshoz.

Itt azt határozzuk meg, hogy az AI-modellnek ki kell választania a GetWeatherForCity meghívás függvényét Boston város időjárás-előrejelzésének lekéréséhez ahelyett, hogy saját tudása alapján találgatja. A modell először a GetWeatherForCity meghívás függvényét választja ki az időjárás-előrejelzés lekéréséhez. Ezzel az információval a modell ezután meghatározhatja az ég valószínű színét Bostonban a hívás GetWeatherForCityválasza alapján.

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

Egy yaML-sablonkonfiguráció azonos példája:

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

Azt is megteheti, hogy a kernelben regisztrált összes függvényt igény szerint el lehet adni az AI-modellnek. A Szemantikus Kernel azonban csak azokat hívja meg, amelyeket az AI-modell az első kérés eredményeként választott. A függvények nem lesznek elküldve az AI-modellnek a későbbi kérésekben, hogy megakadályozzák a végtelen ciklust, ahogy fentebb említettük.

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

Itt csak egy függvényt adunk meg az AI-modellnek, get_weather_for_cityés kényszerítjük, hogy ezt a függvényt válassza ki a meghíváshoz az időjárás-előrejelzés lekéréséhez.

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)

Egy yaML-sablonkonfiguráció azonos példája:

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

Jótanács

Hamarosan további frissítések érkeznek a Java SDK-ba.

A 'None' függvény választási viselkedésének használata

A None viselkedés arra utasítja az AI-modellt, hogy használja a megadott függvény(ek)et anélkül, hogy bármelyiket kiválasztaná a meghíváshoz, és ehelyett üzenetválaszt hoz létre. Ez hasznos lehet tesztfuttatások során, amikor a hívó szeretné látni, hogy a modell mely függvényeket választaná anélkül, hogy ténylegesen meghívná őket. Az AI-modell alatti mintában például helyesen listázza azokat a függvényeket, amelyek alapján bostoni égbolt színét határozza meg.


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

Egy megfelelő példa a YAML parancssori sablonkonfigurációjában:

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

A NoneInvoke viselkedés arra utasítja az AI-modellt, hogy használja a megadott függvény(ek)et anélkül, hogy bármelyiket kiválasztaná a meghíváshoz, és ehelyett üzenetválaszt hoz létre. Ez hasznos lehet tesztfuttatások során, amikor a hívó szeretné látni, hogy a modell mely függvényeket választaná anélkül, hogy ténylegesen meghívná őket. Az AI-modell alatti mintában például helyesen listázza azokat a függvényeket, amelyek alapján bostoni égbolt színét határozza meg.

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.

Egy yaML-sablonkonfiguráció azonos példája:

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.

Itt minden függvényt meghirdetünk a DateTimeUtilsWeatherForecastUtils beépülő moduloktól az AI-modellig, de arra utasítjuk, hogy ne válasszon egyet sem. Ehelyett a modell választ ad, amely leírja, hogy mely függvényeket választaná az ég színének meghatározásához Bostonban egy megadott napon.

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

Jótanács

Hamarosan további frissítések érkeznek a Java SDK-ba.

Függvényválasztási viselkedés opciói

A függvényválasztási viselkedések bizonyos aspektusai úgy konfigurálhatók, hogy a viselkedésosztályok az egyes beállításokat a options típus FunctionChoiceBehaviorOptions konstruktorparaméterén keresztül fogadják el. A következő lehetőségek érhetők el:

  • AllowConcurrentInvocation: Ez a beállítás lehetővé teszi a függvények egyidejű meghívását a szemantikai kernel által. Alapértelmezés szerint hamis értékre van állítva, ami azt jelenti, hogy a függvények egymás után lesznek meghívva. Egyidejű meghívás csak akkor lehetséges, ha az AI-modell több függvényt is kiválaszthat egyetlen kérelemben való meghíváshoz; ellenkező esetben nincs különbség a szekvenciális és az egyidejű meghívás között

  • AllowParallelCalls: Ezzel a beállítással az AI-modell több függvényt is kiválaszthat egy kérelemben. Előfordulhat, hogy egyes AI-modellek nem támogatják ezt a funkciót; ilyen esetekben a lehetőségnek nincs hatása. Ez a beállítás alapértelmezés szerint null értékűre van állítva, ami azt jelzi, hogy a rendszer az AI-modell alapértelmezett viselkedését használja.

    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
    

A függvényválasztási viselkedések bizonyos aspektusai úgy konfigurálhatók, hogy a viselkedésosztályok az egyes beállításokat a options típus FunctionChoiceBehaviorOptions konstruktorparaméterén keresztül fogadják el. A következő lehetőségek érhetők el:

  • AllowParallelCalls: Ezzel a beállítással az AI-modell több függvényt is kiválaszthat egy kérelemben. Előfordulhat, hogy egyes AI-modellek nem támogatják ezt a funkciót; ilyen esetekben a lehetőségnek nincs hatása. Ez a beállítás alapértelmezés szerint null értékűre van állítva, ami azt jelzi, hogy a rendszer az AI-modell alapértelmezett viselkedését használja.

Függvényhívás

A függvényhívás az a folyamat, amelynek során a Szemantikus Kernel meghívja az AI-modell által kiválasztott függvényeket. A függvényhívásról további információt a függvényhívási cikk tartalmaz.

Támogatott AI-összekötők

A szemantikus kernelben a következő AI-összekötők támogatják a függvényhívási modellt:

AI-összekötő Funkcióválasztási viselkedés ToolCallBehavior
Anthrópiai Tervezett
AzureAIInference Hamarosan
AzureOpenAI ✔️ ✔️
Ikrek Tervezett ✔️
HuggingFace Tervezett
Misztrál Tervezett ✔️
Ollama Hamarosan
Onnx Hamarosan
OpenAI ✔️ ✔️

A szemantikus kernelben a következő AI-összekötők támogatják a függvényhívási modellt:

AI-összekötő Funkcióválasztási viselkedés ToolCallBehavior
Anthrópiai ✔️
AzureAIInference ✔️
Fekükőzet ✔️
Google AI ✔️
Vertex AI ✔️
HuggingFace Tervezett
Miistral AI ✔️
Ollama ✔️
Onnx
OpenAI ✔️ ✔️
Azure OpenAI ✔️ ✔️

Figyelmeztetés

Nem minden modell támogatja a függvényhívást, míg egyes modellek csak nem streamelési módban támogatják a függvényhívást. A függvényhívások használata előtt ismerje meg a használt modell korlátait.

A szemantikus kernelben a következő AI-összekötők támogatják a függvényhívási modellt:

AI-összekötő Funkcióválasztási viselkedés ToolCallBehavior
AzureOpenAI ✔️ ✔️
Ikrek Tervezett ✔️
OpenAI ✔️ ✔️