关于LangChain的介绍,能够参考上一篇文章(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)replit.com/@linkxzhou/…
(2)blog.csdn.net/qq_35361412…