如何提升大模型Agent的能力 ——LLM Agent框架 Modelscope-Agent 实战

简介: 本文介绍Agent到底是什么 ,如何进行优化,以及如何使用Agen框架。

大型语言模型(LLM)的出现带火了Agent。利用LLM理解人类意图、生成复杂计划并且能够自主行动的能力。Agent具有无与伦比的能力,能够做出类似于人类复杂性的决策和完成一些复杂的工作。目前市面上已经出现非常多得Agent框架:XAgent, AutoGPT、BabyAGI、CAMEL、MetaGPT、AutoGen、DSPy、AutoAgents、OpenAgents、Agents、AgentVerse、ChatDev。他们将LLM作为核心引擎,给模型增加记忆,装上工具,去完成一些复杂的任务,使得LLM更像一个人去工作,不得不说Agent的威力还是很值得期待。

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

ModelScope-Agent框架

ModelScope-Agent是一个通用的、可定制的Agent框架,以大语言模型作为核心驱动的应用开发框架,笔者之前在王鹏:Qwen 7B大模型ReAct Prompt详解以及LLM 智能体Agent实战 这篇文章中详细的介绍了一下Agent的原理,本质上还是prompt工程,通过Prompt去驱动模型进行 计划和工具调用。

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

ModelScope-Agent

如何提升Agent的能力呢

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

  • 1.使用更强大的LLM
  • 2.设计更合理的Prompt和Agent Pipeline
  • 3.使用特定数据进行微调

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

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

XAgent

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

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

XAgent

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 帮我进行读取并可视化

name

count

a

1

b

2

c

3


结语

最后可以看看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

点击直达modelscope-agent开源地址,欢迎star~

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

相关文章
|
6月前
|
弹性计算 关系型数据库 API
自建Dify平台与PAI EAS LLM大模型
本文介绍了如何使用阿里云计算巢(ECS)一键部署Dify,并在PAI EAS上搭建LLM、Embedding及重排序模型,实现知识库支持的RAG应用。内容涵盖Dify初始化、PAI模型部署、API配置及RAG知识检索设置。
自建Dify平台与PAI EAS LLM大模型
|
4月前
|
存储 缓存 负载均衡
LLM推理成本直降60%:PD分离在大模型商业化中的关键价值
在LLM推理中,Prefill(计算密集)与Decode(访存密集)阶段特性不同,分离计算可提升资源利用率。本文详解vLLM框架中的PD分离实现及局限,并分析Dynamo、Mooncake、SGLang等主流方案,探讨KV缓存、传输机制与调度策略,助力LLM推理优化。建议点赞收藏,便于后续查阅。
2478 4
|
3月前
|
监控 安全 Docker
10_大模型开发环境:从零搭建你的LLM应用平台
在2025年,大语言模型(LLM)已经成为AI应用开发的核心基础设施。无论是企业级应用、科研项目还是个人创新,拥有一个高效、稳定、可扩展的LLM开发环境都至关重要。
|
3月前
|
人工智能 监控 安全
06_LLM安全与伦理:部署大模型的防护指南
随着大型语言模型(LLM)在各行业的广泛应用,其安全风险和伦理问题日益凸显。2025年,全球LLM市场规模已超过6400亿美元,年复合增长率达30.4%,但与之相伴的是安全威胁的复杂化和伦理挑战的多元化
|
6月前
|
机器学习/深度学习 人工智能 编解码
AI-Compass LLM合集-多模态模块:30+前沿大模型技术生态,涵盖GPT-4V、Gemini Vision等国际领先与通义千问VL等国产优秀模型
AI-Compass LLM合集-多模态模块:30+前沿大模型技术生态,涵盖GPT-4V、Gemini Vision等国际领先与通义千问VL等国产优秀模型
AI-Compass LLM合集-多模态模块:30+前沿大模型技术生态,涵盖GPT-4V、Gemini Vision等国际领先与通义千问VL等国产优秀模型
|
6月前
|
人工智能 自然语言处理 数据可视化
AI-Compass LLM评估框架:CLiB中文大模型榜单、OpenCompass司南、RAGas、微软Presidio等构建多维度全覆盖评估生态系统
AI-Compass LLM评估框架:CLiB中文大模型榜单、OpenCompass司南、RAGas、微软Presidio等构建多维度全覆盖评估生态系统
 AI-Compass LLM评估框架:CLiB中文大模型榜单、OpenCompass司南、RAGas、微软Presidio等构建多维度全覆盖评估生态系统
|
7月前
|
人工智能 搜索推荐 测试技术
通义灵码 Agent+MCP:打造自动化菜品推荐平台,从需求到部署实现全流程创新
通过通义灵码编程智能体模式和 MCP 的集成,开发者可以高效构建在线菜品推荐网站。智能体模式大幅提升了开发效率,MCP 服务则为功能扩展提供了无限可能。
|
7月前
|
存储 分布式计算 API
基于PAI-FeatureStore的LLM embedding功能,结合通义千问大模型,可通过以下链路实现对物品标题、内容字段的离线和在线特征管理。
本文介绍了基于PAI-FeatureStore和通义千问大模型的LLM embedding功能,实现物品标题、内容字段的离线与在线特征管理。核心内容包括:1) 离线特征生产(MaxCompute批处理),通过API生成Embedding并存储;2) 在线特征同步,实时接入数据并更新Embedding至在线存储;3) Python SDK代码示例解析;4) 关键步骤说明,如客户端初始化、参数配置等;5) 最佳实践,涵盖性能优化、数据一致性及异常处理;6) 应用场景示例,如推荐系统和搜索排序。该方案支持端到端文本特征管理,满足多种语义理解需求。
260 1