1. LangChain提示模板中的{tool_names}和{agent_scratchpad}解析
在LangChain框架中,提示模板(Prompt Template)是构建智能代理(Agent)的核心组件之一。不同于传统编程中的变量替换,LangChain的提示模板中有两个特殊变量{tool_names}和{agent_scratchpad},它们具有独特的自动填充机制。理解这两个变量的工作原理,对于开发高效的LangChain应用至关重要。
1.1 提示模板的基本结构
一个典型的ReAct范式提示模板如下所示:
python复制from langchain.prompts import PromptTemplate
template = '''
尽你所能用中文回答以下问题。如果能力不够你可以使用以下工具:\n\n
{tools}\n\n
Use the following format:\n\n
Question: the input question you must answer\n
Thought: you should always think about what to do\n
Action: the action to take, should be one of [{tool_names}]\n
Action Input: the input to the action\n
Observation: the result of the action\n
... (this Thought/Action/Action Input/Observation can repeat N times)\n
Thought: I now know the final answer\n
Final Answer: the final answer to the original input question\n\n
Begin!\n\n
Question: {input}\n
Thought:{agent_scratchpad}'''
这个模板中包含了多个变量占位符,其中{tools}、{input}等变量需要开发者显式提供值,而{tool_names}和{agent_scratchpad}则由LangChain框架自动处理。
提示:ReAct(Reasoning and Acting)是一种结合推理和行动的AI代理范式,通过"思考-行动-观察"的循环机制解决复杂问题。
1.2 变量自动填充机制对比
为了更清晰地理解这些变量的区别,我们来看一个对比表格:
| 变量名 | 是否需手动赋值 | 填充时机 | 填充来源 | 是否动态变化 |
|--------|--------------|----------|----------
