Skip to content

OpenAI Agents SDK Cheatsheet

OpenAI Agents SDK Cheatsheet

The OpenAI Agents SDK is a small, opinionated Python framework for building agentic apps. It exposes four core primitives — Agents (an LLM plus instructions and tools), Tools (Python functions or hosted tools), Handoffs (delegating a run to another agent), and Guardrails (validating inputs and outputs) — with Sessions for memory and Tracing built in. It is provider-flexible but works out of the box with OpenAI models.

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)Run synchronously
await Runner.run(agent, input)Run asynchronously
Runner.run_streamed(agent, input)Stream events as they happen
result.final_outputThe agent’s final answer
result.new_itemsStructured run items (messages, tool calls, 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_toolTurn a typed Python function into a tool (schema auto-generated from the signature/docstring)
Hosted toolsBuilt-ins like web search and file search
tool_use_behaviorControl whether tool output ends the turn
Agents as toolsagent.as_tool(...) exposes one agent as a callable tool of another

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 transfer the full conversation to the receiving agent within a single run; input guardrails apply to the first agent and output guardrails to the agent that produces the final output.

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_guardrailBefore the agentValidate/screen user input
@output_guardrailAfter the final outputValidate the agent’s response
Tool guardrailsAround each tool callCheck inputs/outputs of individual tools
TripwireOn triggerRaises an exception to halt the run

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
SQLiteSessionLocal/persistent conversation memory
In-memory sessionEphemeral context within a process
Custom sessionImplement the session protocol for your own store

Tracing

FeatureDescription
Automatic tracesEvery Runner.run records model calls, tool calls, handoffs, guardrail outcomes, and timing
DashboardTraces appear under your project on the OpenAI platform
trace(...)Group multiple runs into one workflow trace
External processorsExport spans to third-party observability tools

Common Workflows

# Streaming tokens to a 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