Python项目中LangChain Agent与工具的正确使用及常见问题解答
关于LangChain Agent与Chain的核心问题解答
1. Agent如何决定是否使用工具?
LangChain的Agent(比如你用的zero-shot-react-description)依赖ReAct思维框架和工具的description字段做决策:
- LLM会先分析用户查询,结合所有工具的描述,判断当前任务是否需要调用工具,或是直接生成回答。
- 如果判定需要工具,会进一步匹配最符合任务场景的工具(完全依赖工具描述的准确性)。
- 你的代码里工具描述
"Processes input"过于模糊,LLM无法明确触发条件,所以没调用工具。需要把描述写得具体,明确适用场景、输入输出格式。
2. 真实项目中工具的正确结构是什么?
工具需要满足单一职责、描述清晰、鲁棒性强三个核心要求,以下是标准实现示例:
步骤1:实现单一职责的工具函数
函数聚焦一个具体功能,加入参数校验和错误处理:
def text_uppercase_processor(input_text: str) -> str: # 参数校验 if not isinstance(input_text, str) or not input_text.strip(): return "Error: Input must be a non-empty string." # 核心功能 return f"Processed (uppercase): {input_text.upper()}"
步骤2:用Tool类封装并编写精准描述
描述要包含适用场景、输入要求、输出说明,让LLM能准确判断调用时机:
from langchain.agents import Tool, initialize_agent from langchain.llms import OpenAI tools = [ Tool( name="TextUppercaseProcessor", func=text_uppercase_processor, description="Use this tool ONLY when you need to convert user-provided text to uppercase. The input must be a non-empty string. Returns the uppercase version of the input text with a prefix." ) ] # 初始化Agent并测试 llm = OpenAI(temperature=0) # 低temperature减少随机性 agent = initialize_agent( tools, llm, agent="zero-shot-react-description", verbose=True ) response = agent.run("Convert 'hello world' to uppercase") print(response)
进阶:使用StructuredTool处理复杂参数
如果工具需要多参数,推荐用StructuredTool(支持Pydantic模型定义参数),避免LLM传参错误:
from langchain.tools import StructuredTool from pydantic import BaseModel, Field class TextProcessInput(BaseModel): text: str = Field(description="The text to process") to_upper: bool = Field(description="Whether to convert to uppercase") def process_text(text: str, to_upper: bool) -> str: if to_upper: return text.upper() return text.lower() structured_tool = StructuredTool.from_function( func=process_text, name="TextProcessor", description="Process text by converting to uppercase or lowercase. Requires two parameters: text (non-empty string) and to_upper (boolean).", args_schema=TextProcessInput )
3. 何时应该使用Chain而非Agent?
优先选择Chain的场景:
- 固定流程任务:比如"提取文本关键词→生成摘要→翻译成法语",步骤固定,不需要动态决策。
- 性能敏感场景:Agent需要多次调用LLM(思考→调用工具→观察→再思考),耗时更长;Chain的LLM调用次数固定,速度更快。
- 无工具需求的纯文本任务:比如文本分类、情感分析,不需要调用外部工具,用Chain更直接。
- 高可预测性需求:Agent可能出现幻觉或错误调用工具,Chain的执行步骤完全可控,结果更稳定。
内容的提问来源于stack exchange,提问作者Milan Suryavanshi
相关产品推荐
相关产品推荐

