Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
İşlev seçimi davranışları, bir geliştiricinin şunları yapılandırmasına olanak tanıyan yapılandırma bitleridir:
- Yapay zeka modellerine tanıtılan işlevler.
- Modellerin invokasyon için bunları nasıl seçeceği.
- Semantik Çekirdeğin bu işlevleri nasıl çağırabileceği.
Bugün itibarıyla işlev seçimi davranışları sınıfının üç statik yöntemiyle FunctionChoiceBehavior temsil edilir:
- Otomatik: Yapay zeka modelinin çağrı için sağlanan işlevlerden sıfır veya daha fazla işlev arasından seçim yapmasına izin verir.
- Gerekli: Yapay zeka modelini çağrı için sağlanan işlevlerden bir veya daha fazla işlev seçmeye zorlar.
- Hiçbiri: Yapay zeka modeline herhangi bir işlev seçmemelerini ister.
Bugün itibarıyla işlev seçimi davranışları sınıfının üç sınıf yöntemiyle FunctionChoiceBehavior temsil edilir:
- Otomatik: Yapay zeka modelinin çağrı için sağlanan işlevlerden sıfır veya daha fazla işlev arasından seçim yapmasına izin verir.
- Gerekli: Yapay zeka modelini çağrı için sağlanan işlevlerden bir veya daha fazla işlev seçmeye zorlar.
- NoneInvoke: Yapay zeka modeline herhangi bir işlev seçmeme talimatını getirir.
Not
Diğer edebiyatlardan gelen davranışlar None hakkında daha fazla bilgi sahibi olabilirsiniz. Python NoneInvoke anahtar sözcüğüyle karışıklığı önlemek için kullanırızNone.
- Otomatik: Yapay zeka modelinin çağrı için sağlanan işlevlerden sıfır veya daha fazla işlev arasından seçim yapmasına izin verir.
- Gerekli: Yapay zeka modelini çağrı için sağlanan işlevlerden bir veya daha fazla işlev seçmeye zorlar.
- Hiçbiri: Yapay zeka modeline herhangi bir işlev seçmemelerini ister.
Not
Kodunuz ToolCallBehavior sınıfı tarafından temsil edilen işlev çağırma özelliklerini kullanıyorsa, kodu en son işlev çağırma modeline güncelleştirmek için lütfen geçiş kılavuzuna bakın.
Not
İşlev çağırma özellikleri şu ana kadar yalnızca birkaç yapay zeka bağlayıcısı tarafından destekleniyor. Daha fazla ayrıntı için aşağıdaki Desteklenen Yapay Zeka Bağlayıcıları bölümüne bakın.
İşlev Reklamları
İşlev tanıtımı, yapay zeka modellerine işlev sağlama ve daha fazla çağrı yapma işlemidir. Üç işlev seçimi davranışı da parametre olarak functions tanıtılan işlevlerin listesini kabul eder. Varsayılan olarak null değeridir; bu da Çekirdekte kayıtlı eklentilerdeki tüm işlevlerin yapay zeka modeline sağlandığı anlamına gelir.
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));
İşlevlerin listesi sağlanırsa yapay zeka modeline yalnızca bu işlevler gönderilir:
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));
İşlevlerin boş bir listesi, yapay zeka modeline işlev sağlanmadığı anlamına gelir ve bu da işlev çağrısını devre dışı bırakmaya eşdeğerdir.
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));
İşlev tanıtımı, yapay zeka modellerine işlev sağlama ve daha fazla çağrı yapma işlemidir. Varsayılan olarak, çekirdekte kayıtlı eklentilerdeki tüm işlevler , filtreler belirtilmediği sürece yapay zeka modeline sağlanır.
Filtreler , şu anahtarlara sahip bir sözlüktür: excluded_plugins, included_plugins, excluded_functions, included_functions. Yapay zeka modeline tanıtılması gereken işlevleri belirtmenize olanak sağlar.
Önemli
excluded_plugins ve included_plugins veya excluded_functions ve included_functions aynı anda belirtilmesine izin verilmez.
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)
Bir filtre sağlanırsa, yapay zeka modeline yalnızca filtreyi geçenler gönderilir:
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)
Önemli
included_plugins veya included_functions'e boş bir liste sağlamak herhangi bir etki yapmaz. Fonksiyon çağrısını devre dışı bırakmak istiyorsanız function_choice_behavior değerini NoneInvoke olarak ayarlamanız gerekir.
İşlev tanıtımı, yapay zeka modellerine işlev sağlama ve daha fazla çağrı yapma işlemidir. Üç işlev seçimi davranışı da parametre olarak functions tanıtılan işlevlerin listesini kabul eder. Varsayılan olarak null değeridir; bu da Çekirdekte kayıtlı eklentilerdeki tüm işlevlerin yapay zeka modeline sağlandığı anlamına gelir.
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();
İşlevlerin listesi sağlanırsa yapay zeka modeline yalnızca bu işlevler gönderilir:
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();
İşlevlerin boş bir listesi, yapay zeka modeline işlev sağlanmadığı anlamına gelir ve bu da işlev çağrısını devre dışı bırakmaya eşdeğerdir.
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();
Otomatik İşlev Seçimi Davranışını Kullanma
İşlev Auto seçimi davranışı, yapay zeka modeline çağrı için sağlanan işlevlerden sıfır veya daha fazla işlev arasından seçim yapma talimatını getirir.
Bu örnekte, DateTimeUtils ve WeatherForecastUtils eklentilerindeki tüm işlevler istemle birlikte yapay zeka modeline sağlanacaktır.
Bu bilgiler işlev için giriş olarak gerektiğinden, model ilk olarak geçerli tarih ve saati almak üzere çağırma işlevini GetCurrentTime seçerGetWeatherForCity.
Ardından, elde edilen tarih ve saati kullanarak Boston şehrinin hava durumu tahminini almak için çağrı işlevini seçecektir GetWeatherForCity .
Bu bilgilerle, model Boston'da gökyüzünün olası rengini belirleyebilecek.
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));
Aynı örnek, YAML istem şablonu yapılandırmasında kolayca modellenebilir:
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));
Bu örnekte, WeatherPlugin ve DateTimePlugin eklentilerindeki tüm işlevler istemle birlikte yapay zeka modeline sağlanacaktır. Model, bu bilgilerin GetCurrentUtcDateTime eklentisinden DateTimePlugin işlevine giriş olarak gerekli olması nedeniyle, ilk olarak GetWeatherForCity eklentisinden WeatherPlugin işlevini çağırarak geçerli tarih ve saati almayı seçecektir. Ardından, elde edilen tarih ve saati kullanarak Seattle şehrinin hava durumu tahminini almak için çağrı işlevini seçer GetWeatherForCity . Bu bilgilerle model, kullanıcı sorgusunu doğal dilde yanıtlayabilecektir.
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)
Aynı örnek, YAML istem şablonu yapılandırmasında kolayca modellenebilir:
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();
Tavsiye
Java SDK'sına yakında daha fazla güncelleştirme eklenecek.
Gerekli İşlev Seçimi Davranışını Kullanma
Davranış, Required modeli çağrı için sağlanan işlevlerden bir veya daha fazla işlev seçmeye zorlar. Bu, yapay zeka modelinin kendi bilgisinden değil, belirtilen işlevlerden gerekli bilgileri alması gereken senaryolar için kullanışlıdır.
Not
Davranış, ilk istekteki işlevleri yalnızca yapay zeka modeline tanıtıyor ve modelin sürekli çağrı için aynı işlevleri seçmeye devam ettiği sonsuz bir döngünün önüne geçmek için sonraki isteklerde göndermeyi durduruyor.
Burada yapay zeka modelinin kendi bilgisine göre tahmin etmek yerine Boston şehrinin hava durumu tahminini elde etmek için çağrı işlevini seçmesi GetWeatherForCity gerektiğini belirteceğiz.
Model, önce havadurumu tahminini almak üzere GetWeatherForCity işlevini çağırmak için seçer.
Bu bilgilerle model, çağrısından GetWeatherForCitygelen yanıtı kullanarak Boston'daki gökyüzünün olası rengini belirleyebilir.
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));
YAML şablon yapılandırmasında aynı örnek:
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));
Alternatif olarak, çekirdekte kayıtlı tüm işlevler yapay zeka modeline gerektiği gibi sağlanabilir. Ancak yalnızca ilk isteğin sonucu olarak yapay zeka modeli tarafından seçilenler Anlam Çekirdeği tarafından çağrılır. İşlevler yukarıda belirtildiği gibi sonsuz döngünün önlenmesi için sonraki isteklerde yapay zeka modeline gönderilmez.
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));
Burada yapay zeka modeline tek bir işlev get_weather_for_city(, ) sağlıyoruz ve hava durumu tahminini almak üzere çağrı yapmak üzere bu işlevi seçmeye zorlayacağız.
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)
YAML şablon yapılandırmasında aynı örnek:
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();
Tavsiye
Java SDK'sına yakında daha fazla güncelleştirme eklenecek.
None Fonksiyonunu Seçme Davranışı Kullanma
Bu davranış, None yapay zeka modeline çağrı için herhangi birini seçmeden sağlanan işlevleri kullanmasını ve bunun yerine bir ileti yanıtı oluşturmasını söyler. Arayan, modelin gerçekten çağırmadan hangi işlevleri seçeceğini görmek isteyebileceğinde bu, kuru çalıştırmalar için yararlıdır. Örneğin yapay zeka modelinin altındaki örnekte Boston'da gökyüzünün rengini belirlemek için seçeceği işlevler doğru şekilde listelenmektedir.
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).
YAML istem şablonu yapılandırmasında karşılık gelen örnek:
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));
Bu davranış, NoneInvoke yapay zeka modeline çağrı için herhangi birini seçmeden sağlanan işlevleri kullanmasını ve bunun yerine bir ileti yanıtı oluşturmasını söyler. Arayan, modelin gerçekten çağırmadan hangi işlevleri seçeceğini görmek isteyebileceğinde bu, kuru çalıştırmalar için yararlıdır. Örneğin yapay zeka modelinin altındaki örnekte Boston'da gökyüzünün rengini belirlemek için seçeceği işlevler doğru şekilde listelenmektedir.
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.
YAML şablon yapılandırmasında aynı örnek:
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.
Burada, DateTimeUtils ve WeatherForecastUtils eklentilerindeki tüm işlevleri yapay zeka modeline tanıtıyoruz ancak bunlardan hiçbirini seçmemesini söylüyoruz.
Bunun yerine model, belirli bir tarihte Boston'da gökyüzünün rengini belirlemek için hangi işlevleri seçeceğini açıklayan bir yanıt sağlayacaktır.
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).
Tavsiye
Java SDK'sına yakında daha fazla güncelleştirme eklenecek.
İşlev Seçimi Davranış Seçenekleri
İşlev seçimi davranışlarının belirli yönleri, her işlev seçimi davranış sınıfının options türündeki FunctionChoiceBehaviorOptions oluşturucu parametresi aracılığıyla kabul ettiği seçenekler sayesinde yapılandırılabilir. Aşağıdaki seçenekler kullanılabilir:
AllowConcurrentInvocation: Bu seçenek, Anlam Çekirdeği tarafından işlevlerin eşzamanlı çağrılmasına olanak tanır. Varsayılan olarak false olarak ayarlanır, yani işlevler sırayla çağrılır. Eşzamanlı çağırma yalnızca yapay zeka modeli tek bir istekte çağrı için birden çok işlev seçebiliyorsa mümkündür; aksi takdirde, sıralı ve eşzamanlı çağrı arasında ayrım yoktur
AllowParallelCalls: Bu seçenek, yapay zeka modelinin tek bir istekte birden çok işlev seçmesini sağlar. Bazı yapay zeka modelleri bu özelliği desteklemeyebilir; bu gibi durumlarda seçeneğin hiçbir etkisi olmaz. Varsayılan olarak, bu seçenek null olarak ayarlanır ve yapay zeka modelinin varsayılan davranışının kullanılacağını belirtir.
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
İşlev seçimi davranışlarının belirli yönleri, her işlev seçimi davranış sınıfının options türündeki FunctionChoiceBehaviorOptions oluşturucu parametresi aracılığıyla kabul ettiği seçenekler sayesinde yapılandırılabilir. Aşağıdaki seçenekler kullanılabilir:
- AllowParallelCalls: Bu seçenek, yapay zeka modelinin tek bir istekte birden çok işlev seçmesini sağlar. Bazı yapay zeka modelleri bu özelliği desteklemeyebilir; bu gibi durumlarda seçeneğin hiçbir etkisi olmaz. Varsayılan olarak, bu seçenek null olarak ayarlanır ve yapay zeka modelinin varsayılan davranışının kullanılacağını belirtir.
İşlev Çağırma
İşlev çağırma, Anlam Çekirdeği'nin yapay zeka modeli tarafından seçilen işlevleri çağırdığı işlemdir. İşlev çağırma hakkında daha fazla bilgi için işlev çağırma makalesine bakın.
Desteklenen Yapay Zeka Bağlayıcıları
Bugün itibarıyla Anlam Çekirdeği'ndeki aşağıdaki yapay zeka bağlayıcıları işlev çağırma modelini destekler:
| AI Bağlayıcısı | FonksiyonSeçimDavranışı | ToolCallBehavior |
|---|---|---|
| İnsansı | Planlandı | ❌ |
| AzureAIInference | Yakında | ❌ |
| AzureOpenAI | ✔️ | ✔️ |
| Gemini | Planlandı | ✔️ |
| HuggingFace | Planlandı | ❌ |
| Mistral rüzgarı | Planlandı | ✔️ |
| Ollama | Yakında | ❌ |
| Onnx | Yakında | ❌ |
| OpenAI | ✔️ | ✔️ |
Bugün itibarıyla Anlam Çekirdeği'ndeki aşağıdaki yapay zeka bağlayıcıları işlev çağırma modelini destekler:
| AI Bağlayıcısı | FonksiyonSeçimDavranışı | ToolCallBehavior |
|---|---|---|
| İnsansı | ✔️ | ❌ |
| AzureAIInference | ✔️ | ❌ |
| Bedrock | ✔️ | ❌ |
| Google AI | ✔️ | ❌ |
| Vertex AI | ✔️ | ❌ |
| HuggingFace | Planlandı | ❌ |
| Mistral AI | ✔️ | ❌ |
| Ollama | ✔️ | ❌ |
| Onnx | ❌ | ❌ |
| OpenAI | ✔️ | ✔️ |
| Azure OpenAI | ✔️ | ✔️ |
Uyarı
Bazı modeller yalnızca akış dışı modda işlev çağrısını desteklerken, tüm modeller işlev çağrısını desteklemez. İşlev çağrısını kullanmaya çalışmadan önce lütfen kullandığınız modelin sınırlamalarını anlayın.
Bugün itibarıyla Anlam Çekirdeği'ndeki aşağıdaki yapay zeka bağlayıcıları işlev çağırma modelini destekler:
| AI Bağlayıcısı | FonksiyonSeçimDavranışı | ToolCallBehavior |
|---|---|---|
| AzureOpenAI | ✔️ | ✔️ |
| Gemini | Planlandı | ✔️ |
| OpenAI | ✔️ | ✔️ |