惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
有赞技术团队
有赞技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
Y
Y Combinator Blog
Jina AI
Jina AI
G
Google Developers Blog
Last Week in AI
Last Week in AI
博客园 - 叶小钗
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LangChain Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
Visual Studio Blog
aimingoo的专栏
aimingoo的专栏
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
J
Java Code Geeks
Stack Overflow Blog
Stack Overflow Blog
IT之家
IT之家
The GitHub Blog
The GitHub Blog
D
Docker
量子位
罗磊的独立博客
腾讯CDC

OpenAI Developers

API deployment checklist | OpenAI API Sora 2 Prompting Guide Codex Prompting Guide Docs MCP | OpenAI Developers Gpt-image-1.5 Prompting Guide GPT-5.2 Prompting Guide Transcribing User Audio with a Separate Realtime Request Modernizing your Codebase with Codex GitHub - openai/openai-sora-sample-app: Sample app to get started using the Video API with Sora GitHub - openai/openai-apps-sdk-examples: Example apps for the Apps SDK GitHub - openai/openai-chatkit-advanced-samples: Starter app to build with OpenAI ChatKit SDK GitHub - openai/openai-chatkit-starter-app: Starter app to build with OpenAI ChatKit + Agent Builder Rate limits | OpenAI API Web search | OpenAI API Getting started with datasets | OpenAI API Prompt optimizer | OpenAI API Verifying gpt-oss implementations How to run gpt-oss locally with LM Studio Fine-tuning with gpt-oss and Hugging Face Transformers How to run gpt-oss locally with Ollama Function calling | OpenAI API Models | OpenAI API Reasoning best practices | OpenAI API Reasoning models | OpenAI API Background mode | OpenAI API Batch API | OpenAI API Conversation state | OpenAI API File search | OpenAI API Flex processing | OpenAI API MCP and Connectors | OpenAI API
Quickstart - OpenAI Agents SDK
2025-07-21 · via OpenAI Developers

Create a project and virtual environment

You'll only need to do this once.

mkdir my_project
cd my_project
python -m venv .venv

Activate the virtual environment

Do this every time you start a new terminal session.

On macOS or Linux:

source .venv/bin/activate

On Windows:

Install the Agents SDK

pip install openai-agents # or `uv add openai-agents`, etc

Set an OpenAI API key

If you don't have one, follow these instructions to create an OpenAI API key.

These commands set the key for your current terminal session.

On macOS or Linux:

export OPENAI_API_KEY=sk-...

On Windows PowerShell:

$env:OPENAI_API_KEY = "sk-..."

On Windows Command Prompt:

set "OPENAI_API_KEY=sk-..."

Create your first agent

Agents are defined with instructions, a name, and optional configuration such as a specific model.

from agents import Agent

agent = Agent(
    name="History Tutor",
    instructions="You answer history questions clearly and concisely.",
)

Run your first agent

Use Runner to execute the agent and get a RunResult back.

import asyncio
from agents import Agent, Runner

agent = Agent(
    name="History Tutor",
    instructions="You answer history questions clearly and concisely.",
)

async def main():
    result = await Runner.run(agent, "When did the Roman Empire fall?")
    print(result.final_output)

if __name__ == "__main__":
    asyncio.run(main())

For a second turn, you can either pass result.to_input_list() back into Runner.run(...), attach a session, or reuse OpenAI server-managed state with conversation_id / previous_response_id. The running agents guide compares these approaches.

Use this rule of thumb:

If you want... Start with...
Full manual control and provider-agnostic history result.to_input_list()
The SDK to load and save history for you session=...
OpenAI-managed server-side continuation previous_response_id or conversation_id

For the tradeoffs and exact behaviors, see Running agents.

Use a plain Agent plus Runner when the task mainly lives in prompts, tools, and conversation state. If the agent should inspect or modify real files in an isolated workspace, jump to the Sandbox agents quickstart.

You can give an agent tools to look up information or perform actions.

import asyncio
from agents import Agent, Runner, function_tool


@function_tool
def history_fun_fact() -> str:
    """Return a short history fact."""
    return "Sharks are older than trees."


agent = Agent(
    name="History Tutor",
    instructions="Answer history questions clearly. Use history_fun_fact when it helps.",
    tools=[history_fun_fact],
)


async def main():
    result = await Runner.run(
        agent,
        "Tell me something surprising about ancient life on Earth.",
    )
    print(result.final_output)


if __name__ == "__main__":
    asyncio.run(main())

Add a few more agents

Before you choose a multi-agent pattern, decide who should own the final answer:

  • Handoffs: a specialist takes over the conversation for that part of the turn.
  • Agents as tools: an orchestrator stays in control and calls specialists as tools.

This quickstart continues with handoffs because it is the shortest first example. For the manager-style pattern, see Agent orchestration and Tools: agents as tools.

Additional agents can be defined in the same way. handoff_description gives the routing agent extra context about when to delegate.

from agents import Agent

history_tutor_agent = Agent(
    name="History Tutor",
    handoff_description="Specialist agent for historical questions",
    instructions="You answer history questions clearly and concisely.",
)

math_tutor_agent = Agent(
    name="Math Tutor",
    handoff_description="Specialist agent for math questions",
    instructions="You explain math step by step and include worked examples.",
)

Define your handoffs

On an agent, you can define an inventory of outgoing handoff options that it can choose from while solving the task.

triage_agent = Agent(
    name="Triage Agent",
    instructions="Route each homework question to the right specialist.",
    handoffs=[history_tutor_agent, math_tutor_agent],
)

Run the agent orchestration

The runner handles executing individual agents, any handoffs, and any tool calls.

import asyncio
from agents import Runner


async def main():
    result = await Runner.run(
        triage_agent,
        "Who was the first president of the United States?",
    )
    print(result.final_output)
    print(f"Answered by: {result.last_agent.name}")


if __name__ == "__main__":
    asyncio.run(main())

Reference examples

The repository includes full scripts for the same core patterns:

View your traces

To review what happened during your agent run, navigate to the Trace viewer in the OpenAI Dashboard to view traces of your agent runs.

Next steps

Learn how to build more complex agentic flows: