共用方式為


配置代理與語義核心插件

這很重要

這項功能位於候選版階段。 此階段的功能幾乎完整且一般穩定,不過在達到完整正式運作之前,它們可能會經歷輕微的精簡或優化。

語義核心中的函數與外掛程式

函數呼叫是一個強大的工具,可讓開發人員添加自訂功能並擴展 AI 應用程式的能力。 語義核心插件架構提供了一個靈活的框架來支持函數調用。 在Agent中,整合插件函數呼叫是建立在這個基礎的語義核心功能之上。

設定完成後,代理人會選擇何時及如何呼叫可用的函式,就像在Agent Framework之外的任何情況下使用時一樣。

為代理程式新增插件

任何插件可供Agent使用,都由其相應的Kernel實例管理。 此設定使每個 Agent 能夠根據其特定角色存取不同的功能。

外掛程式 可以在Kernel建立之前或之後新增到Agent中。 初始化插件的過程遵循任何語意內核實施所使用的相同模式,從而確保一致性並輕鬆管理AI功能。

備註

必須針對 ChatCompletionAgent 明確啟用函式呼叫模式。 OpenAIAssistant 代理程序總是基於自動化函數調用。

// Factory method to product an agent with a specific role.
// Could be incorporated into DI initialization.
ChatCompletionAgent CreateSpecificAgent(Kernel kernel, string credentials)
{
    // Clone kernel instance to allow for agent specific plug-in definition
    Kernel agentKernel = kernel.Clone();

    // Import plug-in from type
    agentKernel.ImportPluginFromType<StatelessPlugin>();

    // Import plug-in from object
    agentKernel.ImportPluginFromObject(new StatefulPlugin(credentials));

    // Create the agent
    return
        new ChatCompletionAgent()
        {
            Name = "<agent name>",
            Instructions = "<agent instructions>",
            Kernel = agentKernel,
            Arguments = new KernelArguments(
                new OpenAIPromptExecutionSettings()
                {
                    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
                })
        };
}

有兩種方法可以使用插件來創建ChatCompletionAgent

方法一:透過構造函數指定插件

您可以直接傳遞插件列表到構造函數。

from semantic_kernel.agents import ChatCompletionAgent

# Create the Chat Completion Agent instance by specifying a list of plugins
agent = ChatCompletionAgent(
    service=AzureChatCompletion(),
    instructions="<instructions>",
    plugins=[SamplePlugin()]
)

小提示

預設情況下,自動函數呼叫是啟用的。 要禁用它,請在構造函數中將function_choice_behavior參數設置為function_choice_behavior=FunctionChoiceBehavior.Auto(auto_invoke=False)。 在此設定下,插件會被廣播到模型,但不會自動啟動。 如果執行設定指定的service_idai_model_id與 AI 服務組態相同,則執行設定中定義的函式呼叫行為(通過KernelArguments)將優先於在建構函式中設定的函式選擇行為。

方法二:手動配置內核

如果沒有通過構造函數提供 kernel,則會在模型驗證過程中自動創建一個。 任何傳入的插件將優先處理,並添加到內核中。 若要對核心狀態進行更細緻的控制,請遵循以下步驟:

from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel

# Create the instance of the Kernel
kernel = Kernel()

# Add the chat completion service to the Kernel
kernel.add_service(AzureChatCompletion())

# Get the AI Service settings
settings = kernel.get_prompt_execution_settings_from_service_id()

# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()

# Add the Plugin to the Kernel
kernel.add_plugin(SamplePlugin(), plugin_name="<plugin name>")

# Create the agent
agent = ChatCompletionAgent(
    kernel=kernel,
    name=<agent name>,
    instructions=<agent instructions>,
    arguments=KernelArguments(settings=settings),
)

小提示

若在將服務新增至核心時未指定service_id,則將預設為default。 在核心上配置多個 AI 服務時,建議使用 service_id 參數來區分它們。 這允許您為特定的service_id檢索執行設定,並將這些設定與所需的服務關聯起來。

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 SamplePlugin(), "<plugin name>"))
    .build();

var agent = ChatCompletionAgent.builder()
    .withKernel(kernel)
    .withName("<agent name>")
    .withInstructions("<agent instructions>")
    .build();

將功能新增至代理

使用插件是配置函數調用的最常見方法。 然而,獨立的功能也可以被獨立提供,包括提示功能。

// Factory method to product an agent with a specific role.
// Could be incorporated into DI initialization.
ChatCompletionAgent CreateSpecificAgent(Kernel kernel)
{
    // Clone kernel instance to allow for agent specific plug-in definition
    Kernel agentKernel = kernel.Clone();

    // Create plug-in from a static function
    var functionFromMethod = agentKernel.CreateFunctionFromMethod(StatelessPlugin.AStaticMethod);

    // Create plug-in from a prompt
    var functionFromPrompt = agentKernel.CreateFunctionFromPrompt("<your prompt instructions>");

    // Add to the kernel
    agentKernel.ImportPluginFromFunctions("my_plugin", [functionFromMethod, functionFromPrompt]);

    // Create the agent
    return
        new ChatCompletionAgent()
        {
            Name = "<agent name>",
            Instructions = "<agent instructions>",
            Kernel = agentKernel,
            Arguments = new KernelArguments(
                new OpenAIPromptExecutionSettings()
                {
                    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
                })
        };
}
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel

# Create the instance of the Kernel
kernel = Kernel()

# Add the chat completion service to the Kernel
kernel.add_service(AzureChatCompletion())

# Create the AI Service settings
settings = AzureChatPromptExecutionSettings()

# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()

# Add the Plugin to the Kernel
kernel.add_function(
    plugin_name="<plugin_name>",
    function=KernelFunctionFromPrompt(
        function_name="<function_name>",
        prompt="<your prompt instructions>",
    )
)

# Create the agent
agent = ChatCompletionAgent(
    kernel=kernel,
    name=<agent name>,
    instructions=<agent instructions>,
    arguments=KernelArguments(settings=settings),
)
var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

// Create function from method
var functionFromMethod = KernelFunction.createFromMethod(SamplePlugin.class.getMethod("method"), new SamplePlugin());

// Create function from prompt
var functionFromPrompt = KernelFunction.createFromPrompt("<your prompt instructions>");

// Create the kernel with a plugin from the two functions
Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromFunctions("SamplePlugin", List.of(functionFromMethod, functionFromPrompt)))
    .build();

InvocationContext invocationContext = InvocationContext.builder()
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true))
    .build();

// Create the agent
var agent = ChatCompletionAgent.builder()
    .withKernel(kernel)
    .withName("<agent name>")
    .withInstructions("<agent instructions>")
    .withInvocationContext(invocationContext)
    .build();

代理功能呼叫的限制

當直接調用 aChatCompletionAgent 時,所有的功能選擇行為都是支持的。 不過,使用 OpenAIAssistant時,目前只能使用自動 函數呼叫

操作指南

如需使用函式呼叫的端對端範例,請參閱:

後續步驟