并行运行OpenAI Agents SDK的专用代理

您为什么要这样做? 在许多生产工作流中,您必须针对同一内容回答几个独立的问题。 逐一进行这些分析会增加延迟,并且如果任何步骤失败并强制重试,可能会增加总成本。 通过同时“分发”多个专用代理,然后将它们的输出“汇集”到一个最终的“元”代理中,您可以减少此延迟。

本笔记本提供了一个玩具示例,您可能不会在现实世界中对其进行并行化,但它展示了:

  1. 如何使用OpenAI Agents SDK定义几个专注的代理。
  2. 如何使用Python的 asyncio 实现较低延迟、轻量级并行化,或直接通过 Agents SDK 实现并行化,以方便管理和动态工具调用规划。
  3. 如何收集它们的各个输出并将它们输入到生成最终、用户就绪答案的下游元代理中。
  4. 一个简单的时间线可视化,以便您可以看到并行化的延迟优势。

此模式可以应用于现实场景,例如客户支持分类、内容审核或其他您可能希望对输入运行多个独立分析并将其合并为单一结果的场景。

  1. 安装依赖项
%pip install openai-agents asyncio matplotlib nest_asyncio

import time

import asyncio
import matplotlib.pyplot as plt
import nest_asyncio

from agents import Agent, Runner

nest_asyncio.apply()
  1. 定义您的代理
# 专注于产品功能的代理
features_agent = Agent(
    name="FeaturesAgent",
    instructions="从评论中提取关键产品功能。"
)

# 专注于优缺点的代理
pros_cons_agent = Agent(
    name="ProsConsAgent",
    instructions="列出评论中提到的优点和缺点。"
)

# 专注于情感分析的代理
sentiment_agent = Agent(
    name="SentimentAgent",
    instructions="总结评论中的整体用户情感。"
)

# 专注于推荐摘要的代理
recommend_agent = Agent(
    name="RecommendAgent",
    instructions="说明您是否会推荐此产品以及原因。"
)

parallel_agents = [
    features_agent,
    pros_cons_agent,
    sentiment_agent,
    recommend_agent
]

# 用于合并输出的元代理
meta_agent = Agent(
    name="MetaAgent",
    instructions="您将获得多个标记为功能、优缺点、情感和推荐的摘要。"
    "将它们合并为产品评论的简洁执行摘要,并为每个摘要区域提供1-5星的评分。"
)
starts, ends = [], []
async def run_agent(agent, review_text: str):
    agent_name = agent.name

    start = time.time()
    starts.append((agent_name, start))

    result = await Runner.run(agent, review_text)

    end = time.time()
    ends.append((agent_name, end))

    return result
  1. 创建并行执行函数
async def run_agents(review_text: str):
    responses = await asyncio.gather(
        *(run_agent(agent, review_text) for agent in parallel_agents)
    )

    labeled_summaries = [
        f"### {resp.last_agent.name}\n{resp.final_output}"
        for resp in responses
    ]

    collected_summaries = "\n".join(labeled_summaries)
    final_summary = await run_agent(meta_agent, collected_summaries)


    print('Final summary:', final_summary.final_output)

    return
review_text = """
I recently upgraded to the AuroraSound X2 wireless noise-cancelling headphones, and after two weeks of daily use I have quite a bit to share. First off, the design feels premium without being flashy: the matte‐finish ear cups are softly padded and rotate smoothly for storage, while the headband’s memory‐foam cushion barely presses on my temples even after marathon work calls. Connectivity is seamless—pairing with my laptop and phone took under five seconds each time, and the Bluetooth 5.2 link held rock-solid through walls and down the hallway.

The noise-cancelling performance is genuinely impressive. In a busy café with music and chatter swirling around, flipping on ANC immediately quiets low-level ambient hums, and it even attenuates sudden noises—like the barista’s milk frother—without sounding distorted. The “Transparency” mode is equally well‐tuned: voices come through clearly, but the world outside isn’t overwhelmingly loud. Audio quality in standard mode is rich and balanced, with tight bass, clear mids, and a hint of sparkle in the highs. There’s also a dedicated EQ app, where you can toggle between “Podcast,” “Bass Boost,” and “Concert Hall” presets or craft your own curve.

On the control front, intuitive touch panels let you play/pause, skip tracks, and adjust volume with a simple swipe or tap. One neat trick: holding down on the right ear cup invokes your phone’s voice assistant. Battery life lives up to the hype, too—over 30 hours with ANC on, and the quick‐charge feature delivers 2 hours of playtime from just a 10-minute top‐up.

That said, it isn’t perfect. For one, the carrying case is a bit bulky, so it doesn’t slip easily into a slim bag. And while the touch interface is mostly reliable, I occasionally trigger a pause when trying to adjust the cup position. The headphones also come in only two colorways—black or white—which feels limiting given the premium price point.
"""

asyncio.get_event_loop().run_until_complete(run_agents(review_text))

def plot_timeline(starts, ends):

    # Plot the timeline of the agents
    # normalize times to zero
    base = min(t for _, t in starts)
    labels = [n for n, _ in starts]
    start_offsets = [t - base for _, t in starts]
    lengths = [ends[i][1] - starts[i][1] for i in range(len(starts))]

    plt.figure(figsize=(8, 3))
    plt.barh(labels, lengths, left=start_offsets)
    plt.xlabel("Seconds since kickoff")
    plt.title("Agent Execution Timeline")
    plt.show()

plot_timeline(starts, ends)
Final summary: ### FeaturesAgent

The AuroraSound X2 headphones feature a premium matte-finish design with comfortable, memory-foam padded earcups that rotate for storage. The headband is also cushioned for comfort during long calls. They offer seamless Bluetooth 5.2 connectivity, pairing quickly with multiple devices and maintaining a stable connection. The noise-cancelling is highly effective, reducing ambient noise and even sudden sounds without distortion. The "Transparency" mode allows clear voice passthrough. Audio quality is rich and balanced, with customizable EQ presets (Podcast, Bass Boost, Concert Hall) available via an app. Controls are intuitive touch panels for playback and volume adjustment. A neat feature is the ability to invoke the phone's voice assistant by holding the right earcup. Battery life is rated at over 30 hours with ANC on, and a 10-minute quick charge provides 2 hours of playtime.

### ProsConsAgent

**Pros:**

*   Premium design and comfortable fit for extended wear.
*   Seamless and stable Bluetooth 5.2 connectivity.
*   Impressive noise-cancelling performance that handles ambient and sudden noises well.
*   Well-tuned "Transparency" mode for clear voice passthrough.
*   Rich and balanced audio quality with customizable EQ options.
*   Intuitive touch controls for playback and volume.
*   Long battery life (30+ hours with ANC).
*   Quick-charge feature (2 hours from 10 minutes).
*   Voice assistant integration.

**Cons:**

*   Carrying case is bulky.
*   Occasional accidental triggering of touch controls when adjusting earcups.
*   Limited color options (only black or white).

### SentimentAgent

The overall user sentiment for the AuroraSound X2 headphones is highly positive. Users are impressed with the premium design, comfort, seamless connectivity, and the effectiveness of the noise-cancelling and transparency modes. The audio quality and battery life are also significant highlights. While there are minor drawbacks like a bulky case, occasional touch control sensitivity, and limited color choices, these do not seem to detract significantly from the overall positive user experience.

### RecommendAgent

Yes, I would recommend the AuroraSound X2 wireless noise-cancelling headphones. They offer a compelling combination of premium design, excellent comfort, robust noise-cancelling technology, and high-quality audio. The seamless connectivity and long battery life further enhance their appeal. While the carrying case could be more compact and the touch controls occasionally finicky, these are minor issues compared to the overall strong performance and features. They are a great choice for users looking for a high-quality audio experience.

Final summary: ### Executive Summary

The AuroraSound X2 wireless noise-cancelling headphones offer a blend of premium design and advanced features. The headphones boast a matte-finish with comfortable, memory-foam padding, making them ideal for extended use. With Bluetooth 5.2, they provide seamless connectivity and stable communication. The noise-cancelling capabilities effectively reduce ambient noise and feature a well-tuned Transparency mode for essential sound transmission.

**Audio Quality** is a highlight, delivering rich, balanced sound with customizable EQ presets including “Podcast,” “Bass Boost,” and “Concert Hall.” Intuitive touch controls allow for easy navigation, though some users report occasional misfires. The extended battery life offers over 30 hours with ANC on, with a quick-charge option for convenience.

**Minor Limitations** include a bulky carrying case, occasional touch control issues, and limited color choices (black or white). Despite these, the overall sentiment is highly positive, with users particularly appreciating the headphones' design, connectivity, and performance. The product is recommended for those seeking high-quality audio experiences with effective noise-cancelling features.

### Star Ratings

- **Features**: ★★★★☆
- **Pros & Cons**: ★★★★☆
- **Sentiment**: ★★★★★
- **Recommendation**: ★★★★★

Overall, the AuroraSound X2 headphones are a compelling choice, offering excellent value despite minor drawbacks.

![png](parallel_agents_files/parallel_agents_8_1.png)

代理也可以通过SDK直接通过“代理作为工具”的路线进行并行化,从而增加便利性并由规划器动态决定调用哪些工具,但会以更高的延迟为代价。这种延迟既来自于前期额外的规划API调用,也来自于工具调用对象更高开销和上下文。

from agents import ModelSettings


meta_agent_parallel_tools = Agent(
    name="MetaAgent",
    instructions="您将获得多个标记为功能、优缺点、情感和推荐的摘要。"
    "将它们合并为产品评论的简洁执行摘要,并为每个摘要区域提供1-5星的评分。",
   model_settings=ModelSettings(
       parallel_tool_calls=True
   ),
    tools=[
        features_agent.as_tool(
            tool_name="features",
            tool_description="从评论中提取关键产品功能。",
        ),
        pros_cons_agent.as_tool(
            tool_name="pros_cons",
            tool_description="列出评论中提到的优点和缺点。",
        ),
        sentiment_agent.as_tool(
            tool_name="sentiment",
            tool_description="总结评论中的整体用户情感。",
        ),
        recommend_agent.as_tool(
            tool_name="recommend",
            tool_description="说明您是否会推荐此产品以及原因。",
        ),
    ],
)

starts, ends = [], []
result = await run_agent(meta_agent_parallel_tools, review_text)

print('Final summary:', result.final_output)

plot_timeline(starts, ends)
Final summary: **Executive Summary: AuroraSound X2 Wireless Noise-Cancelling Headphones**

**Features (⭐️⭐️⭐️⭐️⭐️ 5/5):** The headphones boast a premium, matte-finish design with comfortable memory-foam cushioning. They offer seamless Bluetooth 5.2 connectivity, impressive noise-cancelling capabilities, and a well-tuned "Transparency" mode. The audio quality is rich and balanced, with customizable sound options via a dedicated EQ app. Additional features include intuitive touch controls and excellent battery life paired with a quick-charge option.

**Pros and Cons (⭐️⭐️⭐️⭐️ 4/5):**

- **Pros:** Premium design, comfortable fit, seamless connectivity, effective noise-cancelling, clear voice input in "Transparency" mode, customizable audio, intuitive controls, long battery life.
- **Cons:** Bulky carrying case, occasional touch control sensitivity issues, limited color options.

**Sentiment (⭐️⭐️⭐️⭐️ 4/5):** The overall sentiment is highly positive, with appreciation for the design, comfort, connectivity, noise-cancelling effectiveness, and audio quality. Minor drawbacks are noted but do not outweigh the benefits.

**Recommendation (⭐️⭐️⭐️⭐️ 4/5):** Highly recommended for those seeking premium noise-cancelling headphones with versatile features and excellent audio performance. The minor drawbacks are outweighed by the comprehensive suite of high-quality features.

![png](parallel_agents_files/parallel_agents_10_1.png)

Summary

From the above, we can see two different patterns for parallelizing agents. Ultimately, the approach you use will depend on the balance you want between:

  1. Convenience vs. customization
    • If you prefer convenience, the agent as tool route is the way to go. If you want to customize how agents fan in and out across multiple layers, building a graph with asyncio.gather might make more sense
  2. Planning vs. determinism
    • If you want your planner (in this case the meta agent) to dynamically decide which tools to call and the order, you should use agents as tools whereas asyncio.gather makes more sense if you want a deterministic order.
  3. Latency sensitivity
    • If you're highly sensitive to latency, you may want to use asyncio to avoid the additional upfront cost of planning the parallel tools and the overhead of tool outputs and longer context windows.