Nuta
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować się zalogować lub zmienić katalog.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
Zachowanie wyboru funkcji to bity konfiguracji, które umożliwiają deweloperowi skonfigurowanie:
- Które funkcje są udostępniane dla modeli sztucznej inteligencji.
- Jak modele powinny dokonywać ich wyboru do wywołania.
- Sposób wywoływania tych funkcji przez jądro semantyczne.
Obecnie zachowania wyboru funkcji są reprezentowane przez trzy statyczne metody FunctionChoiceBehavior klasy:
- Automatycznie: umożliwia modelowi sztucznej inteligencji wybór spośród zera lub większej liczby funkcji z podanych funkcji na potrzeby wywołania.
- Wymagane: wymusza, aby model AI wybrał jedną lub więcej funkcji z dostępnych i je wywołał.
- Brak: nakazuje modelowi sztucznej inteligencji, aby nie wybierał żadnych funkcji.
Na dzień dzisiejszy, zachowania wyboru funkcji są reprezentowane przez trzy metody klasy FunctionChoiceBehavior.
- Automatycznie: umożliwia modelowi sztucznej inteligencji wybór spośród zera lub większej liczby funkcji z podanych funkcji na potrzeby wywołania.
- Wymagane: wymusza, aby model AI wybrał jedną lub więcej funkcji z dostępnych i je wywołał.
- NoneInvoke: instruuje model sztucznej inteligencji, aby nie wybierał żadnych funkcji.
Uwaga
Możesz być bardziej zaznajomiony z zachowaniem None z innej literatury. Używamy NoneInvoke do unikania pomyłek ze słowem kluczowym Pythona None.
- Automatycznie: umożliwia modelowi sztucznej inteligencji wybór spośród zera lub większej liczby funkcji z podanych funkcji na potrzeby wywołania.
- Wymagane: wymusza, aby model AI wybrał jedną lub więcej funkcji z dostępnych i je wywołał.
- Brak: nakazuje modelowi sztucznej inteligencji, aby nie wybierał żadnych funkcji.
Uwaga
Jeśli kod używa funkcji wywołujących funkcje reprezentowane przez klasę ToolCallBehavior, zapoznaj się z przewodnikiem migracji , aby zaktualizować kod do najnowszego modelu wywoływania funkcji.
Uwaga
Możliwości wywoływania funkcji są obsługiwane tylko przez kilka łączników sztucznej inteligencji do tej pory, zobacz sekcję Obsługiwane łączniki sztucznej inteligencji poniżej, aby uzyskać więcej informacji.
Reklama funkcji
Udostępnianie funkcji to proces przekazywania funkcji modelom sztucznej inteligencji w celu ich dalszego wywoływania. Wszystkie trzy zachowania wyboru funkcji akceptują listę funkcji do reklamowania jako parametru functions. Domyślnie jest to wartość null, co oznacza, że wszystkie funkcje z wtyczek zarejestrowanych w jądrze są dostarczane do 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));
Jeśli zostanie podana lista funkcji, tylko te funkcje są wysyłane do 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();
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));
Pusta lista funkcji oznacza, że do modelu AI nie są udostępniane żadne funkcje, co jest równoważne wyłączeniu wywoływania funkcji.
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));
Udostępnianie funkcji to proces przekazywania funkcji modelom sztucznej inteligencji w celu ich dalszego wywoływania. Domyślnie wszystkie funkcje z wtyczek zarejestrowanych w jądrze są udostępniane modelowi sztucznej inteligencji, chyba że określono filtry .
Filtry to słownik z następującymi kluczami: excluded_plugins, , included_pluginsexcluded_functions, included_functions. Umożliwiają one określenie, które funkcje powinny być reklamowane w modelu AI.
Ważne
Nie można określić jednocześnie parametrów excluded_plugins i i included_pluginsexcluded_functions i included_functions .
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)
Jeśli zostanie podany filtr, tylko te, które przechodzą przez filtr, są wysyłane do modelu AI.
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)
Ważne
Podanie pustej listy do included_plugins lub included_functions nie ma żadnego wpływu. Jeśli chcesz wyłączyć wywoływanie funkcji, powinieneś ustawić function_choice_behavior na NoneInvoke.
Udostępnianie funkcji to proces przekazywania funkcji modelom sztucznej inteligencji w celu ich dalszego wywoływania. Wszystkie trzy zachowania wyboru funkcji akceptują listę funkcji do reklamowania jako parametru functions. Domyślnie jest to wartość null, co oznacza, że wszystkie funkcje z wtyczek zarejestrowanych w jądrze są dostarczane do 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();
Jeśli zostanie podana lista funkcji, tylko te funkcje są wysyłane do 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();
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();
Pusta lista funkcji oznacza, że do modelu AI nie są udostępniane żadne funkcje, co jest równoważne wyłączeniu wywoływania funkcji.
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();
Korzystanie z automatycznego wybierania funkcji
Zachowanie Auto wyboru funkcji nakazuje modelowi sztucznej inteligencji wybranie spośród zera lub większej liczby funkcji z podanych funkcji w celu wywołania.
W tym przykładzie wszystkie funkcje z wtyczki DateTimeUtils i WeatherForecastUtils zostaną udostępnione modelowi sztucznej inteligencji wraz z podpowiedzią.
Model najpierw wybierze GetCurrentTime funkcję wywołania w celu uzyskania bieżącej daty i godziny, ponieważ te informacje są potrzebne jako dane wejściowe dla GetWeatherForCity funkcji.
Następnie wybierze GetWeatherForCity funkcję wywołania, aby uzyskać prognozę pogody dla miasta Boston przy użyciu uzyskanej daty i godziny.
Dzięki tym informacjom model będzie mógł określić prawdopodobny kolor nieba w Bostonie.
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));
Ten sam przykład można łatwo modelować w konfiguracji szablonu monitu 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));
W tym przykładzie wszystkie funkcje z wtyczki WeatherPlugin i DateTimePlugin zostaną udostępnione modelowi sztucznej inteligencji wraz z podpowiedzią. Model najpierw wybierze GetCurrentUtcDateTime funkcję z DateTimePlugin wtyczki do wywołania w celu uzyskania bieżącej daty i godziny, ponieważ te informacje są potrzebne jako dane wejściowe dla GetWeatherForCity funkcji z WeatherPlugin wtyczki. Następnie wybierze GetWeatherForCity funkcję wywołania, aby uzyskać prognozę pogody dla miasta Seattle przy użyciu uzyskanej daty i godziny. Dzięki tym informacjom model będzie mógł odpowiedzieć na zapytanie użytkownika w języku naturalnym.
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)
Ten sam przykład można łatwo modelować w konfiguracji szablonu monitu 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();
Wskazówka
Wkrótce do zestawu JAVA SDK pojawi się więcej aktualizacji.
Używanie wymaganego zachowania wyboru funkcji
Zachowanie Required wymusza wybranie przez model co najmniej jednej funkcji z podanych funkcji w celu wywołania. Jest to przydatne w scenariuszach, w których model sztucznej inteligencji musi uzyskać wymagane informacje z określonych funkcji, a nie z własnej wiedzy.
Uwaga
Zachowanie anonsuje funkcje w pierwszym żądaniu tylko do modelu AI i zatrzymuje wysyłanie ich w kolejnych żądaniach, aby zapobiec nieskończonej pętli, w której model wielokrotnie wybiera te same funkcje do wywołania.
W tym miejscu określamy, że model sztucznej inteligencji musi wybrać GetWeatherForCity funkcję wywołania, aby uzyskać prognozę pogody dla miasta Boston, a nie odgadnąć ją na podstawie własnej wiedzy.
Model najpierw wybierze funkcję GetWeatherForCity, którą wywoła, aby pobrać prognozę pogody.
Dzięki tym informacjom model może następnie określić prawdopodobny kolor nieba w Bostonie, korzystając z odpowiedzi na wywołanie do 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));
Identyczny przykład konfiguracji szablonu 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));
Alternatywnie wszystkie funkcje zarejestrowane w jądrze mogą być udostępniane modelowi sztucznej inteligencji zgodnie z wymaganiami. Jednak tylko te wybrane przez model AI w wyniku pierwszego żądania będą wywoływane przez jądro semantyczne. Funkcje nie będą wysyłane do modelu AI w kolejnych żądaniach, aby zapobiec nieskończonej pętli, jak wspomniano powyżej.
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));
W tym miejscu udostępniamy tylko jedną funkcję , get_weather_for_citydo modelu AI i wymuszamy wybranie tej funkcji w celu wywołania w celu uzyskania prognozy pogody.
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)
Identyczny przykład konfiguracji szablonu 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();
Wskazówka
Wkrótce do zestawu JAVA SDK pojawi się więcej aktualizacji.
Używanie zachowania wyboru funkcji None
Zachowanie None instruuje model sztucznej inteligencji, aby używał udostępnionych funkcji bez wybierania któregokolwiek z nich do wywołania i zamiast tego generuje odpowiedź komunikatu. Jest to przydatne w przypadku przebiegów suchych, gdy obiekt wywołujący może chcieć zobaczyć, które funkcje model wybierze bez wywoływania ich. Na przykład w poniższym przykładzie model sztucznej inteligencji poprawnie wyświetla listę funkcji, które wybierze, aby określić kolor nieba w Bostonie.
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).
Odpowiedni przykład w konfiguracji szablonu monitu 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));
Zachowanie NoneInvoke instruuje model sztucznej inteligencji, aby używał udostępnionych funkcji bez wybierania któregokolwiek z nich do wywołania i zamiast tego generuje odpowiedź komunikatu. Jest to przydatne w przypadku przebiegów suchych, gdy obiekt wywołujący może chcieć zobaczyć, które funkcje model wybierze bez wywoływania ich. Na przykład w poniższym przykładzie model sztucznej inteligencji poprawnie wyświetla listę funkcji, które wybierze, aby określić kolor nieba w Bostonie.
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.
Identyczny przykład konfiguracji szablonu 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.
W tym miejscu reklamujemy wszystkie funkcje z wtyczek DateTimeUtils i WeatherForecastUtils do modelu AI, ale instruujemy go, aby nie wybierał żadnej z nich.
Zamiast tego model udostępni odpowiedź opisującą funkcje, które wybierze, aby określić kolor nieba w Bostonie w określonej dacie.
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).
Wskazówka
Wkrótce do zestawu JAVA SDK pojawi się więcej aktualizacji.
Opcje zachowania wyboru funkcji
Niektóre aspekty zachowań wyboru funkcji można skonfigurować za pomocą opcji, które każda klasa zachowania wyboru funkcji akceptuje za pośrednictwem options parametru konstruktora FunctionChoiceBehaviorOptions typu. Dostępne są następujące opcje:
AllowConcurrentInvocation: ta opcja umożliwia współbieżne wywołanie funkcji przez jądro semantyczne. Domyślnie jest ustawiona wartość false, co oznacza, że funkcje są wywoływane sekwencyjnie. Współbieżne wywołanie jest możliwe tylko wtedy, gdy model sztucznej inteligencji może wybrać wiele funkcji do wywołania w jednym żądaniu; w przeciwnym razie nie ma rozróżnienia między sekwencyjnym i współbieżną wywołaniem
AllowParallelCalls: ta opcja umożliwia modelowi sztucznej inteligencji wybranie wielu funkcji w jednym żądaniu. Niektóre modele sztucznej inteligencji mogą nie obsługiwać tej funkcji; w takich przypadkach opcja nie będzie miała żadnego wpływu. Domyślnie ta opcja jest ustawiona na wartość null, co oznacza, że będzie używane domyślne zachowanie modelu sztucznej inteligencji.
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
Niektóre aspekty zachowań wyboru funkcji można skonfigurować za pomocą opcji, które każda klasa zachowania wyboru funkcji akceptuje za pośrednictwem options parametru konstruktora FunctionChoiceBehaviorOptions typu. Dostępne są następujące opcje:
- AllowParallelCalls: ta opcja umożliwia modelowi sztucznej inteligencji wybranie wielu funkcji w jednym żądaniu. Niektóre modele sztucznej inteligencji mogą nie obsługiwać tej funkcji; w takich przypadkach opcja nie będzie miała żadnego wpływu. Domyślnie ta opcja jest ustawiona na wartość null, co oznacza, że będzie używane domyślne zachowanie modelu sztucznej inteligencji.
Wywołanie funkcji
Wywołanie funkcji to proces, w którym semantyczne jądro wywołuje funkcje wybrane przez model AI. Aby uzyskać więcej informacji na temat wywołania funkcji, zobacz artykuł wywołania funkcji.
Obsługiwane łączniki sztucznej inteligencji
Od dziś następujące łączniki sztucznej inteligencji w jądrze semantycznym obsługują model wywoływania funkcji:
| Łącznik sztucznej inteligencji | ZachowanieWybieraniaFunkcji | ToolCallBehavior |
|---|---|---|
| Antropiczny | Planowane | ❌ |
| AzureAIInference | Wkrótce | ❌ |
| AzureOpenAI | ✔️ | ✔️ |
| Bliźnięta | Planowane | ✔️ |
| HuggingFace | Planowane | ❌ |
| Mistral | Planowane | ✔️ |
| Ollama | Wkrótce | ❌ |
| Onnx | Wkrótce | ❌ |
| OpenAI | ✔️ | ✔️ |
Od dziś następujące łączniki sztucznej inteligencji w jądrze semantycznym obsługują model wywoływania funkcji:
| Łącznik sztucznej inteligencji | FunctionChoiceBehavior | ToolCallBehavior |
|---|---|---|
| Antropiczny | ✔️ | ❌ |
| AzureAIInference | ✔️ | ❌ |
| Bedrock | ✔️ | ❌ |
| Google AI | ✔️ | ❌ |
| Wierzchołek AI | ✔️ | ❌ |
| HuggingFace | Planowane | ❌ |
| Mistral Sztuczna Inteligencja | ✔️ | ❌ |
| Ollama | ✔️ | ❌ |
| Onnx | ❌ | ❌ |
| OpenAI | ✔️ | ✔️ |
| Azure OpenAI | ✔️ | ✔️ |
Ostrzeżenie
Nie wszystkie modele obsługują wywoływanie funkcji, podczas gdy niektóre modele obsługują tylko wywoływanie funkcji w trybie przesyłania strumieniowego. Przed podjęciem próby użycia wywołania funkcji zapoznaj się z ograniczeniami modelu, którego używasz.
Od dziś następujące łączniki sztucznej inteligencji w jądrze semantycznym obsługują model wywoływania funkcji:
| Łącznik sztucznej inteligencji | ZachowanieWyboruFunkcji | ToolCallBehavior |
|---|---|---|
| AzureOpenAI | ✔️ | ✔️ |
| Bliźnięta | Planowane | ✔️ |
| OpenAI | ✔️ | ✔️ |