Install the package and set API key:
pip install openai-agents
export OPENAI_API_KEY="your-key"
Or programmatically:
from agents import set_default_openai_key
set_default_openai_key("your-key")
Import necessary modules and create an agent:
from agents import Agent, Runner
agent = Agent(
name="Assistant",
instructions="You are a helpful assistant.",
tools=[my_function_tool],
handoffs=[other_agent],
input_guardrails=[my_input_check],
output_guardrails=[my_output_check],
output_type=str # Optional type
)
Execute an agent with user input and get results:
async def main():
result = await Runner.run(
agent, "Your input message"
)
print(result.final_output)
asyncio.run(main())
Define a function tool that agents can use:
from agents import function_tool
@function_tool
def get_current_date() -> str:
"""Returns current date in YYYY-MM-DD format."""
return datetime.date.today().isoformat()
Use in an agent:
agent = Agent(
tools=[get_current_date],
instructions="Use get_current_date when needed"
)
Create input validation to filter unsafe content:
from agents import input_guardrail, output_guardrail, GuardrailFunctionOutput
@input_guardrail
def check_input(context, agent, input_text):
if "badword" in input_text.lower():
return GuardrailFunctionOutput(
output_info="Please avoid profanity.",
tripwire_triggered=True
)
return GuardrailFunctionOutput(
output_info=None,
tripwire_triggered=False
)
Import handoff functionality:
from agents import handoff, HandoffInputData
Basic handoff (automatic):
agent1 = Agent(name="Agent1", ...)
agent2 = Agent(
name="Agent2",
handoffs=[agent1] # Automatic handoff
)
Custom handoff with special handling:
custom_handoff = handoff(
agent1,
on_handoff=my_handoff_function,
input_filter=my_filter_function
)
Set up tracing for debugging agent execution:
from agents import add_trace_processor
from agents.tracing.processors import ConsoleSpanExporter
add_trace_processor(ConsoleSpanExporter())
Create custom spans for detailed tracing:
from agents import agent_span, custom_span
with custom_span(name="My Operation",
data={"key": "value"}):
# code to trace
await asyncio.sleep(0.1)
Define structured output with Pydantic:
from pydantic import BaseModel
class WeatherReport(BaseModel):
city: str
temperature: float
condition: str
Configure agent to return this type:
agent = Agent(
output_type=WeatherReport,
instructions="Return weather data"
)
Access the typed result:
# Access as strongly typed object
print(result.final_output.temperature)
Create a tool for SQL database queries:
@function_tool
def execute_query(db_path, query, params):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(query, params)
results = cursor.fetchall()
columns = [d[0] for d in cursor.description]
conn.close()
return [dict(zip(columns, row)) for row in results]
A multi-agent workflow:
triage_agent → specialist_agent → output
With validation:
input → validator → processor → output