ChatGPT|LangChain Agent原理介绍
关于LangChain的介绍,可以参考上一篇文章(ChatGPT|LangChain介绍),本文主要详细介绍Agent的原理,LangChain是如何和ChatGPT结合实现问题拆分的。
Agent是什么
基于用户输入动态地调用chains,LangChani可以将问题拆分为几个步骤,然后每个步骤可以根据提供个Agents做相关的事情。
工具代码
from langchain.tools import BaseTool
# 搜索工具
class SearchTool(BaseTool):
name = "Search"
description = "如果我想知道天气,'鸡你太美'这两个问题时,请使用它"
return_direct = True # 直接返回结果
def _run(self, query: str) -> str:
print("\nSearchTool query: " + query)
return "这个是一个通用的返回"
async def _arun(self, query: str) -> str:
raise NotImplementedError("暂时不支持异步")
# 计算工具
class CalculatorTool(BaseTool):
name = "Calculator"
description = "如果是关于数学计算的问题,请使用它"
def _run(self, query: str) -> str:
print("\nCalculatorTool query: " + query)
return "3"
async def _arun(self, query: str) -> str:
raise NotImplementedError("暂时不支持异步")
以上代码提供了两个基于langchain的BaseTool工具:
1、SearchTool逻辑是实现搜索功能
(1)description="如果我想知道或者查询'天气','鸡你太美'知识时,请使用它",意思是查询类似的问题会走到SearchTool._run方法,无论什么这里我都返回"这个是一个通用的返回"
(2)return_direct=True,表示只要执行完SearchTool就不会进步一步思考,直接返回
2、CalculatorTool逻辑是实现计算功能
(1)description = "如果是关于数学计算的问题,请使用它",意思是计算类的问题会走到CalculatorTool._run方法,无论什么这里我都返回100
(2)return_direct是默认值(False),表示执行完CalculatorTool,OpenAI会继续思考问题
执行逻辑
1、先问一个问题
llm = OpenAI(temperature=0)
tools = [SearchTool(), CalculatorTool()]
agent = initialize_agent(
tools, llm, agent="zero-shot-react-description", verbose=True)
print("问题:")
print("答案:" + agent.run("告诉我'鸡你太美'是什么意思"))
2、执行结果
问题:
> Entering new AgentExecutor chain...
I should try to find an answer online
Action: Search
Action Input: '鸡你太美'
SearchTool query: '鸡你太美'
Observation: 这个是一个通用的返回
> Finished chain.
答案:这个是一个通用的返回
3、如何实现的呢? LangChain Agent中,内部是一套问题模板:
PREFIX = """Answer the following questions as best you can. You have access to the following tools:"""
FORMAT_INSTRUCTIONS = """Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question"""
SUFFIX = """Begin!
Question: {input}
Thought:{agent_scratchpad}"""
通过这个模板,加上我们的问题以及自定义的工具,会变成下面这个样子(# 后面是增加的注释):
# 尽可能的去回答以下问题,你可以使用以下的工具:
Answer the following questions as best you can. You have access to the following tools:
Calculator: 如果是关于数学计算的问题,请使用它
Search: 如果我想知道天气,'鸡你太美'这两个问题时,请使用它
Use the following format: # 请使用以下格式(回答)
# 你必须回答输入的问题
Question: the input question you must answer
# 你应该一直保持思考,思考要怎么解决问题
Thought: you should always think about what to do
# 你应该采取[计算器,搜索]之一
Action: the action to take, should be one of [Calculator, Search]
Action Input: the input to the action # 动作的输入
Observation: the result of the action # 动作的结果
# 思考-行动-输入-输出 的循环可以重复N次
... (this Thought/Action/Action Input/Observation can repeat N times)
# 最后,你应该知道最终结果
Thought: I now know the final answer
# 针对于原始问题,输出最终结果
Final Answer: the final answer to the original input question
Begin! # 开始
Question: 告诉我'鸡你太美'是什么意思 # 问输入的问题
Thought:
通过这个模板向openai规定了一系列的规范,包括目前现有哪些工具集,你需要思考回答什么问题,你需要用到哪些工具,你对工具需要输入什么内容等。 如果仅仅是这样,openai会完全补完你的回答,中间无法插入任何内容。 因此LangChain使用OpenAI的stop参数,截断了AI当前对话。"stop": ["\nObservation: ", "\n\tObservation: "]。 做了以上设定以后,OpenAI仅仅会给到Action和 Action Input两个内容就被stop停止。 最后根据LangChain的参数设定就能实现得到返回值『这个是一个通用的返回』,如果return_direct设置为False,openai将会继续执行,直到找到正确答案(具体可以看下面这个『计算的例子』)。
4、计算的例子
llm = OpenAI(temperature=0)
tools = [SearchTool(), CalculatorTool()]
agent = initialize_agent(
tools, llm, agent="zero-shot-react-description", verbose=True)
print("问题:")
print("答案:" + agent.run("告诉我10的3次方是多少?"))
执行结果:
问题:
> Entering new AgentExecutor chain...
这是一个数学计算问题,我应该使用计算器来解决它。
Action: Calculator
Action Input: 10^3
CalculatorTool query: 10^3
Observation: 5
Thought: 我现在知道最终答案了
Final Answer: 10的3次方是1000
> Finished chain.
答案:10的3次方是1000
发现经过CalculatorTool执行后,拿到的Observation: 5,但是openai认为答案是错误的,于是返回最终代码『10的3次方是1000』。
完整样例
from langchain.agents import initialize_agent
from langchain.llms import OpenAI
from langchain.tools import BaseTool
# 搜索工具
class SearchTool(BaseTool):
name = "Search"
description = "如果我想知道天气,'鸡你太美'这两个问题时,请使用它"
return_direct = True # 直接返回结果
def _run(self, query: str) -> str:
print("\nSearchTool query: " + query)
return "这个是一个通用的返回"
async def _arun(self, query: str) -> str:
raise NotImplementedError("暂时不支持异步")
# 计算工具
class CalculatorTool(BaseTool):
name = "Calculator"
description = "如果是关于数学计算的问题,请使用它"
def _run(self, query: str) -> str:
print("\nCalculatorTool query: " + query)
return "100"
async def _arun(self, query: str) -> str:
raise NotImplementedError("暂时不支持异步")
llm = OpenAI(temperature=0.5)
tools = [SearchTool(), CalculatorTool()]
agent = initialize_agent(
tools, llm, agent="zero-shot-react-description", verbose=True)
print("问题:")
print("答案:" + agent.run("查询这周天气"))
print("问题:")
print("答案:" + agent.run("告诉我'鸡你太美'是什么意思"))
print("问题:")
print("答案:" + agent.run("告诉我'hello world'是什么意思"))
print("问题:")
print("答案:" + agent.run("告诉我10的3次方是多少?"))
参考
(1)https://replit.com/@linkxzhou/ChatbotGPT#example_agent.py (2)https://blog.csdn.net/qq_35361412/article/details/129797199
相关文章
- ChatGPT当面试官觉得合格吗?
- 国内“谁”能实现chatgpt,短期穷出的类ChatGPT简评(算法侧角度为主),以及对MOSS、ChatYuan给出简评,一文带你深入了解宏观技术路线。
- ChatGPT怎么下载 ChatGPT官方下载地址
- ChatGPT 大智近妖,从宇宙人生到手搓光刻机,从哄女朋友到写年终总结我们聊得非常开心,反而让人越来越忧心
- OpenAI超级对话模型ChatGPT发布!智能回答堪比雅思口语满分案例
- 【NLP】深入浅出,解析ChatGPT背后的工作原理
- 深入浅出!ChatGPT背后的原理详解
- OpenAi[ChatGPT] 使用Python对接OpenAi APi 实现智能QQ机器人-学习详解篇
- OpenAI揭秘ChatGPT升级计划:你找到的bug都在改了
- ChatGPT发展历程、原理、技术架构详解和产业未来
- chatGPT辣么火,你却不会注册!
- ChatGPT-4正式发布!国内怎么使用chatgpt-一步教你
- 在ChatGPT帮助下创造简单的shinyAPP
- ChatGPT | 分享论文 Rebuttal、Review 时可能会用到的 Prompt
- 可以直接访问的ChatGPT来了
- [ChatGPT]-01-chatgpt可以做什么?如何调教
- ChatGPT引AI大牛新老之争?谷歌钢铁侠速归救火;Prime Air首飞业绩捉急
- 0门槛克隆ChatGPT方案再升级,开源模型完整复现,在线体验无需注册
- UCL汪军呼吁创新:后ChatGPT通用人工智能理论及其应用
- 最新chatgpt 可用源码 自己搭建 可连续聊天
- ChatGPT Web