langchain ZERO_SHOT_REACT运行逻辑

	ZERO_SHOT_REACT_DESCRIPTION
		代码逻辑
			1、initialize_agent函数
				langchain\agents\initialize.py
				ZeroShotAgent : from_llm_and_tools
					langchain\agents\mrkl\base.py
					Construct an agent from an LLM and tools
					prompt = cls.create_prompt
						Create prompt in the style of the zero shot agent.
						tools: Sequence[BaseTool],
						prefix: str = PREFIX,
						suffix: str = SUFFIX,
						将prefix、工具名称以及工具描述、suffix组装成prompt给LLMChain
					llm_chain = LLMChain 构建LLMChain
					_output_parser = output_parser or cls._get_default_output_parser()
				return AgentExecutor.from_agent_and_tools
			2、 run函数
				langchain\chains\base.py
				Chain :__call__函数: Execute the chain.
					AgentExecuter: _call
						langchain\agents\agent.py
						Run text through and get agent response
						while self._should_continue(iterations, time_elapsed) 通过该while循环
							_take_next_step
								_iter_next_step
									Take a single step in the thought-action-observation loop
									output = self.agent.plan
										Call the LLM to see what to do
										LLMChain : predict 
											langchain\chains\llm.py
											Format prompt with kwargs and pass to LLM
											Chain : __call__函数
												LLMChain:_call函数
													response = self.generate([inputs], run_manager=run_manager)
													Generate LLM result from inputs 将问题输入给LLM,获取LLM的结果

													生成的response的内容包括:
													text": " I need to find out the age of Yao Ming's wife first.\n
													Action: Search\n
													Action Input: \"Yao Ming's wife age
									执行工具,获取工具调用的结果
### LangChain Agent 的概述 LangChain 是一种用于构建基于大型语言模型的应用程序的框架,而其中的核心组件之一就是 **Agent**。Agent 能够根据输入的任务动态调用不同的工具集,并通过迭代的方式完成复杂任务[^1]。 #### 什么是 LangChain Agent? LangChain 中的 Agent 是指能够自主决策并执行操作的一种机制。它可以根据用户的请求自动选择合适的工具(Tools),并通过多次交互逐步解决问题。这种能力使得 Agent 成为了处理多步推理和复杂查询的理想解决方案[^3]。 --- ### LangChain Agent 的工作原理 Agent 的核心功能在于其能够解析用户输入、选择适当的工具以及生成最终响应。以下是它的主要流程: 1. 用户提供自然语言指令。 2. Agent 解析该指令并将其转化为可执行的操作序列。 3. 基于这些操作,Agent 动态调用预定义的一组工具(如搜索引擎、数据库接口或其他外部服务)。 4. 工具返回的结果被反馈到 Agent,后者会继续优化后续动作直至目标达成[^5]。 例如,在 OpenAI 提供的支持函数调用的功能中,默认提示可以通过如下方式加载: ```python from langchain.agents import load_tools, initialize_agent from langchain.llms import OpenAI llm = OpenAI(temperature=0) tools = load_tools(["serpapi", "llm-math"], llm=llm) agent_chain = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) ``` 上述代码片段展示了如何初始化一个简单的零样本反应描述型代理 (Zero-Shot React Description),此类型的代理无需任何训练即可运行[^2]。 --- ### 示例代码:创建自定义 LangChain Agent 下面是一个完整的例子,演示了如何利用 SerpAPI 和 LLM 数学计算工具来解决涉及网络搜索与算术运算的问题。 ```python import os from langchain.agents import Tool, initialize_agent, AgentType from langchain.tools import BaseTool from langchain.utilities import SerpAPIWrapper from langchain.prompts import PromptTemplate from langchain.chains import LLMChain from langchain.llms import OpenAI class CustomSearchTool(BaseTool): name = "custom_search" description = "A tool that uses a custom search engine to find information." def _run(self, query: str) -> str: serp_api_key = os.getenv('SERP_API_KEY') search = SerpAPIWrapper(serpapi_api_key=serp_api_key) result = search.run(query) return f"Searched for {query}. Found: {result}" async def _arun(self, query: str) -> str: raise NotImplementedError() # 初始化LLM实例 llm = OpenAI(model_name="text-davinci-003") # 加载工具 search_tool = CustomSearchTool() tools = [ Tool( name=search_tool.name, func=search_tool._run, description=search_tool.description ) ] # 设置Prompt模板 prompt_template = """Use the following pieces of context to answer the question at the end. {context} Question: {question} Answer:""" prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"]) # 构建链式结构 chain = LLMChain(llm=llm, prompt=prompt) # 初始化Agent agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) # 测试Agent response = agent.run("What is the capital city of France and what's its population?") print(response) ``` 在这个脚本里,我们首先定义了一个名为 `CustomSearchTool` 的类继承自 `BaseTool` 接口;接着配置好所需的参数之后便可以轻松实现跨平台数据抓取等功能[^4]。 --- ### 总结 综上所述,LangChain Agents 不仅提供了强大的灵活性还简化了许多繁琐的手动编码环节,让开发者得以专注于业务逻辑本身而非底层细节。无论是初学者还是资深工程师都能从中受益匪浅。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值