zl程序教程

您现在的位置是:首页 >  大数据

当前栏目

ChatGPT|LangChain Agent原理介绍

chatGPT原理 介绍 Agent
2023-06-13 09:18:41 时间

关于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