Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
I comportamenti di scelta della funzione sono bit di configurazione che consentono a uno sviluppatore di configurare:
- Quali funzioni vengono annunciate ai modelli di intelligenza artificiale.
- Come i modelli dovrebbero essere scelti per l'invocazione.
- Come il kernel semantico potrebbe richiamare tali funzioni.
A partire da oggi, i comportamenti di scelta della funzione sono rappresentati da tre metodi statici della FunctionChoiceBehavior classe :
- Auto: consente al modello di intelligenza artificiale di scegliere tra zero o più funzioni dalle funzioni specificate per la chiamata.
- Obbligatorio: forza il modello di intelligenza artificiale a scegliere una o più funzioni dalle funzioni fornite per la chiamata.
- Nessuno: indica al modello di intelligenza artificiale di non scegliere alcuna funzione.
A partire da oggi, i comportamenti di scelta della funzione sono rappresentati da tre metodi di classe della FunctionChoiceBehavior classe :
- Auto: consente al modello di intelligenza artificiale di scegliere tra zero o più funzioni dalle funzioni specificate per la chiamata.
- Obbligatorio: forza il modello di intelligenza artificiale a scegliere una o più funzioni dalle funzioni fornite per la chiamata.
- NoneInvoke: indica al modello di intelligenza artificiale di non scegliere alcuna funzione.
Nota
Potresti essere più familiare con il None comportamento di altre opere letterarie. Viene usato NoneInvoke per evitare confusione con la parola chiave Python None .
- Auto: consente al modello di intelligenza artificiale di scegliere tra zero o più funzioni dalle funzioni specificate per la chiamata.
- Obbligatorio: forza il modello di intelligenza artificiale a scegliere una o più funzioni dalle funzioni fornite per la chiamata.
- Nessuno: indica al modello di intelligenza artificiale di non scegliere alcuna funzione.
Nota
Se il codice usa le funzionalità di chiamata di funzione rappresentate dalla classe ToolCallBehavior, fare riferimento alla guida alla migrazione per aggiornare il codice al modello di chiamata di funzione più recente.
Nota
Le funzionalità di chiamata alle funzioni sono supportate solo da alcuni connettori di intelligenza artificiale finora, per altri dettagli, vedere la sezione Connettori di intelligenza artificiale supportati di seguito.
Pubblicità sulle funzionalità
L'esposizione delle funzioni è il processo di fornitura di funzioni ai modelli di intelligenza artificiale per ulteriori chiamate e invocazioni. Tutti e tre i comportamenti di scelta della funzione accettano un elenco di funzioni da annunciare come functions parametro. Per impostazione predefinita, è Null, ovvero tutte le funzioni dei plug-in registrati nel kernel vengono fornite al modello di intelligenza artificiale.
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));
Se viene fornito un elenco di funzioni, solo queste funzioni vengono inviate al modello di intelligenza artificiale:
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));
Un elenco vuoto di funzioni significa che non viene fornita alcuna funzione al modello di intelligenza artificiale, che equivale alla disabilitazione della chiamata di funzione.
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'esposizione delle funzioni è il processo di fornitura di funzioni ai modelli di intelligenza artificiale per ulteriori chiamate e invocazioni. Per impostazione predefinita, tutte le funzioni dei plug-in registrati nel kernel vengono fornite al modello di intelligenza artificiale, a meno che non vengano specificati filtri .
I filtri sono un dizionario con le chiavi seguenti: excluded_plugins, included_plugins, excluded_functions, included_functions. Consentono di specificare quali funzioni devono essere annunciate al modello di intelligenza artificiale.
Importante
Non è consentito specificare sia excluded_plugins e included_plugins oppure excluded_functions e included_functions contemporaneamente.
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)
Se viene fornito un filtro, al modello di intelligenza artificiale vengono inviati solo quelli che passano il filtro:
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)
Importante
Se si specifica un elenco vuoto a included_plugins o included_functions non si verifica alcun effetto. Per disabilitare la chiamata di funzione, è necessario impostare function_choice_behavior su NoneInvoke.
L'esposizione delle funzioni è il processo di fornitura di funzioni ai modelli di intelligenza artificiale per ulteriori chiamate e invocazioni. Tutti e tre i comportamenti di scelta della funzione accettano un elenco di funzioni da annunciare come functions parametro. Per impostazione predefinita, è Null, ovvero tutte le funzioni dei plug-in registrati nel kernel vengono fornite al modello di intelligenza artificiale.
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();
Se viene fornito un elenco di funzioni, solo queste funzioni vengono inviate al modello di intelligenza artificiale:
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();
Un elenco vuoto di funzioni significa che non viene fornita alcuna funzione al modello di intelligenza artificiale, che equivale alla disabilitazione della chiamata di funzione.
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();
Uso del comportamento di selezione automatica delle funzioni
Il Auto comportamento di scelta della funzione indica al modello di intelligenza artificiale di scegliere tra zero o più funzioni dalle funzioni specificate per la chiamata.
In questo esempio, al modello di intelligenza artificiale verranno fornite tutte le funzioni dei plugin DateTimeUtils e WeatherForecastUtils, insieme al prompt.
Il modello sceglierà prima la funzione GetCurrentTime per ottenere la data e l'ora correnti, poiché queste informazioni sono necessarie come input per la funzione GetWeatherForCity.
Successivamente, sceglierà GetWeatherForCity la funzione per la chiamata per ottenere le previsioni meteo per la città di Boston usando la data e l'ora ottenute.
Con queste informazioni, il modello sarà in grado di determinare il colore probabile del cielo a 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));
Lo stesso esempio può essere facilmente modellato in una configurazione del modello di richiesta 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));
In questo esempio, al modello di intelligenza artificiale verranno fornite tutte le funzioni dei plugin WeatherPlugin e DateTimePlugin, insieme al prompt. Il modello sceglierà prima la funzione GetCurrentUtcDateTime dal plug-in DateTimePlugin per l'invocazione, al fine di ottenere la data e l'ora correnti, poiché queste informazioni sono necessarie come input per la funzione GetWeatherForCity dal plug-in WeatherPlugin. Successivamente, sceglierà la funzione da invocare per ottenere le previsioni meteo per la città di Seattle utilizzando la data e l'ora ottenute. Con queste informazioni, il modello sarà in grado di rispondere alla query dell'utente in linguaggio naturale.
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)
Lo stesso esempio può essere facilmente modellato in una configurazione del modello di richiesta 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();
Suggerimento
Altri aggiornamenti saranno presto disponibili per Java SDK.
Uso del comportamento di scelta della funzione richiesta
Il Required comportamento forza il modello a scegliere una o più funzioni dalle funzioni specificate per la chiamata. Ciò è utile per gli scenari in cui il modello di intelligenza artificiale deve ottenere informazioni necessarie dalle funzioni specificate anziché dalle proprie conoscenze.
Nota
Il comportamento annuncia le funzioni nella prima richiesta solo al modello di intelligenza artificiale e interrompe l'invio nelle richieste successive per impedire un ciclo infinito in cui il modello continua a scegliere le stesse funzioni per la chiamata ripetutamente.
In questo caso, si specifica che il modello di intelligenza artificiale deve scegliere la GetWeatherForCity funzione per la chiamata per ottenere le previsioni meteo per la città di Boston, invece di indovinarla in base alla propria conoscenza.
Il modello sceglierà prima la funzione da invocare per recuperare le previsioni del tempo.
Con queste informazioni, il modello può quindi determinare il colore probabile del cielo a Boston usando la risposta dalla chiamata a 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));
Esempio identico in una configurazione del modello 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));
In alternativa, tutte le funzioni registrate nel kernel possono essere fornite al modello di intelligenza artificiale in base alle esigenze. Tuttavia, solo quelli scelti dal modello di intelligenza artificiale in seguito alla prima richiesta verranno richiamati dal kernel semantico. Le funzioni non verranno inviate al modello di intelligenza artificiale nelle richieste successive per impedire un ciclo infinito, come indicato in precedenza.
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));
In questo caso viene specificata una sola funzione, get_weather_for_city, al modello di intelligenza artificiale e viene forzata la scelta di questa funzione per la chiamata per ottenere le previsioni meteo.
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)
Esempio identico in una configurazione del modello 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();
Suggerimento
Altri aggiornamenti saranno presto disponibili per Java SDK.
Utilizzo del comportamento per la scelta della funzione 'Nessuna'
Il None comportamento indica al modello di intelligenza artificiale di usare le funzioni fornite senza sceglierle per la chiamata e generare invece una risposta di messaggio. Questo è utile per simulazioni quando il chiamante può voler vedere quali funzioni il modello selezionerebbe senza effettivamente richiamarle. Ad esempio, nell'esempio seguente il modello di intelligenza artificiale elenca correttamente le funzioni che sceglierebbe di determinare il colore del cielo a 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).
Esempio corrispondente in una configurazione del modello di richiesta 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));
Il NoneInvoke comportamento indica al modello di intelligenza artificiale di usare le funzioni fornite senza sceglierle per la chiamata e generare invece una risposta di messaggio. Questo è utile per simulazioni quando il chiamante può voler vedere quali funzioni il modello selezionerebbe senza effettivamente richiamarle. Ad esempio, nell'esempio seguente il modello di intelligenza artificiale elenca correttamente le funzioni che sceglierebbe di determinare il colore del cielo a 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.
Esempio identico in una configurazione del modello 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.
In questo caso, pubblicizziamo tutte le funzioni dai plug-in DateTimeUtils e WeatherForecastUtils al modello di intelligenza artificiale, ma indichiamo di non sceglierne nessuna.
Al contrario, il modello fornirà una risposta che descrive quali funzioni sceglierebbe di determinare il colore del cielo a Boston in una data specificata.
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).
Suggerimento
Altri aggiornamenti saranno presto disponibili per Java SDK.
Opzioni di comportamento nella scelta della funzione
Alcuni aspetti dei comportamenti di scelta della funzione possono essere configurati tramite opzioni che ogni classe di comportamento di scelta della funzione accetta tramite il parametro del options costruttore del FunctionChoiceBehaviorOptions tipo. Sono disponibili le opzioni seguenti:
AllowConcurrentInvocation: questa opzione abilita la chiamata simultanea delle funzioni dal kernel semantico. Per impostazione predefinita, è impostato su false, ovvero le funzioni vengono richiamate in sequenza. La chiamata simultanea è possibile solo se il modello di intelligenza artificiale può scegliere più funzioni per la chiamata in una singola richiesta; in caso contrario, non esiste alcuna distinzione tra chiamate sequenziali e simultanee
AllowParallelCalls: questa opzione consente al modello di intelligenza artificiale di scegliere più funzioni in una richiesta. Alcuni modelli di intelligenza artificiale potrebbero non supportare questa funzionalità; in questi casi, l'opzione non avrà alcun effetto. Per impostazione predefinita, questa opzione è impostata su Null, a indicare che verrà usato il comportamento predefinito del modello di intelligenza artificiale.
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
Alcuni aspetti dei comportamenti di scelta della funzione possono essere configurati tramite opzioni che ogni classe di comportamento di scelta della funzione accetta tramite il parametro del options costruttore del FunctionChoiceBehaviorOptions tipo. Sono disponibili le opzioni seguenti:
- AllowParallelCalls: questa opzione consente al modello di intelligenza artificiale di scegliere più funzioni in una richiesta. Alcuni modelli di intelligenza artificiale potrebbero non supportare questa funzionalità; in questi casi, l'opzione non avrà alcun effetto. Per impostazione predefinita, questa opzione è impostata su Null, a indicare che verrà usato il comportamento predefinito del modello di intelligenza artificiale.
Chiamata di funzione
La chiamata di funzione è il processo in cui il kernel semantico richiama le funzioni scelte dal modello di intelligenza artificiale. Per altri dettagli sulla chiamata di funzione, vedere l'articolo sulla chiamata di funzione.
Connettori di intelligenza artificiale supportati
A partire da oggi, i connettori di intelligenza artificiale seguenti in Semantic Kernel supportano il modello di chiamata della funzione:
| Connettore di intelligenza artificiale | FunctionChoiceBehavior | ToolCallBehavior |
|---|---|---|
| Antropico | Pianificato | ❌ |
| AzureAIInference | Presto disponibile | ❌ |
| AzureOpenAI | ✔️ | ✔️ |
| Gemelli | Pianificato | ✔️ |
| HuggingFace | Pianificato | ❌ |
| Maestrale | Pianificato | ✔️ |
| Ollama | Presto disponibile | ❌ |
| Onnx | Presto disponibile | ❌ |
| OpenAI | ✔️ | ✔️ |
A partire da oggi, i connettori di intelligenza artificiale seguenti in Semantic Kernel supportano il modello di chiamata della funzione:
| Connettore di intelligenza artificiale | FunctionChoiceBehavior | ToolCallBehavior |
|---|---|---|
| Antropico | ✔️ | ❌ |
| AzureAIInference | ✔️ | ❌ |
| Roccia madre | ✔️ | ❌ |
| Google AI | ✔️ | ❌ |
| Vertex AI | ✔️ | ❌ |
| HuggingFace | Pianificato | ❌ |
| Intelligenza artificiale Mistral | ✔️ | ❌ |
| Ollama | ✔️ | ❌ |
| Onnx | ❌ | ❌ |
| OpenAI | ✔️ | ✔️ |
| Azure OpenAI | ✔️ | ✔️ |
Avviso
Non tutti i modelli supportano la chiamata di funzione mentre alcuni modelli supportano solo le chiamate di funzione in modalità non di streaming. Si prega di comprendere le limitazioni del modello in uso prima di provare a utilizzare le funzioni.
A partire da oggi, i connettori di intelligenza artificiale seguenti in Semantic Kernel supportano il modello di chiamata della funzione:
| Connettore di intelligenza artificiale | FunctionChoiceBehavior | ToolCallBehavior |
|---|---|---|
| AzureOpenAI | ✔️ | ✔️ |
| Gemelli | Pianificato | ✔️ |
| OpenAI | ✔️ | ✔️ |