Microsoft Agent Framework는 OpenAI 응답 서비스를 사용하는 에이전트 만들기를 지원합니다.
시작하기
필요한 NuGet 패키지를 프로젝트에 추가합니다.
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
OpenAI 응답 에이전트 만들기
첫 번째 단계로 OpenAI 서비스에 연결할 클라이언트를 만들어야 합니다.
using System;
using Microsoft.Agents.AI;
using OpenAI;
OpenAIClient client = new OpenAIClient("<your_api_key>");
OpenAI는 모델 호출 기능을 모두 제공하는 여러 서비스를 지원합니다. 응답 기반 에이전트를 만들려면 응답 서비스를 선택해야 합니다.
#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates.
var responseClient = client.GetOpenAIResponseClient("gpt-4o-mini");
#pragma warning restore OPENAI001
마지막으로 CreateAIAgent에 ResponseClient 확장 메서드를 사용하여 에이전트를 만듭니다.
AIAgent agent = responseClient.CreateAIAgent(
instructions: "You are good at telling jokes.",
name: "Joker");
// Invoke the agent and output the text result.
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));
에이전트 사용
에이전트는 표준 AIAgent 이며 모든 표준 AIAgent 작업을 지원합니다.
에이전트를 실행하고 상호 작용하는 방법에 대한 자세한 내용은 에이전트 시작 자습서 를 참조하세요.
필수 조건
Microsoft Agent Framework 패키지를 설치합니다.
pip install agent-framework --pre
구성 / 설정
환경 변수
OpenAI 인증에 필요한 환경 변수를 설정합니다.
# Required for OpenAI API access
OPENAI_API_KEY="your-openai-api-key"
OPENAI_RESPONSES_MODEL_ID="gpt-4o" # or your preferred Responses-compatible model
또는 프로젝트 루트에서 .env 파일을 사용할 수 있습니다.
OPENAI_API_KEY=your-openai-api-key
OPENAI_RESPONSES_MODEL_ID=gpt-4o
시작하기
에이전트 프레임워크에서 필요한 클래스를 가져옵니다.
import asyncio
from agent_framework.openai import OpenAIResponsesClient
OpenAI 응답 에이전트 만들기
기본 에이전트 만들기
응답 에이전트를 만드는 가장 간단한 방법은 다음과 같습니다.
async def basic_example():
# Create an agent using OpenAI Responses
agent = OpenAIResponsesClient().create_agent(
name="WeatherBot",
instructions="You are a helpful weather assistant.",
)
result = await agent.run("What's a good way to check the weather?")
print(result.text)
명시적 구성 사용
환경 변수를 사용하는 대신 명시적 구성을 제공할 수 있습니다.
async def explicit_config_example():
agent = OpenAIResponsesClient(
ai_model_id="gpt-4o",
api_key="your-api-key-here",
).create_agent(
instructions="You are a helpful assistant.",
)
result = await agent.run("Tell me about AI.")
print(result.text)
기본 사용 패턴
스트리밍 응답
사용자 환경을 향상하기 위해 생성된 응답을 가져옵니다.
async def streaming_example():
agent = OpenAIResponsesClient().create_agent(
instructions="You are a creative storyteller.",
)
print("Assistant: ", end="", flush=True)
async for chunk in agent.run_stream("Tell me a short story about AI."):
if chunk.text:
print(chunk.text, end="", flush=True)
print() # New line after streaming
에이전트 기능
추론 모델
GPT-5와 같은 모델에서 고급 추론 기능을 사용합니다.
from agent_framework import HostedCodeInterpreterTool, TextContent, TextReasoningContent
async def reasoning_example():
agent = OpenAIResponsesClient(ai_model_id="gpt-5").create_agent(
name="MathTutor",
instructions="You are a personal math tutor. When asked a math question, "
"write and run code to answer the question.",
tools=HostedCodeInterpreterTool(),
reasoning={"effort": "high", "summary": "detailed"},
)
print("Assistant: ", end="", flush=True)
async for chunk in agent.run_stream("Solve: 3x + 11 = 14"):
if chunk.contents:
for content in chunk.contents:
if isinstance(content, TextReasoningContent):
# Reasoning content in gray text
print(f"\033[97m{content.text}\033[0m", end="", flush=True)
elif isinstance(content, TextContent):
print(content.text, end="", flush=True)
print()
구조적 출력
정형 형식으로 응답을 가져옵니다.
from pydantic import BaseModel
from agent_framework import AgentRunResponse
class CityInfo(BaseModel):
"""A structured output for city information."""
city: str
description: str
async def structured_output_example():
agent = OpenAIResponsesClient().create_agent(
name="CityExpert",
instructions="You describe cities in a structured format.",
)
# Non-streaming structured output
result = await agent.run("Tell me about Paris, France", response_format=CityInfo)
if result.value:
city_data = result.value
print(f"City: {city_data.city}")
print(f"Description: {city_data.description}")
# Streaming structured output
structured_result = await AgentRunResponse.from_agent_response_generator(
agent.run_stream("Tell me about Tokyo, Japan", response_format=CityInfo),
output_format_type=CityInfo,
)
if structured_result.value:
tokyo_data = structured_result.value
print(f"City: {tokyo_data.city}")
print(f"Description: {tokyo_data.description}")
함수 도구
에이전트에 사용자 지정 함수를 장착합니다.
from typing import Annotated
from pydantic import Field
def get_weather(
location: Annotated[str, Field(description="The location to get weather for")]
) -> str:
"""Get the weather for a given location."""
# Your weather API implementation here
return f"The weather in {location} is sunny with 25°C."
async def tools_example():
agent = OpenAIResponsesClient().create_agent(
instructions="You are a helpful weather assistant.",
tools=get_weather,
)
result = await agent.run("What's the weather like in Tokyo?")
print(result.text)
이미지 생성
응답 API를 사용하여 이미지를 생성합니다.
from agent_framework import DataContent, UriContent
async def image_generation_example():
agent = OpenAIResponsesClient().create_agent(
instructions="You are a helpful AI that can generate images.",
tools=[{
"type": "image_generation",
"size": "1024x1024",
"quality": "low",
}],
)
result = await agent.run("Generate an image of a sunset over the ocean.")
# Check for generated images in the response
for content in result.contents:
if isinstance(content, (DataContent, UriContent)):
print(f"Image generated: {content.uri}")
코드 인터프리터
도우미가 Python 코드를 실행하도록 설정합니다.
from agent_framework import HostedCodeInterpreterTool
async def code_interpreter_example():
agent = OpenAIResponsesClient().create_agent(
instructions="You are a helpful assistant that can write and execute Python code.",
tools=HostedCodeInterpreterTool(),
)
result = await agent.run("Calculate the factorial of 100 using Python code.")
print(result.text)
에이전트 사용
에이전트는 표준 BaseAgent 이며 모든 표준 에이전트 작업을 지원합니다.
에이전트를 실행하고 상호 작용하는 방법에 대한 자세한 내용은 에이전트 시작 자습서 를 참조하세요.