书生浦语实战营第二期之AgentLego智能体

title

1. 环境配置

选择镜像为 Cuda12.2-conda。

1.1 创建环境

step1: mkdir -p /root/agent

step2: studio-conda -t agent -o pytorch-2.1.2

进行完上面的操作之后,我们还需要安装 Lagent 和 AgentLego:

step1: 进入到对应的文件夹  cd /root/agent
step2: 激活环境  conda activate agent
step3: 拉取仓库并安装
		git clone https://gitee.com/internlm/lagent.git
		cd lagent && git checkout 581d9fb && pip install -e . && cd ..
		git clone https://gitee.com/internlm/agentlego.git
		cd agentlego && git checkout 7769e0d && pip install -e . && cd ..

conda环境创建成功,如下图所示:
a
lagent拉取并安装成功,如下图所示:

b

agentlego拉取并安装成功,如下图所示:
c

1.2 安装其他依赖

我们之后会用到LMDeploy,可以执行如下命令:

conda activate agent

pip install lmdeploy==0.3.0

d

1.3 拉取直接可用的脚本

cd /root/agent

git clone -b camp2 https://gitee.com/internlm/Tutorial.git

2. Lagent Web Demo实践

2.1 使用 LMDeploy 部署

由于 Lagent 的 Web Demo 需要用到 LMDeploy 所启动的 api_server,因此我们首先在 vscode terminal 中执行如下代码使用 LMDeploy 启动一个 api_server。

step1: conda activate agent
step2: lmdeploy serve api_server /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-7b \
                            --server-name 127.0.0.1 \
                            --model-name internlm2-chat-7b \
                            --cache-max-entry-count 0.1

如下图所示:

2.2 启动并使用 Lagent Web Demo

首先,我们需要新建一个terminal,然后依次执行以下命令:

step1: conda activate agent
step2: cd /root/agent/lagent/examples
step3: streamlit run internlm2_agent_web_demo.py --server.address 127.0.0.1 --server.port 7860

在等待 LMDeploy 的 api_server 与 Lagent Web Demo 完全启动后(如下图所示),在本地进行端口映射,将 LMDeploy api_server 的23333端口以及 Lagent Web Demo 的7860端口映射到本地。可以执行以下命令:

ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p 端口号

上述操作成功时,结果应为:

e

f

接下来在本地的浏览器页面中打开 http://localhost:7860 以使用 Lagent Web Demo。注意模型 IP 为 127.0.0.1:23333,在输入完成后按下回车键以确认。并且demo中只有ArxivSearch插件,所以我们可以使用它让模型获得在 arxiv 上搜索论文的能力。

效果如图所示:
dd

2.3. 用 Lagent 自定义工具

首先Lagent 中关于工具部分的介绍文档位于 https://lagent.readthedocs.io/zh-cn/latest/tutorials/action.html 。

使用 Lagent 自定义工具主要分为以下几步:

step1: 继承 BaseAction 类
step2: 实现简单工具的 run 方法;或者实现工具包内每个子工具的功能
step3: 简单工具的 run 方法可选被 tool_api 装饰;工具包内每个子工具的功能都需要被 tool_api 装饰

下面将实现一个调用和风天气 API 的工具以完成实时天气查询的功能。

2.1 创建工具文件

step1: 创建文件  touch /root/agent/lagent/lagent/actions/weather.py
step2: 编写实现逻辑(我这里直接使用官方code)

2.2 获取 API KEY

第一步:为了获得稳定的天气查询服务,我们首先要获取 API KEY。首先打开 https://dev.qweather.com/docs/api/ 后,点击右上角控制台。
第二步:进入控制台后,点击左侧项目管理,然后点击右上角创建项目以创建新项目。
第三步:接下来回到项目管理页面,查看我们刚刚创建的 key,并且复制好以供2.3节中使用。

2.3 体验天气查询效果

与前面部分类似,在两个 terminal 中分别启动 LMDeploy 服务和 Tutorial 已经写好的用于这部分的 Web Demo:

step1: 激活环境  conda activate agent
step2: 启动server  
		lmdeploy serve api_server /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-7b \
		                            --server-name 127.0.0.1 \
		                            --model-name internlm2-chat-7b \
		                            --cache-max-entry-count 0.1

c

然后,这里需要新开一个terminal启动webdemo

step3: export WEATHER_API_KEY=刚刚获取的API KEY
step4: conda activate agent
step5: cd /root/agent/Tutorial/agent
step6: streamlit run internlm2_weather_web_demo.py --server.address 127.0.0.1 --server.port 7860
step7: 进行端口映射,和上面是一样的,如果有问题的话,可以评论区留言。

das

下面是效果展示图:
aa

可以发现,效果还是非常不错的!

3. AgentLego:组装智能体“乐高”

3.1 直接使用 AgentLego

首先下载 demo 文件:

step1: cd /root/agent
step2: wget http://download.openmmlab.com/agentlego/road.jpg

由于 AgentLego 在安装时并不会安装某个特定工具的依赖,因此我们接下来准备安装目标检测工具运行时所需依赖。

AgentLego 所实现的目标检测工具是基于 mmdet (MMDetection) 算法库中的 RTMDet-Large 模型,因此我们首先安装 mim,然后通过 mim 工具来安装 mmdet。这一步所需时间可能会较长,请耐心等待。

conda activate agent
pip install openmim==0.3.9
mim install mmdet==3.3.0

在安装完成后,可能会观察到以下现象(如下图所示),但请放心,这是正常现象,这并不会影响到我们的使用。

pip error

然后通过在 /root/agent 目录下新建 direct_use.py 以直接使用目标检测工具。

 touch /root/agent/direct_use.py

然后使用官方模板。

接下来再执行 python /root/agent/direct_use.py 以进行推理。在等待 RTMDet-Large 权重下载并推理完成后,我们就可以看到如下输出以及一张位于 /root/agent 名为 road_detection_direct.jpg 的图片:
xxx

原图:

yuantu

处理之后:

cdsd

效果非常好,值得夸赞一波!!!

3. 2 作为智能体工具使用

3.2.1 修改相关文件

由于 AgentLego 算法库默认使用 InternLM2-Chat-20B 模型,因此我们首先需要修改文件的第 105行位置,将 internlm2-chat-20b 修改为 internlm2-chat-7b模型。

modify_file

文件位于/root/agent/agentlego/webui/modules/agents/lagent_agent.py

3.2.2 使用 LMDeploy 部署

由于 AgentLego 的 WebUI 需要用到 LMDeploy 所启动的 api_server,因此我们首先按在 vscode terminal 中执行如下代码使用 LMDeploy 启动一个 api_server。

conda activate agent
lmdeploy serve api_server /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-7b \
                            --server-name 127.0.0.1 \
                            --model-name internlm2-chat-7b \
                            --cache-max-entry-count 0.1

如图所示:
lmdeploy

3.2.3 启动 AgentLego WebUI

接下来我们新建一个 terminal 以启动 AgentLego WebUI。在新建的 terminal 中执行如下指令:

conda activate agent

cd /root/agent/agentlego/webui

python one_click.py

如图所示:

one_click

在等待 LMDeploy 的 api_server 与 AgentLego WebUI 完全启动后,在本地进行端口映射,将 LMDeploy api_server 的23333端口以及 AgentLego WebUI 的7860端口映射到本地。可以执行:

ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p 你的 ssh 端口号
3.2.4 使用 AgentLego WebUI

接下来在本地的浏览器页面中打开 http://localhost:7860 以使用 AgentLego WebUI。首先来配置 Agent,如下图所示。

配置 Agent

然后配置工具,如下图所示。

配置工具

为了确保调用工具的成功率,请在使用时确保仅有这一个工具启用。

选择工具

接下来就可以愉快地使用 Agent 了。点击右下角文件夹以上传图片,上传图片后输入指令并点击 generate 以得到模型回复。如下图所示,我们上传了图片,模型成功地调用了工具,并详细地告诉了我们图中的内容。

使用 Agent

3.3 用 AgentLego 自定义工具

AgentLego 在这方面提供了较为详尽的文档,文档地址为 https://agentlego.readthedocs.io/zh-cn/latest/modules/tool.html 。自定义工具主要分为以下几步:

1. 继承 BaseTool 类
2. 修改 default_desc 属性(工具功能描述)
3. 如有需要,重载 setup 方法(重型模块延迟加载)
4. 重载 apply 方法(工具功能实现)

其中第一二四步是必须的步骤。下面我们将实现一个调用 MagicMaker 的 API 以实现图像生成的工具。

MagicMaker 是汇聚了优秀 AI 算法成果的免费 AI 视觉素材生成与创作平台。主要提供图像生成、图像编辑和视频生成三大核心功能,全面满足用户在各种应用场景下的视觉素材创作需求。体验更多功能可以访问 https://magicmaker.openxlab.org.cn/home 。

3.1 创建工具文件
首先通过 touch /root/agent/agentlego/agentlego/tools/magicmaker_image_generation.py(大小写敏感)的方法新建工具文件。该文件的内容如下:

import json
import requests

import numpy as np

from agentlego.types import Annotated, ImageIO, Info
from agentlego.utils import require
from .base import BaseTool


class MagicMakerImageGeneration(BaseTool):

    default_desc = ('This tool can call the api of magicmaker to '
                    'generate an image according to the given keywords.')

    styles_option = [
        'dongman',  # 动漫
        'guofeng',  # 国风
        'xieshi',   # 写实
        'youhua',   # 油画
        'manghe',   # 盲盒
    ]
    aspect_ratio_options = [
        '16:9', '4:3', '3:2', '1:1',
        '2:3', '3:4', '9:16'
    ]

    @require('opencv-python')
    def __init__(self,
                 style='guofeng',
                 aspect_ratio='4:3'):
        super().__init__()
        if style in self.styles_option:
            self.style = style
        else:
            raise ValueError(f'The style must be one of {self.styles_option}')
        
        if aspect_ratio in self.aspect_ratio_options:
            self.aspect_ratio = aspect_ratio
        else:
            raise ValueError(f'The aspect ratio must be one of {aspect_ratio}')

    def apply(self,
              keywords: Annotated[str,
                                  Info('A series of Chinese keywords separated by comma.')]
        ) -> ImageIO:
        import cv2
        response = requests.post(
            url='https://magicmaker.openxlab.org.cn/gw/edit-anything/api/v1/bff/sd/generate',
            data=json.dumps({
                "official": True,
                "prompt": keywords,
                "style": self.style,
                "poseT": False,
                "aspectRatio": self.aspect_ratio
            }),
            headers={'content-type': 'application/json'}
        )
        image_url = response.json()['data']['imgUrl']
        image_response = requests.get(image_url)
        image = cv2.cvtColor(cv2.imdecode(np.frombuffer(image_response.content, np.uint8), cv2.IMREAD_COLOR),cv2.COLOR_BGR2RGB)
        return ImageIO(image)
        

3.2 注册新工具
接下来修改 /root/agent/agentlego/agentlego/tools/init.py 文件,将我们的工具注册在工具列表中。如下所示,我们将 MagicMakerImageGeneration 通过 from .magicmaker_image_generation import MagicMakerImageGeneration 导入到了文件中,并且将其加入了 all 列表中。

from .base import BaseTool
from .calculator import Calculator
from .func import make_tool
from .image_canny import CannyTextToImage, ImageToCanny
from .image_depth import DepthTextToImage, ImageToDepth
from .image_editing import ImageExpansion, ImageStylization, ObjectRemove, ObjectReplace
from .image_pose import HumanBodyPose, HumanFaceLandmark, PoseToImage
from .image_scribble import ImageToScribble, ScribbleTextToImage
from .image_text import ImageDescription, TextToImage
from .imagebind import AudioImageToImage, AudioTextToImage, AudioToImage, ThermalToImage
from .object_detection import ObjectDetection, TextToBbox
from .ocr import OCR
from .scholar import *  # noqa: F401, F403
from .search import BingSearch, GoogleSearch
from .segmentation import SegmentAnything, SegmentObject, SemanticSegmentation
from .speech_text import SpeechToText, TextToSpeech
from .translation import Translation
from .vqa import VQA
from .magicmaker_image_generation import MagicMakerImageGeneration  # 新增加的

__all__ = [
    'CannyTextToImage', 'ImageToCanny', 'DepthTextToImage', 'ImageToDepth',
    'ImageExpansion', 'ObjectRemove', 'ObjectReplace', 'HumanFaceLandmark',
    'HumanBodyPose', 'PoseToImage', 'ImageToScribble', 'ScribbleTextToImage',
    'ImageDescription', 'TextToImage', 'VQA', 'ObjectDetection', 'TextToBbox', 'OCR',
    'SegmentObject', 'SegmentAnything', 'SemanticSegmentation', 'ImageStylization',
    'AudioToImage', 'ThermalToImage', 'AudioImageToImage', 'AudioTextToImage',
    'SpeechToText', 'TextToSpeech', 'Translation', 'GoogleSearch', 'Calculator',
    'BaseTool', 'make_tool', 'BingSearch', 'MagicMakerImageGeneration',  # 新增加的
]


3.3 体验自定义工具效果
与2.2,2.3以及2.4节类似,我们在两个 terminal 中分别启动 LMDeploy 服务和 AgentLego 的 WebUI 以体验我们自定义的工具的效果。

注意,确保 2.2 节中的 LMDeploy 服务以及 2.3 节中的 Web Demo 服务已经停止(即 terminal 已关闭),否则会出现 CUDA Out of Memory 或是端口已占用的情况!

conda activate agent
lmdeploy serve api_server /root/share/new_models/Shanghai_AI_Laboratory/internlm2-chat-7b \
                            --server-name 127.0.0.1 \
                            --model-name internlm2-chat-7b \
                            --cache-max-entry-count 0.1
conda activate agent
cd /root/agent/agentlego/webui
python one_click.py

并在本地进行端口映射(和之前是一样的)。

在 Tool 界面选择 MagicMakerImageGeneration 点击 save 后, Chat 页面选择 MagicMakerImageGeneration 工具后就可以开始使用了。为了确保调用工具的成功率,请在使用时确保仅有这一个工具启用。下图是一个例子。可以看到模型成功地调用了工具并得到了结果。

如图所示:

output
picture

REFERENCE:

  1. https://github.com/InternLM/Tutorial/tree/camp2/agent
  2. https://github.com/InternLM/Tutorial/blob/camp2/agent/lagent.md
  3. https://github.com/InternLM/Tutorial/blob/camp2/agent/agentlego.md
  • 22
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值