Microsoft Agent Framework는 OpenAI Assistants 서비스를 사용하는 에이전트 만들기를 지원합니다.
경고
OpenAI Assistants API는 더 이상 사용되지 않으며 종료됩니다. 자세한 내용은 OpenAI 설명서를 참조하세요.
시작하기
필요한 NuGet 패키지를 프로젝트에 추가합니다.
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
OpenAI Assistants 에이전트 만들기
첫 번째 단계로 OpenAI 서비스에 연결할 클라이언트를 만들어야 합니다.
using System;
using Microsoft.Agents.AI;
using OpenAI;
OpenAIClient client = new OpenAIClient("<your_api_key>");
OpenAI는 모두 모델 호출 기능을 제공하는 여러 서비스를 지원합니다. 이 예제에서는 Assistants 클라이언트를 사용하여 Assistants 기반 에이전트를 만듭니다.
#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
var assistantClient = client.GetAssistantClient();
#pragma warning restore OPENAI001
OpenAI Assistants 서비스를 사용하려면 서비스에서 도우미 리소스를 만들어야 합니다. OpenAI SDK를 사용하거나 Microsoft 에이전트 프레임워크 도우미를 사용하여 이 작업을 수행할 수 있습니다.
OpenAI SDK 사용
클라이언트를 사용하여 도우미를 만들고 AIAgent로 검색합니다.
// Create a server-side assistant
var createResult = await assistantClient.CreateAssistantAsync(
"gpt-4o-mini",
new() { Name = "Joker", Instructions = "You are good at telling jokes." });
// Retrieve the assistant as an AIAgent
AIAgent agent1 = await assistantClient.GetAIAgentAsync(createResult.Value.Id);
// Invoke the agent and output the text result.
Console.WriteLine(await agent1.RunAsync("Tell me a joke about a pirate."));
에이전트 프레임워크 도우미 사용
한 번에 AIAgent을(를) 만들고 반환할 수도 있습니다.
AIAgent agent2 = await assistantClient.CreateAIAgentAsync(
model: "gpt-4o-mini",
name: "Joker",
instructions: "You are good at telling jokes.");
OpenAI 어시스턴트 재사용
ID를 사용하여 기존 OpenAI Assistant를 검색하여 다시 사용할 수 있습니다.
AIAgent agent3 = await assistantClient.GetAIAgentAsync("<agent-id>");
에이전트 사용
에이전트는 표준 AIAgent 이며 모든 표준 에이전트 작업을 지원합니다.
에이전트를 실행하고 상호 작용하는 방법에 대한 자세한 내용은 에이전트 시작 자습서를 참조하세요.
필수 조건
Microsoft Agent Framework 패키지를 설치합니다.
pip install agent-framework --pre
구성 / 설정
환경 변수
OpenAI 인증에 필요한 환경 변수를 설정합니다.
# Required for OpenAI API access
OPENAI_API_KEY="your-openai-api-key"
OPENAI_CHAT_MODEL_ID="gpt-4o-mini" # or your preferred model
또는 프로젝트 루트에서 .env 파일을 사용할 수 있습니다.
OPENAI_API_KEY=your-openai-api-key
OPENAI_CHAT_MODEL_ID=gpt-4o-mini
시작하기
에이전트 프레임워크에서 필요한 클래스를 가져옵니다.
import asyncio
from agent_framework import ChatAgent
from agent_framework.openai import OpenAIAssistantsClient
OpenAI Assistants 에이전트 만들기
기본 에이전트 만들기
에이전트를 만드는 가장 간단한 방법은 도우미를 OpenAIAssistantsClient 자동으로 만들고 관리하는 방법을 사용하는 것입니다.
async def basic_example():
# Create an agent with automatic assistant creation and cleanup
async with OpenAIAssistantsClient().create_agent(
instructions="You are a helpful assistant.",
name="MyAssistant"
) as agent:
result = await agent.run("Hello, how are you?")
print(result.text)
명시적 구성 사용
환경 변수를 사용하는 대신 명시적 구성을 제공할 수 있습니다.
async def explicit_config_example():
async with OpenAIAssistantsClient(
ai_model_id="gpt-4o-mini",
api_key="your-api-key-here",
).create_agent(
instructions="You are a helpful assistant.",
) as agent:
result = await agent.run("What's the weather like?")
print(result.text)
기존 도우미 사용
ID를 제공하여 기존 OpenAI 도우미를 다시 사용할 수 있습니다.
from openai import AsyncOpenAI
async def existing_assistant_example():
# Create OpenAI client directly
client = AsyncOpenAI()
# Create or get an existing assistant
assistant = await client.beta.assistants.create(
model="gpt-4o-mini",
name="WeatherAssistant",
instructions="You are a weather forecasting assistant."
)
try:
# Use the existing assistant with Agent Framework
async with ChatAgent(
chat_client=OpenAIAssistantsClient(
async_client=client,
assistant_id=assistant.id
),
instructions="You are a helpful weather agent.",
) as agent:
result = await agent.run("What's the weather like in Seattle?")
print(result.text)
finally:
# Clean up the assistant
await client.beta.assistants.delete(assistant.id)
에이전트 기능
함수 도구
도우미에 사용자 지정 함수를 장착할 수 있습니다.
from typing import Annotated
from pydantic import Field
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")]
) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is sunny with 25°C."
async def tools_example():
async with ChatAgent(
chat_client=OpenAIAssistantsClient(),
instructions="You are a helpful weather assistant.",
tools=get_weather, # Provide tools to the agent
) as agent:
result = await agent.run("What's the weather like in Tokyo?")
print(result.text)
코드 인터프리터
도우미가 Python 코드를 실행하도록 설정합니다.
from agent_framework import HostedCodeInterpreterTool
async def code_interpreter_example():
async with ChatAgent(
chat_client=OpenAIAssistantsClient(),
instructions="You are a helpful assistant that can write and execute Python code.",
tools=HostedCodeInterpreterTool(),
) as agent:
result = await agent.run("Calculate the factorial of 100 using Python code.")
print(result.text)
파일 검색
도우미가 업로드된 문서를 검색할 수 있도록 설정합니다.
from agent_framework import HostedFileSearchTool, HostedVectorStoreContent
async def create_vector_store(client: OpenAIAssistantsClient) -> tuple[str, HostedVectorStoreContent]:
"""Create a vector store with sample documents."""
file = await client.client.files.create(
file=("todays_weather.txt", b"The weather today is sunny with a high of 75F."),
purpose="user_data"
)
vector_store = await client.client.vector_stores.create(
name="knowledge_base",
expires_after={"anchor": "last_active_at", "days": 1},
)
result = await client.client.vector_stores.files.create_and_poll(
vector_store_id=vector_store.id,
file_id=file.id
)
if result.last_error is not None:
raise Exception(f"Vector store file processing failed with status: {result.last_error.message}")
return file.id, HostedVectorStoreContent(vector_store_id=vector_store.id)
async def delete_vector_store(client: OpenAIAssistantsClient, file_id: str, vector_store_id: str) -> None:
"""Delete the vector store after using it."""
await client.client.vector_stores.delete(vector_store_id=vector_store_id)
await client.client.files.delete(file_id=file_id)
async def file_search_example():
print("=== OpenAI Assistants Client Agent with File Search Example ===\n")
client = OpenAIAssistantsClient()
async with ChatAgent(
chat_client=client,
instructions="You are a helpful assistant that searches files in a knowledge base.",
tools=HostedFileSearchTool(),
) as agent:
query = "What is the weather today? Do a file search to find the answer."
file_id, vector_store = await create_vector_store(client)
print(f"User: {query}")
print("Agent: ", end="", flush=True)
async for chunk in agent.run_stream(
query, tool_resources={"file_search": {"vector_store_ids": [vector_store.vector_store_id]}}
):
if chunk.text:
print(chunk.text, end="", flush=True)
print() # New line after streaming
await delete_vector_store(client, file_id, vector_store.vector_store_id)
스레드 관리
여러 상호 작용 간에 대화 컨텍스트를 유지 관리합니다.
async def thread_example():
async with OpenAIAssistantsClient().create_agent(
name="Assistant",
instructions="You are a helpful assistant.",
) as agent:
# Create a persistent thread for conversation context
thread = agent.get_new_thread()
# First interaction
first_query = "My name is Alice"
print(f"User: {first_query}")
first_result = await agent.run(first_query, thread=thread)
print(f"Agent: {first_result.text}")
# Second interaction - agent remembers the context
second_query = "What's my name?"
print(f"User: {second_query}")
second_result = await agent.run(second_query, thread=thread)
print(f"Agent: {second_result.text}") # Should remember "Alice"
기존 비서와 협력하기
ID를 제공하여 기존 OpenAI 도우미를 다시 사용할 수 있습니다.
from openai import AsyncOpenAI
async def existing_assistant_example():
# Create OpenAI client directly
client = AsyncOpenAI()
# Create or get an existing assistant
assistant = await client.beta.assistants.create(
model="gpt-4o-mini",
name="WeatherAssistant",
instructions="You are a weather forecasting assistant."
)
try:
# Use the existing assistant with Agent Framework
async with OpenAIAssistantsClient(
async_client=client,
assistant_id=assistant.id
).create_agent() as agent:
result = await agent.run("What's the weather like in Seattle?")
print(result.text)
finally:
# Clean up the assistant
await client.beta.assistants.delete(assistant.id)
스트리밍 응답
사용자 환경을 향상하기 위해 생성된 응답을 가져옵니다.
async def streaming_example():
async with OpenAIAssistantsClient().create_agent(
instructions="You are a helpful assistant.",
) as agent:
print("Assistant: ", end="", flush=True)
async for chunk in agent.run_stream("Tell me a story about AI."):
if chunk.text:
print(chunk.text, end="", flush=True)
print() # New line after streaming is complete
에이전트 사용
에이전트는 표준 BaseAgent 이며 모든 표준 에이전트 작업을 지원합니다.
에이전트를 실행하고 상호 작용하는 방법에 대한 자세한 내용은 에이전트 시작 자습서를 참조하세요.