1 Star 0 Fork 0

nlp_my / modelscope-agent

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

ModelScope-Agent: 基于开源大语言模型的可定制Agent系统



魔搭社区论文 | Demo体验
中文&nbsp | &nbspEnglish

简介

Modelscope-Agent是一个可定制的、可扩展的Agent代码框架。单Agent具有角色扮演、LLM调用、工具使用、规划、记忆等能力。 主要具有以下特点:

  • 简单的Agent实现流程:仅需指定角色描述、LLM名称、工具名列表,即可实现一个Agent应用,框架内部自动实现工具使用、规划、记忆等工作流的编排。
  • 丰富的模型和工具:框架内置丰富的LLM接口,例如Dashscope和Modelscope模型接口,OpenAI模型接口等。内置丰富的工具,例如代码运行天气查询文生图网页解析等,方便定制专属Agent。
  • 统一的接口和高扩展性:框架具有清晰的工具、LLM注册机制,方便用户扩展能力更加丰富的Agent应用。
  • 低耦合性:开发者可以方便的直接使用内置的工具、LLM、记忆等组件,而不需要绑定更上层的Agent。

更新

  • 2024.3。15: Modelscope-Agent 和 Agentfabric(面向GPT的开源版本)正在modelscope studio的生产环境中运行。
  • 2024.2.10:在中国新年期间,我们将modelscope agent升级到v0.3版本,以便开发者通过编码更方便地定制各类agent,并使创建多agent演示变得更加容易。更多详情,您可以参考#267#293
  • 2023.11.26: AgentFabric支持ModelScope创空间多人使用,支持分享定制应用到创空间,更新到最新的GTE text embedding。
  • 2023.11.17: AgentFabric 发布,这是一个交互式的智能体构建工具,用于方便地创建针对各种现实应用量身定制智能体。
  • 2023.10.30: Facechain Agent 发布了人脸写真Agent本地版本,可以在本地运行,具体使用见Facechain Agent
  • 2023.10.25: Story Agent 发布了故事绘本图文生成Agent本地版本,可以在本地运行,具体使用见Story Agent
  • 2023.9.20: ModelScope GPT gradio提供了本地版本,可以在本地运行,可以进入demo/msgpt/目录后执行bash run_msgpt.sh
  • 2023.9.4: 三个基于Agent开发的应用,demo_qwen, demo_retrieval_agent and demo_register_tool 已添加,并提供了详细的教程。
  • 2023.9.2: 与该项目相关的论文 已发布到arxiv。
  • 2023.8.22: 支持使用 ModelScope 令牌访问各种 AI 模型 API。
  • 2023.8.7: modelscope-agent仓库的初始版本已发布。

安装

克隆repo并安装依赖:

git clone https://github.com/modelscope/modelscope-agent.git
cd modelscope-agent && pip install -r requirements.txt

使用ModelScope提供的notebook环境【推荐】

ModelScope(魔搭社区)提供给新用户初始的免费计算资源,参考ModelScope Notebook

Notebook环境使用简单,您只需要按以下步骤操作(注意:目前暂不提供永久存储,实例重启后数据会丢失):

# Step1: 我的notebook -> PAI-DSW -> GPU环境

# Step2: 下载[demo文件](https://github.com/modelscope/modelscope-agent/blob/master/demo/demo_qwen_agent.ipynb)并把它上传到打开的notebook机器上

# Step3: 按顺序执行demo里面的代码块

快速入门

agent结合了大型语言模型(LLM)以及特定任务的工具,并利用LLM来确定为了完成用户任务需要调用哪个或哪些工具。

在一开始,您所需要做的就是使用相应的任务初始化一个RolePlay对象。

  • 样本代码使用了 qwen-max 模型、绘图工具和天气预报工具。
    • 使用 qwen-max 模型需要将示例中的 YOUR_DASHSCOPE_API_KEY 替换为您的 API-KEY,以便代码正常运行。您的 YOUR_DASHSCOPE_API_KEY 可以在这里获得。绘图工具也调用了 DASHSCOPE API(wanx),因此不需要额外配置。
    • 在使用天气预报工具时,需要将示例中的 YOUR_AMAP_TOKEN 替换为您的高德天气 API-KEY,以便代码能够正常运行。您的 YOUR_AMAP_TOKEN 可以在这里获得。
# 配置环境变量;如果您已经提前将api-key提前配置到您的运行环境中,可以省略这个步骤
import os
os.environ['DASHSCOPE_API_KEY']=YOUR_DASHSCOPE_API_KEY
os.environ['AMAP_TOKEN']=YOUR_AMAP_TOKEN

# 选用RolePlay 配置agent
from modelscope_agent.agents.role_play import RolePlay  # NOQA

role_template = '你扮演一个天气预报助手,你需要查询相应地区的天气,并调用给你的画图工具绘制一张城市的图。'

llm_config = {'model': 'qwen-max', 'model_server': 'dashscope'}

# input tool name
function_list = ['amap_weather', 'image_gen']

bot = RolePlay(
    function_list=function_list, llm=llm_config, instruction=role_template)

response = bot.run('朝阳区天气怎样?')

text = ''
for chunk in response:
    text += chunk

结果

  • Terminal 运行
# 第一次调用llm的输出
Action: amap_weather
Action Input: {"location": "朝阳区"}

# 第二次调用llm的输出
目前,朝阳区的天气状况为阴天,气温为1度。

Action: image_gen
Action Input: {"text": "朝阳区城市风光", "resolution": "1024*1024"}

# 第三次调用llm的输出
目前,朝阳区的天气状况为阴天,气温为1度。同时,我已为你生成了一张朝阳区的城市风光图,如下所示:

![](https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/1d/45/20240204/3ab595ad/96d55ca6-6550-4514-9013-afe0f917c7ac-1.jpg?Expires=1707123521&OSSAccessKeyId=LTAI5tQZd8AEcZX6KZV4G8qL&Signature=RsJRt7zsv2y4kg7D9QtQHuVkXZY%3D)

主要组件

Agent对象包括以下组件:

  • LLM:负责处理用户输入并决策调用合适工具。
  • function_list:包含代理可用工具的列表。

我们为用户提供了这些组件的默认实现,但用户也可以根据自己的需求自定义组件。

目前,Agent 的配置可能包含以下参数:

  • llm: 该代理的语言模型配置
    • 当为字典时:设置语言模型的配置为 {'model': '', 'api_key': '', 'model_server': ''}
    • 当为 BaseChatModel 时:语言模型由另一个agent发送
  • function_list: 工具列表
    • 当为字符串时:工具名称
    • 当为字典时:工具配置
  • storage_path: 如果没有另外指定,所有数据都将以键值对的形式存储在这里,通过内存
  • instruction: 该agent的系统指令
  • name: agent的名称
  • description: agent的描述,用于multi_agent
  • kwargs: 其他潜在参数

agent 作为一个基类,不能直接初始化和调用。代理的子类需要继承它。它们必须实现函数_run,主要包括三个部分:生成消息或提示,调用 llm(语言模型),以及基于 llm 结果的工具调用。我们为用户提供了RolePlay中这些组件的实现,您也可以根据您的需求自定义组件。

from modelscope_agent import Agent
class YourCustomAgent(Agent):
    def _run(self, user_request, **kwargs):
        # 定制您的工作流程

配置

对于用户隐私相关的配置,如 user_token 等不应该公开,因此我们建议您使用 dotenv 包和 .env 文件来设置这些配置。

具体来说,我们提供了一个模版文件 .env.template ,用户可以复制并更改文件名为.env 来进行个人配置管理,

并通过 load_dotenv(find_dotenv()) 来加载这些配置。 另外,用户也可以直接通过设置环境变量的方式来进行token的配置。

除此之外,我们还提供了一个模型配置文件模版 cfg_model_template.json ,和一个工具类配置文件模版 cfg_tool_template.json.

我们已经将默认的配置填入,用户可以直接使用,也可以复制并更改文件名,进行深度定制。

LLM

LLM 是代理的核心模块,它确保了交互结果的质量。

目前,LLM 的配置可能包含以下参数:

  • model: 特定的模型名称,将直接传递给模型服务提供商。
  • model_server: 模型服务的提供商。

BaseChatModel作为 LLM 的基类,不能直接初始化和调用。子类需要继承它。它们必须分别实现函数 _chat_stream_chat_no_stream,这两个函数分别对应流式输出和非流式输出。 可选实现 chat_with_functionschat_with_raw_prompt 函数,用于调用功能和文本补全。

目前我们提供了三个模型服务提供商的实现:dashscope(用于 qwen 系列模型)、zhipu(用于 glm 系列模型)和 openai(用于所有 openai api 格式模型)。您可以直接使用上述服务提供商支持的模型,或者您可以定制您自己的 LLM。

有关更多信息,请参阅docs/modules/llm.md

有关本地部署的更多信息,请参阅docs/local_deploy.md

自定义工具

我们提供了几种多领域工具,可以在agent中配置和使用。 您也可以通过继承基础工具,并根据预定义的模式设置工具的名称、描述和参数来自定义您的工具。根据您的需要,可以实现 call() 函数。 一个自定义工具的例子提供在 以下是支持的工具示例: demo_register_new_tool

您可以将您想要使用的工具名称或配置传递给agent。

# by tool name
function_list = ['amap_weather', 'image_gen']
bot = RolePlay(function_list=function_list, ...)

# by tool configuration
from langchain.tools import ShellTool
function_list = [{'terminal':ShellTool()}]
bot = RolePlay(function_list=function_list, ...)

# by mixture
function_list = ['amap_weather', {'terminal':ShellTool()}]
bot = RolePlay(function_list=function_list, ...)

Built-in tools

训练框架

我们在demo/tool_agent_finetune_swift中提供了一个开源大模型训练框架,主要集成了来自ModelScope的SWIFT训练框架。此外,我们还发布了一个大规模的工具指令微调数据集MSAgent-Bench。

MSAgent-Bench数据集

MSAgent-Bench是一个包含598k个对话的综合工具数据集,包括通用API、模型API、面向API的问答和与API无关的指令。您可以直接在数据集链接上下载它,或通过SDK访问:

from modelscope.msdatasets import MsDataset

ds = MsDataset.load('damo/MSAgent-Bench', split='train')
one_ds = next(iter(ds))

image

训练微调

训练样本可以组织成以下形式,其中:<|startofthink|>和<|endofthink|>之间包含的是API请求生成内容,<|startofexec|>和<|endofexec|>之间包含的是API执行结果。

{
    "id":"MS_Agent_Bench_20",
    "conversations":[
        {
            "from":"system",
            "value": "你是达摩院xxxx"
        },
        {
            "from":"user",
            "value":"按照给定的schema抽取出下面文本对应的信息\nschema:{\"人物\": null, \"地理位置\": null, \"组织机构\": null}\n近日,美国政府宣布将对中国1000多种商品加征关税,并威胁进一步加征关税。"
        },
        {
            "from":"assistant",
            "value":"<|startofthink|>```JSON\n{\"api_name\": \"modelscope_text-ie\", \"url\": \"http://9.32.64.200:5873/damo/nlp_structbert_siamese-uie_chinese-base\", \"parameters\": {\"text\": \"近日,美国政府宣布将对中国1000多种商品加征关税,并威胁进一步加征关税。\", \"schema\": \"{\\\"人物\\\": null, \\\"地理位置\\\": null, \\\"组织机构\\\": null}\"}}\n```<|endofthink|>\n\n<|startofexec|>```JSON\n{\"人物\": [], \"地理位置\": [\"中国\", \"美国\"], \"组织机构\": []}\n```<|endofexec|>\n信息抽取结果:{\"人物\": [], \"地理位置\": [\"中国\", \"美国\"], \"组织机构\": []}。"
        }
    ]
}

执行下面这个脚本训练模型

cd demo/tool_agent_finetune_swift
PYTHONPATH=./ bash scripts/train/run_qwen_ddp.sh

相关教程

如果您还想进一步了解Agent细节,可以参考我们的文章和视频教程

分享您的Agent

我们感谢您对参与我们的开源ModelScope-Agent项目的热情。如果您遇到任何问题,请随时向我们提问。如果您已经构建了一个新的Agent Demo并准备与我们分享您的工作,请随时创建一个pull请求!如果您需要任何进一步的帮助,请邮件contact@modelscope.cn或者交流群联系我们

Facechain Agent

Facechain是一个开源的人脸写真项目,用户上传几张图片就可以生成各种风格的个人写真,我们通过modelscope-agent框架,接入facechain的能力,极大的简化了使用流程,通过对话的方式即可完成人脸写真

FaceChainAgent创空间应用地址:https://modelscope.cn/studios/CVstudio/facechain_agent_studio/summary

可以直接在notebook/colab/本地中运行:https://www.modelscope.cn/my/mynotebook

! git clone -b feat/facechain_agent https://github.com/modelscope/modelscope-agent.git

! cd modelscope-agent && ! pip install -r requirements.txt
! cd modelscope-agent/demo/facechain_agent/demo/facechain_agent && ! pip install -r requirements.txt
! pip install http://dashscope-cn-beijing.oss-cn-beijing.aliyuncs.com/zhicheng/modelscope_agent-0.1.0-py3-none-any.whl
! PYTHONPATH=/mnt/workspace/modelscope-agent/demo/facechain_agent && cd modelscope-agent/demo/facechain_agent/demo/facechain_agent && python app_v1.0.py

Story Agent

Story Agent是一个开源的故事绘本生成智能体,用户通过对话交流的方式即可完成一个绘本的创作,整个流程Agent会智能的引导用户如何创作绘本

StoryAgent 创空间应用地址:https://modelscope.cn/studios/damo/story_agent/summary

也可以直接在notebook中运行:https://www.modelscope.cn/my/mynotebook

! git clone -b feat/story_agent_gradio https://github.com/modelscope/modelscope-agent.git

import os
os.environ['DASHSCOPE_API_KEY'] = '替换成你的'
#DASHSCOPE_API_KEY可以从dashscope网站 https://dashscope.console.aliyun.com/apiKey获取
! cd modelscope-agent && ! pip install -r requirements.txt
! cd modelscope-agent/demo/story_agent && ! pip install -r requirement_gr.txt
! cd modelscope-agent/demo/story_agent && ! sh run_story_agent.sh

引用

如果您觉得这个工作很有用,请考虑给这个项目加星,并引用我们的论文,感谢:

@misc{li2023modelscopeagent,
      title={ModelScope-Agent: Building Your Customizable Agent System with Open-source Large Language Models},
      author={Chenliang Li and Hehong Chen and Ming Yan and Weizhou Shen and Haiyang Xu and Zhikai Wu and Zhicheng Zhang and Wenmeng Zhou and Yingda Chen and Chen Cheng and Hongzhu Shi and Ji Zhang and Fei Huang and Jingren Zhou},
      year={2023},
      eprint={2309.00986},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}

License

本项目使用 Apache License (Version 2.0)进行许可。

Star History

Star History Chart

Copyright 2022-2023 Alibaba ModelScope. All rights reserved. Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2020-2022 Alibaba ModelScope. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

暂无描述 展开 收起
Python 等 4 种语言
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/nlp_my/modelscope-agent.git
git@gitee.com:nlp_my/modelscope-agent.git
nlp_my
modelscope-agent
modelscope-agent
master

搜索帮助

344bd9b3 5694891 D2dac590 5694891