OpenAI Agents SDK 入门:实用指南

coding入门17 分钟阅读2026/7/11

上个月,我正在搭建一个客户支持自动化系统。一开始,我写了个简单的脚本,调用了 OpenAI 的 Chat API,外面套了个 while 循环,再硬凑上几个 function calls。这玩意儿吧,勉强能跑。但是,随着需要管理的对话状态、工具执行逻辑,以及协调多个专业 Bot 的工作量增加,代码很快就变成了一团乱麻般的条件判断。后来听说 OpenAI 发布了 Agents SDK,我一开始是持怀疑态度的:我们真的还需要一个新框架吗?但花了一个周末用它重构了我的支持系统后,我确信答案是:确实需要。下面是我的上手过程,包括踩过的坑。

问题所在:Chat API 不等于 Agent

有件事我是吃了苦头才明白的:chat completion 接口并不等于 Agent。当我使用标准的 openai.chat.completions.create() 时,每一次工具调用、每一次向不同“人设”的交接、每一次护栏检查——我都得手动把这些逻辑串起来。我的代码看起来就像是一个没做规划的人硬拼出来的状态机。

OpenAI Agents SDK 解决了这个问题,它提供了恰当的抽象。Agent 不仅仅是一段 prompt;它是一个配置好的实体,拥有名字、指令、模型、可选的工具,以及向其他 Agent 移交任务的能力。SDK 会处理 Agent 循环——也就是调用模型、执行工具、反馈结果、决定何时停止这一整套流程——你就不用自己操心了。

第一步:安装与配置

首先,我创建了一个干净的虚拟环境并安装了 SDK:

mkdir support-agents && cd support-agents
python -m venv venv
source venv/bin/activate
pip install openai-agents

你需要把 OpenAI API 密钥设置为环境变量:

export OPENAI_API_KEY="sk-your-key-here"

我一开始犯了个错,试着运行了 pip install openai-agents-sdk——根本没这个包。包名其实就是 openai-agents。事虽小,但让我懵了十分钟。

第二步:创建你的第一个 Agent

咱们从简单的开始。我想创建一个专门处理退款的 Agent:

from agents import Agent, Runner

refund_agent = Agent(
    name="Refund Specialist",
    instructions="""You are a refund processing specialist for an e-commerce store.
    Help customers with refund requests. Always ask for the order number first.
    Be empathetic but follow policy: refunds are only available within 30 days of purchase.
    If a customer has a question about shipping or product details, say you'll transfer them.""",
    model="gpt-4o"
)

这就行了。不需要搞什么系统消息字典,也不需要手动构建消息数组。你只要定义好 Agent 是谁、做什么,剩下的 SDK 会搞定。

现在,来实际运行一下:

result = await Runner.run(refund_agent, "Hi, I bought a jacket two weeks ago and it doesn't fit. Can I get a refund?")

print(result.final_output)

我第一次跑这段代码时报错了,因为我没用 await 直接调了 Runner.run()——这是个异步函数。你要么在异步上下文里运行它,要么在简单脚本里用 Runner.run_sync()

# 适合快速脚本和测试
result = Runner.run_sync(refund_agent, "Hi, I bought a jacket two weeks ago and it doesn't fit. Can I get a refund?")

print(result.final_output)

输出的效果一开始就出奇地好:

I'm sorry to hear the jacket doesn't fit! I'd be happy to help you with a refund.
Could you please provide your order number so I can look up your purchase details?

Agent 遵循了指令——先问了订单号,有同理心,而且守住了自己的职责边界。

第三步:给 Agent 加上工具

光靠指令走不远。真正的 Agent 需要实事。我想让退款 Agent 能真正查询订单状态,所以我加了个工具:

from agents import Agent, Runner, function_tool

@function_tool
def check_order(order_number: str) -> str:
    """Check the status and date of an order by its order number."""
    # 在生产环境中,这里会查数据库
    fake_orders = {
        "ORD-1234": {"date": "2025-04-10", "status": "delivered", "item": "Winter Jacket"},
        "ORD-5678": {"date": "2025-02-01", "status": "delivered", "item": "Running Shoes"},
    }
    order = fake_orders.get(order_number)
    if order:
        return f"Order {order_number}: {order['item']}, status: {order['status']}, purchased on {order['date']}"
    return f"Order {order_number} not found."

refund_agent = Agent(
    name="Refund Specialist",
    instructions="""You are a refund processing specialist for an e-commerce store.
    Help customers with refund requests. Always ask for the order number first.
    Use the check_order tool to verify the order and purchase date.
    Refunds are only available within 30 days of purchase. Today's date is 2025-05-15.
    If the order is eligible, confirm the refund. If not, explain the policy clearly.""",
    model="gpt-4o",
    tools=[check_order]
)

这里有几个我踩坑得出的经验。第一,文档字符串(docstring)很重要——模型会读它来决定什么时候用这个工具。一定要写清楚。第二,函数参数上的类型提示是必填的。SDK 会利用它们自动生成工具的 schema。如果不写,你会得到莫名其妙的校验报错。

咱们来测试一下:

result = Runner.run_sync(refund_agent, "I want a refund for order ORD-1234")

print(result.final_output)

输出:

I've checked your order. Order ORD-1234 was for a Winter Jacket, purchased on April 10, 2025.
Since your purchase was within the 30-day refund window, you're eligible for a refund!
I've confirmed your refund. You should see the funds back on your original payment method within 5-7 business days.

现在试试不符合条件的订单:

result = Runner.run_sync(refund_agent, "I want a refund for order ORD-5678")

print(result.final_output)

输出:

I've looked up your order. Order ORD-5678 was for Running Shoes, purchased on February 1, 2025.
Unfortunately, our refund policy only allows refunds within 30 days of purchase, and your order
was placed over 30 days ago. I'm unable to process a refund for this order. Is there anything
else I can help you with?

Agent 自己调用了工具,根据规则核对了日期,并给出了恰当的回复。根本不需要我手动写 if/else 判断。

第四步:通过交接(Handoffs)添加多个 Agent

这才是 SDK 真正大放异彩的地方。我的支持系统不能只处理退款。我想要一个分诊 Agent,能把客户路由到合适的专业人员那里:

from agents import Agent, Runner, function_tool

# 工具
@function_tool
def check_order(order_number: str) -> str:
    """Check the status and date of an order by its order number."""
    fake_orders = {
        "ORD-1234": {"date": "2025-04-10", "status": "delivered", "item": "Winter Jacket"},
        "ORD-5678": {"date": "2025-02-01", "status": "delivered", "item": "Running Shoes"},
    }
    order = fake_orders.get(order_number)
    if order:
        return f"Order {order_number}: {order['item']}, status: {order['status']}, purchased on {order['date']}"
    return f"Order {order_number} not found."

@function_tool
def search_faq(query: str) -> str:
    """Search the FAQ for answers to common questions."""
    faq = {
        "shipping": "Standard shipping takes 3-5 business days. Express shipping takes 1-2 business days.",
        "returns": "Returns are accepted within 30 days of purchase with original tags attached.",
        "sizing": "Our sizing runs true to standard US sizes. Check the size chart on each product page.",
    }
    for key, value in faq.items():
        if key in query.lower():
            return value
    return "No FAQ match found. Please transfer to a human agent."

# 专业 Agent
refund_agent = Agent(
    name="Refund Specialist",
    instructions="""You handle refund requests. Always verify the order using check_order first.
    Refunds only within 30 days. Today is 2025-05-15. Be empathetic and clear about policy.""",
    model="gpt-4o",
    tools=[check_order],
)

faq_agent = Agent(
    name="FAQ Agent",
    instructions="""You answer general questions about shipping, returns policy, and sizing.
    Use the search_faq tool to find answers. If you can't find an answer, say you'll transfer to a human.""",
    model="gpt-4o",
    tools=[search_faq],
)

# 分诊 - 门面担当
triage_agent = Agent(
    name="Support Triage",
    instructions="""You are the first point of contact for customer support.
    Determine what the customer needs and transfer them to the right specialist:
    - Refund requests -> Refund Specialist
    - General questions about shipping, sizing, or returns policy -> FAQ Agent
    If you're unsure, ask a clarifying question before transferring.""",
    model="gpt-4o",
    handoffs=[refund_agent, faq_agent],
)

handoffs 参数是关键。它告诉分诊 Agent 可以把任务移交给哪些其他 Agent。SDK 会自动创建模型可以调用的交接工具。

运行一下:

result = Runner.run_sync(triage_agent, "How long does shipping usually take?")

print(result.final_output)

幕后发生了这样的事:分诊 Agent 识别出这是一个 FAQ 问题,把它交给了 FAQ Agent,FAQ Agent 使用了搜索工具,然后你得到了答案。result 对象还会记录完整的历史,所以你可以看到交接路径:

for event in result.all_model_responses:
    print(f"Agent: {event.agent_name}, Action: {event.type}")

第五步:检查到底发生了什么

早期让我踩坑的一件事:理解 Agent 的决策过程。SDK 提供了追踪功能,这帮我省了几个小时的调试时间:

from agents import trace

with trace("support-session-1"):
    result = Runner.run_sync(triage_agent, "I want a refund for ORD-5678")

这会记录完整的执行追踪,包括每一步是哪个 Agent 在活跃、调用了什么工具,以及为什么发生交接。你可以在 OpenAI 的控制台里查看这些信息。要是没这功能,当 Agent 做出意外交接时,我简直就是两眼一抹黑。

实用建议与坦诚的局限性

用这个 SDK 开发了几周后,有些话我真希望一开始就有人告诉我:

建议:

  • 先从单个 Agent 跑通开始,再加交接功能。多 Agent 系统的调试难度超乎你的想象。
  • 指令一定要极其具体。模糊的指令会导致模糊的行为,而在 Agent 身上,这就意味着乱调工具和瞎交接。
  • 开发和测试时用 Runner.run_sync(),上线生产环境时再切回异步。
  • 工具函数一定要加上类型提示和文档字符串。SDK 靠它们生成工具 schema,缺少或写错类型会导致静默失败。
  • 测试时把模型设为 model="gpt-4o-mini" 来省钱。它的行为跟大模型差不多,足够用来迭代,等上线再切回 gpt-4o

局限性:

  • SDK 还比较新,文档依然很少。我在交接链(Agent A 交接给 B,B 又交接给 C)上遇到了一些边界情况,文档里根本没写。
  • 工具执行默认是本地且同步的。如果你需要调用带重试、超时或异步行为的外部 API,你得自己在工具函数内部处理。
  • 没有内置的记忆或对话持久化。每次 Runner.run() 调用都是独立的。对于多轮对话,你需要自己管理对话历史并传回去。
  • 护栏系统虽然有,但很基础。如果你需要复杂的输出校验或内容过滤,打算好自己再加几层吧。

OpenAI Agents SDK 并不完美,但它解决了我面临的核心问题:把一团乱麻的手写 Agent 循环变成了结构清晰、易于维护的代码。对于我的支持自动化项目来说,它让我的代码量减半,而且 Agent 的行为变得可预测多了。如果你在开发任何超越简单聊天机器人的东西——尤其是包含多个专业角色和工具调用的系统——这绝对值得你花时间去学学。

相关 Agent

G

GitHub Copilot

AI结对编程助手,提供实时代码建议。

了解更多 →