简介:Lagent&AgentLego

Lagent 是什么

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

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

  • Arxiv 搜索

  • Bing 地图

  • Google 学术搜索

  • Google 搜索

  • 交互式 IPython 解释器

  • IPython 解释器

  • PPT

  • Python 解释器

AgentLego 是什么

AgentLego 是一个提供了多种开源工具 API 的多模态工具包,旨在像是乐高积木一样,让用户可以快速简便地拓展自定义工具,从而组装出自己的智能体。通过 AgentLego 算法库,不仅可以直接使用多种工具,也可以利用这些工具,在相关智能体框架(如 Lagent,Transformers Agent 等)的帮助下,快速构建可以增强大语言模型能力的智能体。

AgentLego 目前提供了如下工具:

通用能力

语音相关

图像处理

AIGC

计算器谷歌搜索

文本 -> 音频(TTS)音频 -> 文本(STT)

描述输入图像识别文本(OCR)视觉问答(VQA)人体姿态估计人脸关键点检测图像边缘提取(Canny)深度图生成生成涂鸦(Scribble)检测全部目标检测给定目标SAM分割一切分割给定目标

文生图图像拓展删除给定对象替换给定对象根据指令修改ControlNet 系列根据边缘+描述生成根据深度图+描述生成根据姿态+描述生成根据涂鸦+描述生成ImageBind 系列音频生成图像热成像生成图像音频+图像生成图像音频+文本生成图像

两者的关系

经过上面的介绍,我们可以发现,Lagent 是一个智能体框架,而 AgentLego 与大模型智能体并不直接相关,而是作为工具包,在相关智能体的功能支持模块发挥作用。

两者之间的关系可以用下图来表示:

flowchart LR subgraph Lagent tool[调用工具] subgraph AgentLego tool_support[工具功能支持] end tool_output(工具输出) tool --> tool_support --> tool_output end input(输入) --> LLM[大语言模型] LLM --> IF{是否需要调用工具} IF -->|否| output(一般输出) IF -->|是| tool tool_output -->|处理| agent_output(智能体输出)

一、Lagent:轻量级智能体框架

1. Lagent Web Demo

1.1 使用 LMDeploy 部署

由于 Lagent 的 Web Demo 需要用到 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

1.2 启动并使用 Lagent Web Demo

然后新建一个 terminal 以启动 Lagent Web Demo。在新建的 terminal 中执行如下指令:

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

LMDeploy api_server

Lagent Web Demo

image-20240424132513630

image-20240424132526447

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

image-20240424132629597

我们输入“请帮我搜索 InternLM2 Technical Report” 以让模型搜索书生·浦语2的技术报告。效果如下图所示:

image-20240424132819773

可以看到模型正确输出了 InternLM2 技术报告的相关信息。尽管还输出了其他论文,但这是由 arxiv 搜索 API 的相关行为导致的。

2. 用 Lagent 自定义工具

我们要实现一个调用和风天气 API 的工具以完成实时天气查询的功能,Lagent 中关于工具部分的介绍文档位于 https://lagent.readthedocs.io/zh-cn/latest/tutorials/action.html ,使用 Lagent 自定义工具主要分为以下几步:

  1. 继承 BaseAction 类

  2. 实现简单工具的 run 方法;或者实现工具包内每个子工具的功能

  3. 简单工具的 run 方法可选被 tool_api 装饰;工具包内每个子工具的功能都需要被 tool_api 装饰

2.1 创建工具文件

首先通过 touch /root/agent/lagent/lagent/actions/weather.py(大小写敏感)新建工具文件,该文件内容如下:

import json
import os
import requests
from typing import Optional, Type
​
from lagent.actions.base_action import BaseAction, tool_api
from lagent.actions.parser import BaseParser, JsonParser
from lagent.schema import ActionReturn, ActionStatusCode
​
class WeatherQuery(BaseAction):
    """Weather plugin for querying weather information."""
    
    def __init__(self,
                 key: Optional[str] = None,
                 description: Optional[dict] = None,
                 parser: Type[BaseParser] = JsonParser,
                 enable: bool = True) -> None:
        super().__init__(description, parser, enable)
        key = os.environ.get('WEATHER_API_KEY', key)
        if key is None:
            raise ValueError(
                'Please set Weather API key either in the environment '
                'as WEATHER_API_KEY or pass it as `key`')
        self.key = key
        self.location_query_url = 'https://geoapi.qweather.com/v2/city/lookup'
        self.weather_query_url = 'https://devapi.qweather.com/v7/weather/now'
​
    @tool_api
    def run(self, query: str) -> ActionReturn:
        """一个天气查询API。可以根据城市名查询天气信息。
        
        Args:
            query (:class:`str`): The city name to query.
        """
        tool_return = ActionReturn(type=self.name)
        status_code, response = self._search(query)
        if status_code == -1:
            tool_return.errmsg = response
            tool_return.state = ActionStatusCode.HTTP_ERROR
        elif status_code == 200:
            parsed_res = self._parse_results(response)
            tool_return.result = [dict(type='text', content=str(parsed_res))]
            tool_return.state = ActionStatusCode.SUCCESS
        else:
            tool_return.errmsg = str(status_code)
            tool_return.state = ActionStatusCode.API_ERROR
        return tool_return
    
    def _parse_results(self, results: dict) -> str:
        """Parse the weather results from QWeather API.
        
        Args:
            results (dict): The weather content from QWeather API
                in json format.
        
        Returns:
            str: The parsed weather results.
        """
        now = results['now']
        data = [
            f'数据观测时间: {now["obsTime"]}',
            f'温度: {now["temp"]}°C',
            f'体感温度: {now["feelsLike"]}°C',
            f'天气: {now["text"]}',
            f'风向: {now["windDir"]},角度为 {now["wind360"]}°',
            f'风力等级: {now["windScale"]},风速为 {now["windSpeed"]} km/h',
            f'相对湿度: {now["humidity"]}',
            f'当前小时累计降水量: {now["precip"]} mm',
            f'大气压强: {now["pressure"]} 百帕',
            f'能见度: {now["vis"]} km',
        ]
        return '\n'.join(data)
​
    def _search(self, query: str):
        # get city_code
        try:
            city_code_response = requests.get(
                self.location_query_url,
                params={'key': self.key, 'location': query}
            )
        except Exception as e:
            return -1, str(e)
        if city_code_response.status_code != 200:
            return city_code_response.status_code, city_code_response.json()
        city_code_response = city_code_response.json()
        if len(city_code_response['location']) == 0:
            return -1, '未查询到城市'
        city_code = city_code_response['location'][0]['id']
        # get weather
        try:
            weather_response = requests.get(
                self.weather_query_url,
                params={'key': self.key, 'location': city_code}
            )
        except Exception as e:
            return -1, str(e)
        return weather_response.status_code, weather_response.json()

2.2 体验自定义工具效果

当我们根据课程步骤获取完api以后,我们在两个 terminal 中分别启动 LMDeploy 服务和 Tutorial 已经写好的用于这部分的 Web Demo:

  • 终端1

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
  • 终端2

export WEATHER_API_KEY=获取的API KEY
# 比如 export WEATHER_API_KEY=1234567890abcdef
conda activate agent
cd /root/agent/Tutorial/agent
streamlit run internlm2_weather_web_demo.py --server.address 127.0.0.1 --server.port 7860

下面是运行结果:

image-20240424134127350

二、AgentLego:组装智能体“乐高”

1. 直接使用 AgentLego

完成环境创建以后,在 /root/agent 目录下新建 direct_use.py 以直接使用目标检测工具,代码如下:

import re
​
import cv2
from agentlego.apis import load_tool
​
# load tool
tool = load_tool('ObjectDetection', device='cuda')
​
# apply tool
visualization = tool('/root/agent/road.jpg')
print(visualization)
​
# visualize
image = cv2.imread('/root/agent/road.jpg')
​
preds = visualization.split('\n')
pattern = r'(\w+) \((\d+), (\d+), (\d+), (\d+)\), score (\d+)'
​
for pred in preds:
    name, x1, y1, x2, y2, score = re.match(pattern, pred).groups()
    x1, y1, x2, y2, score = int(x1), int(y1), int(x2), int(y2), int(score)
    cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 1)
    cv2.putText(image, f'{name} {score}', (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 1)
​
cv2.imwrite('/root/agent/road_detection_direct.jpg', image)

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

原图

结果

image-20240424135457630

image-20240424135441347

2. 作为智能体工具使用

当完成文件修改以后,进行下一步,由于 AgentLego 的 WebUI 的启动和Lagent一样都需要使用 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

接下来我们新建一个 terminal 用来启动 AgentLego WebUI,命令如下:

conda activate agent
cd /root/agent/agentlego/webui
python one_click.py

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

image-20240424140910155

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

image-20240424141124169

等待工具加载完成后,点击上方 Chat 以进入对话页面。在页面下方选择工具部分只选择 ObjectDetection 工具,如下图所示。为了确保调用工具的成功率,请在使用时确保仅有这一个工具启用。

image-20240424141325818

然后上传图片进行识别:

image-20240424141537953

3. 用 AgentLego 自定义工具

下面我们要实现一个调用 MagicMaker 的 API 以实现图像生成的工具。

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

AgentLego 自定义工具文档地址为 https://agentlego.readthedocs.io/zh-cn/latest/modules/tool.html 。自定义工具主要分为以下几步:

  1. 继承 BaseTool 类

  2. 修改 default_desc 属性(工具功能描述)

  3. 如有需要,重载 setup 方法(重型模块延迟加载)

  4. 重载 apply 方法(工具功能实现)

其中第一二四步是必须的步骤。

首先创建/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)

接下来修改 /root/agent/agentlego/agentlego/tools/__init__.py 文件,将我们的工具注册在工具列表中。如下所示:

# 19行
+ from .magicmaker_image_generation import MagicMakerImageGeneration
# 29行
-     'BaseTool', 'make_tool', 'BingSearch'
+     'BaseTool', 'make_tool', 'BingSearch', 'MagicMakerImageGeneration'

然后还是和前面的命令一样,启动两个终端运行不同的命令,启动完成以后在 Tool 界面选择 MagicMakerImageGeneration 后点击 save 后,回到 Chat 页面选择 MagicMakerImageGeneration 工具后就可以开始使用了,使用效果如下:

image-20240424143658840

同时你还可以修改MagicMakerImageGeneration类,来调整图片风格和大小。

image-20240424144703729

image-20240424144811055