다음을 통해 공유


의미 체계 커널 템플릿에서 에이전트 만들기

의미 체계 커널의 프롬프트 템플릿

에이전트의 역할은 주로 수신하는 지침에 따라 형성되며, 이는 해당 동작과 동작을 지시합니다. 프롬프트를 호출하는 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에서 기능을 사용할 수 없습니다.

사용 방법

프롬프트 템플릿에이전트를 만드는 엔드 투 엔드 예제는 다음을 참조하세요.

다음 단계