Remarque
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de vous connecter ou de modifier des répertoires.
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de modifier des répertoires.
Les comportements de choix de fonction sont des bits de configuration qui permettent à un développeur de configurer :
- Quelles fonctions sont présentées aux modèles IA.
- Comment les modèles doivent les choisir pour l'invocation.
- Comment le noyau sémantique peut appeler ces fonctions.
À compter d’aujourd’hui, les comportements de choix de fonction sont représentés par trois méthodes statiques de la FunctionChoiceBehavior classe :
- Auto : permet au modèle IA de choisir entre zéro ou plusieurs fonctions dans la ou les fonctions fournies pour l’appel.
- Obligatoire : force le modèle IA à choisir une ou plusieurs fonctions dans la ou les fonctions fournies pour l’appel.
- Aucun : indique au modèle IA de ne pas choisir de fonction(s).
À compter d’aujourd’hui, les comportements de choix de fonction sont représentés par trois méthodes de classe de la FunctionChoiceBehavior classe :
- Auto : permet au modèle IA de choisir entre zéro ou plusieurs fonctions dans la ou les fonctions fournies pour l’appel.
- Obligatoire : force le modèle IA à choisir une ou plusieurs fonctions dans la ou les fonctions fournies pour l’appel.
- NoneInvoke : indique au modèle IA de ne pas choisir de fonction(s).
Remarque
Vous êtes peut-être plus familiarisé avec le comportement None dans d'autres ouvrages. Nous utilisons NoneInvoke pour éviter toute confusion avec le mot clé Python None .
- Auto : permet au modèle IA de choisir entre zéro ou plusieurs fonctions dans la ou les fonctions fournies pour l’appel.
- Obligatoire : force le modèle IA à choisir une ou plusieurs fonctions dans la ou les fonctions fournies pour l’appel.
- Aucun : indique au modèle IA de ne pas choisir de fonction(s).
Remarque
Si votre code utilise les fonctionnalités d’appel de fonction représentées par la classe ToolCallBehavior, reportez-vous au guide de migration pour mettre à jour le code vers le dernier modèle d’appel de fonction.
Remarque
Les fonctionnalités d’appel de fonction ne sont prises en charge que par quelques connecteurs IA jusqu’à présent, consultez la section Connecteurs IA pris en charge ci-dessous pour plus d’informations.
Promotion des fonctionnalités
L'exposition de fonctions est le processus de fourniture de fonctions aux modèles IA pour les appeler et les invoquer. Les trois comportements de choix de fonction acceptent une liste de fonctions à publier en tant que functions paramètre. Par défaut, il s’agit de null, ce qui signifie que toutes les fonctions des plug-ins inscrits sur le noyau sont fournies au modèle IA.
using Microsoft.SemanticKernel;
IKernelBuilder builder = Kernel.CreateBuilder();
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>();
Kernel kernel = builder.Build();
// All functions from the DateTimeUtils and WeatherForecastUtils plugins will be sent to AI model together with the prompt.
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() };
await kernel.InvokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?", new(settings));
Si une liste de fonctions est fournie, seules ces fonctions sont envoyées au modèle IA :
using Microsoft.SemanticKernel;
IKernelBuilder builder = Kernel.CreateBuilder();
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>();
Kernel kernel = builder.Build();
KernelFunction getWeatherForCity = kernel.Plugins.GetFunction("WeatherForecastUtils", "GetWeatherForCity");
KernelFunction getCurrentTime = kernel.Plugins.GetFunction("DateTimeUtils", "GetCurrentUtcDateTime");
// Only the specified getWeatherForCity and getCurrentTime functions will be sent to AI model alongside the prompt.
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(functions: [getWeatherForCity, getCurrentTime]) };
await kernel.InvokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?", new(settings));
Une liste vide de fonctions signifie qu’aucune fonction n’est fournie au modèle IA, ce qui équivaut à désactiver l’appel de fonction.
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));
L'exposition de fonctions est le processus de fourniture de fonctions aux modèles IA pour les appeler et les invoquer. Par défaut, toutes les fonctions des plug-ins inscrits sur le noyau sont fournies au modèle IA, sauf si des filtres sont spécifiés .
Les filtres sont un dictionnaire avec les clés suivantes : excluded_plugins, , included_pluginsexcluded_functions, included_functions. Ils vous permettent de spécifier quelles fonctions doivent être rendues accessibles au modèle IA.
Important
Il n'est pas permis de spécifier à la fois excluded_plugins et included_plugins ou excluded_functions et included_functions en même temps.
from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.kernel import Kernel
kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())
# Assuming that WeatherPlugin, DateTimePlugin, and LocationPlugin are already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
kernel.add_plugin(DateTimePlugin(), "DateTimePlugin")
kernel.add_plugin(LocationPlugin(), "LocationPlugin")
query = "What is the weather in my current location today?"
arguments = KernelArguments(
settings=PromptExecutionSettings(
# Advertise all functions from the WeatherPlugin, DateTimePlugin, and LocationPlugin plugins to the AI model.
function_choice_behavior=FunctionChoiceBehavior.Auto(),
)
)
response = await kernel.invoke_prompt(query, arguments=arguments)
Si un filtre est fourni, seuls ceux qui passent le filtre sont envoyés au modèle IA :
from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.kernel import Kernel
kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())
# Assuming that WeatherPlugin, DateTimePlugin, and LocationPlugin are already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
kernel.add_plugin(DateTimePlugin(), "DateTimePlugin")
kernel.add_plugin(LocationPlugin(), "LocationPlugin")
query = "What is the weather in Seattle today?"
arguments = KernelArguments(
settings=PromptExecutionSettings(
# Advertise all functions from the WeatherPlugin and DateTimePlugin plugins to the AI model.
function_choice_behavior=FunctionChoiceBehavior.Auto(filters={"included_plugins": ["WeatherPlugin", "DateTimePlugin"]}),
)
)
response = await kernel.invoke_prompt(query, arguments=arguments)
Important
Fournir une liste vide à included_plugins ou à included_functions n'a aucun effet. Si vous souhaitez désactiver l’appel de fonction, vous devez définir function_choice_behavior à NoneInvoke.
L'exposition de fonctions est le processus de fourniture de fonctions aux modèles IA pour les appeler et les invoquer. Les trois comportements de choix de fonction acceptent une liste de fonctions à publier en tant que functions paramètre. Par défaut, il s’agit de null, ce qui signifie que toutes les fonctions des plug-ins inscrits sur le noyau sont fournies au modèle IA.
var chatCompletion = OpenAIChatCompletion.builder()
.withModelId("<model-id>")
.withOpenAIAsyncClient(new OpenAIClientBuilder()
.credential(new AzureKeyCredential("<api-key>"))
.endpoint("<endpoint>")
.buildAsyncClient())
.build();
Kernel kernel = Kernel.builder()
.withAIService(ChatCompletionService.class, chatCompletion)
.withPlugin(KernelPluginFactory.createFromObject(new WeatherForecastUtils(), "WeatherForecastUtils"))
.withPlugin(KernelPluginFactory.createFromObject(new DateTimeUtils(), "DateTimeUtils"))
.build();
InvocationContext invocationContext = InvocationContext.builder()
// All functions from the DateTimeUtils and WeatherForecastUtils plugins will be sent to AI model together with the prompt.
.withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true))
.build();
var response = kernel.invokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?",
KernelArguments.builder().build(),
invocationContext
).block();
Si une liste de fonctions est fournie, seules ces fonctions sont envoyées au modèle IA :
var chatCompletion = OpenAIChatCompletion.builder()
.withModelId("<model-id>")
.withOpenAIAsyncClient(new OpenAIClientBuilder()
.credential(new AzureKeyCredential("<api-key>"))
.endpoint("<endpoint>")
.buildAsyncClient())
.build();
Kernel kernel = Kernel.builder()
.withAIService(ChatCompletionService.class, chatCompletion)
.withPlugin(KernelPluginFactory.createFromObject(new WeatherForecastUtils(), "WeatherForecastUtils"))
.withPlugin(KernelPluginFactory.createFromObject(new DateTimeUtils(), "DateTimeUtils"))
.build();
var getWeatherForCity = kernel.getFunction("WeatherPlugin", "getWeatherForCity");
var getCurrentTime = kernel.getFunction("WeatherPlugin", "getWeatherForCity");
InvocationContext invocationContext = InvocationContext.builder()
// Only the specified getWeatherForCity and getCurrentTime functions will be sent to AI model alongside the prompt.
.withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true, List.of(getWeatherForCity, getCurrentTime)))
.build();
var response = kernel.invokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?",
KernelArguments.builder().build(),
invocationContext
).block();
Une liste vide de fonctions signifie qu’aucune fonction n’est fournie au modèle IA, ce qui équivaut à désactiver l’appel de fonction.
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();
Utilisation du comportement de sélection automatique des fonctions
Le Auto comportement de choix de fonction indique au modèle IA de choisir entre zéro ou plusieurs fonctions dans la ou les fonctions fournies pour l’appel.
Dans cet exemple, toutes les fonctions des plugins DateTimeUtils et WeatherForecastUtils seront fournies au modèle IA en même temps que l'invite.
Le modèle choisira d'abord la fonction GetCurrentTime pour son invocation afin d'obtenir la date et l'heure actuelles, car ces informations sont nécessaires comme entrée pour la fonction GetWeatherForCity.
Ensuite, il choisira GetWeatherForCity la fonction d’appel pour obtenir les prévisions météorologiques de la ville de Boston à l’aide de la date et de l’heure obtenues.
Avec ces informations, le modèle sera en mesure de déterminer la couleur probable du ciel à 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));
Le même exemple peut être facilement modélisé dans une configuration de modèle d’invite 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));
Dans cet exemple, toutes les fonctions des plugins WeatherPlugin et DateTimePlugin seront fournies au modèle IA en même temps que l'invite. Le modèle choisit d’abord la GetCurrentUtcDateTime fonction à partir du DateTimePlugin plug-in pour l’appel pour obtenir la date et l’heure actuelles, car ces informations sont nécessaires en tant qu’entrée pour la GetWeatherForCity fonction à partir du WeatherPlugin plug-in. Ensuite, il choisira la GetWeatherForCity fonction d’appel pour obtenir les prévisions météorologiques de la ville de Seattle à l’aide de la date et de l’heure obtenues. Avec ces informations, le modèle pourra répondre à la requête de l’utilisateur en langage naturel.
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)
Le même exemple peut être facilement modélisé dans une configuration de modèle d’invite 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();
Conseil / Astuce
D’autres mises à jour seront bientôt disponibles dans le Kit de développement logiciel (SDK) Java.
Utilisation du comportement requis pour le choix de fonctions
Le Required comportement force le modèle à choisir une ou plusieurs fonctions dans la ou les fonctions fournies pour l’appel. Cela est utile pour les scénarios lorsque le modèle IA doit obtenir des informations requises à partir des fonctions spécifiées plutôt qu’à partir de ses propres connaissances.
Remarque
Le comportement publie des fonctions dans la première requête au modèle IA uniquement et cesse de les envoyer dans les requêtes suivantes pour empêcher une boucle infinie où le modèle continue de choisir les mêmes fonctions pour l’appel à plusieurs reprises.
Ici, nous spécifions que le modèle IA doit choisir la GetWeatherForCity fonction d’appel pour obtenir les prévisions météorologiques de la ville de Boston, plutôt que de deviner celle-ci en fonction de ses propres connaissances.
Le modèle choisit d’abord la GetWeatherForCity fonction d’appel pour récupérer les prévisions météorologiques.
Avec ces informations, le modèle peut ensuite déterminer la couleur probable du ciel à Boston à l’aide de la réponse de l’appel à 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));
Exemple identique dans une configuration de modèle 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));
Vous pouvez également fournir toutes les fonctions inscrites dans le noyau au modèle IA en fonction des besoins. Toutefois, seules les seules personnes choisies par le modèle IA à la suite de la première requête seront appelées par le noyau sémantique. Les fonctions ne seront pas envoyées au modèle IA dans les requêtes suivantes pour empêcher une boucle infinie, comme mentionné ci-dessus.
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));
Ici, nous fournissons une seule fonction, get_weather_for_cityau modèle IA et forcez-le à choisir cette fonction pour l’appel pour obtenir les prévisions météorologiques.
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)
Exemple identique dans une configuration de modèle 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();
Conseil / Astuce
D’autres mises à jour seront bientôt disponibles dans le Kit de développement logiciel (SDK) Java.
Utilisation du comportement de choix de la fonction None
Le comportement None indique au modèle IA d’utiliser les fonctions proposées sans en choisir aucune pour l'invocation et de générer plutôt une réponse sous forme de message. Cela est utile pour les simulations lorsque l'utilisateur peut vouloir voir quelles fonctions le modèle choisirait sans les invoquer réellement. Par exemple, dans l’exemple ci-dessous, le modèle IA répertorie correctement les fonctions qu’il choisirait de déterminer la couleur du ciel à 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).
Exemple correspondant dans une configuration de modèle de prompt 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));
Le comportement NoneInvoke indique au modèle IA d’utiliser les fonctions proposées sans en choisir aucune pour l'invocation et de générer plutôt une réponse sous forme de message. Cela est utile pour les simulations lorsque l'utilisateur peut vouloir voir quelles fonctions le modèle choisirait sans les invoquer réellement. Par exemple, dans l’exemple ci-dessous, le modèle IA répertorie correctement les fonctions qu’il choisirait de déterminer la couleur du ciel à 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.
Exemple identique dans une configuration de modèle 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.
Ici, nous publions toutes les fonctions des plug-ins DateTimeUtils et WeatherForecastUtils au modèle d'IA, mais lui demandons de ne pas les choisir.
Au lieu de cela, le modèle fournit une réponse décrivant les fonctions qu’il choisirait de déterminer la couleur du ciel à Boston à une date spécifiée.
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).
Conseil / Astuce
D’autres mises à jour seront bientôt disponibles dans le Kit de développement logiciel (SDK) Java.
Options de comportement du choix de fonction
Certains aspects des comportements de choix de fonction peuvent être configurés via des options que chaque classe de comportement de choix de fonction accepte via le options paramètre de constructeur du FunctionChoiceBehaviorOptions type. Les options suivantes sont disponibles :
AllowConcurrentInvocation : cette option active l’appel simultané des fonctions par le noyau sémantique. Par défaut, elle est définie sur false, ce qui signifie que les fonctions sont appelées séquentiellement. L’appel simultané n’est possible que si le modèle IA peut choisir plusieurs fonctions pour l’appel dans une seule requête ; sinon, il n’existe aucune distinction entre l’appel séquentiel et simultané
AllowParallelCalls : cette option permet au modèle IA de choisir plusieurs fonctions dans une requête. Certains modèles IA peuvent ne pas prendre en charge cette fonctionnalité ; dans ce cas, l’option n’aura aucun effet. Par défaut, cette option est définie sur Null, ce qui indique que le comportement par défaut du modèle IA sera utilisé.
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
Certains aspects des comportements de choix de fonction peuvent être configurés via des options que chaque classe de comportement de choix de fonction accepte via le options paramètre de constructeur du FunctionChoiceBehaviorOptions type. Les options suivantes sont disponibles :
- AllowParallelCalls : cette option permet au modèle IA de choisir plusieurs fonctions dans une requête. Certains modèles IA peuvent ne pas prendre en charge cette fonctionnalité ; dans ce cas, l’option n’aura aucun effet. Par défaut, cette option est définie sur Null, ce qui indique que le comportement par défaut du modèle IA sera utilisé.
Appel de fonction
L’appel de fonction est le processus dans lequel le noyau sémantique appelle les fonctions choisies par le modèle IA. Pour plus d’informations sur l’appel de fonction, consultez l’article sur l’appel de fonction.
Connecteurs IA pris en charge
À compter d’aujourd’hui, les connecteurs IA suivants dans le noyau sémantique prennent en charge le modèle d’appel de fonction :
| Connecteur AI | ComportementDeChoixDeFonction | ToolCallBehavior |
|---|---|---|
| Anthropique | Planifié | ❌ |
| AzureAIInference | Bientôt disponible | ❌ |
| AzureOpenAI | ✔️ | ✔️ |
| Gémeaux | Planifié | ✔️ |
| HuggingFace | Planifié | ❌ |
| Mistral | Planifié | ✔️ |
| Ollama | Bientôt disponible | ❌ |
| Onnx | Bientôt disponible | ❌ |
| OpenAI | ✔️ | ✔️ |
À compter d’aujourd’hui, les connecteurs IA suivants dans le noyau sémantique prennent en charge le modèle d’appel de fonction :
| Connecteur AI | ComportementDuChoixDeFonction | ToolCallBehavior |
|---|---|---|
| Anthropique | ✔️ | ❌ |
| AzureAIInference | ✔️ | ❌ |
| Soubassement | ✔️ | ❌ |
| Google AI | ✔️ | ❌ |
| Vertex AI | ✔️ | ❌ |
| HuggingFace | Planifié | ❌ |
| Mistral IA | ✔️ | ❌ |
| Ollama | ✔️ | ❌ |
| Onnx | ❌ | ❌ |
| OpenAI | ✔️ | ✔️ |
| Azure OpenAI | ✔️ | ✔️ |
Avertissement
Tous les modèles ne prennent pas en charge l’appel de fonction, tandis que certains modèles prennent uniquement en charge l’appel de fonction en mode non streaming. Comprenez les limitations du modèle que vous utilisez avant de tenter d’utiliser l’appel de fonction.
À compter d’aujourd’hui, les connecteurs IA suivants dans le noyau sémantique prennent en charge le modèle d’appel de fonction :
| Connecteur AI | ComportementDeChoixDeFonction | ToolCallBehavior |
|---|---|---|
| AzureOpenAI | ✔️ | ✔️ |
| Gémeaux | Planifié | ✔️ |
| OpenAI | ✔️ | ✔️ |