Microsoft Agent Framework의 이점
- 간소화된 API: 복잡성 감소 및 상용구 코드.
- 성능 향상: 최적화된 개체 만들기 및 메모리 사용.
- 통합 인터페이스: 여러 AI 공급자의 일관된 패턴입니다.
- 향상된 개발자 환경: 보다 직관적이고 검색 가능한 API입니다.
다음 섹션에서는 코드를 마이그레이션하는 데 도움이 되는 의미 체계 커널 에이전트 프레임워크와 Microsoft 에이전트 프레임워크 간의 주요 차이점을 요약합니다.
1. 네임스페이스 업데이트
시맨틱 커널
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
에이전트 프레임워크
에이전트 프레임워크 네임스페이스는 아래에 Microsoft.Agents.AI있습니다.
에이전트 프레임워크는 핵심 AI 메시지와 콘텐츠 형식 Microsoft.Extensions.AI 을 구성 요소 간 통신에 사용합니다.
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;
2. 에이전트 만들기 간소화
시맨틱 커널
의미 체계 커널의 모든 에이전트는 인스턴스에 Kernel 따라 달라지며 제공되지 않으면 비어 Kernel 있습니다.
Kernel kernel = Kernel
.AddOpenAIChatClient(modelId, apiKey)
.Build();
ChatCompletionAgent agent = new() { Instructions = ParrotInstructions, Kernel = kernel };
Azure AI Foundry는 에이전트 리소스를 사용하는 로컬 에이전트 클래스를 만들기 전에 클라우드에서 에이전트 리소스를 만들어야 합니다.
PersistentAgentsClient azureAgentClient = AzureAIAgent.CreateAgentsClient(azureEndpoint, new AzureCliCredential());
PersistentAgent definition = await azureAgentClient.Administration.CreateAgentAsync(
deploymentName,
instructions: ParrotInstructions);
AzureAIAgent agent = new(definition, azureAgentClient);
에이전트 프레임워크
에이전트 프레임워크에서 에이전트를 만드는 방법은 모든 주 공급자가 제공하는 확장을 사용하여 더 간단하게 만들 수 있습니다.
AIAgent openAIAgent = chatClient.CreateAIAgent(instructions: ParrotInstructions);
AIAgent azureFoundryAgent = await persistentAgentsClient.CreateAIAgentAsync(instructions: ParrotInstructions);
AIAgent openAIAssistantAgent = await assistantClient.CreateAIAgentAsync(instructions: ParrotInstructions);
또한 호스트된 에이전트 공급자의 경우 이 메서드를 사용하여 GetAIAgent 기존 호스트된 에이전트에서 에이전트를 검색할 수도 있습니다.
AIAgent azureFoundryAgent = await persistentAgentsClient.GetAIAgentAsync(agentId);
3. 에이전트 스레드 만들기
시맨틱 커널
호출자는 스레드 유형을 알고 수동으로 만들어야 합니다.
// Create a thread for the agent conversation.
AgentThread thread = new OpenAIAssistantAgentThread(this.AssistantClient);
AgentThread thread = new AzureAIAgentThread(this.Client);
AgentThread thread = new OpenAIResponseAgentThread(this.Client);
에이전트 프레임워크
에이전트는 스레드를 만드는 역할을 담당합니다.
// New.
AgentThread thread = agent.GetNewThread();
4. 호스트된 에이전트 스레드 정리
이 사례는 호스트된 스레드를 여전히 제공하는 몇 가지 AI 공급자에만 적용됩니다.
시맨틱 커널
스레드에는 삭제 메서드가 self 있습니다.
OpenAI Assistants 공급자:
await thread.DeleteAsync();
에이전트 프레임워크
비고
OpenAI 응답은 대화 처리 방법을 간소화하는 새로운 대화 모델을 도입했습니다. 이 변경은 현재 사용되지 않는 OpenAI Assistants 모델에 비해 호스트된 스레드 관리를 간소화합니다. 자세한 내용은 OpenAI Assistants 마이그레이션 가이드를 참조하세요.
에이전트 프레임워크에는 모든 공급자가 호스트된 스레드 또는 스레드 삭제를 AgentThread 지원하지 않으므로 형식에 스레드 삭제 API가 없습니다. 이 디자인은 더 많은 공급자가 응답 기반 아키텍처로 전환함에 따라 더 일반화됩니다.
스레드 삭제가 필요하고 공급자가 허용하는 경우 호출자는 생성된 스레드를 추적하고 공급자의 SDK를 통해 필요한 경우 나중에 삭제 해야 합니다 .
OpenAI Assistants 공급자:
await assistantClient.DeleteThreadAsync(thread.ConversationId);
5. 도구 등록
시맨틱 커널
함수를 도구로 노출하려면 다음을 수행해야 합니다.
- 특성을 사용하여 함수를 데코레이트
[KernelFunction]합니다. - 클래스를 사용
Plugin하거나 함수를KernelPluginFactory래핑하는 데 사용합니다. -
Kernel플러그 인을 추가할 수 있습니다. - 에이전트에
Kernel전달합니다.
KernelFunction function = KernelFunctionFactory.CreateFromMethod(GetWeather);
KernelPlugin plugin = KernelPluginFactory.CreateFromFunctions("KernelPluginName", [function]);
Kernel kernel = ... // Create kernel
kernel.Plugins.Add(plugin);
ChatCompletionAgent agent = new() { Kernel = kernel, ... };
에이전트 프레임워크
에이전트 프레임워크에서 단일 호출에서 에이전트 생성 프로세스에서 직접 도구를 등록할 수 있습니다.
AIAgent agent = chatClient.CreateAIAgent(tools: [AIFunctionFactory.Create(GetWeather)]);
6. 에이전트 비 스트리밍 호출
메서드 이름, 반환 형식 및 매개 변수Invoke에서 Run 주요 차이점을 AgentRunOptions확인할 수 있습니다.
시맨틱 커널
비 스트리밍은 여러 에이전트 메시지를 반환하는 스트리밍 패턴을 IAsyncEnumerable<AgentResponseItem<ChatMessageContent>> 사용합니다.
await foreach (AgentResponseItem<ChatMessageContent> result in agent.InvokeAsync(userInput, thread, agentOptions))
{
Console.WriteLine(result.Message);
}
에이전트 프레임워크
비 스트리밍은 여러 메시지를 포함할 수 있는 에이전트 응답이 포함된 단일 AgentRunResponse 메시지를 반환합니다.
실행의 텍스트 결과는 다음에서 AgentRunResponse.Text 사용할 수 있습니다.AgentRunResponse.ToString()
응답의 일부로 만든 모든 메시지가 목록에 반환 AgentRunResponse.Messages 됩니다.
여기에는 도구 호출 메시지, 함수 결과, 추론 업데이트 및 최종 결과가 포함될 수 있습니다.
AgentRunResponse agentResponse = await agent.RunAsync(userInput, thread);
7. 에이전트 스트리밍 호출
주요 차이점은 메서드 이름, InvokeRun반환 형식 및 매개 변수 AgentRunOptions에 있습니다.
시맨틱 커널
await foreach (StreamingChatMessageContent update in agent.InvokeStreamingAsync(userInput, thread))
{
Console.Write(update);
}
에이전트 프레임워크
에이전트 프레임워크에는 비슷한 스트리밍 API 패턴이 있으며, 주요 차이점은 업데이트당 더 많은 에이전트 관련 정보를 포함하는 개체를 반환 AgentRunResponseUpdate 한다는 점입니다.
AIAgent의 기본 서비스에 의해 생성된 모든 업데이트가 반환됩니다. 에이전트의 텍스트 결과는 값을 연결하여 AgentRunResponse.Text 사용할 수 있습니다.
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync(userInput, thread))
{
Console.Write(update); // Update is ToString() friendly
}
8. 도구 함수 서명
문제: 의미 체계 커널 플러그 인 메서드에는 특성이 필요합니다 [KernelFunction] .
public class MenuPlugin
{
[KernelFunction] // Required.
public static MenuItem[] GetMenu() => ...;
}
해결 방법: 에이전트 프레임워크는 특성 없이 직접 메서드를 사용할 수 있습니다.
public class MenuTools
{
[Description("Get menu items")] // Optional description.
public static MenuItem[] GetMenu() => ...;
}
9. 옵션 구성
문제: 의미 체계 커널의 복잡한 옵션 설정
OpenAIPromptExecutionSettings settings = new() { MaxTokens = 1000 };
AgentInvokeOptions options = new() { KernelArguments = new(settings) };
해결 방법: 에이전트 프레임워크의 간소화된 옵션입니다.
ChatClientAgentRunOptions options = new(new() { MaxOutputTokens = 1000 });
중요합니다
이 예제에서는 구현별 옵션을 .에 전달하는 방법을 보여 있습니다 ChatClientAgent. 모든 AIAgents 지원 ChatClientAgentRunOptions은 아닙니다.
ChatClientAgent 는 기본 유추 서비스를 기반으로 에이전트를 빌드하기 위해 제공되므로 다음과 같은 MaxOutputTokens유추 옵션을 지원합니다.
10. 종속성 주입
시맨틱 커널
Kernel 모든 에이전트 추상화를 속성으로 초기화 Kernel 해야 하므로 에이전트를 만들려면 서비스 컨테이너에 등록이 필요합니다.
의미 체계 커널은 이 형식을 Agent 에이전트의 기본 추상화 클래스로 사용합니다.
services.AddKernel().AddProvider(...);
serviceContainer.AddKeyedSingleton<SemanticKernel.Agents.Agent>(
TutorName,
(sp, key) =>
new ChatCompletionAgent()
{
// Passing the kernel is required.
Kernel = sp.GetRequiredService<Kernel>(),
});
에이전트 프레임워크
Agent Framework는 AIAgent 기본 추상화 클래스로 형식을 제공합니다.
services.AddKeyedSingleton<AIAgent>(() => client.CreateAIAgent(...));
11. 에이전트 유형 통합
시맨틱 커널
의미 체계 커널은 다양한 서비스에 대한 특정 에이전트 클래스를 제공합니다. 예를 들면 다음과 같습니다.
-
ChatCompletionAgent채팅 완료 기반 유추 서비스와 함께 사용할 수 있습니다. -
OpenAIAssistantAgentOpenAI Assistants 서비스와 함께 사용할 수 있습니다. -
AzureAIAgentAzure AI Foundry Agents 서비스와 함께 사용할 수 있습니다.
에이전트 프레임워크
에이전트 프레임워크는 단일 에이전트 유형을 ChatClientAgent통해 언급된 모든 서비스를 지원합니다.
ChatClientAgent 는 인터페이스를 구현하는 SDK를 제공하는 기본 서비스를 사용하여 에이전트를 IChatClient 빌드하는 데 사용할 수 있습니다.
주요 차이점
다음은 코드를 마이그레이션하는 데 도움이 되는 의미 체계 커널 에이전트 프레임워크와 Microsoft 에이전트 프레임워크 간의 주요 차이점에 대한 요약입니다.
1. 업데이트 패키지 및 가져오기
시맨틱 커널
의미 체계 커널 패키지는 다음과 같이 semantic-kernel 설치되고 다음과 같이 semantic_kernel가져옵니다. 또한 패키지에는 다양한 AI 공급자 및 기타 기능에 대한 다양한 종속성을 설치하기 위해 설치할 수 있는 많은 extras 항목이 있습니다.
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent
에이전트 프레임워크
에이전트 프레임워크 패키지는 다음과 같이 agent-framework 설치되고 .로 agent_framework가져옵니다.
에이전트 프레임워크는 다르게 빌드되고 핵심 기능을 포함하는 핵심 패키지 agent-framework-core 가 있으며, 코어 패키지(예: agent-framework-azure-ai등agent-framework-mem0agent-framework-copilotstudio)를 사용하는 여러 패키지가 있습니다. 실행 pip install agent-framework --pre 하면 핵심 패키지와 모든 패키지가 설치되므로 모든 기능을 빠르게 시작할 수 있습니다. 필요한 것을 알고 있기 때문에 패키지 수를 줄일 준비가 되면 필요한 패키지만 설치할 수 있으므로 예를 들어 Azure AI Foundry 및 Mem0만 사용하려는 경우 이러한 두 패키지만 설치할 수 있습니다. 즉, pip install agent-framework-azure-ai agent-framework-mem0 --pre 이러한 두 패키지agent-framework-core에 대한 종속성이므로 자동으로 설치됩니다.
패키지가 분할되더라도 가져오기는 모두 모듈에서 agent_framework가져온 것입니다. 예를 들어 Azure AI Foundry에 대한 클라이언트를 가져오려면 다음을 수행합니다.
from agent_framework.azure import AzureAIAgentClient
가장 일반적으로 사용되는 많은 형식은 다음에서 agent_framework직접 가져옵니다.
from agent_framework import ChatMessage, ChatAgent
2. 에이전트 유형 통합
시맨틱 커널
의미 체계 커널은 ChatCompletionAgent, AzureAIAgent, OpenAIAssistantAgent 등 다양한 서비스에 대한 특정 에이전트 클래스를 제공합니다. 의미 체계 커널의 에이전트 형식을 참조하세요.
에이전트 프레임워크
에이전트 프레임워크에서 대부분의 에이전트는 Azure AI Foundry, OpenAI ChatCompletion 및 OpenAI 응답과 같은 모든 ChatAgent 기반 서비스에서 사용할 수 있는 기능을 사용하여 ChatClient 빌드됩니다. Copilot Studio와 함께 사용하고 A2A에서 CopilotStudioAgent 사용하기 위한 두 가지 추가 에이전트 A2AAgent 가 있습니다.
모든 기본 제공 에이전트는 BaseAgent(from agent_framework import BaseAgent)를 기반으로 합니다. 그리고 모든 에이전트는 (AgentProtocol) 인터페이스와 from agent_framework import AgentProtocol 일치합니다.
3. 에이전트 만들기 간소화
시맨틱 커널
의미 체계 커널의 모든 에이전트는 인스턴스에 Kernel 따라 달라지며 제공되지 않으면 비어 Kernel 있습니다.
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
agent = ChatCompletionAgent(
service=OpenAIChatCompletion(),
name="Support",
instructions="Answer in one sentence.",
)
에이전트 프레임워크
에이전트 프레임워크에서 에이전트를 만드는 작업은 다음 두 가지 방법으로 직접 수행할 수 있습니다.
from agent_framework.azure import AzureAIAgentClient
from agent_framework import ChatMessage, ChatAgent
agent = ChatAgent(chat_client=AzureAIAgentClient(credential=AzureCliCredential()), instructions="You are a helpful assistant")
또는 채팅 클라이언트에서 제공하는 편리한 방법으로 다음을 수행합니다.
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).create_agent(instructions="You are a helpful assistant")
직접 메서드는 에이전트에 대해 설정할 수 있는 모든 가능한 매개 변수를 노출합니다. 편의 메서드에는 하위 집합이 있지만 내부적으로 직접 메서드를 호출하기 때문에 동일한 매개 변수 집합을 전달할 수 있습니다.
4. 에이전트 스레드 만들기
시맨틱 커널
호출자는 스레드 유형을 알고 수동으로 만들어야 합니다.
from semantic_kernel.agents import ChatHistoryAgentThread
thread = ChatHistoryAgentThread()
에이전트 프레임워크
에이전트는 새 스레드를 만들도록 요청할 수 있습니다.
agent = ...
thread = agent.get_new_thread()
그런 다음 세 가지 방법 중 하나로 스레드가 만들어집니다.
- 에이전트
thread_id에 (또는conversation_id이와 유사한) 집합이 있는 경우 해당 ID를 사용하여 기본 서비스에 스레드를 만듭니다. 스레드가 있으면service_thread_id더 이상 메모리에 메시지를 저장하는 데 사용할 수 없습니다. 이는 서비스 쪽 스레드 개념이 있는 에이전트에만 적용됩니다. Azure AI Foundry 에이전트 및 OpenAI Assistants와 같은 - 에이전트에 집합이 있는
chat_message_store_factory경우 해당 팩터리를 사용하여 메시지 저장소를 만들고 이를 사용하여 메모리 내 스레드를 만듭니다. 그런 다음 매개 변수가 .로 설정된store에이전트와 함께True더 이상 사용할 수 없습니다. - 이전 설정 중 어느 것도 설정되지 않은 경우 이 설정이 고려되며
uninitialized사용 방법에 따라 메모리 내 스레드 또는 서비스 스레드가 됩니다.
에이전트 프레임워크
비고
OpenAI 응답은 대화 처리 방법을 간소화하는 새로운 대화 모델을 도입했습니다. 이렇게 하면 현재 사용되지 않는 OpenAI Assistants 모델에 비해 호스트된 스레드 관리가 간소화됩니다. 자세한 내용은 OpenAI Assistants 마이그레이션 가이드를 참조하세요.
에이전트 프레임워크에는 모든 공급자가 호스트된 스레드 또는 스레드 삭제를 지원하지 않으므로 형식에 AgentThread 스레드 삭제 API가 없으며, 더 많은 공급자가 응답 기반 아키텍처로 전환함에 따라 이 API가 더 일반화됩니다.
스레드 삭제가 필요하고 공급자가 이를 허용하는 경우 호출자는 생성된 스레드를 추적하고 공급자의 sdk를 통해 필요한 경우 나중에 삭제 해야 합니다 .
OpenAI Assistants 공급자:
# OpenAI Assistants threads have self-deletion method in Semantic Kernel
await thread.delete_async()
5. 도구 등록
시맨틱 커널
함수를 도구로 노출하려면 다음을 수행해야 합니다.
- 데코레이터를 사용하여 함수를
@kernel_function데코레이트합니다. - 클래스를 사용
Plugin하거나 커널 플러그 인 팩터리를 사용하여 함수를 래핑합니다. -
Kernel플러그 인을 추가할 수 있습니다. - 에이전트에
Kernel전달합니다.
from semantic_kernel.functions import kernel_function
class SpecialsPlugin:
@kernel_function(name="specials", description="List daily specials")
def specials(self) -> str:
return "Clam chowder, Cobb salad, Chai tea"
agent = ChatCompletionAgent(
service=OpenAIChatCompletion(),
name="Host",
instructions="Answer menu questions accurately.",
plugins=[SpecialsPlugin()],
)
에이전트 프레임워크
단일 호출에서 에이전트 생성 프로세스에서 직접 도구를 등록할 수 있습니다. 에이전트 프레임워크에는 여러 함수를 래핑하는 플러그 인의 개념이 없지만 원하는 경우 계속 수행할 수 있습니다.
도구를 만드는 가장 간단한 방법은 Python 함수를 만드는 것입니다.
def get_weather(location: str) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is sunny."
agent = chat_client.create_agent(tools=get_weather)
비고
매개 변수는 tools 에이전트 생성, run 메서드 및 run_stream 메서드 get_responseget_streaming_response 둘 다에 존재하며, 이를 통해 도구를 목록 또는 단일 함수로 제공할 수 있습니다.
그러면 함수 이름이 도구의 이름이 되고 문서 문자열이 도구의 설명이 되며 매개 변수에 설명을 추가할 수도 있습니다.
from typing import Annotated
def get_weather(location: Annotated[str, "The location to get the weather for."]) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is sunny."
마지막으로 데코레이터를 사용하여 도구의 이름과 설명을 추가로 사용자 지정할 수 있습니다.
from typing import Annotated
from agent_framework import ai_function
@ai_function(name="weather_tool", description="Retrieves weather information for any location")
def get_weather(location: Annotated[str, "The location to get the weather for."])
"""Get the weather for a given location."""
return f"The weather in {location} is sunny."
여러 도구를 메서드로 사용하여 클래스를 만들 때도 작동합니다.
에이전트를 만들 때 이제 함수 도구를 매개 변수에 전달하여 에이전트에 tools 제공할 수 있습니다.
class Plugin:
def __init__(self, initial_state: str):
self.state: list[str] = [initial_state]
def get_weather(self, location: Annotated[str, "The location to get the weather for."]) -> str:
"""Get the weather for a given location."""
self.state.append(f"Requested weather for {location}. ")
return f"The weather in {location} is sunny."
def get_weather_details(self, location: Annotated[str, "The location to get the weather details for."]) -> str:
"""Get detailed weather for a given location."""
self.state.append(f"Requested detailed weather for {location}. ")
return f"The weather in {location} is sunny with a high of 25°C and a low of 15°C."
plugin = Plugin("Initial state")
agent = chat_client.create_agent(tools=[plugin.get_weather, plugin.get_weather_details])
... # use the agent
print("Plugin state:", plugin.state)
비고
도구의 이름과 설명을 사용자 지정하기 위해 클래스 내의 함수를 데코레이 @ai_function 팅할 수도 있습니다.
이 메커니즘은 연결, 비밀 등과 같이 LLM에서 제공할 수 없는 추가 입력이 필요한 도구에도 유용합니다.
호환성: KernelFunction을 에이전트 프레임워크 도구로 사용
프롬프트 또는 메서드에서 인스턴스가 있는 KernelFunction 기존 의미 체계 커널 코드가 있는 경우 메서드를 사용하여 .as_agent_framework_tool 에이전트 프레임워크 도구로 변환할 수 있습니다.
중요합니다
이 기능을 사용하려면 버전 1.38 이상이 필요합니다 semantic-kernel .
프롬프트 템플릿에서 KernelFunction 사용
from semantic_kernel import Kernel
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion, OpenAIChatPromptExecutionSettings
from semantic_kernel.prompt_template import KernelPromptTemplate, PromptTemplateConfig
from agent_framework.openai import OpenAIResponsesClient
# Create a kernel with services and plugins
kernel = Kernel()
# will get the api_key and model_id from the environment
kernel.add_service(OpenAIChatCompletion(service_id="default"))
# Create a function from a prompt template that uses plugin functions
function_definition = """
Today is: {{time.date}}
Current time is: {{time.time}}
Answer to the following questions using JSON syntax, including the data used.
Is it morning, afternoon, evening, or night (morning/afternoon/evening/night)?
Is it weekend time (weekend/not weekend)?
"""
prompt_template_config = PromptTemplateConfig(template=function_definition)
prompt_template = KernelPromptTemplate(prompt_template_config=prompt_template_config)
# Create a KernelFunction from the prompt
kernel_function = KernelFunctionFromPrompt(
description="Determine the kind of day based on the current time and date.",
plugin_name="TimePlugin",
prompt_execution_settings=OpenAIChatPromptExecutionSettings(service_id="default", max_tokens=100),
function_name="kind_of_day",
prompt_template=prompt_template,
)
# Convert the KernelFunction to an Agent Framework tool
agent_tool = kernel_function.as_agent_framework_tool(kernel=kernel)
# Use the tool with an Agent Framework agent
agent = OpenAIResponsesClient(model_id="gpt-4o").create_agent(tools=agent_tool)
response = await agent.run("What kind of day is it?")
print(response.text)
메서드에서 KernelFunction 사용
from semantic_kernel.functions import kernel_function
from agent_framework.openai import OpenAIResponsesClient
# Create a plugin class with kernel functions
@kernel_function(name="get_weather", description="Get the weather for a location")
def get_weather(self, location: str) -> str:
return f"The weather in {location} is sunny."
# Get the KernelFunction and convert it to an Agent Framework tool
agent_tool = get_weather.as_agent_framework_tool()
# Use the tool with an Agent Framework agent
agent = OpenAIResponsesClient(model_id="gpt-4o").create_agent(tools=agent_tool)
response = await agent.run("What's the weather in Seattle?")
print(response.text)
create_search_function VectorStore 사용
에이전트 프레임워크와 Semantic Kernel의 VectorStore 통합을 사용할 수도 있습니다. 벡터 저장소 컬렉션의 메서드는 create_search_function 에이전트 프레임워크 도구로 변환할 수 있는 메서드를 반환 KernelFunction 합니다.
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import OpenAITextEmbedding
from semantic_kernel.connectors.azure_ai_search import AzureAISearchCollection
from semantic_kernel.functions import KernelParameterMetadata
from agent_framework.openai import OpenAIResponsesClient
# Define your data model
class HotelSampleClass:
HotelId: str
HotelName: str
Description: str
# ... other fields
# Create an Azure AI Search collection
collection = AzureAISearchCollection[str, HotelSampleClass](
record_type=HotelSampleClass,
embedding_generator=OpenAITextEmbedding()
)
async with collection:
await collection.ensure_collection_exists()
# Load your records into the collection
# await collection.upsert(records)
# Create a search function from the collection
search_function = collection.create_search_function(
description="A hotel search engine, allows searching for hotels in specific cities.",
search_type="keyword_hybrid",
filter=lambda x: x.Address.Country == "USA",
parameters=[
KernelParameterMetadata(
name="query",
description="What to search for.",
type="str",
is_required=True,
type_object=str,
),
KernelParameterMetadata(
name="city",
description="The city that you want to search for a hotel in.",
type="str",
type_object=str,
),
KernelParameterMetadata(
name="top",
description="Number of results to return.",
type="int",
default_value=5,
type_object=int,
),
],
string_mapper=lambda x: f"(hotel_id: {x.record.HotelId}) {x.record.HotelName} - {x.record.Description}",
)
# Convert the search function to an Agent Framework tool
search_tool = search_function.as_agent_framework_tool()
# Use the tool with an Agent Framework agent
agent = OpenAIResponsesClient(model_id="gpt-4o").create_agent(
instructions="You are a travel agent that helps people find hotels.",
tools=search_tool
)
response = await agent.run("Find me a hotel in Seattle")
print(response.text)
이 패턴은 모든 의미 체계 커널 VectorStore 커넥터(Azure AI Search, Qdrant, Pinecone 등)에서 작동하므로 에이전트 프레임워크 에이전트와 함께 기존 벡터 검색 인프라를 활용할 수 있습니다.
이 호환성 계층을 사용하면 에이전트 프레임워크의 간소화된 에이전트 만들기 및 실행 패턴을 활용하면서 기존 구현을 KernelFunction 다시 사용하여 의미 체계 커널에서 에이전트 프레임워크로 코드를 점진적으로 마이그레이션할 수 있습니다.
6. 에이전트 비 스트리밍 호출
메서드 이름, invokerun반환 형식(예 AgentRunResponse: ) 및 매개 변수에서 주요 차이점을 확인할 수 있습니다.
시맨틱 커널
비 스트리밍 호출은 비동기 반복기 패턴을 사용하여 여러 에이전트 메시지를 반환합니다.
async for response in agent.invoke(
messages=user_input,
thread=thread,
):
print(f"# {response.role}: {response}")
thread = response.thread
그리고 최종 응답을 얻을 수있는 편리한 방법이 있었다 :
response = await agent.get_response(messages="How do I reset my bike tire?", thread=thread)
print(f"# {response.role}: {response}")
에이전트 프레임워크
비 스트리밍 실행은 여러 메시지를 포함할 수 있는 에이전트 응답이 있는 단일 AgentRunResponse 을 반환합니다.
실행의 텍스트 결과는 다음에서 response.text 사용할 수 있습니다.str(response)
응답의 일부로 만든 모든 메시지가 목록에 반환 response.messages 됩니다.
여기에는 도구 호출 메시지, 함수 결과, 추론 업데이트 및 최종 결과가 포함될 수 있습니다.
agent = ...
response = await agent.run(user_input, thread)
print("Agent response:", response.text)
7. 에이전트 스트리밍 호출
메서드 이름 invokerun_stream간, 반환 형식(AgentRunResponseUpdate) 및 매개 변수의 주요 차이점입니다.
시맨틱 커널
async for update in agent.invoke_stream(
messages="Draft a 2 sentence blurb.",
thread=thread,
):
if update.message:
print(update.message.content, end="", flush=True)
에이전트 프레임워크
업데이트당 더 많은 에이전트 관련 정보를 포함하여 개체를 반환 AgentRunResponseUpdate 한다는 점과 주요 차이점이 있는 유사한 스트리밍 API 패턴입니다.
에이전트의 기본 서비스에 의해 생성된 모든 콘텐츠가 반환됩니다. 에이전트의 최종 결과는 값을 단일 응답에 결합하여 update 사용할 수 있습니다.
from agent_framework import AgentRunResponse
agent = ...
updates = []
async for update in agent.run_stream(user_input, thread):
updates.append(update)
print(update.text)
full_response = AgentRunResponse.from_agent_run_response_updates(updates)
print("Full agent response:", full_response.text)
직접 수행할 수도 있습니다.
from agent_framework import AgentRunResponse
agent = ...
full_response = AgentRunResponse.from_agent_response_generator(agent.run_stream(user_input, thread))
print("Full agent response:", full_response.text)
8. 옵션 구성
문제: 의미 체계 커널의 복잡한 옵션 설정
from semantic_kernel.connectors.ai.open_ai import OpenAIPromptExecutionSettings
settings = OpenAIPromptExecutionSettings(max_tokens=1000)
arguments = KernelArguments(settings)
response = await agent.get_response(user_input, thread=thread, arguments=arguments)
해결 방법: 에이전트 프레임워크의 간소화된 옵션
에이전트 프레임워크를 사용하면 모든 매개 변수를 관련 메서드에 직접 전달할 수 있으므로 원하는 경우가 아니면 추가 항목을 가져오거나 옵션 개체를 만들 필요가 없습니다. 내부적으로 개체를 ChatOptionsChatClients 사용하며 ChatAgents, 원하는 경우 만들고 전달할 수도 있습니다. 또한 옵션을 보관하기 위해 생성 ChatAgent 되며 호출당 재정의할 수 있습니다.
agent = ...
response = await agent.run(user_input, thread, max_tokens=1000, frequency_penalty=0.5)
비고
위의 내용은 다른 에이전트에 ChatAgent다른 옵션이 있을 수 있으므로 해당 에이전트가 모두 매개 변수로 수락 messages 해야 합니다. 이는 에 정의 AgentProtocol되어 있기 때문입니다.