书生大模型实战营(第三期闯关大挑战)- 进阶岛 第二关 Lagent 自定义你的 Agent 智能体

1.Lagent 介绍

Lagent 是一个轻量级开源智能体框架,旨在让用户可以高效地构建基于大语言模型的智能体。同时它也提供了一些典型工具以增强大语言模型的能力。

Lagent 目前已经支持了包括 AutoGPT、ReAct 等在内的多个经典智能体范式,也支持了如下工具:

  • Arxiv 搜索
  • Bing 地图
  • Google 学术搜索
  • Google 搜索
  • 交互式 IPython 解释器
  • IPython 解释器
  • PPT
  • Python 解释器

其基本结构如下所示:

image-20240819155734605

2.环境配置

创建开发机和 conda 环境

开发机选择 30% A100,镜像选择为 Cuda12.2-conda。

image-20240819160322747

开发机创建完成后点击“进入开发机”

image-20240819160610982

3.环境安装

# 创建环境
conda create -n lagent python=3.10 -y
# 激活环境
conda activate lagent
# 安装 torch
conda install pytorch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 pytorch-cuda=12.1 -c pytorch -c nvidia -y
# 安装其他依赖包
pip install termcolor==2.4.0 -i  https://pypi.tuna.tsinghua.edu.cn/simple/
pip install lmdeploy==0.5.2 -i  https://pypi.tuna.tsinghua.edu.cn/simple/

接下来,我们通过源码安装的方式安装 lagent。

# 创建目录以存放代码
mkdir -p /root/lagent
cd /root/lagent
git clone https://github.com/InternLM/lagent.git
cd lagent && pip install -e . && cd ..

4.Lagent Web Demo 使用

接下来,我们将使用 Lagent 的 Web Demo 来体验 InternLM2.5-7B-Chat 的智能体能力。

首先,我们先使用 LMDeploy 部署 InternLM2.5-7B-Chat,并启动一个 API Server。

conda activate lagent
lmdeploy serve api_server /share/new_models/Shanghai_AI_Laboratory/internlm2_5-7b-chat --model-name internlm2_5-7b-chat

image-20240819171623254

然后,我们在另一个窗口中启动 Lagent 的 Web Demo。

cd /root/lagent/lagent
conda activate lagent
# 解决griffe 版本过高问题
pip install griffe==0.48
streamlit run examples/internlm2_agent_web_demo.py

image-20240819171640613

当2个服务都启动好了。我们使用本地poweshell 代理访问Web Demo ,使用端口映射

image-20240819165930460

ssh -CNg -L 8501:127.0.0.1:8501 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p 35680

image-20240819171710669

输入密码 后,打开浏览器 输入 http://127.0.0.1:8501/

修改后端模型地址 将10.140.0.220:23333 修改成127.00.1:23333 模型换成 internlm2_5-7b-chat

image-20240819183705167

我们测试一下lagent 自带的ArxivSearch agent智能体

image-20240819183816804

通过以上方式我们将自带的agent智能体 跑起来了。

5.基于 Lagent 自定义智能体

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

  1. 继承 BaseAction
  2. 实现简单工具的 run 方法;或者实现工具包内每个子工具的功能
  3. 简单工具的 run 方法可选被 tool_api 装饰;工具包内每个子工具的功能都需要被 tool_api 装饰

下面我们将实现一个调用 MagicMaker API 以完成文生图的功能。

首先,我们先来创建工具文件:

cd /root/lagent/lagent
touch lagent/actions/magicmaker.py

然后,我们将下面的代码复制进入 /root/lagent/lagent/lagent/actions/magicmaker.py

import json
import requests

from lagent.actions.base_action import BaseAction, tool_api
from lagent.actions.parser import BaseParser, JsonParser
from lagent.schema import ActionReturn, ActionStatusCode


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

    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}')
    
    @tool_api
    def generate_image(self, keywords: str) -> dict:
        """Run magicmaker and get the generated image according to the keywords.

        Args:
            keywords (:class:`str`): the keywords to generate image

        Returns:
            :class:`dict`: the generated image
                * image (str): path to the generated image
        """
        try:
            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'}
            )
        except Exception as exc:
            return ActionReturn(
                errmsg=f'MagicMaker exception: {exc}',
                state=ActionStatusCode.HTTP_ERROR)
        image_url = response.json()['data']['imgUrl']
        return {'image': image_url}

image-20240819184228895

最后,我们修改 /root/lagent/lagent/examples/internlm2_agent_web_demo.py 来适配我们的自定义工具。

  1. from lagent.actions import ActionExecutor, ArxivSearch, IPythonInterpreter 的下一行添加 from lagent.actions.magicmaker import MagicMaker

  2. 在第27行添加 MagicMaker()

    image-20240819184631003

    接下来,启动 Web Demo 来体验一下吧!我们重启

    streamlit run examples/internlm2_agent_web_demo.py
    

    image-20240819184816208

    我们同时启用两个工具,然后输入“请帮我生成一幅山水画”

image-20240819185456361image-20240819185305706

以上就一定自定义新的智能体了,当然如果小伙伴可以根据https://lagent.readthedocs.io/zh-cn/latest/tutorials/action.html 文档制作更多的智能体。

  • 16
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值