用通俗易懂的方式讲解:如何提升大模型 Agent 的能力?

本文介绍了大型语言模型(LLMs)驱动的Agent在理解和执行复杂任务中的潜力,探讨了各种Agent框架如ModelScope-Agent和XAgent的使用,强调了优化Prompt、LLM选择和数据微调的重要性。作者通过实例展示了如何使用ModelScope-Agent进行知识检索和代码执行,以及提升Agent性能的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大型语言模型(LLM)的出现带火了Agent。利用LLM理解人类意图、生成复杂计划并且能够自主行动的能力。Agent具有无与伦比的能力,能够做出类似于人类复杂性的决策和完成一些复杂的工作。

目前市面上已经出现非常多得Agent框架:XAgent, AutoGPT、BabyAGI、CAMEL、MetaGPT、AutoGen、DSPy、AutoAgents、OpenAgents、Agents、AgentVerse、ChatDev。他们将LLM作为核心引擎,给模型增加记忆,装上工具,去完成一些复杂的任务,使得LLM更像一个人去工作,不得不说Agent的威力还是很值得期待。

接下来我就使用一个 Agent 框架去介绍一下,Agent到底是什么 ,如何进行优化,以及如何使用 Agent 框架。

ModelScope-Agent框架

ModelScope-Agent是一个通用的、可定制的Agent框架,以大语言模型作为核心驱动的应用开发框架,通过Prompt去驱动模型进行计划和工具调用。

框架的好处将有记忆能力,计划能力,工具调用能力的Agent封装成了一个类,用户只需要使用简单的接口就能实现将知识和工具注入到Agent类当中。整个Agent的运行会遵循下方流程:准备好记忆和工具,然后进行计划,最终按照计划使用记忆,调用工具,返回结果。

在这里插入图片描述

通俗易懂讲解大模型系列

如何提升Agent的能力呢

之前一直知道大模型有计划推理能力,但是做过一些实验,有时候自定义的工具经常会调用失败,而且有时候结果也不尽如人意。如何在特定的场景进行一些能力增强呢?或者问题问大一点,如何提升Agent的能力呢。主要有3个方面的工作可以做:

  • 1.使用更强大的LLM

  • 2.设计更合理的Prompt和Agent Pipeline

  • 3.使用特定数据进行微调

1.更强的大语言模型LLM(使用gpt4)

下方是XAgent框架的使用建议,建议用gpt4来作为Agent的核心引擎,不然效果会大打折扣。可以看出其实很多大模型的计划推理和反思能力其实不足以去完成一个复杂任务。

在这里插入图片描述

2.更优的Prompt和工作流程设计(prompt工程和pipeline设计)

下方是XAgent的流程设计,包含了任务拆解,结果验证与反思这一个循环,更符合人类思维模式的进化习惯了。当然速度也会更慢,如果是特定领域,也可以设计特定领域的工作流程去将Agent打造成某一领域的专家(也就是GPTS)。
在这里插入图片描述

3.更多的推理,决策,计划,反思类数据的训练。(llm微调)

下方是千问的为了让模型具备工具调用能力微调数据,可以看出就是将模型推理过程数据化了。

[
  {
    "conversations": [
      {
        "from": "user",
        "value": "Answer the following questions as best you can. You have access to the following APIs:\\n\\ngoogle_search: Call this tool to interact with the Google Search API. What is the Google Search API useful for? Google Search is a general search engine that can be used to access the internet, query encyclopedia knowledge, and stay informed about current events. Format the arguments as a JSON object. Parameters: [{\\"name\\": \\"search_query\\", \\"description\\": \\"Search keywords or phrases\\", \\"required\\": true, \\"schema\\": {\\"type\\": \\"string\\"}}]\\n\\ncode_interpreter: Call this tool to interact with the Code Interpreter API. What is the Code Interpreter API useful for? Code interpreter that can execute Python code.Enclose the code within triple backticks (`) at the beginning and end of the code. Parameters: [{\\"name\\": \\"code\\", \\"description\\": \\"Code to be executed\\", \\"required\\": true, \\"schema\\": {\\"type\\": \\"string\\"}}]\\n\\nUse the following format:\\n\\nQuestion: the input question you must answer\\nThought: you should always think about what to do\\nAction: the action to take, should be one of [google_search, code_interpreter]\\nAction Input: the input to the action\\nObservation: the result of the action\\n... (this Thought/Action/Action Input/Observation can be repeated zero or more times)\\nThought: I now know the final answer\\nFinal Answer: the final answer to the original input question\\n\\nBegin!\\n\\nQuestion: Who is jay chou? And who is his wife?"
      },
      {
        "from": "assistant",
        "value": "Thought: I need to google Jay Chou.\\nAction: google_search\\nAction Input: {\\"search_query\\": \\"Jay Chou\\"}\\nObservation: Jay Chou is ...\\nThought: I need to google Jay's wife.\\nAction: google_search\\nAction Input: {\\"search_query\\": \\"Jay Chou's wife\\"}\\nObservation: Jay Chou's wife is ...\\nThought: I now know the final answer\\nFinal Answer: Jay Chou is ... His wife is ..."
      }
    ]
  },
  {
    "conversations": [
      {
        "from": "user",
        "value": "Answer the following questions as best you can. You have access to the following APIs:\\n\\ngoogle_search: Call this tool to interact with the Google Search API. What is the Google Search API useful for? Google Search is a general search engine that can be used to access the internet, query encyclopedia knowledge, and stay informed about current events. Format the arguments as a JSON object. Parameters: [{\\"name\\": \\"search_query\\", \\"description\\": \\"Search keywords or phrases\\", \\"required\\": true, \\"schema\\": {\\"type\\": \\"string\\"}}]\\n\\ncode_interpreter: Call this tool to interact with the Code Interpreter API. What is the Code Interpreter API useful for? Code interpreter that can execute Python code.Enclose the code within triple backticks (`) at the beginning and end of the code. Parameters: [{\\"name\\": \\"code\\", \\"description\\": \\"Code to be executed\\", \\"required\\": true, \\"schema\\": {\\"type\\": \\"string\\"}}]\\n\\nUse the following format:\\n\\nQuestion: the input question you must answer\\nThought: you should always think about what to do\\nAction: the action to take, should be one of [google_search, code_interpreter]\\nAction Input: the input to the action\\nObservation: the result of the action\\n... (this Thought/Action/Action Input/Observation can be repeated zero or more times)\\nThought: I now know the final answer\\nFinal Answer: the final answer to the original input question\\n\\nBegin!\\n\\nQuestion: 123+456=?"
      },
      {
        "from": "assistant",
        "value": "Thought: I need to compute the result using Code Interpreter.\\nAction: code_interpreter\\nAction Input:\\n```py\\n123 + 456\\n```\\nObservation: 579\\nThought: I now know the final answer\\nFinal Answer: 579"
      },
      {
        "from": "user",
        "value": "Multiply the result by 2."
      },
      {
        "from": "assistant",
        "value": "Thought: Code Interpreter is helpful for answering this question.\\nAction: code_interpreter\\nAction Input:\\n```py\\n579 * 2\\n```\\nObservation: 1158\\nThought: I now know the final answer\\nFinal Answer: 1158"
      },
      {
        "from": "user",
        "value": "You are so smart, Qwen."
      },
      {
        "from": "assistant",
        "value": "Thought: I now know the final answer\\nFinal Answer: Thank you."
      },
      {
        "from": "user",
        "value": "Please re-execute the code for computing my first question again."
      },
      {
        "from": "assistant",
        "value": "Thought: I need to re-compute the result.\\nAction: code_interpreter\\nAction Input:\\n```py\\n123 + 456\\n```\\nObservation: 579\\nThought: I now know the final answer\\nFinal Answer: 579"
      }
    ]
  }
]

ModelScope-Agent框架实战

下方实现了一个带记忆,能够使用code interpreter工具的一个agent,用到的大模型就是qwen-max

from modelscope_agent.agent import AgentExecutor
from modelscope_agent.tools import CodeInterpreter
from  modelscope_agent.agent_types import AgentType
from modelscope_agent.llm import LLMFactory
from langchain.embeddings import ModelScopeEmbeddings, DashScopeEmbeddings
from langchain.vectorstores import FAISS
from modelscope_agent.retrieve import ToolRetrieval, KnowledgeRetrieval
import faiss

from dotenv import load_dotenv  
import os
from modelscope.utils.config import Config
os.environ['DASHSCOPE_API_KEY'] = "你的千问key"
model_cfg = Config.from_file("./config/cfg_model_template.json")

model_name = 'qwen-max'
llm = LLMFactory.build_llm(model_name, model_cfg)

# 额外工具列表,这里只有一个code_interpreter
additional_tool_list = {
    CodeInterpreter.name: CodeInterpreter()
}

# 基于阿里云DashScope向量Embedding的配置
embeddings = DashScopeEmbeddings(model="text-embedding-v1")
# 构建知识库
file_path = 'qa.txt'
knowledge_retrieval = KnowledgeRetrieval.from_file(file_path, embeddings, FAISS)

# 构建Agent,需要传入llm,工具配置config以及工具检索
agent = AgentExecutor(llm, agent_type=AgentType.MRKL, additional_tool_list=additional_tool_list,tool_retrieval=False, knowledge_retrieval=knowledge_retrieval)
available_tool_list = ['code_interpreter']
agent.set_available_tools(available_tool_list)

# 接下来就可以进行agent.run了

检索示例——知识库检索

在这里插入图片描述

code interpreter 读取excel并可视化

给定下方一个execl 文档,希望agent使用python 帮我进行读取并可视化

namecount
a1
b2
c3

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

结语

最后可以看看agent的历史聊天记录,整个过程,包括模型的计划,推理和工具使用等还是大量使用了ReAct Prompt,没有特别的设计。这样我们从这一个简单的Agent 流,进一步认识到Agent是什么,同时也可以了解到从哪些方面进行进一步优化。

图片

[{'content': 'Answer the following questions as best you can. You have access '
             'to the following tools: `\\n'
             '\\n'
             'code_interpreter: code_interpreter API. Executes code on the '
             "user's machine, **in the users local environment**, and returns "
             'the output 输入参数: [{"name": "language", "description": "The '
             'programming language (required parameter to the `execute` '
             'function)", "required": true}, {"name": "code", "description": '
             '"The code to execute (required)", "required": true}]\\n'
             '\\n'
             'Use the following format:\\n'
             '\\n'
             'Question: the input question you must answer\\n'
             'Thought: you should always think about what to do\\n'
             'Action: the action to take, should be one of '
             "['code_interpreter']\\n"
             'Action Input: the input to the action\\n'
             'Observation: the result of the action\\n'
             '... (this Thought/Action/Action Input/Observation can be '
             'repeated zero or more times)\\n'
             'Thought: I now know the final answer\\n'
             'Final Answer: the final answer to the original input question\\n'
             '\\n'
             'Begin!\\n'
             "Question: 读取一个文件'./123.xlsx'\\n",
  'role': 'user'},
 {'content': 'Thought: 我需要使用代码来读取一个Excel文件。\\n'
             'Action: code_interpreter\\n'
             'Action Input:\\n'
             '```py\\n'
             'import pandas as pd\\n'
             '# 读取Excel文件\\n'
             "df = pd.read_excel('./123.xlsx')\\n"
             '# 显示数据框的前几行\\n'
             'df.head()\\n'
             '```\\n'
             'Observation: name  count\\n'
             '\\n'
             '0    a      1\\n'
             '\\n'
             '1    b      2\\n'
             '\\n'
             '2    c      3\\n'
             '\\n'
             '\\n'
             'Thought: 代码成功读取了Excel文件并显示了数据的前几行。\\n'
             "Final Answer: 文件'./123.xlsx'的内容如下:\\n"
             '\\n'
             '| name | count |\\n'
             '| ---- | ----- |\\n'
             '| a    | 1     |\\n'
             '| b    | 2     |\\n'
             '| c    | 3     |\\n'
             '\\n'
             '请注意,这只是一个示例,实际文件内容可能会有所不同。',
  'role': 'assistant'},
 {'content': 'Question: 然后帮我把结果可视化一下,并保存成./123.png\\n', 'role': 'user'},
 {'content': 'Thought: 我需要使用代码来创建一个数据的可视化并保存为PNG文件。\\n'
             'Action: code_interpreter\\n'
             'Action Input:\\n'
             '```py\\n'
             'import pandas as pd\\n'
             'import matplotlib.pyplot as plt\\n'
             '\\n'
             '# 读取Excel文件\\n'
             "df = pd.read_excel('./123.xlsx')\\n"
             '\\n'
             '# 创建图表\\n'
             "plt.bar(df['name'], df['count'])\\n"
             "plt.xlabel('Name')\\n"
             "plt.ylabel('Count')\\n"
             "plt.title('Name vs Count')\\n"
             '\\n'
             '# 保存图表为PNG文件\\n'
             "plt.savefig('./123.png')\\n"
             '```\\n'
             'Observation: <BarContainer object of 3 artists>\\n'
             '\\n'
             "Text(0.5, 0, 'Name')\\n"
             '\\n'
             "Text(0, 0.5, 'Count')\\n"
             '\\n'
             "Text(0.5, 1.0, 'Name vs Count')\\n"
             ' \\n'
             '\\n'
             "Thought: 代码成功创建了一个条形图并保存为'./123.png'。\\n"
             'Final Answer: '
             "我已经将'./123.xlsx'文件中的数据可视化为一个条形图,并将其保存为'./123.png'。这个图表显示了每个名字对应的计数。你可以查看'./123.png'文件来查看生成的图表。请注意,由于这是一个文本环境,我无法直接展示图像。但是在你的本地环境中,你应该能在相同目录下看到生成的图像文件。",
  'role': 'assistant'}]

参考

https://link.zhihu.com/?target=https%3A//github.com/OpenBMB/XAgent/nt/

https://github.com/modelscope/modelscope-agent

<think>好的,用户之前询问了LangChain的六大模块,现在他想要一个关于Agents的具体使用示例。我需要先回顾一下之前关于Agents的介绍,确保内容一致。用户可能对Agents的工作机制不太清楚,或者想通过实例更好地理解如何在实际项目中应用。 首先,用户需要的是具体的例子,而不仅仅是理论。我需要考虑如何用简单明了的案例展示Agents的用法。比如,天气查询、数学计算或数据库查询这样的常见场景比较适合,因为它们容易理解。 接下来,要确保示例的结构清晰,分步骤说明代理的工作流程。可能需要解释代理如何选择工具、执行动作以及整合结果。同时,代码示例会很有帮助,但用户可能不熟悉Python或LangChain的具体语法,所以需要用伪代码或简化代码来说明,避免过于复杂。 另外,用户可能想知道如何自定义工具,比如添加自己的API或函数。这部分需要简明扼要地说明,让用户明白扩展的可能性。同时,需要提到参数如verbose和handle_parsing_errors的作用,帮助用户在实际使用中调试和处理错误。 还要注意用户可能的深层需求,比如如何将Agents与其他模块结合使用,或者如何处理复杂的任务流程。这时候可以简要提到与其他模块的协作,比如提示模板或记忆模块,但重点还是放在Agents本身。 最后,确保语言通俗易懂,避免专业术语过多,必要时进行解释。例如,解释什么是ReAct框架,或者为什么需要工具的选择。这有助于用户更好地理解示例背后的逻辑。</think>好的!我将通过一个**天气查询助手**的示例,详细讲解 LangChain 中 **Agents(代理)** 的使用逻辑和步骤。 --- ### 场景描述 用户问:“北京今天的气温是多少度?” 代理需要完成: 1. **理解问题意图** → 需要获取实时天气数据 2. **选择工具** → 调用天气API 3. **解析结果** → 提取温度信息 4. **生成回答** → 组织自然语言回复 --- ### 代码示例(简化版) ```python from langchain.agents import AgentType, initialize_agent from langchain.llms import OpenAI from langchain.tools import Tool # 1. 定义工具:天气API查询函数 def get_weather(city: str) -> str: # 假设这里调用真实API,返回示例数据 return f"{city} 今天晴,气温 25℃" # 2. 将函数封装为Tool对象 weather_tool = Tool( name="WeatherAPI", func=get_weather, description="用于查询城市天气,输入应为城市名称(如'北京')" ) # 3. 初始化代理 llm = OpenAI(temperature=0) # 选择语言模型 agent = initialize_agent( tools=[weather_tool], # 工具列表 llm=llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, # 代理类型 verbose=True # 显示详细执行过程 ) # 4. 执行代理 response = agent.run("北京今天的气温是多少度?") print(response) ``` --- ### 执行过程解析 启用 `verbose=True` 后,控制台会显示代理的**思考链**: ``` > 进入 AgentExecutor 链... 我需要回答用户关于北京气温的问题。我没有实时天气数据,但有一个WeatherAPI工具可以查询。 Action: WeatherAPI Action Input: "北京" Observation: 北京 今天晴,气温 25℃ 现在我知道北京今天的气温是25℃,可以直接回答用户。 最终答案:北京今天的气温是25℃。 ``` --- ### Agents 核心机制 1. **工具选择(Tool Selection)** - 代理根据问题描述和工具的 `description` 字段,自动匹配最合适的工具。 - 例如:问题含“天气”→选择 `WeatherAPI`;含“计算”→选择计算器工具。 2. **输入参数解析(Input Parsing)** - 自动从用户问题中提取工具所需的参数(如从“北京今天气温”提取 `city="北京"`)。 3. **结果整合(Result Synthesis)** - 将工具返回的原始数据(如 `"25℃"`)转化为自然语言回答。 --- ### 高级用法示例:多工具协作 若代理可同时使用**天气API**和**单位转换工具**: ```python 用户问:“旧金山今天的温度是多少华氏度?” → 代理执行流程: 1. 调用天气API → 获取摄氏温度(如20℃) 2. 调用单位转换工具 → 将20℃转换为68℉ 3. 生成回答:“旧金山今天气温为68华氏度” ``` --- ### 关键参数说明 - **Agent Types**: - `ZERO_SHOT_REACT_DESCRIPTION`:无历史上下文,依赖即时推理(示例中使用) - `CONVERSATIONAL_REACT_DESCRIPTION`:支持多轮对话记忆 - **Tools**:可自定义工具(如数据库查询、网络搜索、代码执行等) - **handle_parsing_errors**:处理工具调用失败时的错误恢复策略 --- ### 应用场景拓展 1. **数据分析代理**:调用 SQL 查询工具 + 数据可视化工具 2. **客服助手**:结合知识库检索工具 + 工单系统 API 3. **科研代理**:论文检索工具 + 公式计算工具 通过灵活组合工具,Agents 可让 LLM 突破纯文本生成的限制,实现**动态决策**和**外部系统交互**,是 LangChain 中最具扩展性的模块之一。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值