次の方法で共有


セマンティック カーネル テンプレートからエージェントを作成する

セマンティック カーネルのプロンプト テンプレート

エージェントの役割は、主に受け取る命令によって形成され、その動作とアクションが決まります。 Kernel promptの呼び出しと同様に、エージェントの命令には、実行中に動的に置換されるテンプレート化されたパラメーター (値と関数の両方) を含めることができます。 これにより、柔軟でコンテキストに対応した応答が可能になり、エージェントはリアルタイム入力に基づいて出力を調整できます。

さらに、プロンプト テンプレート構成を使用してエージェントを直接構成できます。これにより、開発者は構造化された再利用可能な方法で動作を定義できます。 このアプローチは、エージェントの指示を標準化およびカスタマイズするための強力なツールを提供し、動的な適応性を維持しながら、さまざまなユース ケース間で一貫性を確保します。

機能は現在 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" },
        }
    };
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を使用する場合に特に強力です。 この方法では、特定のタスクまたはコンテキストに合わせて調整された異なるパラメーター値を使用して、1 つのアシスタント定義を複数回作成して再利用できます。 これにより、より効率的なセットアップが可能になり、同じアシスタント フレームワークがコア動作の一貫性を維持しながら、さまざまなシナリオを処理できるようになります。

// 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 では使用できません。

使い方

prompt-templateからエージェントを作成するエンド ツー エンドの例については、次を参照してください。

次のステップ