Bagikan melalui


Perilaku Pilihan Fungsi

Perilaku pilihan fungsi adalah bit konfigurasi yang memungkinkan pengembang untuk mengonfigurasi:

  1. Fungsi mana yang diiklankan ke model AI.
  2. Bagaimana model harus memilihnya untuk pemanggilan.
  3. Bagaimana Semantic Kernel mungkin memanggil fungsi-fungsi tersebut.

Pada hari ini, perilaku pilihan fungsi diwakili oleh tiga metode FunctionChoiceBehavior statis kelas:

  • Otomatis: Memungkinkan model AI untuk memilih dari nol atau lebih fungsi dari fungsi yang disediakan untuk pemanggilan.
  • Diperlukan: Memaksa model AI untuk memilih satu atau beberapa fungsi dari fungsi yang disediakan untuk pemanggilan.
  • Tidak Ada: Menginstruksikan model AI untuk tidak memilih fungsi apa pun.

Sebagai per hari ini, perilaku pilihan fungsi diwakili oleh tiga metode kelas FunctionChoiceBehavior.

  • Otomatis: Memungkinkan model AI untuk memilih dari nol atau lebih fungsi dari fungsi yang disediakan untuk pemanggilan.
  • Diperlukan: Memaksa model AI untuk memilih satu atau beberapa fungsi dari fungsi yang disediakan untuk pemanggilan.
  • NoneInvoke: Menginstruksikan model AI untuk tidak memilih fungsi apa pun.

Nota

Anda mungkin lebih akrab dengan perilaku None dalam literatur lain. Kami menggunakan NoneInvoke untuk menghindari kebingungan dengan kata kunci Python None .

  • Otomatis: Memungkinkan model AI untuk memilih dari nol atau lebih fungsi dari fungsi yang disediakan untuk pemanggilan.
  • Diperlukan: Memaksa model AI untuk memilih satu atau beberapa fungsi dari fungsi yang disediakan untuk pemanggilan.
  • Tidak Ada: Menginstruksikan model AI untuk tidak memilih fungsi apa pun.

Nota

Jika kode Anda menggunakan kemampuan pemanggilan fungsi yang diwakili oleh kelas ToolCallBehavior, lihat panduan migrasi untuk memperbarui kode ke model pemanggilan fungsi terbaru.

Nota

Kemampuan pemanggilan fungsi hanya didukung oleh beberapa konektor AI sejauh ini, lihat bagian Konektor AI yang didukung di bawah ini untuk detail selengkapnya.

Iklan Fungsional

Pemasaran fungsi adalah proses penyediaan fungsi untuk model AI untuk pemanggilan dan penggunaan lebih lanjut. Ketiga perilaku pilihan fungsi menerima daftar fungsi untuk diiklankan sebagai functions parameter. Secara default, ini null, yang berarti semua fungsi dari plugin yang terdaftar di Kernel disediakan untuk model AI.

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

// All functions from the DateTimeUtils and WeatherForecastUtils plugins will be sent to AI model together with the prompt.
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() }; 

await kernel.InvokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?", new(settings));

Jika daftar fungsi disediakan, hanya fungsi tersebut yang dikirim ke model AI:

using Microsoft.SemanticKernel;

IKernelBuilder builder = Kernel.CreateBuilder(); 
builder.AddOpenAIChatCompletion("<model-id>", "<api-key>");
builder.Plugins.AddFromType<WeatherForecastUtils>();
builder.Plugins.AddFromType<DateTimeUtils>(); 

Kernel kernel = builder.Build();

KernelFunction getWeatherForCity = kernel.Plugins.GetFunction("WeatherForecastUtils", "GetWeatherForCity");
KernelFunction getCurrentTime = kernel.Plugins.GetFunction("DateTimeUtils", "GetCurrentUtcDateTime");

// Only the specified getWeatherForCity and getCurrentTime functions will be sent to AI model alongside the prompt.
PromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(functions: [getWeatherForCity, getCurrentTime]) }; 

await kernel.InvokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?", new(settings));

Daftar fungsi kosong berarti tidak ada fungsi yang disediakan untuk model AI, yang setara dengan menonaktifkan panggilan fungsi.

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));

Iklan fungsi adalah proses menyediakan fungsi ke model AI untuk dipanggil dan digunakan lebih lanjut. Secara bawaan, fungsi plugin yang terdaftar di Kernel akan diterapkan pada model AI kecuali jika filter ditentukan. Filter adalah kamus dengan kunci berikut: excluded_plugins, , included_pluginsexcluded_functions, included_functions. Mereka memungkinkan Anda menentukan fungsi mana yang harus diiklankan ke model AI.

Penting

Tidak diperbolehkan untuk menentukan dan excluded_pluginsincluded_plugins atau excluded_functions dan included_functions pada saat yang sama.

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)

Jika filter disediakan, hanya yang lolos dari filter yang dikirim ke model AI.

from semantic_kernel.connectors.ai.function_choice_behavior import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.kernel import Kernel

kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())

# Assuming that WeatherPlugin, DateTimePlugin, and LocationPlugin are already implemented
kernel.add_plugin(WeatherPlugin(), "WeatherPlugin")
kernel.add_plugin(DateTimePlugin(), "DateTimePlugin")
kernel.add_plugin(LocationPlugin(), "LocationPlugin")

query = "What is the weather in Seattle today?"
arguments = KernelArguments(
    settings=PromptExecutionSettings(
        # Advertise all functions from the WeatherPlugin and DateTimePlugin plugins to the AI model.
        function_choice_behavior=FunctionChoiceBehavior.Auto(filters={"included_plugins": ["WeatherPlugin", "DateTimePlugin"]}),
    )
)

response = await kernel.invoke_prompt(query, arguments=arguments)

Penting

Memberikan daftar kosong ke included_plugins atau included_functions tidak berpengaruh apa pun. Jika Anda ingin menonaktifkan panggilan fungsi, Anda harus mengatur function_choice_behavior ke NoneInvoke.

Pencantuman fungsi adalah proses penyediaan fungsi untuk model AI agar dapat dipanggil dan digunakan lebih lanjut. Ketiga perilaku pemilihan fungsi menerima daftar fungsi untuk ditampilkan sebagai parameter functions. Secara default, ini null, yang berarti semua fungsi dari plugin yang terdaftar di Kernel disediakan untuk model AI.

var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromObject(new WeatherForecastUtils(), "WeatherForecastUtils"))
    .withPlugin(KernelPluginFactory.createFromObject(new DateTimeUtils(), "DateTimeUtils"))
    .build();

InvocationContext invocationContext = InvocationContext.builder()
    // All functions from the DateTimeUtils and WeatherForecastUtils plugins will be sent to AI model together with the prompt.
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true))
    .build();

var response = kernel.invokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?",
    KernelArguments.builder().build(),
    invocationContext
).block();

Jika daftar fungsi disediakan, hanya fungsi tersebut yang dikirim ke model AI:

var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromObject(new WeatherForecastUtils(), "WeatherForecastUtils"))
    .withPlugin(KernelPluginFactory.createFromObject(new DateTimeUtils(), "DateTimeUtils"))
    .build();

var getWeatherForCity = kernel.getFunction("WeatherPlugin", "getWeatherForCity");
var getCurrentTime = kernel.getFunction("WeatherPlugin", "getWeatherForCity");

InvocationContext invocationContext = InvocationContext.builder()
    // Only the specified getWeatherForCity and getCurrentTime functions will be sent to AI model alongside the prompt.
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true, List.of(getWeatherForCity, getCurrentTime)))
    .build();

var response = kernel.invokePromptAsync("Given the current time of day and weather, what is the likely color of the sky in Boston?",
    KernelArguments.builder().build(),
    invocationContext
).block();

Daftar fungsi kosong berarti tidak ada fungsi yang disediakan untuk model AI, yang setara dengan menonaktifkan panggilan fungsi.

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();

Menggunakan Perilaku Pilihan Fungsi Otomatis

Perilaku pemilihan fungsi Auto menginstruksikan model AI untuk memilih satu atau beberapa fungsi dari fungsi yang disediakan untuk pelaksanaan.

Dalam contoh ini, semua fungsi dari DateTimeUtils plugin dan WeatherForecastUtils akan disediakan untuk model AI bersama perintah. Model pertama-tama akan memilih GetCurrentTime fungsi untuk pemanggilan untuk mendapatkan tanggal dan waktu saat ini, karena informasi ini diperlukan sebagai input untuk fungsi.GetWeatherForCity Selanjutnya, ia akan memilih GetWeatherForCity fungsi untuk pemanggilan untuk mendapatkan prakiraan cuaca untuk kota Boston menggunakan tanggal dan waktu yang diperoleh. Dengan informasi ini, model akan dapat menentukan kemungkinan warna langit di 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));

Contoh yang sama dapat dengan mudah dimodelkan dalam konfigurasi templat 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: 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));

Dalam contoh ini, semua fungsi dari WeatherPlugin plugin dan DateTimePlugin akan disediakan untuk model AI bersama perintah. Model pertama-tama akan memilih GetCurrentUtcDateTime fungsi dari DateTimePlugin plugin untuk pemanggilan untuk mendapatkan tanggal dan waktu saat ini, karena informasi ini diperlukan sebagai input untuk GetWeatherForCity fungsi dari WeatherPlugin plugin. Selanjutnya, ia akan memilih fungsi GetWeatherForCity untuk melakukan pemanggilan guna mendapatkan prakiraan cuaca untuk kota Seattle dengan menggunakan tanggal dan waktu yang diperoleh. Dengan informasi ini, model akan dapat menjawab kueri pengguna dalam bahasa alami.

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)

Contoh yang sama dapat dengan mudah dimodelkan dalam konfigurasi templat prompt 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();

Petunjuk / Saran

Pembaruan lainnya akan segera hadir di Java SDK.

Menggunakan pola pemilihan fungsi yang wajib

Perilaku Required memaksa model untuk memilih satu atau beberapa fungsi yang disediakan untuk pemanggilan. Ini berguna untuk skenario ketika model AI harus mendapatkan informasi yang diperlukan dari fungsi yang ditentukan daripada dari pengetahuannya sendiri.

Nota

Perilaku mengiklankan fungsi dalam permintaan pertama ke model AI saja dan berhenti mengirimnya dalam permintaan berikutnya untuk mencegah perulangan tak terbatas di mana model terus memilih fungsi yang sama untuk pemanggilan berulang kali.

Di sini, kami menentukan bahwa model AI harus memilih GetWeatherForCity fungsi untuk pemanggilan untuk mendapatkan prakiraan cuaca untuk kota Boston, daripada menebaknya berdasarkan pengetahuannya sendiri. Model pertama-tama akan memilih fungsi pemanggilan GetWeatherForCity untuk mengambil prakiraan cuaca. Dengan informasi ini, model kemudian dapat menentukan kemungkinan warna langit di Boston menggunakan respons dari panggilan ke 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));

Contoh yang identik dalam konfigurasi templat 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));

Atau, semua fungsi yang terdaftar dalam kernel dapat disediakan untuk model AI sesuai kebutuhan. Namun, hanya yang dipilih oleh model AI sebagai hasil dari permintaan pertama yang akan dipanggil oleh Kernel Semantik. Fungsi tidak akan dikirim ke model AI dalam permintaan berikutnya untuk mencegah perulangan tak terbatas, seperti yang disebutkan di atas.

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));

Di sini, kami hanya menyediakan satu fungsi, get_weather_for_city, ke model AI dan memaksanya untuk memilih fungsi ini untuk pemanggilan untuk mendapatkan prakiraan cuaca.

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)

Contoh yang identik dalam konfigurasi templat 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();

Petunjuk / Saran

Pembaruan lainnya akan segera hadir di Java SDK.

Menggunakan Perilaku Pilihan Fungsi Tidak Ada

Perilaku None menginstruksikan model AI untuk menggunakan fungsi yang diberikan tanpa memilih untuk memanggil salah satunya, melainkan menghasilkan pesan respons. Ini berguna untuk uji coba ketika pihak yang memanggil mungkin ingin melihat fungsi mana yang akan dipilih model tanpa benar-benar memanggilnya. Misalnya dalam sampel di bawah model AI mencantumkan fungsi yang akan dipilihnya untuk menentukan warna langit di 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).

Contoh yang sesuai dalam konfigurasi templat perintah 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));

Perilaku NoneInvoke menginstruksikan model AI untuk menggunakan fungsi yang disediakan tanpa memilih dan memanggil salah satunya, dan hanya menghasilkan tanggapan pesan. Ini berguna untuk eksekusi kering ketika pemanggil mungkin ingin melihat fungsi mana yang akan dipilih model tanpa benar-benar memanggilnya. Misalnya dalam sampel di bawah model AI mencantumkan fungsi yang akan dipilihnya untuk menentukan warna langit di 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.

Contoh yang identik dalam konfigurasi templat 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.

Di sini, kami mengiklankan semua fungsi dari DateTimeUtils plugin dan WeatherForecastUtils ke model AI tetapi menginstruksikannya untuk tidak memilih salah satunya. Sebagai gantinya, model akan memberikan respons yang menjelaskan fungsi mana yang akan dipilihnya untuk menentukan warna langit di Boston pada tanggal tertentu.

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).

Petunjuk / Saran

Pembaruan lainnya akan segera hadir di Java SDK.

Opsi Pilihan Perilaku Fungsi

Aspek tertentu dari perilaku pilihan fungsi dapat dikonfigurasi melalui opsi yang diterima oleh setiap kelas perilaku pilihan fungsi melalui parameter konstruktor jenis optionsFunctionChoiceBehaviorOptions. Opsi berikut ini tersedia:

  • AllowConcurrentInvocation: Opsi ini memungkinkan pemanggilan fungsi bersamaan oleh Kernel Semantik. Secara default, ini diatur ke false, yang berarti bahwa fungsi dipanggil secara berurutan. Pemanggilan bersamaan hanya dimungkinkan jika model AI dapat memilih beberapa fungsi untuk pemanggilan dalam satu permintaan; jika tidak, tidak ada perbedaan antara pemanggilan berurutan dan bersamaan

  • AllowParallelCalls: Opsi ini memungkinkan model AI untuk memilih beberapa fungsi dalam satu permintaan. Beberapa model AI mungkin tidak mendukung fitur ini; dalam kasus seperti itu, opsi tidak akan berpengaruh. Secara default, opsi ini diatur ke null, menunjukkan bahwa perilaku default model AI akan digunakan.

    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
    

Aspek tertentu dari perilaku pemilihan fungsi dapat dikonfigurasi melalui opsi yang diterima oleh setiap kelas perilaku pemilihan fungsi melalui parameter konstruktor options dari jenis FunctionChoiceBehaviorOptions. Opsi berikut ini tersedia:

  • AllowParallelCalls: Opsi ini memungkinkan model AI untuk memilih beberapa fungsi dalam satu permintaan. Beberapa model AI mungkin tidak mendukung fitur ini; dalam kasus seperti itu, opsi tidak akan berpengaruh. Secara default, opsi ini diatur ke null, menunjukkan bahwa perilaku default model AI akan digunakan.

Pemanggilan Fungsi

Pemanggilan fungsi adalah proses di mana Kernel Semantik memanggil fungsi yang dipilih oleh model AI. Untuk detail selengkapnya tentang pemanggilan fungsi, lihat artikel pemanggilan fungsi.

Konektor AI yang didukung

Mulai hari ini, konektor AI berikut di Kernel Semantik mendukung model panggilan fungsi:

Konektor AI FunctionChoiceBehavior ToolCallBehavior
Antropik Direncanakan
AzureAIInference Segera datang
AzureOpenAI ✔️ ✔️
Gemini Direncanakan ✔️
HuggingFace Direncanakan
Mistral Direncanakan ✔️
Ollama Segera datang
Onnx Segera datang
OpenAI ✔️ ✔️

Mulai hari ini, konektor AI berikut di Kernel Semantik mendukung model panggilan fungsi:

Konektor AI FunctionChoiceBehavior ToolCallBehavior
Antropik ✔️
AzureAIInference ✔️
Bedrock ✔️
Google AI ✔️
Vertex AI ✔️
HuggingFace Direncanakan
Mistral Kecerdasan Buatan ✔️
Ollama ✔️
Onnx
OpenAI ✔️ ✔️
Azure OpenAI ✔️ ✔️

Peringatan

Tidak semua model mendukung panggilan fungsi, sedangkan beberapa model hanya mendukung panggilan fungsi dalam mode non-streaming. Harap pahami batasan model yang Anda gunakan sebelum mencoba menggunakan panggilan fungsi.

Mulai hari ini, konektor AI berikut di Kernel Semantik mendukung model panggilan fungsi:

Konektor AI FunctionChoiceBehavior ToolCallBehavior
AzureOpenAI ✔️ ✔️
Gemini Direncanakan ✔️
OpenAI ✔️ ✔️