This article introduces OpenAI Agents SDK installation, agent creation, function tool definition, and basic multi-agent collaboration. Includes complete code examples showing how to define tools with function_tool decorator, configure agent instructions, and execute agents via Runner.
The OpenAI Agents SDK is a lightweight Python library for building and orchestrating AI agents. Unlike LangChain, it focuses on core agent orchestration capabilities with a simple API and powerful multi-agent collaboration (handoffs).
pip install openai-agentsfrom agents import Agent
agent = Agent(
name="Math Tutor",
instructions="You are a math tutor who explains concepts and calculations clearly."
)
Use @function_tool decorator to define tools:
from agents import function_tool, Agent, Runner
import asyncio
@function_tool
def calculate(expression: str) -> str:
"""Execute mathematical expression calculation
Args:
expression: Mathematical expression, e.g., "2 + 3 * 4"
"""
try:
result = eval(expression)
return str(result)
except Exception as e:
return f"Calculation error: {e}"
# Create agent with tools
math_agent = Agent(
name="Calculator",
instructions="You are a calculator assistant. Use the calculate tool for math operations.",
tools=[calculate]
)
# Run agent
async def main():
result = await Runner.run(math_agent, "Calculate 25 * 4 + 10")
print(result.final_output)
asyncio.run(main())
from agents import Agent, Runner
import asyncio
# Define expert agents
coder = Agent(
name="Coder",
instructions="You are a Python programming expert who helps users write code."
)
researcher = Agent(
name="Researcher",
instructions="You are a research assistant who helps users find and analyze information."
)
# Triage agent (router)
triage = Agent(
name="Triage",
instructions="Analyze user questions and route them to the appropriate expert.",
handoffs=[coder, researcher]
)
# Run
async def main():
result = await Runner.run(triage, "Help me write a quicksort algorithm")
print(f"Answer: {result.final_output}")
print(f"Handled by: {result.last_agent.name}")
asyncio.run(main())
from agents import function_tool, Agent, Runner
import asyncio
@function_tool
def search_knowledge_base(query: str, category: str = "general") -> str:
"""Search for relevant information in the knowledge base
Args:
query: Search keyword
category: Knowledge category, default is general
"""
# Simulated knowledge base search
return f"Found results about '{query}' in {category} category"
assistant = Agent(
name="Knowledge Assistant",
instructions="You are a knowledge assistant. Use the knowledge base search tool to answer questions.",
tools=[search_knowledge_base]
)
async def main():
result = await Runner.run(
assistant,
"Find information about Python async programming"
)
print(result.final_output)
asyncio.run(main())
from agents import Agent, Runner, function_tool
import asyncio
@function_tool
def create_task(title: str, priority: str = "medium") -> str:
"""Create a new task
Args:
title: Task title
priority: Priority level (high/medium/low)
"""
return f"Created task: [{priority}] {title}"
@function_tool
def list_tasks() -> str:
"""List all tasks"""
return "Current tasks:\n1. [high] Complete report\n2. [medium] Reply to email"
task_agent = Agent(
name="Task Manager",
instructions="You are a task management assistant who helps users create and manage tasks.",
tools=[create_task, list_tasks]
)
async def main():
result = await Runner.run(task_agent, "Create a high priority code review task")
print(result.final_output)
asyncio.run(main())
Q1: Where does the @function_tool description come from?
Q2: What's the difference between Handoffs and Tools?
Q3: How to debug agent execution?
Runner.run() with verbose=True parameterresult.last_agent to find the final handler所有示例代码语法正确,逻辑完整
代码示例符合 OpenAI Agents SDK 规范