←返回文章列表

LangChain 提示词分析:按 Agent 执行流程拆解

LangChain提示词工程Agent
10 分钟-阅读

LangChain 的默认 prompt 不是零散模板,而是 Agent 执行流程里的协议层:它决定如何记忆、路由、调用工具、检索、合并上下文、约束输出和执行前校验。

LangChain 提示词分析:按 Agent 执行流程拆解

LangChain 里的内置 prompt,不只是几段默认英文模板。更准确地说,它们是 Agent 执行流程里的协议层。

一个 Agent 不只是把用户问题交给模型回答。它可能要读取历史、决定是否调用工具、把问题路由到不同链路、改写检索查询、合并多段文档、生成结构化结果,最后还要做执行前校验或质量复核。每一步如果都让模型自由发挥,程序就很难稳定编排;prompt 的作用,就是把模型输出压成下游组件能理解的格式。

本文以 langchain 0.3.19 和 langchain-core 0.3.40 为例,按 Agent 的执行流程拆解这些默认 prompt。

flowchart TD
  U["用户输入"] --> M["记忆与历史压缩"]
  M --> A["Agent 行动决策"]
  A --> D{"需要外部能力?"}
  D -->|选择链路| R0["路由 prompt"]
  D -->|调用工具| T0["工具 action prompt"]
  D -->|检索知识| R["检索改写 prompt"]
  D -->|直接回答| G["任务生成 prompt"]
  R --> C["文档合并 prompt"]
  C --> G
  R0 --> G
  T0 --> A
  G --> F["格式约束 / 输出解析"]
  F --> Q{"结果会被执行?"}
  Q -->|是| V["执行前校验 prompt"]
  Q -->|否| Z["最终结果"]
  V --> Z

1. 先把历史变成可用状态

Agent 面对的输入通常不是单轮问题,而是一段持续对话。历史不能无限塞进上下文,所以 LangChain 的 memory prompt 会先把对话压缩成摘要、实体或知识三元组。

langchain.memory.prompt 里的摘要模板很典型:

_DEFAULT_SUMMARIZER_TEMPLATE = """Progressively summarize the lines of conversation provided,
adding onto the previous summary returning a new summary.

Current summary:
{summary}

New lines of conversation:
{new_lines}

New summary:"""

这类 prompt 的输出不是给用户看的答案,而是写回状态存储。它在 Agent 流程里的位置很靠前:用户输入进来后,系统先整理历史,再把整理后的状态交给后续决策。

实体抽取也是同一个思路:

ENTITY_EXTRACTION_PROMPT = PromptTemplate(
    input_variables=["history", "input"],
    template=_DEFAULT_ENTITY_EXTRACTION_TEMPLATE,
)

模板要求模型只从最后一轮对话里抽专有名词,输出逗号分隔列表,或者返回 NONE。这里已经能看到 LangChain prompt 的基本风格:不是只描述任务,还规定输出协议。

2. Agent prompt 决定下一步动作

当上下文准备好后,Agent prompt 开始决定下一步:直接回答,还是调用工具。

早期 Conversational Agent 使用纯文本协议。langchain.agents.conversational.prompt 中的核心格式是:

FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:

Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action

When you have a response to say to the Human, or if you do not need to use a tool:

Thought: Do I need to use a tool? No
{ai_prefix}: [your response here]
"""

这个 prompt 做了两件事。

第一,它把模型输出分成两类:要么是工具调用,要么是最终回答。程序只要识别 Action 或 {ai_prefix},就能决定是否继续循环。

第二,它把中间步骤留给 agent_scratchpad:

SUFFIX = """Begin!

Previous conversation history:
{chat_history}

New input: {input}
{agent_scratchpad}"""

chat_history 是对话历史,agent_scratchpad 是已经发生的工具调用和观察结果。Agent 每轮生成时都会看到之前做过什么,于是形成循环:

用户问题 -> Thought / Action -> 工具执行 -> Observation -> 下一轮 Thought -> Final Answer

这类纯文本协议容易理解,但也脆弱。模型多写一句解释,解析器就可能失败。所以 LangChain 后来引入了更结构化的 JSON action。

3. 把工具调用封装成 JSON action

langchain.agents.conversational_chat.prompt 要求模型始终输出 Markdown 代码块里的 JSON。

调用工具时:

{
  "action": "工具名",
  "action_input": "工具输入"
}

直接回答时:

{
  "action": "Final Answer",
  "action_input": "最终回答"
}

源码里的格式说明很直接:

FORMAT_INSTRUCTIONS = """RESPONSE FORMAT INSTRUCTIONS

Option 1:
{
    "action": string,
    "action_input": string
}

Option #2:
{
    "action": "Final Answer",
    "action_input": string
}
"""

这个变化的关键,不是让模型更聪明,而是让程序更容易解析。无论是工具调用还是最终回答,都被统一成 action + action_input。Agent 只需要判断 action 字段,就知道下一步该继续执行工具,还是结束。

LangChain 的 ReAct prompt 也是同一类协议,只是外壳不同:

Question: ...
Thought: ...
Action: ...
Action Input: ...
Observation: ...
Thought: I now know the final answer
Final Answer: ...

ReAct 的价值在于把推理和行动交替展开。它的边界也很清楚:Observation 应该来自真实工具执行,而不是模型自己编造。

4. 如果有多条链,先路由

Agent 不一定只有一条处理链。一个应用可能有数学链、物理问答链、检索问答链、SQL 链。此时需要先判断用户输入适合交给谁。

langchain.chains.router.multi_prompt_prompt 的路由模板要求模型输出一个 JSON:

MULTI_PROMPT_ROUTER_TEMPLATE = """Given a raw text input to a language model select
the model prompt best suited for the input.

Return a markdown code snippet with a JSON object formatted to look like:
{
    "destination": string,
    "next_inputs": string
}

"destination" MUST be one of the candidate prompt names specified below OR "DEFAULT".

<< CANDIDATE PROMPTS >>
{destinations}

<< INPUT >>
{input}
"""

这里的 prompt 不是回答问题,而是选择下游链路。它和 Agent action 容易混,但层级不同:Agent action 管的是当前 Agent 循环里下一步做什么;Router prompt 管的是把整个请求分发给哪条链。

5. 需要外部知识时,先改写检索问题

RAG 场景里,用户问题经常依赖历史上下文。比如用户先问“LangChain 的 PromptTemplate 是什么”,下一轮追问“那 ChatPromptTemplate 呢”。如果直接拿“那 ChatPromptTemplate 呢”去检索,召回会不稳定。

langchain.chains.conversational_retrieval.prompts 先把追问改写成独立问题:

_template = """Given the following conversation and a follow up question,
rephrase the follow up question to be a standalone question, in its original language.

Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:"""

这一步的产物不是答案,而是更适合检索的 query。它把多轮上下文压进一个独立问题里,让 retriever 能看到完整语义。

随后才进入基础 QA prompt:

prompt_template = """Use the following pieces of context to answer the question at the end.
If you don't know the answer, just say that you don't know, don't try to make up an answer.

{context}

Question: {question}
Helpful Answer:"""

这段模板很朴素,但契约明确:答案必须依据 context,不知道就说不知道。生产 RAG 通常还会补充来源引用、冲突处理和时间边界,但默认模板已经说明了 RAG prompt 的基本职责。

6. 文档多了以后,要先合并上下文

检索回来的是多段文档,不能总是原样塞给模型。LangChain 的 question answering 和 summarize 链里有几种常见合并策略:stuff、map_reduce、refine、map_rerank。

最简单的 stuff 就是把上下文直接放进 prompt:

prompt_template = """Use the following pieces of context to answer the question at the end.
If you don't know the answer, just say that you don't know, don't try to make up an answer.

{context}

Question: {question}
Helpful Answer:"""

如果文档很长,map_reduce 会先对每个 chunk 单独处理,再合并中间结果;refine 会拿已有答案逐步吸收新文档;map_rerank 则让模型对每段 context 生成答案并打分。

这一类 prompt 不应该简单归到“任务执行”。它解决的是上下文窗口问题:材料太多时,先怎么拆、怎么压缩、怎么合并,再交给最终回答 prompt。

7. 任务 prompt 生成可消费的中间产物

有些任务不是直接生成自然语言答案,而是生成可执行中间产物,比如 SQL、Cypher、API URL 或数学表达式。

SQL prompt 是最典型的例子:

_DEFAULT_TEMPLATE = """Given an input question, first create a syntactically correct
{dialect} query to run, then look at the results of the query and return the answer.

Never query for all the columns from a specific table, only ask for the few relevant columns.
Pay attention to use only the column names that you can see in the schema description.

Use the following format:

Question: Question here
SQLQuery: SQL Query to run
SQLResult: Result of the SQLQuery
Answer: Final answer here
"""

这里 prompt 做了三层约束:

  • 只生成目标数据库方言的 SQL。
  • 只能使用 schema 中存在的表和列。
  • 输出必须符合 Question / SQLQuery / SQLResult / Answer 的固定结构。

模型负责把自然语言翻译成 SQL,真正执行 SQL 的仍然是外部系统。prompt 在这里是翻译器,也是协议说明书。

8. 输出解析前,先把格式说死

当模型输出要被程序继续消费时,格式约束不能只靠解析器兜底。LangChain 的 output parser 会把格式说明注入 prompt。

langchain.output_parsers.format_instructions 里有几类典型模板:

STRUCTURED_FORMAT_INSTRUCTIONS = """The output should be a markdown code snippet
formatted in the following schema:

<json code fence>
{{
{format}
}}
</json code fence>"""

Pydantic parser 的约束更强:

PYDANTIC_FORMAT_INSTRUCTIONS = """The output should be formatted as a JSON instance
that conforms to the JSON schema below.

Here is the output schema:
<schema code fence>
{schema}
</schema code fence>"""

这说明输出解析不是纯代码能力。解析器负责校验和提取,prompt 负责提前把模型推向可解析格式。越需要程序稳定消费,格式说明就越要具体。

9. 会被执行的结果,还需要执行前校验

SQL、API URL、图查询这类输出一旦交给下游执行,错误就不只是“回答不准”,还可能变成慢查询、权限问题或安全风险。

SQL 链路里,生成 prompt 和校验 prompt 是分开的。生成 prompt 在 langchain.chains.sql_database.prompt,而 query checker 模板由 SQL database tool 转发导出。它的职责不是生成新答案,而是在执行前检查查询是否有常见错误。

这类 prompt 的位置更像 guardrail:

用户问题 -> 生成 SQL -> 检查 SQL -> 执行 SQL -> 回答

它不能替代权限控制、白名单和数据库侧安全策略,但能在模型生成和真实执行之间多加一道防线。

10. 复核不是主流程,但常在关键场景补上

LangChain 还有 evaluation、constitutional AI、LLM checker 等 prompt。它们不是每个 Agent 都必须跑,但在高风险回答里很有用。

评估 prompt 让模型当裁判,判断答案是否正确、是否满足 criteria,或比较两个回答谁更好。Constitutional prompt 让模型先批判再改写。LLM checker 则把答案拆成断言,逐条核查后再重写。

这些 prompt 和格式约束容易混,因为它们最后也会输出 Y/N、分数或修订结果。但它们真正解决的问题不是“格式”,而是“这个结果是否可靠,是否需要修改”。

总结:prompt 是 Agent 的协议层

沿着 Agent 执行流程看,LangChain 的默认 prompt 大致承担这些角色:

  • 记忆 prompt:把历史压缩成可复用状态。
  • Agent prompt:决定是否调用工具,以及如何表达 action。
  • Router prompt:把请求分发到合适链路。
  • Retriever prompt:把用户问题改写成更适合检索的 query。
  • 文档合并 prompt:在上下文窗口内组织证据。
  • 任务 prompt:生成答案或可执行中间产物。
  • 格式 prompt:让输出能被 parser 稳定读取。
  • 校验 prompt:在执行前检查高风险输出。
  • 复核 prompt:对答案做评估、批判或事实性检查。

所以,LangChain 的提示词体系不是“模板库”,而是一套围绕 Agent 编排的工程协议。写自己的 LangChain prompt 时,最重要的不是把指令写得更长,而是先判断它位于流程的哪一步:它是在维护状态、选择动作、改写查询、合并证据、生成中间产物,还是在校验和复核结果。

位置清楚了,prompt 该包含哪些变量、该约束什么格式、该交给哪个解析器,都会自然变得清楚。

YL

我是姚磊

大模型应用开发者,关注 RAG、Agent 和产品化工程。沉淀实践中的判断、踩坑记录和可复用方法。联系我:yaolei_agent@163.com

LLM AppsRAGProductEngineering Notes