Skip to content

第 3 章:并行化 ​

并行化模式概览 ​

前几章介绍了顺序工作流中的提示链(Prompt Chaining),以及用于动态决策与路径切换的路由(Routing)。二者都很重要,但许多复杂的智能体任务包含多个可以 同时 (concurrently) 推进、而非逐项串行执行的子任务——这时,并行化 (Parallelization) 就尤为关键。

并行化即并发运行多个组件:LLM 调用、工具使用,乃至多个完整的子智能体(见图 1)。不必等上一步结束再开下一步;彼此独立的任务可同时推进,从而显著压缩那些能够拆分为独立并行部分的任务的总耗时。

子智能体并行化

图 1. 子智能体并行化示例

设想一个要调研主题并汇总结论的智能体。若按顺序来做,大致是:

  1. 检索来源 A。
  2. 总结来源 A。
  3. 检索来源 B。
  4. 总结来源 B。
  5. 从摘要 A 与 B 综合出最终答案。

若改走并行,则可以:

  1. 同时 检索来源 A 与来源 B。
  2. 两次检索均完成后,同时 总结来源 A 与来源 B。
  3. 再据摘要 A、B 综合最终答案(这一步一般仍须串行,需等并行阶段全部结束)。

核心在于识别工作流中那些不依赖其他步骤即时输出的环节,并将它们并行执行。当任务涉及 API、数据库等本身就有往返延迟的外部服务时,这种做法尤为有效:可以一次性并发发起多条请求。

落地并行化往往需要框架支持异步执行,或多线程/多进程。当代智能体框架普遍面向异步设计,定义可并行执行的步骤也更为顺手。

LangChain、LangGraph、Google ADK 等框架都提供并行执行能力。在 LangChain 表达式语言(LCEL)中,可通过将多个 runnable 组织成并行结构,让多条路径同时运行。LangGraph 则借助图拓扑来表达工作流:从同一次状态转移中扇出多个节点,自然形成并行分支。Google ADK 则原生支持多智能体的并行编排,有助于提升复杂系统的吞吐与扩展性,让“多智能体同时运行”成为一等能力。

并行化能明显提升智能体系统的效率与响应速度,在多次独立查询、并行计算或同时调用多条外部接口时尤其明显,是复杂工作流中常用的性能优化手段。

实际应用与用例 ​

并行化在多种场景下都能显著提升智能体系统的表现:

1. 信息收集与研究 ​

同时从多处拉取信息,是最典型的用法之一。

  • 用例: 研究某家公司的智能体。
    • 并行任务: 同时搜索新闻、拉取股价数据、查看社交媒体提及,并查询公司数据库。
    • 收益: 比顺序查询更快获得全面视图。

2. 数据处理与分析 ​

对不同数据片段并行采用不同分析方法,或对同一批数据并行运行多种分析。

  • 用例: 分析客户反馈的智能体。
    • 并行任务: 在一批反馈条目上同时运行情感分析、关键词抽取、分类与紧急问题识别。
    • 收益: 快速得到多维度分析。

3. 多 API 或工具交互 ​

并行调用彼此独立的 API 或工具,分别取数或执行不同动作。

  • 用例: 旅行规划智能体。
    • 并行任务: 同时查机票、搜酒店空房、查当地活动、找餐厅推荐。
    • 收益: 更快呈现完整行程方案。

4. 多组件内容生成 ​

把一篇复杂内容拆成多块,并行生成后再拼装。

  • 用例: 撰写营销邮件的智能体。
    • 并行任务: 同时生成主题行、正文草稿、相关配图与行动号召按钮文案。
    • 收益: 更高效组装最终邮件。

5. 校验与验证 ​

多条彼此独立的校验规则或检查项,可一并跑完。

  • 用例: 校验用户输入的智能体。
    • 并行任务: 同时检查邮箱格式、验证电话、对照数据库校验地址、检测不当用语。
    • 收益: 更快反馈输入是否有效。

6. 多模态处理 ​

针对同一输入,对文本、图像、音频等不同模态并行处理。

  • 用例: 分析同时包含文字与图片的社交媒体帖子的智能体。
    • 并行任务: 同时对文本进行情感与关键词分析,并对图像进行物体识别与场景描述分析。
    • 收益: 更快整合不同模态的洞察。

7. A/B 测试或多方案生成 ​

并行产出多版回复或结果,便于对比后择优。

  • 用例: 生成多种创意文案选项的智能体。
    • 并行任务: 用略有不同的提示或模型同时为文章生成三个标题。
    • 收益: 便于快速比较并选出最佳方案。

并行化(Parallelization) 是智能体设计中的基础优化手段:将彼此独立、可并行的任务并发执行,应用整体会更快,响应也更及时。

动手代码示例(LangChain) ​

在 LangChain 里,并行主要靠 LangChain 表达式语言(LCEL):把多个可运行组件放进字典或列表;该集合再作为下游环节的输入时,LCEL 会并发调度其中的各个 runnable。

LangGraph 把同一思路落在图结构上:让若干彼此没有直接先后依赖的节点,从同一个父节点一并扇出;各分支并行推进,再在后面的汇合节点上汇总结果。

下面的示例用 LangChain 搭了一条并行工作流:同一条用户查询会并发触发多条彼此独立的处理链路(摘要、问题、关键词等),最后再合并输出。

运行前需安装相关 Python 包(如 langchain、langchain-community、langchain-openai 等),并在本机为所选模型提供商配置有效的 API 密钥。

python
import os
import asyncio
from typing import Optional

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import Runnable, RunnableParallel, RunnablePassthrough

# --- Configuration ---
# Ensure your API key environment variable is set (e.g., OPENAI_API_KEY)
try:
    llm: Optional[ChatOpenAI] = ChatOpenAI(model="gpt-4o-mini", temperature=0.7)
except Exception as e:
    print(f"Error initializing language model: {e}")
    llm = None

# --- Define Independent Chains ---
# These three chains represent distinct tasks that can be executed in parallel.
summarize_chain: Runnable = (
    ChatPromptTemplate.from_messages([
        ("system", "Summarize the following topic concisely:"),
        ("user", "{topic}"),
    ])
    | llm
    | StrOutputParser()
)

questions_chain: Runnable = (
    ChatPromptTemplate.from_messages([
        ("system", "Generate three interesting questions about the following topic:"),
        ("user", "{topic}"),
    ])
    | llm
    | StrOutputParser()
)

terms_chain: Runnable = (
    ChatPromptTemplate.from_messages([
        ("system", "Identify 5-10 key terms from the following topic, separated by commas:"),
        ("user", "{topic}"),
    ])
    | llm
    | StrOutputParser()
)

# --- Build the Parallel + Synthesis Chain ---
# 1. Define the block of tasks to run in parallel. The results of these,
#    along with the original topic, will be fed into the next step.
map_chain = RunnableParallel(
    {
        "summary": summarize_chain,
        "questions": questions_chain,
        "key_terms": terms_chain,
        "topic": RunnablePassthrough(),  # Pass the original topic through
    }
)

# 2. Define the final synthesis prompt which will combine the parallel results.
synthesis_prompt = ChatPromptTemplate.from_messages([
    (
        "system",
        """Based on the following information:
        Summary: {summary}
        Related Questions: {questions}
        Key Terms: {key_terms}
        Synthesize a comprehensive answer."""
    ),
    ("user", "Original topic: {topic}"),
])

# 3. Construct the full chain by piping the parallel results directly
#    into the synthesis prompt, followed by the LLM and output parser.
full_parallel_chain = map_chain | synthesis_prompt | llm | StrOutputParser()

# --- Run the Chain ---
async def run_parallel_example(topic: str) -> None:
    """
    Asynchronously invokes the parallel processing chain with a specific topic
    and prints the synthesized result.

    Args:
        topic: The input topic to be processed by the LangChain chains.
    """
    if not llm:
        print("LLM not initialized. Cannot run example.")
        return

    print(f"\n--- Running Parallel LangChain Example for Topic: '{topic}' ---")
    try:
        # The input to `ainvoke` is the single 'topic' string,
        # then passed to each runnable in the `map_chain`.
        response = await full_parallel_chain.ainvoke(topic)
        print("\n--- Final Response ---")
        print(response)
    except Exception as e:
        print(f"\nAn error occurred during chain execution: {e}")

if __name__ == "__main__":
    test_topic = "The history of space exploration"
    # In Python 3.7+, asyncio.run is the standard way to run an async function.
    asyncio.run(run_parallel_example(test_topic))

这段 Python 示例借助 LangChain 并发运行多条链路,以加快对同一主题的处理。需要注意的是,asyncio 带来的是并发(协作式多任务),并不等同于多核意义上的并行:在单线程中,它依靠事件循环在 I/O 等待期间切换协程,看起来像是“同时推进”;但受 GIL 影响,CPU 密集型部分通常仍主要在单线程内执行。

代码从 langchain_openai、langchain_core 引入模型、提示模板、输出解析与 runnable 抽象;尝试创建 ChatOpenAI(gpt-4o-mini)并设置 temperature,初始化失败时由 try-except 捕获异常,避免示例直接崩溃。接着定义三条互不依赖的链:一条做简短摘要,一条生成三个延伸问题,一条抽取 5–10 个逗号分隔的关键词。每条链都是「ChatPromptTemplate → 模型 → StrOutputParser」。

随后用 RunnableParallel 将三条链组合为并行执行;并行块里还用 RunnablePassthrough 把原始 topic 原样传给下游。再配一个综合用的 ChatPromptTemplate,将摘要、问题、关键词和原始主题一并作为输入传给模型。full_parallel_chain 即 map_chain | synthesis_prompt | llm | StrOutputParser。run_parallel_example 用 ainvoke 异步调用整条链;if __name__ == "__main__": 里以主题「The history of space exploration」调用 asyncio.run 启动示例。

概括而言:先围绕同一主题并行发起多次 LLM 调用(摘要、追问、术语抽取),再由最后一次 LLM 调用完成综合——这就是 LangChain 场景下并行化的典型骨架。

动手代码示例(Google ADK) ​

接下来看 Google ADK 里的具体例子:ParallelAgent、SequentialAgent 等原语怎样拼出一条「先并行、再汇总」的智能体流水线,以提升整体效率。

python
from google.adk.agents import LlmAgent, ParallelAgent, SequentialAgent
from google.adk.tools import google_search

GEMINI_MODEL = "gemini-2.0-flash"

# --- 1. Define Researcher Sub-Agents (to run in parallel) ---

# Researcher 1: Renewable Energy
researcher_agent_1 = LlmAgent(
    name="RenewableEnergyResearcher",
    model=GEMINI_MODEL,
    instruction="""You are an AI Research Assistant specializing in energy. Research the latest advancements in 'renewable energy sources'. Use the Google Search tool provided. Summarize your key findings concisely (1-2 sentences). Output *only* the summary. """,
    description="Researches renewable energy sources.",
    tools=[google_search],
    # Store result in state for the merger agent
    output_key="renewable_energy_result",
)

# Researcher 2: Electric Vehicles
researcher_agent_2 = LlmAgent(
    name="EVResearcher",
    model=GEMINI_MODEL,
    instruction="""You are an AI Research Assistant specializing in transportation. Research the latest developments in 'electric vehicle technology'. Use the Google Search tool provided. Summarize your key findings concisely (1-2 sentences). Output *only* the summary. """,
    description="Researches electric vehicle technology.",
    tools=[google_search],
    # Store result in state for the merger agent
    output_key="ev_technology_result",
)

# Researcher 3: Carbon Capture
researcher_agent_3 = LlmAgent(
    name="CarbonCaptureResearcher",
    model=GEMINI_MODEL,
    instruction="""You are an AI Research Assistant specializing in climate solutions. Research the current state of 'carbon capture methods'. Use the Google Search tool provided. Summarize your key findings concisely (1-2 sentences). Output *only* the summary. """,
    description="Researches carbon capture methods.",
    tools=[google_search],
    # Store result in state for the merger agent
    output_key="carbon_capture_result",
)

# --- 2. Create the ParallelAgent (Runs researchers concurrently) ---
# This agent orchestrates the concurrent execution of the researchers.
# It finishes once all researchers have completed and stored their results in state.
parallel_research_agent = ParallelAgent(
    name="ParallelWebResearchAgent",
    sub_agents=[researcher_agent_1, researcher_agent_2, researcher_agent_3],
    description="Runs multiple research agents in parallel to gather information.",
)

# --- 3. Define the Merger Agent (Runs after the parallel agents) ---
# This agent takes the results stored in the session state by the parallel agents
# and synthesizes them into a single, structured response with attributions.
merger_agent = LlmAgent(
    name="SynthesisAgent",
    model=GEMINI_MODEL,  # Or potentially a more powerful model if needed for synthesis
    instruction="""You are an AI Assistant responsible for combining research findings into a structured report. Your primary task is to synthesize the following research summaries, clearly attributing findings to their source areas. Structure your response using headings for each topic. Ensure the report is coherent and integrates the key points smoothly.

**Crucially:** Your entire response MUST be grounded *exclusively* on the information provided in the 'Input Summaries' below. Do NOT add any external knowledge, facts, or details not present in these specific summaries.

**Input Summaries:**
*   **Renewable Energy:**
    {renewable_energy_result}
*   **Electric Vehicles:**
    {ev_technology_result}
*   **Carbon Capture:**
    {carbon_capture_result}

**Output Format:**
## Summary of Recent Sustainable Technology Advancements

### Renewable Energy Findings (Based on RenewableEnergyResearcher's findings)
[Synthesize and elaborate *only* on the renewable energy input summary provided above.]

### Electric Vehicle Findings (Based on EVResearcher's findings)
[Synthesize and elaborate *only* on the EV input summary provided above.]

### Carbon Capture Findings (Based on CarbonCaptureResearcher's findings)
[Synthesize and elaborate *only* on the carbon capture input summary provided above.]

### Overall Conclusion
[Provide a brief (1-2 sentence) concluding statement that connects *only* the findings presented above.]

Output *only* the structured report following this format. Do not include introductory or concluding phrases outside this structure, and strictly adhere to using only the provided input summary content.
""",
    description="Combines research findings from parallel agents into a structured, cited report, strictly grounded on provided inputs.",
    # No tools needed for merging
    # No output_key needed here, as its direct response is the final output of the sequence
)

# --- 4. Create the SequentialAgent (Orchestrates the overall flow) ---
# This is the main agent that will be run. It first executes the ParallelAgent
# to populate the state, and then executes the MergerAgent to produce the final output.
sequential_pipeline_agent = SequentialAgent(
    name="ResearchAndSynthesisPipeline",
    # Run parallel research first, then merge
    sub_agents=[parallel_research_agent, merger_agent],
    description="Coordinates parallel research and synthesizes the results.",
)

root_agent = sequential_pipeline_agent

示例搭建了一个多智能体调研与综述系统:三个 LlmAgent 分头负责可再生能源、电动车技术、碳捕集方法;均使用 GEMINI_MODEL 与 google_search,各用 1–2 句话写小结,并通过各自的 output_key 写回会话状态。(代码里实例名为 researcher_agent_1 等。)

接着用 ParallelAgent(示例名 ParallelWebResearchAgent)并行拉起三名研究员,以缩短实际经过的时间;待各子智能体执行完毕并将结果写入状态,本阶段即结束。

再定义 MergerAgent(同样是 LlmAgent)做综述:它读取各研究员写入状态的摘要;系统提示要求全文严格依据所给材料、不得臆补;输出按分主题标题组织,并附简短总结段。

最后用 SequentialAgent(ResearchAndSynthesisPipeline)串起全局:先跑并行调研,再跑合并智能体。sequential_pipeline_agent 作为 root_agent 即对外入口。整体思路是「多路并行采数 → 一路结构化成文」。

速览 ​

是什么: 很多智能体任务要拆成多段子任务才能完成终局。若一律串行、步步等上一步,整体往往又慢又僵;一旦涉及外部 I/O(多路 API、多个库),等待时间会线性叠加,成为明显瓶颈。没有并发手段,总耗时≈各段耗时之和,系统就显得迟钝。

为什么: 并行化把彼此不存在先后依赖的步骤放进同一时间窗口内执行,是应对上述瓶颈的常规做法:先识别互不阻塞的工具调用或模型调用,再交给框架调度。LangChain、Google ADK 等都提供相应原语。典型形态是:主流程同时发起多条子任务,待它们全部完成后再继续。整体耗时往往会从各步骤简单相加,变得更接近最慢的那一条。

经验法则: 只要工作流里存在互不依赖、可同时开工的若干操作,就值得考虑并行化——例如从多个来源并行取数、分片处理,或先生成多段内容再统一汇总。

图示摘要:

并行化设计模式

图 2:并行化设计模式

要点 ​

可归纳为:

  • 并行化即并发执行彼此独立的子任务,以略高的设计与运维复杂度换取更短的端到端时延与更高的吞吐。
  • 外部 I/O 多、等待时间长时,收益通常最大。
  • 并发/并行也会增加设计、故障定位与逻辑可读性的成本,要心里有数。
  • LangChain、Google ADK 等框架都内建并行编排能力。
  • LCEL 里常用 RunnableParallel 把多个 runnable 并排挂起。
  • ADK 侧还可借助 LLM 协调:由上层智能体识别可并行的子任务,再分发给子智能体同时执行。
  • 合理并行,能减少端到端延迟(end-to-end latency),让系统在重负载下仍能保持较好的响应性。

结语 ​

并行化(Parallelization) 通过同时推进多条独立子任务来优化工作流,从而压低整体延迟;在多次模型调用或高度依赖外部服务的场景中尤为适用。

不同框架的机制不一样:LangChain 侧可用 RunnableParallel 一类构造,显式声明「这几条链一起跑」;Google Agent Developer Kit(ADK)等则常通过多智能体编排,由协调者把子任务派给可并行的专职智能体。

将并行与顺序链式、条件路由等控制流组合起来,可构建既能承载复杂任务、又能在时延上站得住的智能体系统。

参考资料 ​

以下是有关并行化模式及相关概念的英文参考资料:

  1. LangChain 表达式语言(LCEL)文档:并行执行
  2. Google Agent Developer Kit(ADK)文档:多智能体系统
  3. Python asyncio 文档