Anteckning
Åtkomst till den här sidan kräver auktorisering. Du kan prova att logga in eller ändra kataloger.
Åtkomst till den här sidan kräver auktorisering. Du kan prova att ändra kataloger.
Funktionsvalsbeteenden är konfigurationsbitar som gör att en utvecklare kan konfigurera:
- Vilka funktioner annonseras för AI-modeller.
- Hur modellerna ska välja dem när de anropas.
- Hur semantisk kernel kan anropa dessa funktioner.
Från och med idag representeras funktionsvalsbeteendena av tre statiska metoder i FunctionChoiceBehavior klassen:
- Auto: Gör att AI-modellen kan välja mellan noll eller fler funktioner från de angivna funktionerna för anrop.
- Obligatoriskt: Tvingar AI-modellen att välja en eller flera funktioner från de angivna funktionerna för anrop.
- Ingen: Instruerar AI-modellen att inte välja några funktioner.
Från och med idag representeras funktionsvalsbeteendena av tre klassmetoder i FunctionChoiceBehavior klassen:
- Auto: Gör att AI-modellen kan välja mellan noll eller fler funktioner från de angivna funktionerna för anrop.
- Obligatoriskt: Tvingar AI-modellen att välja en eller flera funktioner från de angivna funktionerna för anrop.
- NoneInvoke: Instruerar AI-modellen att inte välja några funktioner.
Kommentar
Du kanske är mer bekant med beteendet None från andra litteraturer. Vi använder NoneInvoke för att undvika förvirring med Python-nyckelordet None .
- Auto: Gör att AI-modellen kan välja mellan noll eller fler funktioner från de angivna funktionerna för anrop.
- Obligatoriskt: Tvingar AI-modellen att välja en eller flera funktioner från de angivna funktionerna för anrop.
- Ingen: Instruerar AI-modellen att inte välja några funktioner.
Kommentar
Om koden använder funktioner för funktionsanrop som representeras av klassen ToolCallBehavior läser du migreringsguiden för att uppdatera koden till den senaste funktionsanropsmodellen.
Kommentar
Funktionerna för funktionsanrop stöds bara av några FÅ AI-anslutningsappar hittills. Mer information finns i avsnittet AI-anslutningsappar som stöds nedan.
Funktionsannonsering
Funktionsannonsering är processen att tillhandahålla funktioner till AI-modeller för ytterligare samtal och anrop. Alla tre funktionsvalsbeteenden accepterar en lista över funktioner som ska annonseras som en functions parameter. Som standard är det null, vilket innebär att alla funktioner från plugin-program som är registrerade i kerneln tillhandahålls till AI-modellen.
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));
Om en lista över funktioner tillhandahålls skickas endast dessa funktioner till AI-modellen:
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));
En tom lista över funktioner innebär att inga funktioner tillhandahålls till AI-modellen, vilket motsvarar inaktivering av funktionsanrop.
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));
Funktionsannonsering är processen att tillhandahålla funktioner till AI-modeller för ytterligare samtal och anrop. Som standard tillhandahålls alla funktioner från plugin-program som är registrerade i kerneln till AI-modellen om inte filter anges.
Filter är en ordlista med följande nycklar: excluded_plugins, included_plugins, excluded_functions, included_functions. De gör att du kan ange vilka funktioner som ska annonseras till AI-modellen.
Viktigt!
Det är inte tillåtet att ange både excluded_plugins och included_plugins eller excluded_functions och included_functions samtidigt.
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)
Om ett filter tillhandahålls skickas endast de som skickar filtret till AI-modellen:
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)
Viktigt!
Att ange en tom lista till included_plugins eller included_functions har ingen effekt. Om du vill inaktivera funktionsanrop bör du ange function_choice_behavior till NoneInvoke.
Funktionsannonsering är processen att tillhandahålla funktioner till AI-modeller för ytterligare samtal och anrop. Alla tre funktionsvalsbeteenden accepterar en lista över funktioner som ska annonseras som en functions parameter. Som standard är det null, vilket innebär att alla funktioner från plugin-program som är registrerade i kerneln tillhandahålls till AI-modellen.
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();
Om en lista över funktioner tillhandahålls skickas endast dessa funktioner till AI-modellen:
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();
En tom lista över funktioner innebär att inga funktioner tillhandahålls till AI-modellen, vilket motsvarar inaktivering av funktionsanrop.
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();
Beteende vid val av autofunktion
Funktionsvalsbeteendet Auto instruerar AI-modellen att välja mellan noll eller fler funktioner från de angivna funktionerna för anrop.
I det här exemplet kommer alla funktioner från DateTimeUtils och WeatherForecastUtils plugin-program att tillhandahållas till AI-modellen tillsammans med uppmaningen.
Modellen väljer GetCurrentTime först funktion för anrop för att hämta aktuellt datum och tid, eftersom den här informationen behövs som indata för GetWeatherForCity funktionen.
Därefter väljer den GetWeatherForCity-funktionen för att anropa och hämta väderprognosen för staden Boston med det erhållna datumet och tiden.
Med den här informationen kommer modellen att kunna fastställa den troliga färgen på himlen i Boston.
using Microsoft.SemanticKernel;
IKernelBuilder builder = Kernel.CreateBuilder();
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>();
Kernel kernel = builder.Build();
// All functions from the DateTimeUtils and WeatherForecastUtils plugins will be provided to AI model alongside the prompt.
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() };
await kernel.InvokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?", new(settings));
Samma exempel kan enkelt modelleras i en YAML-mallkonfiguration:
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));
I det här exemplet kommer alla funktioner från WeatherPlugin och DateTimePlugin plugin-program att tillhandahållas till AI-modellen tillsammans med uppmaningen. Modellen kommer först att välja GetCurrentUtcDateTime-funktionen från DateTimePlugin-plugin-programmet för att anropa och hämta det aktuella datumet och tiden, eftersom denna information behövs som indata för GetWeatherForCity-funktionen från WeatherPlugin-plugin-programmet. Därefter väljer den GetWeatherForCity funktionen för anrop för att hämta väderprognosen för staden Seattle med hjälp av det erhållna datumet och tiden. Med den här informationen kan modellen svara på användarfrågan på naturligt språk.
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)
Samma exempel kan enkelt modelleras i en YAML-mallkonfiguration:
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();
Tips/Råd
Fler uppdateringar kommer snart till Java SDK.
Använda obligatoriskt funktionsvalsbeteende
Beteendet Required tvingar modellen att välja en eller flera funktioner från de angivna funktionerna för anrop. Detta är användbart för scenarier när AI-modellen måste hämta nödvändig information från de angivna funktionerna i stället för från den egna kunskapen.
Kommentar
Beteendet annonserar funktioner i den första begäran till AI-modellen och slutar skicka dem i efterföljande begäranden för att förhindra en oändlig loop där modellen fortsätter att välja samma funktioner för anrop upprepade gånger.
Här anger vi att AI-modellen måste välja funktionen GetWeatherForCity för anrop för att få väderprognosen för staden Boston, i stället för att gissa den baserat på sin egen kunskap.
Modellen väljer först funktionen GetWeatherForCity för anrop för att hämta väderprognosen.
Med den här informationen kan modellen sedan fastställa den troliga färgen på himlen i Boston med hjälp av svaret från anropet till 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));
Ett identiskt exempel i en YAML-mallkonfiguration:
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));
Du kan också ange alla funktioner som är registrerade i kerneln till AI-modellen efter behov. Men endast de som väljs av AI-modellen som ett resultat av den första begäran anropas av semantisk kernel. Funktionerna skickas inte till AI-modellen i efterföljande begäranden för att förhindra en oändlig loop, som nämnts ovan.
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));
Här tillhandahåller vi bara en funktion, , get_weather_for_citytill AI-modellen och tvingar den att välja den här funktionen för anrop för att hämta väderprognosen.
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)
Ett identiskt exempel i en YAML-mallkonfiguration:
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();
Tips/Råd
Fler uppdateringar kommer snart till Java SDK.
Använda beteende för val av ingen funktion
Beteendet None instruerar AI-modellen att använda de angivna funktionerna utan att välja någon av dem för anrop och i stället generera ett meddelandesvar. Detta är användbart för torrkörningar när anroparen kanske vill se vilka funktioner modellen skulle välja utan att faktiskt anropa dem. I exemplet under AI-modellen visas till exempel korrekt de funktioner som den skulle välja för att fastställa himlens färg i Boston.
Here, we advertise all functions from the `DateTimeUtils` and `WeatherForecastUtils` plugins to the AI model but instruct it not to choose any of them.
Instead, the model will provide a response describing which functions it would choose to determine the color of the sky in Boston on a specified date.
```csharp
using Microsoft.SemanticKernel;
IKernelBuilder builder = Kernel.CreateBuilder();
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>();
Kernel kernel = builder.Build();
KernelFunction getWeatherForCity = kernel.Plugins.GetFunction("WeatherForecastUtils", "GetWeatherForCity");
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.None() };
await kernel.InvokePromptAsync("Specify which provided functions are needed to determine the color of the sky in Boston on a specified date.", new(settings))
// Sample response: To determine the color of the sky in Boston on a specified date, first call the DateTimeUtils-GetCurrentUtcDateTime function to obtain the
// current date and time in UTC. Next, use the WeatherForecastUtils-GetWeatherForCity function, providing 'Boston' as the city name and the retrieved UTC date and time.
// These functions do not directly provide the sky's color, but the GetWeatherForCity function offers weather data, which can be used to infer the general sky condition (e.g., clear, cloudy, rainy).
Ett motsvarande exempel i konfigurationen av en YAML-promptmall:
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));
Beteendet NoneInvoke instruerar AI-modellen att använda de angivna funktionerna utan att välja någon av dem för anrop och i stället generera ett meddelandesvar. Detta är användbart för torrkörningar när anroparen kanske vill se vilka funktioner modellen skulle välja utan att faktiskt anropa dem. I exemplet under AI-modellen visas till exempel korrekt de funktioner som den skulle välja för att fastställa himlens färg i Boston.
from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.kernel import Kernel
kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())
# Assuming that WeatherPlugin and DateTimePlugin are already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
kernel.add_plugin(DateTimePlugin(), "DateTimePlugin")
query = "Specify which provided functions are needed to determine the color of the sky in Boston on the current date."
arguments = KernelArguments(
settings=PromptExecutionSettings(
# Force the AI model to choose the get_weather_for_city function for invocation.
function_choice_behavior=FunctionChoiceBehavior.NoneInvoke(),
)
)
response = await kernel.invoke_prompt(query, arguments=arguments)
# To determine the color of the sky in Boston on the current date, you would need the following functions:
# 1. **functions.DateTimePlugin-get_current_date**: This function is needed to get the current date.
# 2. **functions.WeatherPlugin-get_weather_for_city**: After obtaining the current date,
# this function will allow you to get the weather for Boston, which will indicate the sky conditions
# such as clear, cloudy, etc., helping you infer the color of the sky.
Ett identiskt exempel i en YAML-mallkonfiguration:
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.
Här marknadsför vi alla funktioner från både DateTimeUtils och WeatherForecastUtils plugin-programmen till AI-modellen, men vi instruerar den att inte välja någon av dem.
I stället ger modellen ett svar som beskriver vilka funktioner den skulle välja för att fastställa himlens färg i Boston vid ett angivet datum.
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).
Tips/Råd
Fler uppdateringar kommer snart till Java SDK.
Valalternativ för funktionsbeteende
Vissa aspekter av funktionsvalsbeteenden kan konfigureras via alternativ som varje funktionsvalsbeteendeklass accepterar via options konstruktorparametern för FunctionChoiceBehaviorOptions typen. Följande alternativ är tillgängliga:
AllowConcurrentInvocation: Det här alternativet möjliggör samtidig anrop av funktioner av semantisk kernel. Som standard är den inställd på false, vilket innebär att funktioner anropas sekventiellt. Samtidig anrop är bara möjligt om AI-modellen kan välja flera funktioner för anrop i en enda begäran. i annat fall finns det ingen skillnad mellan sekventiell och samtidig anrop
AllowParallelCalls: Med det här alternativet kan AI-modellen välja flera funktioner i en begäran. Vissa AI-modeller kanske inte stöder den här funktionen. i sådana fall har alternativet ingen effekt. Som standard är det här alternativet inställt på null, vilket indikerar att AI-modellens standardbeteende kommer att användas.
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
Vissa aspekter av funktionsvalsbeteenden kan konfigureras via alternativ som varje funktionsvalsbeteendeklass accepterar via options konstruktorparametern för FunctionChoiceBehaviorOptions typen. Följande alternativ är tillgängliga:
- AllowParallelCalls: Med det här alternativet kan AI-modellen välja flera funktioner i en begäran. Vissa AI-modeller kanske inte stöder den här funktionen. i sådana fall har alternativet ingen effekt. Som standard är det här alternativet inställt på null, vilket indikerar att AI-modellens standardbeteende kommer att användas.
Funktionsanrop
Funktionsanrop är den process där semantisk kernel anropar funktioner som valts av AI-modellen. För mer information om funktionsanrop, se artikeln om funktionsanrop.
Stödda AI-anslutningar
Från och med idag stöder följande AI-anslutningsappar i Semantic Kernel funktionanropsmodellen:
| AI-anslutningsprogram | FunctionChoiceBehavior | ToolCallBehavior |
|---|---|---|
| Människoorienterad | Planerat | ❌ |
| AzureAIInference | Kommer snart | ❌ |
| AzureOpenAI | ✔️ | ✔️ |
| Tvillingarna | Planerat | ✔️ |
| HuggingFace | Planerat | ❌ |
| Mistralen | Planerat | ✔️ |
| Ollama | Kommer snart | ❌ |
| Onnx | Kommer snart | ❌ |
| OpenAI | ✔️ | ✔️ |
Från och med idag stöder följande AI-anslutningsappar i Semantic Kernel funktionanropsmodellen:
| AI-anslutningsprogram | FunctionChoiceBehavior | ToolCallBehavior |
|---|---|---|
| Människoorienterad | ✔️ | ❌ |
| AzureAIInference | ✔️ | ❌ |
| Berggrund | ✔️ | ❌ |
| Google AI | ✔️ | ❌ |
| Vertex AI | ✔️ | ❌ |
| HuggingFace | Planerat | ❌ |
| Mistral AI | ✔️ | ❌ |
| Ollama | ✔️ | ❌ |
| Onnx | ❌ | ❌ |
| OpenAI | ✔️ | ✔️ |
| Azure OpenAI | ✔️ | ✔️ |
Varning
Alla modeller stöder inte funktionsanrop medan vissa modeller endast stöder funktionsanrop i icke-strömningsläge. Förstå begränsningarna i den modell som du använder innan du försöker använda funktionsanrop.
Från och med idag stöder följande AI-anslutningsappar i Semantic Kernel funktionanropsmodellen:
| AI-anslutningsprogram | FunctionChoiceBehavior | ToolCallBehavior |
|---|---|---|
| AzureOpenAI | ✔️ | ✔️ |
| Tvillingarna | Planerat | ✔️ |
| OpenAI | ✔️ | ✔️ |