李晓飞 發表於 2024-2-4 15:44:00

使用开源 LLM 充当 LangChain 智能体

<style></style>
<div id="preview-contents" class="note-content">
<h2>太长不看版</h2>
<p>开源 LLM 现已达到一定的性能水平,可堪作为智能体工作流的推理引擎。在我们的测试基准上,Mixtral 甚至已超越 GPT-3.5,而且我们还可以通过微调轻松地进一步提高其性能。</p>
<h2 id="引言">引言</h2>
<p>经由因果语言建模任务训练出的大语言模型(LLM)可以处理很多任务,但在逻辑、计算及搜索等类型的任务上表现不尽人意。最糟糕的是,它们在数学等领域表现不佳而不自知,仍不自量力地想仅凭一己之力完成所有计算。</p>
<p>为了克服这一弱点,方法之一就是将 LLM 集成到一个含有若干可调用工具的系统中,我们称这样的系统为 LLM 智能体(agent)。</p>
<p>本文,我们首先解释了 ReAct 智能体的内在工作原理,然后展示了如何使用最近集成到 LangChain 中的 <code>ChatHuggingFace</code> 接口来构建自己的智能体。最后,我们把几个开源 LLM 与 GPT-3.5 和 GPT-4 一起在同一基准测试上进行了比较。</p>
<h2 id="目录">目录</h2>
<ul>
<li>
<p>使用开源 LLM 充当 LangChain 智能体</p>
<ul>
<li>
<p>太长不看版</p>
</li>
<li>
<p>引言</p>
</li>
<li>
<p>目录</p>
</li>
<li>
<p>什么是智能体?</p>
</li>
<li>
<p>ReAct 智能体内在机制示例</p>
</li>
<li>
<p>智能体系统面临的挑战</p>
</li>
<li>
<p>使用 LangChain 运行智能体</p>
</li>
<li>
<p>智能体对决:开源 LLM 充当通用推理智能体的表现如何?</p>
</li>
<li>
<p>评估</p>
</li>
<li>
<p>模型</p>
</li>
<li>
<p>结果</p>
</li>
</ul>
</li>
</ul>
<h2 id="什么是智能体">什么是智能体?</h2>
<p>LLM 智能体的定义相当宽泛:LLM 智能体是所有使用 LLM 作为引擎并基于观察对环境采取相应行动的系统。其使用 <code>感知⇒反思⇒行动</code> 的多轮迭代来完成任务,也经常通过规划或知识管理系统来增强性能。如对该领域的全景感兴趣,可参考 Xi et al., 2023 这篇论文。</p>
<p>本文重点关注 <strong>ReAct 智能体</strong>。ReAct 用“<strong>推理</strong>”和“<strong>行动</strong>”这两个词串联起智能体的工作流。我们通过提示告诉模型可以使用哪些工具,并要求它“一步一步”(即思维链)思考并行动,直至获得最终答案。</p>
<p align="center"><img src="https://img2024.cnblogs.com/blog/46419/202402/46419-20240204155331897-1249298431.png" alt="ReAct 智能体" width="90%type=&quot;image/png&quot;"></p>
<h3 id="react-智能体内在机制示例">ReAct 智能体内在机制示例</h3>
<p>上图看上去很高端,但实现起来其实非常简单。</p>
<p>可以参考一下这个 notebook,这里,我们用 <code>transformers</code> 库实现了一个简单的工具调用示例。</p>
<p>我们用下述提示模板循环调用 LLM:</p>
<div class="hljs-line">
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">Here is a question: "{question}"
You have access to these tools: {tools_descriptions}.
You should first reflect with ‘Thought: {your_thoughts}’, then you either:
- call a tool with the proper JSON formatting,
- or your print your final answer starting with the prefix ‘Final Answer:’
</pre>
</div>
<p>等 LLM 输出回答后,就用如下方式解析其回答:</p>
</div>
<ul>
<li>
<p>如果回答中包含字符串 <code>‘Final Answer:’</code>,则结束循环并打印答案。</p>
</li>
<li>
<p>否则,LLM 会输出一个工具调用。你可以解析此输出以获取工具名及参数,并使用所述参数调用所述工具。然后,将此次工具调用的输出附加到提示中,并把扩展后的提示输入给 LLM,直到它有足够的信息生成最终答案。</p>
</li>
</ul>
<p>举个例子,当回答问题 <code>How many seconds are in 1:23:45?</code> 时,LLM 的输出可能如下所示:</p>
<div class="hljs-line">
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">Thought: I need to convert the time string into seconds.

Action:
{
"action": "convert_time",
"action_input": {
"time": "1:23:45"
}
}</pre>
</div>
</div>
<p>由于此回答中不含字符串 <code>‘Final Answer:’</code>,所以其输出的应该是一个工具调用。此时,我们解析此输出并获取工具调用参数:使用参数 <code>{"time": "1:23:45"}</code> 调用工具 <code>convert_time</code>。</p>
<p>可以看到,工具返回了 <code>{'seconds': '5025'}</code>。</p>
<p>此时,我们将整个过程及结果添加到提示中,新提示就变成了如下这样(比之前稍微复杂一些了):</p>
<div class="hljs-line">
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">Here is a question: "How many seconds are in 1:23:45?"
You have access to these tools:
- convert_time: converts a time given in hours:minutes:seconds into seconds.

You should first reflect with ‘Thought: {your_thoughts}’, then you either:
- call a tool with the proper JSON formatting,
- or your print your final answer starting with the prefix ‘Final Answer:’

Thought: I need to convert the time string into seconds.

Action:
{
"action": "convert_time",
"action_input": {
"time": "1:23:45"
}
}
Observation: {'seconds': '5025'}</pre>
</div>
</div>
<p>➡️ 我们再次调用 LLM,并将这个新提示输入给它。鉴于它在 <code>Observation</code> 字段中得到了工具返回的结果,这轮 LLM 很有可能输出如下:</p>
<div class="hljs-line">
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">Thought: I now have the information needed to answer the question.
Final Answer: There are 5025 seconds in 1:23:45.</pre>
</div>
</div>
至此,任务解决!
<h3 id="智能体系统面临的挑战">智能体系统面临的挑战</h3>
<p>智能体系统中的 LLM 引擎需要克服以下几个难点:</p>
<ol>
<li>
<p>从候选工具集中选出能实现预期目标的工具:例如当被问到<code>“大于 30,000 的最小素数是多少?”</code>时,智能体可以调用 <code>Search</code> 工具,并问它`“K2 的高度是多少”,但这么做无济于事。</p>
</li>
<li>
<p>以规定的参数格式调用工具:例如,当尝试计算 10 分钟内行驶了 3 公里的汽车的速度时,必须调用 <code>Calculator</code> 以让其执行“距离”除以“时间”的操作,假设 <code>Calculator</code> 工具能接受 JSON 格式的调用: <code>{"tool": "Calculator", "args": "3km/10min"}</code> ,看上去很简单,但其实会有很多小陷阱,一步不慎就前功尽弃,例如:</p>
<ul>
<li>
<p>工具名称拼写错误:<code>“calculator”</code> 或 <code>“Compute”</code> 是无效的</p>
</li>
<li>
<p>仅给出参数名而未给出参数值:<code>“args”: “distance/time”</code></p>
</li>
<li>
<p>参数格式未标准化:<code>“args”:"3km in 10minutes”</code></p>
</li>
</ul>
</li>
<li>
<p>有效吸收并使用历史信息,无论是原始上下文信息还是前面若干轮工具调用所返回的观察。</p>
</li>
</ol>
<p>那么,在真实场景中如何设置并使用智能体呢?</p>
<h2 id="使用-langchain-运行智能体">使用 LangChain 运行智能体</h2>
<p>我们最近封装了一个 <code>ChatHuggingFace</code> 接口,你可以利用它在 🦜🔗LangChain 中使用开源模型创建智能体。</p>
<p>要创建 ChatModel 并为其提供工具,代码非常简单,你可在 Langchain 文档 中查阅所有内容。</p>
<div class="hljs-line">
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">from langchain_community.llms import HuggingFaceHub
from langchain_community.chat_models.huggingface import ChatHuggingFace

llm = HuggingFaceHub(
repo_id="HuggingFaceH4/zephyr-7b-beta",
task="text-generation",
)

chat_model = ChatHuggingFace(llm=llm)</pre>
</div>
</div>
你可以通过给 `chat_model` 提供 ReAct 风格的提示和工具,将其变成智能体:
<div class="hljs-line">
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">from langchain import hub
from langchain.agents import AgentExecutor, load_tools
from langchain.agents.format_scratchpad import format_log_to_str
from langchain.agents.output_parsers import (
ReActJsonSingleInputOutputParser,
)
from langchain.tools.render import render_text_description
from langchain_community.utilities import SerpAPIWrapper

# setup tools
tools = load_tools(["serpapi", "llm-math"], llm=llm)

# setup ReAct style prompt
prompt = hub.pull("hwchase17/react-json")
prompt = prompt.partial(
tools=render_text_description(tools),
tool_names=", ".join(),
)

# define the agent
chat_model_with_stop = chat_model.bind(stop=["\nObservation"])
agent = (
{
"input": lambda x: x["input"],
"agent_scratchpad": lambda x: format_log_to_str(x["intermediate_steps"]),
}
| prompt
| chat_model_with_stop
| ReActJsonSingleInputOutputParser()
)

# instantiate AgentExecutor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

agent_executor.invoke(
{
"input": "Who is the current holder of the speed skating world record on 500 meters? What is her current age raised to the 0.43 power?"
}
)</pre>
</div>
</div>
智能体第一轮输出如下:
<div class="hljs-line">
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">Thought: To answer this question, I need to find age of the current speedskating world record holder. I will use the search tool to find this information.
Action:
{
"action": "search",
"action_input": "speed skating world record holder 500m age"
}
Observation: ...</pre>
</div>
</div>
<h2 id="智能体对决开源-llm-充当通用推理智能体的表现如何">智能体对决:开源 LLM 充当通用推理智能体的表现如何?</h2>
<p>你可在此处找到我们使用的基准测试代码。</p>
<h3 id="评估">评估</h3>
<p>我们想要度量开源 LLM 作为通用推理智能体时的表现。因此,我们选用的问题都是需要依赖逻辑推演以及一些基本工具的使用才能回答出来的。这里,我们将所需工具限制为计算器和互联网搜索。</p>
<p>最终数据集 结合了以下 3 个数据集的样本:</p>
<ul>
<li>
<p>为了测试互联网搜索能力,我们从HotpotQA中选择了一些问题,该数据集原本是一个检索数据集,但在可以访问互联网时,其可用于通用问答场景。有些问题原先需要结合多个不同来源的信息,对这类问题,我们可以执行多次互联网搜索来综合出最终结果。</p>
</li>
<li>
<p>为了用上计算器,我们添加了来自 GSM8K 的一些问题,该数据集用于测试小学数学四则运算(加、减、乘、除)的能力。</p>
</li>
<li>
<p>我们还从 GAIA 中挑选了一些问题,该数据集是面向通用人工智能助手的一个非常困难的基准测试集。原始数据集中的问题会需要用到很多不同的工具,如代码解释器或 pdf 阅读器,我们精心挑选了一些只需使用搜索和计算器的问题。</p>
</li>
</ul>
<p>评估时,我们选用 Prometheus 格式作为提示格式,并请 GPT-4 对结果以 5 分制李克特量表(Likert scale)形式进行评分。具体使用的提示模板可参阅此处。</p>
<h3 id="模型">模型</h3>
<p>我们对下列先进开源模型进行了评估:</p>
<ul>
<li>
<p>Llama2-70b-chat</p>
</li>
<li>
<p>Mixtral-8x7B-Instruct-v0.1</p>
</li>
<li>
<p>OpenHermes-2.5-Mistral-7B</p>
</li>
<li>
<p>Zephyr-7b-beta</p>
</li>
<li>
<p>SOLAR-10.7B-Instruct-v1.0</p>
</li>
</ul>
<p>上述模型的评估是基于 LangChain 的 ReAct 实现的。因此,其函数调用模板为:</p>
<div class="hljs-line">
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">{
"action": $TOOL_NAME,
"action_input": $INPUT
}</pre>
</div>
</div>
<p>为了进行比较,我们还使用 LangChain 的 OpenAI 智能体在相同的数据集上对 GPT-3.5 和 GPT-4 进行了评估。此时,我们使用 OpenAI 自己的函数调用模板,模型已经针对该模板进行了调优,因此我们认为此时 OpenAI 模型性能处于最佳水平。</p>
<h3 id="结果">结果</h3>
<p>由于并没有专门针对给定调用函数格式进行微调,从这个角度讲,与 OpenAI 智能体相比,开源模型智能体稍有劣势。</p>
<p>尽管如此,还是有一些模型表现让人眼前一亮! 💪</p>
<p>下面给出了 Mixtral-8x7B 回答问题 <code>“Which city has a larger population, Guiyang or Tacheng?”</code> 的一个例子。</p>
<div class="hljs-line">
<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">Thought: To answer this question, I need to find the current populations of both Guiyang and Tacheng. I will use the search tool to find this information.
Action:
{
"action": "search",
"action_input": "current population of Guiyang"
}
4.697 million (2016)

Thought: I have obtained the population of Guiyang, which is 4.697 million (as of 2016). Now, I will use the search tool again to find the population of Tacheng.
Action:
{
"action": "search",
"action_input": "current population of Tacheng"
}
Population: Xinjiang: Tacheng data was reported at 1,110.000 Persons in 2021. This records a decrease from the previous number of 1,138.638 Persons for 2020.
Population: Xinjiang: Tacheng data is updated yearly, averaging 1,023.000 Persons from Dec 2005 to 2021, with 17 observations.

I have obtained the population of Tacheng, which is approximately 1.11 million (as of 2021). Comparing the two populations, Guiyang has a larger population than Tacheng.

Thought: I now know the final answer
Final Answer: Guiyang has a larger population, which is approximately 4.697 million (as of 2016), compared to Tacheng's population of approximately 1.11 million (as of 2021).</pre>
</div>
</div>
以下给出了我们测得的各模型在各数据集上的表现(为了便于阅读,我们把 1-5 分制转换成了 0 - 100%):
<p align="center"><img src="https://img2024.cnblogs.com/blog/46419/202402/46419-20240204155330849-76708337.png" alt="智能体性能基准" width="90%"></p>
<p>如你所见,部分开源模型在智能体工作流中表现欠佳:虽然我们能预料到较小的 Zephyr-7b 可能不尽如人意,但 Llama2-70b 的表现却让我们大跌眼镜。</p>
<p>👉 但 <strong>Mixtral-8x7B 表现得非常好,甚至超越了 GPT-3.5!</strong> 🏆</p>
<p>而且这仅仅是开箱性能:<strong><em>与 GPT-3.5 不同,Mixtral 并没有针对智能体工作流场景微调过</em></strong>(据我们所知),这在一定程度上说明其性能还有进步空间。例如,在 GAIA 上,10% 的失败案例是因为 Mixtral 尝试使用错误的参数格式调用工具。<strong>通过针对函数调用和任务规划技能进行适当的微调,Mixtral 的分数有可能会进一步提高。</strong></p>
<p>➡️我们强烈建议开源社区针对智能体场景微调 Mixtral,以超越 GPT-4! 🚀</p>
<p><strong>最后的话:</strong></p>
<ul>
<li>
<p>虽然本文仅使用了 GAIA 基准的一小部分问题和工具,但该基准似乎有潜力对智能体工作流整体性能进行可靠度量,因为其测例通常需要多步推理以及严格的逻辑。</p>
</li>
<li>
<p>智能体工作流可以提高 LLM 的性能。例如,在 GSM8K 数据集上,GPT-4 的技术报告 表明 5-样本 CoT 提示的成功率为 92%;但一旦使用计算器工具,零样本的成功率就能提升到 95%。而对 Mixtral-8x7B,LLM 排行榜 测得其 5-样本成功率仅为 57.6%,但我们在智能体工作流中测得的零样本成功率为 73%。 <em>(注意,我们只测试了 GSM8K 数据集中的 20 个问题。)</em></p>
</li>
</ul>
<blockquote>
<p>英文原文: https://huggingface.co/blog/open-source-llms-as-agents <br>
原文作者:Aymeric Roucher,Joffrey Thomas,Andrew Reed <br>
译者: Matrix Yao (姚伟峰),英特尔深度学习工程师,工作方向为 transformer-family 模型在各模态数据上的应用及大规模模型的训练推理。</p>

</blockquote>
</div><br><br>
来源:https://www.cnblogs.com/Matrix_Yao/p/18006369
頁: [1]
查看完整版本: 使用开源 LLM 充当 LangChain 智能体