共用方式為


從語意核心範本建立代理程式

語意核心的提示模板

代理程式的角色主要是由收到的指示所塑造,其決定其行為和動作。 類似於叫用Kernel提示,代理程式的指示可以包含範本化參數,包括執行期間動態替代的值和函式。 這可讓彈性的內容感知回應,讓代理程式根據即時輸入調整其輸出。

此外,您可以使用提示範本設定直接設定代理程式,為開發人員提供結構化且可重複使用的方式來定義其行為。 此方法提供功能強大的工具,可標準化和自定義代理程式指示,確保各種使用案例的一致性,同時仍維持動態適應性。

Java 中目前無法使用的功能。

代理程式指示做為範本

使用範本參數建立代理程式,可讓您根據不同的案例或需求輕鬆地自定義其指示,以提供更大的彈性。 此方法可透過將特定值或函式插入範本來量身訂製代理的行為,使其能夠適應各種任務或情境。 藉由利用範本參數,開發人員可以設計更多功能的代理程式,以符合不同的使用案例,而不需要修改核心邏輯。

聊天完成代理程式

// Initialize a Kernel with a chat-completion service
Kernel kernel = ...;

var instructions = "Tell a story about {{$topic}} that is {{$length}} sentences long.";

ChatCompletionAgent agent =
    new(templateFactory: new KernelPromptTemplateFactory(),
        templateConfig: new(instructions) { TemplateFormat = PromptTemplateConfig.SemanticKernelTemplateFormat })
    {
        Kernel = kernel,
        Name = "StoryTeller",
        Arguments = new KernelArguments()
        {
            { "topic", "Dog" },
            { "length", "3" },
        }
    };
agent = ChatCompletionAgent(
    service=AzureChatCompletion(), # or other supported AI Services
    name="StoryTeller",
    instructions="Tell a story about {{$topic}} that is {{$length}} sentences long.",
    arguments=KernelArguments(topic="Dog", length="2"),
)

Java 中目前無法使用的功能。

OpenAI 助理代理

使用 OpenAIAssistantAgent時,範本化指示特別強大。 透過這種方法,可以建立單一助理定義並重複使用多次,每次使用不同的參數值,針對特定工作或內容量身打造。 這可讓設定更有效率,讓相同的小幫手架構處理各種案例,同時維持其核心行為的一致性。

// Retrieve an existing assistant definition by identifier
AzureOpenAIClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(new AzureCliCredential(), new Uri("<your endpoint>"));
AssistantClient assistantClient = client.GetAssistantClient();
Assistant assistant = await client.GetAssistantAsync();
OpenAIAssistantAgent agent = new(assistant, assistantClient, new KernelPromptTemplateFactory(), PromptTemplateConfig.SemanticKernelTemplateFormat)
{
    Arguments = new KernelArguments()
    {
        { "topic", "Dog" },
        { "length", "3" },
    }
}
# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()

# Retrieve the assistant definition from the server based on the assistant ID
definition = await client.beta.assistants.retrieve(
    assistant_id="your-assistant-id",
)

# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
    client=client,
    definition=definition,
    arguments=KernelArguments(topic="Dog", length="3"),
)

Java 中目前無法使用的功能。

預設範本中的代理定義

您也可以使用用於建立核心提示功能的提示範本組態來定義代理。 這可讓統一方法來管理提示和代理程式,促進不同元件的一致性和重複使用。 透過從程式代碼基底外部化代理程式定義,這個方法可簡化多個代理程式的管理,使其更容易更新和維護,而不需要變更基礎邏輯。 此區隔也可提升彈性,讓開發人員只要更新設定,即可修改代理程序行為或引進新的代理程式,而不是調整程序代碼本身。

YAML 範本

name: GenerateStory
template: |
  Tell a story about {{$topic}} that is {{$length}} sentences long.
template_format: semantic-kernel
description: A function that generates a story about a topic.
input_variables:
  - name: topic
    description: The topic of the story.
    is_required: true
  - name: length
    description: The number of sentences in the story.
    is_required: true

代理程式初始化

// Read YAML resource
string generateStoryYaml = File.ReadAllText("./GenerateStory.yaml");
// Convert to a prompt template config
PromptTemplateConfig templateConfig = KernelFunctionYaml.ToPromptTemplateConfig(generateStoryYaml);

// Create agent with Instructions, Name and Description
// provided by the template config.
ChatCompletionAgent agent =
    new(templateConfig)
    {
        Kernel = this.CreateKernelWithChatCompletion(),
        // Provide default values for template parameters
        Arguments = new KernelArguments()
        {
            { "topic", "Dog" },
            { "length", "3" },
        }
    };
import yaml

from semantic_kernel.prompt_template import PromptTemplateConfig

# Read the YAML file
with open("./GenerateStory.yaml", "r", encoding="utf-8") as file:
    generate_story_yaml = file.read()

# Parse the YAML content
data = yaml.safe_load(generate_story_yaml)

# Use the parsed data to create a PromptTemplateConfig object
prompt_template_config = PromptTemplateConfig(**data)

agent = ChatCompletionAgent(
    service=AzureChatCompletion(), # or other supported AI services
    prompt_template_config=prompt_template_config,
    arguments=KernelArguments(topic="Dog", length="3"),
)

Java 中目前無法使用的功能。

覆寫直接調用的範本值

直接叫用代理程式時,可以視需要覆寫代理程式的參數。 這可讓您在特定工作期間更充分地控制及自定義代理程序的行為,讓您能夠即時修改其指示或設定,以符合特定需求。

// Initialize a Kernel with a chat-completion service
Kernel kernel = ...;

ChatCompletionAgent agent =
    new()
    {
        Kernel = kernel,
        Name = "StoryTeller",
        Instructions = "Tell a story about {{$topic}} that is {{$length}} sentences long.",
        Arguments = new KernelArguments()
        {
            { "topic", "Dog" },
            { "length", "3" },
        }
    };

KernelArguments overrideArguments =
    new()
    {
        { "topic", "Cat" },
        { "length", "3" },
    });

// Generate the agent response(s)
await foreach (ChatMessageContent response in agent.InvokeAsync([], options: new() { KernelArguments = overrideArguments }))
{
  // Process agent response(s)...
}
agent = ChatCompletionAgent(
    service=AzureChatCompletion(),
    name="StoryTeller",
    instructions="Tell a story about {{$topic}} that is {{$length}} sentences long.",
    arguments=KernelArguments(topic="Dog", length="2"),
)

# Create a thread to maintain the conversation state
# If no threaded is created, a thread will be returned
# with the initial response
thread = None

override_arguments = KernelArguments(topic="Cat", length="3")

# Two ways to get a response from the agent

# Get the response which returns a ChatMessageContent directly
response = await agent.get_response(messages="user input", arguments=override_arguments)
thread = response.thread

# or use the invoke method to return an AsyncIterable of ChatMessageContent
async for response in agent.invoke(messages="user input", arguments=override_arguments):
    # process agent response(s)...
    thread = response.thread

Java 中目前無法使用的功能。

操作指南

如需一個從 提示範本建立代理的端到端範例,請參閱:

後續步驟