콘텐츠로 이동

OpenAI Agents SDK Cheatsheet

OpenAI Agents SDK Cheatsheet

OpenAI Agents SDK는 agentic 앱을 구축하기 위한 소규모의 체계적인 Python 프레임워크입니다. 네 가지 핵심 기본 요소를 제공합니다. Agents (LLM과 지시사항 및 도구), Tools (Python 함수 또는 호스팅된 도구), Handoffs (다른 에이전트로 실행 위임), Guardrails (입출력 검증) — 그리고 Sessions (메모리)와 Tracing이 기본 내장되어 있습니다. 프로바이더 유연하지만 OpenAI 모델로 기본적으로 작동합니다.

Installation

StepCommand
Installpip install openai-agents
With uvuv add openai-agents
Set the keyexport OPENAI_API_KEY="sk-..."
Voice extraspip install "openai-agents[voice]"
Verifypython -c "import agents; print(agents.__version__)"

Minimal Agent

from agents import Agent, Runner

agent = Agent(
    name="Assistant",
    instructions="You are a concise, helpful assistant.",
)

result = Runner.run_sync(agent, "Summarize the Unix philosophy in one line.")
print(result.final_output)
CallDescription
Runner.run_sync(agent, input)동기적으로 실행
await Runner.run(agent, input)비동기적으로 실행
Runner.run_streamed(agent, input)이벤트가 발생할 때 스트림
result.final_output에이전트의 최종 답변
result.new_items구조화된 실행 항목 (메시지, 도구 호출, handoffs)

Tools

from agents import Agent, function_tool

@function_tool
def get_weather(city: str) -> str:
    """Return the weather for a city."""
    return f"Sunny in {city}"

agent = Agent(name="Weather", tools=[get_weather])
ConceptDescription
@function_tool타입 지정된 Python 함수를 도구로 변환 (서명/docstring에서 스키마 자동 생성)
Hosted tools웹 검색 및 파일 검색 같은 내장 기능
tool_use_behavior도구 출력이 차례를 끝내는지 제어
Agents as toolsagent.as_tool(...)은 한 에이전트를 다른 에이전트의 호출 가능한 도구로 노출

Handoffs

from agents import Agent, handoff

billing = Agent(name="Billing", instructions="Handle billing questions.")
triage = Agent(
    name="Triage",
    instructions="Route the user to the right specialist.",
    handoffs=[billing],          # or handoff(billing, ...)
)

Handoffs는 전체 대화를 단일 실행 내에서 받는 에이전트로 전달합니다. 입력 guardrails는 첫 번째 에이전트에 적용되고 출력 guardrails는 최종 출력을 생성하는 에이전트에 적용됩니다.

Guardrails

from agents import Agent, input_guardrail, GuardrailFunctionOutput

@input_guardrail
async def no_secrets(ctx, agent, user_input):
    tripped = "password" in user_input.lower()
    return GuardrailFunctionOutput(output_info={}, tripwire_triggered=tripped)

agent = Agent(name="Safe", input_guardrails=[no_secrets])
TypeRunsPurpose
@input_guardrail에이전트 전에사용자 입력 검증/스크린
@output_guardrail최종 출력 후에이전트의 응답 검증
Tool guardrails각 도구 호출 주변개별 도구의 입출력 확인
Tripwire트리거 시예외를 발생시켜 실행 중단

Sessions (Memory)

from agents import Agent, Runner, SQLiteSession

session = SQLiteSession("user-123", "conversations.db")
Runner.run_sync(agent, "My name is Nick.", session=session)
Runner.run_sync(agent, "What's my name?", session=session)  # remembers
SessionUse
SQLiteSession로컬/지속성 대화 메모리
In-memory session프로세스 내 임시 컨텍스트
Custom session자신의 저장소에 대한 세션 프로토콜 구현

Tracing

FeatureDescription
Automatic traces모든 Runner.run은 모델 호출, 도구 호출, handoffs, guardrail 결과, 타이밍을 기록합니다
Dashboard추적이 OpenAI 플랫폼의 프로젝트 아래에 표시됩니다
trace(...)여러 실행을 하나의 워크플로우 추적으로 그룹화
External processors타사 observability 도구로 spans 내보내기

Common Workflows

# UI로 토큰 스트리밍
import asyncio
from agents import Agent, Runner

async def main():
    agent = Agent(name="Writer", instructions="Write vividly.")
    streamed = Runner.run_streamed(agent, "Describe a thunderstorm.")
    async for event in streamed.stream_events():
        print(event)

asyncio.run(main())

Resources