skip navigation
skip mega-menu

Exploring LangChain’s ChatAgents

This blog will explore of one of LangChain’s agents: the chat agent with ReAct logic. There are a good number of LangChain agents mentioned in the LangChain documentation但是,我们只关注 ReAct Agent.

So what is the ReAct Agent according to the LangChain documentation?

This agent uses the ReAct 框架,仅根据工具的描述来确定使用哪个工具. Any number of tools can be provided. 此代理要求为每个工具提供描述.

注意:这是最通用的动作剂.

本博客还介绍了一个聊天代理的简单实现,它使用了打包在其中的3个工具 LangChain v.0.0.220. 欲知更多有关游乐场代理的详情,请参阅下文.

Main Idea

The chat agent with ReAct logic 可以访问特定的工具列表和大型语言模型(LLM). 在收到用户生成的消息后,聊天代理会询问LLM哪个工具最适合回答这个问题. 它也可能发送最终答案.

It might choose a tool. 如果是这种情况,则针对工具执行问题或关键字. 然后,该工具返回一个输出,然后用于LLM再次计划下一步要做什么:要么选择另一个工具,要么给出最终答案.

因此,代理使用LLM来计划在循环中下一步做什么,直到找到最终答案或放弃.

Chat Agent Flow

下面是根据聊天代理的流程 LangChain implementation:

Chat Agent Flow

在web或命令行应用程序的典型场景中,流程可以分为两个部分:

  • Setup flow:用于设置代理的主要部分,包括工具和LLM.
  • Execution flow: consists of two loops. 外部循环处理用户输入,内部循环处理代理与工具和LLM的交互.

Understanding the Execution Flow

设置流程通常只是主执行流程的顺序前奏:

Chat agent execution flow

该流执行以下步骤:

  • Accept the user input. 用户输入通常是通过web、移动设备或命令行UI输入的问题.
  • The agent starts its work:它要求法学硕士使用哪种工具来给出最终答案.
  • At this stage, the first process gateway is reached. It has three outputs:
    Use tool法学硕士决定使用一个特定的工具. 在下面的“工具回复”中继续该流程
    Give LLM Based answer法学硕士想出了最后的答案
    Answer not understood: The LLM answer is inconclusive. The process exits here with an error.
  • Tool replies:向第二个网关发送消息
  • The second's workflow gateway is reached. It has three possible outcomes:
    —通常情况下,工具的输出被路由到LLM. 我们回到代理循环的初始步骤.
    -如果执行的工具被标记为“returning tool,工具的响应就是最终的答案
    -错误条件发生:如果工具抛出错误或超时发生或达到最大尝试量,则进程退出并出现错误.

一个非常简单的维基百科,DuckDuckGo, Arxiv代理

我们已经构建了一个非常简单的Agent,它使用了三个内置的 LangChain agents:

  • Wikipedia (the beloved online encyclopedia)
  • Arxiv (科学论文的在线档案)
  • DuckDuckGo (a privacy-oriented search engine)

我们使用了这三个代理,因为它们在LangChain中是开箱即用的,也不需要任何注册或付费订阅.

这个命令行应用程序可以用来谈论不同的主题,并提出以下问题:

  • Who is Donald Duck?
  • What is the weather today in London?
  • Who is Albert Einstein?
  • 谁将是下一届美国总统选举的总统候选人?
  • 2020年十大网博靠谱平台神经网络注意力层最相关的出版物是哪些?

以下是与该工具互动的摘录:

Playing around with the agent

我们尝试用颜色编码工具的输出:

  • green: successful response
  • 红色:错误消息和一些解释
  • blue intermediate step; typically mentioning the tool and the question sent to the tool

Implementation

我们的聊天应用程序可以在这个GitHub存储库中找到:

GitHub - gilfernandes/agent_playground:一个基于LangChain代理的小演示项目.

小型演示项目,具有基于LangChain的功能代理. - GitHub - gilfernandes/agent_playground:小演示…

github.com


The main agent code is in agent_playground.py

使用以下代码配置代理:

class Config():
"""
包含LLM的配置.
"""
model = 'gpt-3.5-turbo-16k'
# model = 'gpt-4'
llm = ChatOpenAI(model=model, temperature=0)

cfg = Config()

We are using gpt-3.5 API as you can see.

在下面这个函数中设置代理:

def create_agent_executor(cfg: Config . cfg, action_detector_func: callable, verbose: bool = False) -> AgentExecutor:
"""
设置代理与三个工具:维基百科,arxiv, duckduckgo搜索
:param cfg LLM的配置.
:param action_detector_funcc一个更灵活的输出解析器实现, 更善于从回应中猜测工具.
:param verbose是否在控制台上有更多输出.
"""
Tools = load_tools(["wikipedia", "arxiv", "ddg-search"], llm=cfg.llm)
agent_executor: AgentExecutor = initialize_agent(
tools,
cfg.llm,
agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
verbose=verbose
)
agent = agent_executor.agent
agent.output_parser = ExtendedChatOutputParser(action_detector_func)
return agent_executor

你可以看到三个工具"维基百科", “arxiv”, 和“ddg-search”在这里加载,代理执行器在这里使用 CHAT_ZERO_SHOT_REACT_DESCRIPTIONtype.

您可能还注意到,我们添加了一个自定义输出解析器. 输出解析器的任务是解析来自LLM的输出. 我们希望有一个更灵活的输出解析器实现,以便更好地检测要使用的工具——这主要是因为我们在测试期间得到了大量的错误. 这是该工具的实现,可以在文件中找到: chat_output_parser.py.

这是输出解析器的自定义实现:

类ExtendedChatOutputParser (ChatOutputParser):

action_detector_func: Callable

def __init__(self, action_detector_func: Callable):
super().__init__ (action_detector_func = action_detector_func)

def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
incles_answer = FINAL_ANSWER_ACTION在文本

try:
action = self.action_detector_func(text)
response = json.loads(action.strip())
incles_action =响应中的"action"
如果包括答案和包括动作:
raise OutputParserException(
"解析LLM输出生成最终答案"
f"and a parse-able action: {text}"
)
print(get_colored_text(f"Tool: {response['action']}", "blue"))
print(get_colored_text(f"Input: {response['action_input']}", "blue"))
print()
return AgentAction(
response["action"], response.get("action_input", {}), text
)

except Exception as e:
if not includes_answer:
引发OutputParserException(f"无法解析LLM输出:{text}: {str(e)}")
return AgentFinish(
{"output": text.split(FINAL_ANSWER_ACTION)[-1].strip()}, text
)

此实现允许指定用于检测动作的自定义函数,或者换句话说,指定下一步使用哪个工具.

我们编写的用于从LLM输入检测下一个的函数可以在 agent_playground.py:

def action_detector_func(text):
"""
方法,该方法试图更好地理解LLM的输出.
参数文本:来自LLM响应的文本.
:返回一个json字符串,其中包含接下来要查询的工具的名称和该工具的输入.
"""
splits = text.split("```")
if len(splits) > 1:
#原始实现+ json片段删除
return re.sub(r"^json", "", splits[1])
else:
lower_text = text.lower()
Tool_tokens = ["wiki", "arxiv", "duckduckgo"]
token_tool_mapping = {
"wiki": "Wikipedia",
"arxiv": "arxiv",
"duckduckgo": "duckduckgo_search"
}
for token in tool_tokens:
if token in lower_text:
return json.dumps({
'action': token_tool_mapping[token],
'action_input': text
})
抛出OutputParserException('无法找到wiki或arxiv或duckduckgo操作或最终答案').')

In this function, 我们不仅要查找预期的JSON输出,还要查找可能指示使用下一个工具的单词.

使用法学硕士的一个问题是,它们在某种程度上是不可预测的,并且以意想不到的方式表达自己, 因此,这个函数只是试图以一种更灵活的方式捕捉法学硕士想要传达的信息.

Observations

我们注意到,LangChain使用了一个特殊的提示符来查询LLM如何对输入做出反应. 这个库中使用的提示符如下:

尽你所能回答以下问题. 您可以使用以下工具:

维基百科:维基百科的包装. 当你需要回答十大网博靠谱平台人的一般性问题时很有用, places, companies, facts, historical events, or other subjects. Input should be a search query.
arxiv: A wrapper around Arxiv.当你需要回答有关物理的问题时非常有用, Mathematics, Computer Science, Quantitative Biology, Quantitative Finance, Statistics, Electrical Engineering, 和经济学从科学文章在arxiv.org. Input should be a search query.
duckduckgo_search: DuckDuckGo搜索的包装. 当你需要回答有关当前事件的问题时非常有用. Input should be a search query.

使用这些工具的方法是指定一个json blob.
Specifically, 这个json应该有一个' action '键(包含要使用的工具的名称)和一个' action_input '键(包含工具的输入到这里).

“action”字段中应该包含的值只有:Wikipedia、arxiv、duckduckgo_search

$JSON_BLOB应该只包含一个动作,不返回多个动作的列表. 下面是一个有效的$JSON_BLOB的例子:

```
{
"action": $TOOL_NAME,
"action_input": $INPUT\n}
```

ALWAYS use the following format:

问题:您必须回答的输入问题
思想:你应该时刻想着要做什么
Action:
```
$JSON_BLOB
```
观察:行动的结果
... (这个想法/行动/观察可以重复N次)
心想:我现在知道最后的答案了
最终答案:原始输入问题的最终答案
Begin! 提醒你在回复时一定要使用准确的“最终答案”.'

提示信息通过系统消息发送给LLM,同时发送的还有来自工具响应的问题或观察结果.

我们想知道你如何指导法学硕士在这种情况下的行为.

Final Thoughts

In this story, 我们试图描述一个简单的聊天代理是如何工作的,并试图理解聊天代理的内部机制. 您可以使用额外的工具来增强大型语言模型的功能,这些工具可以将法学硕士的知识扩展到他们通常无法访问的领域. 法学硕士不是在旧的知识基础上进行培训,而是使用公开可用的信息. 如果你想与法学硕士一起获取前沿新闻,代理是一个不错的选择.

你可以和代理人做更多的事情, 比如让他们参与对抗性场景或代码库, 但我们将在接下来的故事中关注这些场景.

Subscribe to our newsletter

Sign up here