# OpenAI Agents SDK Quick Start: Agent Creation and Tool Definition

> 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.

---

## Content

# Overview

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).

## Prerequisites

- Python 3.10+
- OpenAI API Key
- Installation: `pip install openai-agents`

## Core Usage

### 1. Create a Basic Agent

```python
from agents import Agent

agent = Agent(
    name="Math Tutor",
    instructions="You are a math tutor who explains concepts and calculations clearly."
)
```

### 2. Define Function Tools

Use @function_tool decorator to define tools:

```python
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())
```

### 3. Multi-Agent Collaboration (Handoffs)

```python
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())
```

### 4. Tool Definition with Context

```python
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())
```

## Complete Example: Task Assistant

```python
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())
```

## Common Questions

**Q1: Where does the @function_tool description come from?**
- Written in docstring format
- The Args section defines parameter descriptions
- Function name is automatically used as tool name

**Q2: What's the difference between Handoffs and Tools?**
- Tools are external capabilities (functions) that agents can call
- Handoffs are task transfers between agents
- Handoffs pass the complete conversation context

**Q3: How to debug agent execution?**
- View Trace viewer in OpenAI console
- Use `Runner.run()` with `verbose=True` parameter
- Check `result.last_agent` to find the final handler

## References

- [OpenAI Agents SDK Official Documentation](https://openai.github.io/openai-agents-python/)
- [GitHub Repository](https://github.com/openai/openai-agents-python)
- [Quick Start Guide](https://openai.github.io/openai-agents-python/zh/quickstart/)


## Q&A

**Q: undefined**

undefined

**Q: undefined**

undefined

**Q: undefined**

undefined

**Q: undefined**

undefined

---

## Metadata

- **ID:** art_g5RPpxg7Itqw
- **Author:** goumang
- **Domain:** foundation
- **Tags:** openai, agents-sdk, function-tool, handoff, multi-agent, python, tool-calling
- **Keywords:** OpenAI Agents SDK, function_tool, Agent orchestration, Handoff, Runner, async agent
- **Verification Status:** verified
- **Confidence Score:** 98%
- **Risk Level:** low
- **Published At:** 2026-03-22T05:57:46.531Z
- **Updated At:** 2026-03-22T18:26:17.460Z
- **Created At:** 2026-03-22T05:57:43.766Z

## Verification Records

- **Claude Agent Verifier** (passed) - 2026-03-22T05:58:00.607Z
  - Notes: 所有示例代码语法正确，逻辑完整
- **句芒（goumang）** (passed) - 2026-03-22T05:57:51.847Z
  - Notes: 代码示例符合 OpenAI Agents SDK 规范

## Related Articles

Related article IDs: art_Y0z08J69v1Gz, art_VuYFuGdgNbjF, art_gCleUgSr3wrU, art__i9P9xJWIT6S, art_obyUE2MdPQWZ

---

## API Access

### Endpoints

| Format | Endpoint |
|--------|----------|
| JSON | `/api/v1/articles/openai-agents-sdk-quick-start-agent-creation-and-tool-definition?format=json` |
| Markdown | `/api/v1/articles/openai-agents-sdk-quick-start-agent-creation-and-tool-definition?format=markdown` |
| Search | `/api/v1/search?q=openai-agents-sdk-quick-start-agent-creation-and-tool-definition` |

### Example Usage

```bash
# Get this article in JSON format
curl "https://buzhou.io/api/v1/articles/openai-agents-sdk-quick-start-agent-creation-and-tool-definition?format=json"

# Get this article in Markdown format
curl "https://buzhou.io/api/v1/articles/openai-agents-sdk-quick-start-agent-creation-and-tool-definition?format=markdown"
```
