다음을 통해 공유


에이전트 프레임워크 릴리스 후보판 마이그레이션 가이드

일부 에이전트를 실험 단계에서 릴리스 후보 단계로 전환하면서 사용을 간소화하고 효율화하기 위해 API를 업데이트했습니다. 사용 가능한 최신 API를 사용하도록 기존 코드를 업데이트하는 방법을 알아보려면 특정 시나리오 가이드를 참조하세요.

일반 에이전트 호출 API

버전 1.43.0에서는 공통 API를 통해 모든 에이전트 형식을 호출할 수 있는 새로운 공통 에이전트 호출 API를 릴리스합니다.

이 새로운 API를 사용하도록 설정하기 위해 대화 스레드를 나타내고 다른 에이전트 유형의 다양한 스레드 관리 요구 사항을 추상화하는 개념 AgentThread이 도입되었습니다. 일부 에이전트 형식의 경우 나중에 동일한 에이전트와 함께 다른 스레드 구현을 사용할 수 있습니다.

소개하는 일반적인 Invoke 메서드를 사용하면 에이전트에 전달하려는 메시지와 선택적 메시지를 제공할 수 있습니다 AgentThread. AgentThread이(가) 제공된 경우, 이미 AgentThread에 있는 대화를 계속합니다. 제공된 AgentThread이(가) 없으면 기본 스레드가 새로 생성되어 응답의 일부로 반환됩니다.

AgentThread 인스턴스를 수동으로 만드는 것도 가능합니다. 예를 들어 기본 에이전트 서비스에서 스레드 ID를 가지고 있으며 해당 스레드를 계속하려는 경우가 있습니다. 스레드에 대한 옵션(예: 도구 연결)을 사용자 지정할 수도 있습니다.

다음은 에이전트에 구애받지 않는 코드와 함께 모든 에이전트를 사용할 수 있는 방법의 간단한 예입니다.

private async Task UseAgentAsync(Agent agent, AgentThread? agentThread = null)
{
    // Invoke the agent, and continue the existing thread if provided.
    var responses = agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "Hi"), agentThread);

    // Output results.
    await foreach (AgentResponseItem<ChatMessageContent> response in responses)
    {
        Console.WriteLine(response);
        agentThread = response.Thread;
    }

    // Delete the thread if required.
    if (agentThread is not null)
    {
        await agentThread.DeleteAsync();
    }
}

이러한 변경 내용은 다음에서 적용되었습니다.

Azure AI 에이전트 스레드 옵션

AzureAIAgent 현재 AzureAIAgentThread형식의 스레드만 지원합니다.

에이전트 호출 시 자동으로 스레드를 만들 수 있도록 허용하는 것 외에도 인스턴스를 AzureAIAgentThread수동으로 생성할 수도 있습니다.

AzureAIAgentThread는 사용자 지정된 도구 및 메타데이터와 대화를 시작하는 메시지를 사용하여 생성하는 것을 지원합니다.

AgentThread thread = new AzureAIAgentThread(
    agentsClient,
    messages: seedMessages,
    toolResources: tools,
    metadata: metadata);

기존 대화를 계속하는 인스턴스를 AzureAIAgentThread 생성할 수도 있습니다.

AgentThread thread = new AzureAIAgentThread(
    agentsClient,
    id: "my-existing-thread-id");

Bedrock 에이전트 스레드 옵션

BedrockAgent 현재 BedrockAgentThread형식의 스레드만 지원합니다.

에이전트 호출 시 자동으로 스레드를 만들 수 있도록 허용하는 것 외에도 인스턴스를 BedrockAgentThread수동으로 생성할 수도 있습니다.

AgentThread thread = new BedrockAgentThread(amazonBedrockAgentRuntimeClient);

기존 대화를 계속하는 인스턴스를 BedrockAgentThread 생성할 수도 있습니다.

AgentThread thread = new BedrockAgentThread(
    amazonBedrockAgentRuntimeClient,
    sessionId: "my-existing-session-id");

채팅 완료 에이전트 스레드 옵션

ChatCompletionAgent 현재 ChatHistoryAgentThread형식의 스레드만 지원합니다. ChatHistoryAgentThread 는 메모리 ChatHistory 내 개체를 사용하여 스레드에 메시지를 저장합니다.

에이전트 호출 시 자동으로 스레드를 만들 수 있도록 허용하는 것 외에도 인스턴스를 ChatHistoryAgentThread수동으로 생성할 수도 있습니다.

AgentThread thread = new ChatHistoryAgentThread();

ChatHistoryAgentThread의 인스턴스를 생성하여 기존 메시지가 포함된 ChatHistory 객체를 전달함으로써 기존 대화를 계속할 수도 있습니다.

ChatHistory chatHistory = new([new ChatMessageContent(AuthorRole.User, "Hi")]);

AgentThread thread = new ChatHistoryAgentThread(chatHistory: chatHistory);

OpenAI 도우미 스레드 옵션

OpenAIAssistantAgent 현재 OpenAIAssistantAgentThread형식의 스레드만 지원합니다.

에이전트 호출 시 자동으로 스레드를 만들 수 있도록 허용하는 것 외에도 인스턴스를 OpenAIAssistantAgentThread수동으로 생성할 수도 있습니다.

OpenAIAssistantAgentThread는 사용자 지정된 도구 및 메타데이터와 대화를 시작하는 메시지를 사용하여 생성하는 것을 지원합니다.

AgentThread thread = new OpenAIAssistantAgentThread(
    assistantClient,
    messages: seedMessages,
    codeInterpreterFileIds: fileIds,
    vectorStoreId: "my-vector-store",
    metadata: metadata);

기존 대화를 계속하는 인스턴스를 OpenAIAssistantAgentThread 생성할 수도 있습니다.

AgentThread thread = new OpenAIAssistantAgentThread(
    assistantClient,
    id: "my-existing-thread-id");

OpenAIAssistantAgent C# 마이그레이션 가이드

최근에 OpenAIAssistantAgent 주변에서 의미 체계 커널 에이전트 프레임워크에 상당한 변화를 적용했습니다.

이러한 변경 내용은 다음에서 적용되었습니다.

이러한 변경 내용은 다음을 위한 것입니다.

  • AzureAIAgent을/를 사용하는 패턴에 맞춰 일치시킵니다.
  • 정적 초기화 패턴에 대한 버그를 수정합니다.
  • 기본 SDK의 추상화에 따라 기능을 제한하지 않습니다.

이 가이드에서는 C# 코드를 이전 구현에서 새 구현으로 마이그레이션하기 위한 단계별 지침을 제공합니다. 변경 내용에는 도우미 만들기, 도우미 수명 주기 관리, 스레드, 파일 및 벡터 저장소 처리에 대한 업데이트가 포함됩니다.

1. 클라이언트 인스턴스화

이전에 OpenAIClientProvider가 있어야만 아무 OpenAIAssistantAgent을 만들 수 있었습니다. 이 종속성이 간소화되었습니다.

새로운 방법

OpenAIClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(new AzureCliCredential(), new Uri(endpointUrl));
AssistantClient assistantClient = client.GetAssistantClient();

이전 방법(사용되지 않음)

var clientProvider = new OpenAIClientProvider(...);

2. 어시스턴트 수명 주기

도우미 만들기

이제 기존 또는 새로운 Assistant 정의를 사용하여 OpenAIAssistantAgent를 직접 인스턴스화할 수 있습니다.

새로운 방법
Assistant definition = await assistantClient.GetAssistantAsync(assistantId);
OpenAIAssistantAgent agent = new(definition, client);

플러그 인은 초기화 중에 직접 포함할 수 있습니다.

KernelPlugin plugin = KernelPluginFactory.CreateFromType<YourPlugin>();
Assistant definition = await assistantClient.GetAssistantAsync(assistantId);
OpenAIAssistantAgent agent = new(definition, client, [plugin]);

확장 메서드를 사용하여 새 도우미 정의를 만듭니다.

Assistant assistant = await assistantClient.CreateAssistantAsync(
    model,
    name,
    instructions: instructions,
    enableCodeInterpreter: true);
이전 방법(사용되지 않음)

이전에는 도우미 정의가 간접적으로 관리되었습니다.

3. 에이전트 호출

SDK의 기본 기능에 대한 모든 권한을 사용하도록 직접 RunCreationOptions을 지정할 수 있습니다.

새로운 방법

RunCreationOptions options = new(); // configure as needed
var result = await agent.InvokeAsync(options);

이전 방법(사용되지 않음)

var options = new OpenAIAssistantInvocationOptions();

4. 도우미 삭제

도우미 삭제를 AssistantClient를 사용하여 직접 관리할 수 있습니다.

await assistantClient.DeleteAssistantAsync(agent.Id);

5. 스레드 수명 주기

스레드 만들기

이제 스레드는 .를 통해 AssistantAgentThread관리됩니다.

새로운 방법
var thread = new AssistantAgentThread(assistantClient);
// Calling CreateAsync is an optional step.
// A thread will be created automatically on first use if CreateAsync was not called.
// Note that CreateAsync is not on the AgentThread base implementation since not all
// agent services support explicit thread creation.
await thread.CreateAsync();
이전 방법(사용되지 않음)

이전에는 스레드 관리가 간접 또는 에이전트 바인딩되었습니다.

스레드 삭제

var thread = new AssistantAgentThread(assistantClient, "existing-thread-id");
await thread.DeleteAsync();

6. 파일 수명 주기

이제 파일 만들기 및 삭제가 활용됩니다 OpenAIFileClient.

파일 업로드

string fileId = await client.UploadAssistantFileAsync(stream, "<filename>");

파일 삭제

await client.DeleteFileAsync(fileId);

7. 벡터 저장소 수명 주기

벡터 저장소는 편리한 확장 방법을 통해 VectorStoreClient 직접 관리됩니다.

벡터 저장소 만들기

string vectorStoreId = await client.CreateVectorStoreAsync([fileId1, fileId2], waitUntilCompleted: true);

벡터 저장소 삭제

await client.DeleteVectorStoreAsync(vectorStoreId);

이전 버전과의 호환성

사용되지 않는 패턴은 .로 [Obsolete]표시됩니다. 사용되지 않는 경고(CS0618)를 억제하려면, 프로젝트 파일을 다음과 같이 업데이트합니다.

<PropertyGroup>
  <NoWarn>$(NoWarn);CS0618</NoWarn>
</PropertyGroup>

이 마이그레이션 가이드를 사용하면 새 구현으로 원활하게 전환하여 클라이언트 초기화, 리소스 관리 및 의미 체계 커널 .NET SDK와의 통합을 간소화할 수 있습니다.

중요합니다

의미 체계 커널 Python 1.26.1 이상으로 업그레이드하는 개발자를 위해, GA가 다가옴에 따라 에이전트 프레임워크를 개선하기 위해 중요한 업데이트와 호환성에 영향을 미치는 변경 사항이 도입되었습니다.

이러한 변경 내용은 다음에서 적용되었습니다.

이전 변경 내용은 다음에서 적용되었습니다.

이 가이드에서는 이전 구현에서 새 구현으로 Python 코드를 마이그레이션하기 위한 단계별 지침을 제공합니다.

에이전트 가져오기

모든 에이전트 가져오기 경로가 semantic_kernel.agents 아래로 통합되었습니다.

업데이트된 가져오기 스타일

from semantic_kernel.agents import (
    AutoGenConversableAgent,
    AzureAIAgent,
    AzureAssistantAgent,
    BedrockAgent,
    ChatCompletionAgent,
    OpenAIAssistantAgent,
)

이전 가져오기 스타일(사용되지 않음):

from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.agents.autogen import AutoGenConversableAgent
from semantic_kernel.agents.azure_ai import AzureAIAgent
from semantic_kernel.agents.bedrock import BedrockAgent
from semantic_kernel.agents.open_ai import AzureAssistantAgent, OpenAIAssistantAgent

일반 에이전트 호출 API

의미 체계 커널 Python 1.26.0 이상을 기준으로 모든 에이전트에 대한 스레드를 관리하는 새로운 일반적인 추상화가 도입되었습니다. 이제 각 에이전트에 대해 기본 클래스를 구현하는 스레드 클래스를 AgentThread 노출하여 다음과 같은 create()delete()메서드를 통해 컨텍스트 관리를 허용합니다.

에이전트 응답 get_response(...), invoke(...), invoke_stream(...)은 이제 두 가지 특성이 있는 AgentResponseItem[ChatMessageContent]을 반환합니다.

message: TMessage  # Usually ChatMessageContent
thread: AgentThread  # Contains the concrete type for the given agent

스레드에 메시지 추가

에이전트 messagesget_response(...) 또는 invoke(...) 메서드의 일부로 인수를 invoke_stream(...) 통해 스레드에 메시지를 추가해야 합니다.

Azure AI 에이전트 스레드

다음과 같이 AzureAIAgentThread를 만들 수 있습니다.

from semantic_kernel.agents import AzureAIAgentThread

thread = AzureAIAgentThread(
    client: AIProjectClient,  # required
    messages: list[ThreadMessageOptions] | None = None,  # optional
    metadata: dict[str, str] | None = None,  # optional
    thread_id: str | None = None,  # optional
    tool_resources: "ToolResources | None" = None,  # optional
)

(문자열)을 thread_id 제공하면 기존 대화를 계속할 수 있습니다. 생략하면 새 스레드가 만들어지고 에이전트 응답의 일부로 반환됩니다.

전체 구현 예제:

import asyncio

from azure.identity.aio import DefaultAzureCredential

from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread

USER_INPUTS = [
    "Why is the sky blue?",
    "What are we talking about?",
]

async def main() -> None:
    ai_agent_settings = AzureAIAgentSettings.create()

    async with (
        DefaultAzureCredential() as creds,
        AzureAIAgent.create_client(credential=creds) as client,
    ):
        # 1. Create an agent on the Azure AI agent service
        agent_definition = await client.agents.create_agent(
            model=ai_agent_settings.model_deployment_name,
            name="Assistant",
            instructions="Answer the user's questions.",
        )

        # 2. Create a Semantic Kernel agent for the Azure AI agent
        agent = AzureAIAgent(
            client=client,
            definition=agent_definition,
        )

        # 3. Create a thread for the agent
        # If no thread is provided, a new thread will be
        # created and returned with the initial response
        thread: AzureAIAgentThread = None

        try:
            for user_input in USER_INPUTS:
                print(f"# User: {user_input}")
                # 4. Invoke the agent with the specified message for response
                response = await agent.get_response(messages=user_input, thread=thread)
                print(f"# {response.content}: {response}")
                thread = response.thread
        finally:
            # 6. Cleanup: Delete the thread and agent
            await thread.delete() if thread else None
            await client.agents.delete_agent(agent.id)

if __name__ == "__main__":
    asyncio.run(main())

Bedrock 에이전트 스레드

BedrockAgentBedrockAgentThread을 사용하여 대화 기록 및 컨텍스트를 관리합니다. 대화 컨텍스트를 계속하거나 새로 시작하기 위해 session_id를 제공할 수 있습니다.

from semantic_kernel.agents import BedrockAgentThread

thread = BedrockAgentThread(
    bedrock_runtime_client: Any,
    session_id: str | None = None,
)

session_id이 제공되지 않으면 새 컨텍스트가 자동으로 만들어집니다.

전체 구현 예제:

import asyncio

from semantic_kernel.agents import BedrockAgent, BedrockAgentThread

async def main():
    bedrock_agent = await BedrockAgent.create_and_prepare_agent(
        "semantic-kernel-bedrock-agent",
        instructions="You are a friendly assistant. You help people find information.",
    )

    # Create a thread for the agent
    # If no thread is provided, a new thread will be
    # created and returned with the initial response
    thread: BedrockAgentThread = None

    try:
        while True:
            user_input = input("User:> ")
            if user_input == "exit":
                print("\n\nExiting chat...")
                break

            # Invoke the agent
            # The chat history is maintained in the session
            response = await bedrock_agent.get_response(
                input_text=user_input,
                thread=thread,
            )
            print(f"Bedrock agent: {response}")
            thread = response.thread
    except KeyboardInterrupt:
        print("\n\nExiting chat...")
        return False
    except EOFError:
        print("\n\nExiting chat...")
        return False
    finally:
        # Delete the agent
        await bedrock_agent.delete_agent()
        await thread.delete() if thread else None


if __name__ == "__main__":
    asyncio.run(main())

채팅 기록 담당자 스레드

ChatCompletionAgent은/는 ChatHistoryAgentThread을/를 사용하여 대화 기록을 관리합니다. 다음과 같이 초기화할 수 있습니다.

from semantic_kernel.agents import ChatHistoryAgentThread

thread = ChatHistoryAgentThread(
    chat_history: ChatHistory | None = None, 
    thread_id: str | None = None
)

thread_id를 제공함으로써 기존 대화를 계속할 수 있습니다. 생략하면 새 스레드가 만들어집니다. 스레드 상태의 직렬화 및 리하일레이션은 영구 대화 컨텍스트에 대해 지원됩니다.

전체 구현 예제:

import asyncio

from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion

# Simulate a conversation with the agent
USER_INPUTS = [
    "Hello, I am John Doe.",
    "What is your name?",
    "What is my name?",
]


async def main():
    # 1. Create the agent by specifying the service
    agent = ChatCompletionAgent(
        service=AzureChatCompletion(),
        name="Assistant",
        instructions="Answer the user's questions.",
    )

    # 2. Create a thread to hold the conversation
    # If no thread is provided, a new thread will be
    # created and returned with the initial response
    thread: ChatHistoryAgentThread = None

    for user_input in USER_INPUTS:
        print(f"# User: {user_input}")
        # 3. Invoke the agent for a response
        response = await agent.get_response(
            messages=user_input,
            thread=thread,
        )
        print(f"# {response.name}: {response}")
        # 4. Store the thread, which allows the agent to
        # maintain conversation history across multiple messages.
        thread = response.thread

    # 5. Cleanup: Clear the thread
    await thread.delete() if thread else None

if __name__ == "__main__":
    asyncio.run(main())

OpenAI 도우미 스레드

AzureAssistantAgentOpenAIAssistantAgent는 대화 기록과 컨텍스트를 관리하기 위해 AssistantAgentThread를 사용합니다.

from semantic_kernel.agents import ChatHistoryAgentThread

thread = AssistantAgentThread(
    client: AsyncOpenAI,
    thread_id: str | None = None,
    messages: Iterable["ThreadCreateMessage"] | NotGiven = NOT_GIVEN,
    metadata: dict[str, Any] | NotGiven = NOT_GIVEN,
    tool_resources: ToolResources | NotGiven = NOT_GIVEN,
)

기존 대화에 thread_id를 제공하면 대화가 계속되고, 그렇지 않으면 새 스레드가 생성됩니다.

전체 구현 예제:

# Copyright (c) Microsoft. All rights reserved.
import asyncio

from semantic_kernel.agents import AzureAssistantAgent


# Simulate a conversation with the agent
USER_INPUTS = [
    "Why is the sky blue?",
    "What is the speed of light?",
    "What have we been talking about?",
]


async def main():
    # 1. Create the client using Azure OpenAI resources and configuration
    client, model = AzureAssistantAgent.setup_resources()

    # 2. Create the assistant on the Azure OpenAI service
    definition = await client.beta.assistants.create(
        model=model,
        instructions="Answer questions about the world in one sentence.",
        name="Assistant",
    )

    # 3. Create a Semantic Kernel agent for the Azure OpenAI assistant
    agent = AzureAssistantAgent(
        client=client,
        definition=definition,
    )

    # 4. Create a new thread for use with the assistant
    # If no thread is provided, a new thread will be
    # created and returned with the initial response
    thread = None

    try:
        for user_input in USER_INPUTS:
            print(f"# User: '{user_input}'")
            # 6. Invoke the agent for the current thread and print the response
            response = await agent.get_response(messages=user_input, thread=thread)
            print(f"# {response.name}: {response}")
            thread = response.thread

    finally:
        # 7. Clean up the resources
        await thread.delete() if thread else None
        await agent.client.beta.assistants.delete(assistant_id=agent.id)


if __name__ == "__main__":
    asyncio.run(main())

에이전트 호출에 대한 메시지 입력

이전 구현에서는 get_response(...), invoke(...), 및 invoke_stream(...)와 같은 메서드에 단일 메시지 입력만 허용했습니다. 이제 여러 messages (str | ChatMessageContent | list[str | ChatMessageContent])메서드를 지원하도록 이러한 메서드를 업데이트했습니다. 메시지 입력은 키워드 인수(예: messages 또는 agent.get_response(messages="user input").)를 사용하여 agent.invoke(messages="user input") 전달해야 합니다.

에이전트 호출 방법에는 다음과 같은 업데이트가 필요합니다.

이전 방법

response = await agent.get_response(message="some user input", thread=thread)

새로운 방법

response = await agent.get_response(messages=["some initial inputer", "other input"], thread=thread)

AzureAIAgent

Semantic Kernel Python 1.26.0 이상 버전에서는 AzureAIAgent 개체를 통해 스레드 생성이 관리되며, 이제 클라이언트에서 직접 관리되지 않습니다.

이전 방법

thread = await client.agents.create_thread()

새로운 방법

from semantic_kernel.agents import AzureAIAgentThread

thread = AzureAIAgentThread(
    client: AIProjectClient,  # required
    messages: list[ThreadMessageOptions] | None = None,  # optional
    metadata: dict[str, str] | None = None,  # optional
    thread_id: str | None = None,  # optional
    tool_resources: "ToolResources | None" = None,  # optional
)

처음에 thread_id가 제공되지 않으면, 새 스레드가 만들어져 에이전트 응답에서 반환됩니다.

ChatCompletionAgent

ChatCompletionAgent 서비스 구성, 플러그 인 처리 및 함수 호출 동작을 간소화하도록 업데이트되었습니다. 다음은 마이그레이션할 때 고려해야 할 주요 변경 내용입니다.

1. 서비스 지정

이제 에이전트 생성자의 일부로 서비스를 직접 지정할 수 있습니다.

새로운 방법

from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion

agent = ChatCompletionAgent(
    service=AzureChatCompletion(),
    name="<name>",
    instructions="<instructions>",
)

참고: 커널과 서비스가 모두 제공되는 경우, 동일한 service_id 및 ai_model_id를 공유하면 서비스가 우선적으로 적용됩니다. 그렇지 않으면 별도의 경우 커널에 등록된 첫 번째 AI 서비스가 사용됩니다.

이전 방법(여전히 유효)

이전에는 먼저 커널에 서비스를 추가한 다음, 커널을 에이전트에 전달했습니다.

from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion

kernel = Kernel()
kernel.add_service(AzureChatCompletion())

agent = ChatCompletionAgent(
    kernel=kernel,
    name="<name>",
    instructions="<instructions>",
)

2. 플러그 인 추가

이제 생성자를 통해 플러그 인을 직접 제공할 수 있습니다.

새로운 방법

from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion

agent = ChatCompletionAgent(
    service=AzureChatCompletion(),
    name="<name>",
    instructions="<instructions>",
    plugins=[SamplePlugin()],
)

이전 방법(여전히 유효)

이전에 플러그 인을 커널에 별도로 추가해야 했습니다.

from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion

kernel = Kernel()
kernel.add_plugin(SamplePlugin())

agent = ChatCompletionAgent(
    kernel=kernel,
    name="<name>",
    instructions="<instructions>",
)

참고: 두 방법 모두 유효하지만 플러그 인을 직접 지정하면 초기화가 간소화됩니다.

3. 에이전트 호출

이제 에이전트를 호출하는 두 가지 방법이 있습니다. 새 메서드는 단일 응답을 직접 검색하지만 이전 메서드는 스트리밍을 지원합니다.

새 방법(대화 스레드/컨텍스트 없음)

response = await agent.get_response(messages="user input")
# response is of type AgentResponseItem[ChatMessageContent]

참고: 다음 응답에서 반환된 스레드를 사용하지 않는 경우 대화는 새 스레드를 사용하므로 이전 컨텍스트를 계속 진행하지 않습니다.

새 방법(컨텍스트를 사용하는 단일 응답)

thread = ChatHistoryAgentThread()

for user_input in ["First user input", "Second User Input"]:
    response = await agent.get_response(messages=user_input, thread=thread)
    # response is of type AgentResponseItem[ChatMessageContent]
    thread = response.thread

이전 방법(더 이상 유효하지 않음)

chat_history = ChatHistory()
chat_history.add_user_message("<user_input>")
response = agent.get_response(message="user input", chat_history=chat_history)

4. 함수 호출 제어

이제 에이전트 생성자 내에서 서비스를 지정할 때 함수 호출 동작을 직접 제어할 수 있습니다.

agent = ChatCompletionAgent(
    service=AzureChatCompletion(),
    name="<name>",
    instructions="<instructions>",
    plugins=[MenuPlugin()],
    function_choice_behavior=FunctionChoiceBehavior.Auto(
        filters={"included_functions": ["get_specials", "get_item_price"]}
    ),
)

참고: 이전에는 함수 호출 구성에 커널 또는 서비스 개체에 대한 별도의 설정이 필요했습니다. 실행 설정이 AI 서비스 구성에서 지정한 service_id 또는 ai_model_id와 동일한 경우, 실행 설정에 정의된 함수 호출 동작(KernelArguments 통해)이 생성자에 설정된 함수 선택 동작보다 우선합니다.

이러한 업데이트는 간결성과 구성성을 향상시켜 ChatCompletionAgent를 더 쉽게 통합하고 유지 관리할 수 있도록 합니다.

OpenAIAssistantAgent

AzureAssistantAgent OpenAIAssistantAgent 변경 내용에는 도우미 만들기, 스레드 만들기, 플러그 인 처리, 코드 인터프리터 도구 사용, 파일 검색 도구 작업 및 스레드에 채팅 메시지 추가에 대한 업데이트가 포함됩니다.

리소스 설정

이전 방법

AsyncAzureOpenAI 에이전트 개체를 만드는 과정의 일부로 클라이언트가 만들어졌습니다.

agent = await AzureAssistantAgent.create(
    deployment_name="optional-deployment-name",
    api_key="optional-api-key",
    endpoint="optional-endpoint",
    ad_token="optional-ad-token",
    ad_token_provider=optional_callable,
    default_headers={"optional_header": "optional-header-value"},
    env_file_path="optional-env-file-path",
    env_file_encoding="optional-env-file-encoding",
    ...,
)

새로운 방법

에이전트는 지정된 리소스에 필요한 클라이언트를 만드는 정적 메서드를 제공합니다. 여기서 메서드 수준 키워드 인수는 기존 .env 파일의 환경 변수 및 값보다 우선합니다.

client, model = AzureAssistantAgent.setup_resources(
    ad_token="optional-ad-token",
    ad_token_provider=optional_callable,
    api_key="optional-api-key",
    api_version="optional-api-version",
    base_url="optional-base-url",
    default_headers="optional-default-headers",
    deployment_name="optional-deployment-name",
    endpoint="optional-endpoint",
    env_file_path="optional-env-file-path",
    env_file_encoding="optional-env-file-encoding",
    token_scope="optional-token-scope",
)

1. 도우미 만들기

이전 방법

agent = await AzureAssistantAgent.create(
    kernel=kernel,
    service_id=service_id,
    name=AGENT_NAME,
    instructions=AGENT_INSTRUCTIONS,
    enable_code_interpreter=True,
)

또는

agent = await OpenAIAssistantAgent.create(
    kernel=kernel,
    service_id=service_id,
    name=<name>,
    instructions=<instructions>,
    enable_code_interpreter=True,
)

새로운 방법

# Azure AssistantAgent 

# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()

# Create the assistant definition
definition = await client.beta.assistants.create(
    model=model,
    instructions="<instructions>",
    name="<name>",
)

# Create the agent using the client and the assistant definition
agent = AzureAssistantAgent(
    client=client,
    definition=definition,
)

또는

# OpenAI Assistant Agent

# Create the client using OpenAI resources and configuration
client, model = OpenAIAssistantAgent.setup_resources()

# Create the assistant definition
definition = await client.beta.assistants.create(
    model=model,
    instructions="<instructions>",
    name="<name>",
)

# Create the agent using the client and the assistant definition
agent = OpenAIAssistantAgent(
    client=client,
    definition=definition,
)

2. 스레드 만들기

이전 방법

thread_id = await agent.create_thread()

새로운 방법

from semantic_kernel.agents AssistantAgentThread, AzureAssistantAgent

client, model = AzureAssistantAgent.setup_resources()

# You may create a thread based on an existing thread id
# thread = AssistantAgentThread(client=client, thread_id="existing-thread-id")
# Otherwise, if not specified, a thread will be created during the first invocation
# and returned as part of the response
thread = None

async for response in agent.invoke(messages="user input", thread=thread):
    # handle response
    print(response)
    thread = response.thread

3. 플러그 인 처리

이전 방법

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

# Add the sample plugin to the kernel
kernel.add_plugin(plugin=MenuPlugin(), plugin_name="menu")

agent = await AzureAssistantAgent.create(
    kernel=kernel, 
    name="<name>", 
    instructions="<instructions>"
)

참고: 커널을 통해 플러그 인을 관리할 수 있습니다. 커널을 제공하지 않으면 에이전트를 만들 때 커널이 자동으로 만들어지고 플러그 인이 해당 인스턴스에 추가됩니다.

새로운 방법

# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()

# Create the assistant definition
definition = await client.beta.assistants.create(
    model=model,
    instructions="<instructions>",
    name="<name>",
)

# Create the agent with plugins passed in as a list
agent = AzureAssistantAgent(
    client=client,
    definition=definition,
    plugins=[MenuPlugin()],
)

자세한 내용은 샘플 구현 을 참조하세요.

4. 코드 인터프리터 도구 사용

이전 방법

csv_file_path = ...

agent = await AzureAssistantAgent.create(
    kernel=kernel,
    name="<name>",
    instructions="<instructions>",
    enable_code_interpreter=True,
    code_interpreter_filenames=[csv_file_path],
)

새로운 방법

# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()

csv_file_path = ...

# Load the CSV file as a FileObject
with open(csv_file_path, "rb") as file:
    file = await client.files.create(file=file, purpose="assistants")

# Get the code interpreter tool and resources
code_interpreter_tool, code_interpreter_tool_resource = AzureAssistantAgent.configure_code_interpreter_tool(file.id)

# Create the assistant definition
definition = await client.beta.assistants.create(
    model=model,
    name="<name>",
    instructions="<instructions>.",
    tools=code_interpreter_tool,
    tool_resources=code_interpreter_tool_resource,
)

# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
    client=client,
    definition=definition,
)

자세한 내용은 샘플 구현 을 참조하세요.

5. 파일 검색 도구 사용

이전 방법

pdf_file_path = ...

agent = await AzureAssistantAgent.create(
    kernel=kernel,
    service_id=service_id,
    name=AGENT_NAME,
    instructions=AGENT_INSTRUCTIONS,
    enable_file_search=True,
    vector_store_filenames=[pdf_file_path],
)

새로운 방법

# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()

pdf_file_path = ...

# Load the employees PDF file as a FileObject
with open(pdf_file_path, "rb") as file:
    file = await client.files.create(file=file, purpose="assistants")

# Create a vector store specifying the file ID to be used for file search
vector_store = await client.beta.vector_stores.create(
    name="step4_assistant_file_search",
    file_ids=[file.id],
)

file_search_tool, file_search_tool_resources = AzureAssistantAgent.configure_file_search_tool(vector_store.id)

# Create the assistant definition
definition = await client.beta.assistants.create(
    model=model,
    instructions="Find answers to the user's questions in the provided file.",
    name="FileSearch",
    tools=file_search_tool,
    tool_resources=file_search_tool_resources,
)

# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
    client=client,
    definition=definition,
)

자세한 내용은 샘플 구현 을 참조하세요.

6. 스레드에 채팅 메시지 추가

이전 방법

await agent.add_chat_message(
    thread_id=thread_id, 
    message=ChatMessageContent(role=AuthorRole.USER, content=user_input)
)

새로운 방법

참고: 이전 메서드는 전달 ChatMessageContent하면 계속 작동하지만 이제 간단한 문자열을 전달할 수도 있습니다.

await agent.add_chat_message(
    thread_id=thread_id, 
    message=user_input,
)

7. 리소스 정리

이전 방법

await agent.delete_file(file_id)
await agent.delete_thread(thread_id)
await agent.delete()

새로운 방법

await client.files.delete(file_id)
await thread.delete()
await client.beta.assistants.delete(agent.id)

구조적 출력 처리

이전 방법

이전 방식으로 사용할 수 없음

새로운 방법

# Define a Pydantic model that represents the structured output from the OpenAI service
class ResponseModel(BaseModel):
    response: str
    items: list[str]

# Create the client using Azure OpenAI resources and configuration
client, model = AzureAssistantAgent.setup_resources()

# Create the assistant definition
definition = await client.beta.assistants.create(
    model=model,
    name="<name>",
    instructions="<instructions>",
    response_format=AzureAssistantAgent.configure_response_format(ResponseModel),
)

# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
    client=client,
    definition=definition,
)

자세한 내용은 샘플 구현 을 참조하세요.

이 마이그레이션 가이드는 클라이언트 기반 구성 및 향상된 기능을 활용하여 코드를 새 구현으로 업데이트하는 데 도움이 됩니다.

Java에서는 에이전트를 사용할 수 없습니다.