Lagent & AgentLego 智能体应用搭建实战笔记

概述

为什么要有智能体

大语言模型的局限性:

  • 幻觉:模型可能会生成虚假信息,与现实严重不符或脱节。
  • 时效性:模型训练数据过时无法反映最新趋势和信息。

什么是智能体

  • 可以感知环境中的动态条件。(perception of dynamic conditions in the environment)
  • 能采取动作影响环境。(action to affect conditions in the environment)
  • 能运用推理能力理解信息、解决问题、产生推断、决定动作(reasoning to interpret perceptions, solve problems,draw inferences, and determine actions)
    -----Hayes-Roth 1995
    An Architecture for Adaptive Intelligent Systems

智能体组成

  • 大脑:作为控制器,承担记忆、思考和决策任务。接受来自感知模块的信息,并采取相应动作。
  • 感知:对外部环境的多模态信息进行感知和处理。包括但不限于图像、音频、视频、传感器等。
  • 动作:利用并执行工具以影响环境。工具可能包括文本的检索、调用相关 API、操控机械臂等。

智能体范式

在这里插入图片描述
下面三个图片分别展示了具体信息:在这里插入图片描述在这里插入图片描述
在这里插入图片描述

Lagent 是什么

Lagent 是一个轻量级开源智能体框架,旨在让用户可以高效地构建基于大语言模型的智能体。同时它也提供了一些典型工具以增强大语言模型的能力。
Lagent 目前已经支持了包括 AutoGPT、ReAct 等在内的多个经典智能体范式,也支持了如下工具:

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

AgentLego 是什么

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

两者的关系

经过上面的介绍,我们可以发现,Lagent 是一个智能体框架,而 AgentLego 与大模型智能体并不直接相关,而是作为工具包,在相关智能体的功能支持模块发挥作用。
两者之间的关系可以用下图来表示:
在这里插入图片描述

环境配置

创建开发机和 conda 环境

在创建开发机界面选择镜像为 Cuda12.2-conda,并选择 GPU 为30% A100。进入开发机后,为了方便使用,需要配置一个环境以同时满足 Lagent 和 AgentLego 运行时所需依赖。在开始配置环境前,先创建一个用于存放 Agent 相关文件的目录,可以执行如下命令:

mkdir -p /root/agent

接下来,开始配置 conda 环境,可以输入如下指令:

studio-conda -t agent -o pytorch-2.1.2

这样配置环境速度会很慢,所以采取下面的方式速度会快不少。

conda create -n agent
conda activate agent
conda install python=3.10
conda install pytorch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 pytorch-cuda=11.8 -c pytorch -c nvidia

安装 Lagent 和 AgentLego

Lagent 和 AgentLego 都提供了两种安装方法,一种是通过 pip 直接进行安装,另一种则是从源码进行安装。为了方便使用 Lagent 的 Web Demo 以及 AgentLego 的 WebUI,直接从源码进行安装。 可以执行如下命令进行安装:

cd /root/agent
conda activate agent
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 ..

安装其他依赖

在这一步中,我们将会安装其他将要用到的依赖库,如 LMDeploy,可以执行如下命令:

conda activate agent
pip install lmdeploy==0.3.0

准备 Tutorial

由于后续的 Demo 需要用到 tutorial 已经写好的脚本,因此我们需要将 tutorial 通过 git clone 的方法准备好,以备后续使用:

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

Lagent:轻量级智能体框架

Lagent Web Demo

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

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

在这里插入图片描述

启动并使用 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 完全启动后(如下图所示),在本地进行端口映射,将 LMDeploy api_server 的23333端口以及 Lagent Web Demo 的7860端口映射到本地。vscode的ports块添加这两个端口即可映射到本地。
在这里插入图片描述接下来在本地的浏览器页面中打开 http://localhost:7860 以使用 Lagent Web Demo。首先输入模型 IP 为 127.0.0.1:23333,在输入完成后按下回车键以确认。下图是没有选择插件的情况:
在这里插入图片描述
选择插件为 ArxivSearch,以让模型获得在 arxiv 上搜索论文的能力。如下图所示:
在这里插入图片描述

Lagent 自定义工具

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

创建工具文件

首先通过 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()

获取 API KEY

为了获得稳定的天气查询服务,我们首先要获取 API KEY。首先打开 https://dev.qweather.com/docs/api/ 后。进入控制台,点击左侧项目管理,然后点击右上角创建项目以创建新项目。(如下图所示)。(如下图所示)
在这里插入图片描述
输入相关项目名称,选择免费订阅,Web API 以及输入 key 的名称。(项目名称和 key 的名词自由输入即可,如下图所示)
在这里插入图片描述
在这里插入图片描述
接下来回到项目管理页面,查看我们刚刚创建的 key,以供后续使用。
在这里插入图片描述

体验自定义工具效果

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

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
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

在输入模型地址并选择好工具后,就可以开始体验了。下图是一个例子:
在这里插入图片描述

AgentLego:组装智能体“乐高”

直接使用 AgentLego

首先下载 demo 文件:

cd /root/agent
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

在安装完成后,可能会观察到以下现象(如下图所示),但请放心,这是正常现象。
在这里插入图片描述
然后通过 touch /root/agent/direct_use.py(大小写敏感)的方式在 /root/agent 目录下新建 direct_use.py 以直接使用目标检测工具,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 的图片:
在这里插入图片描述
最终检测的效果图如下:
在这里插入图片描述

作为智能体工具使用

修改相关文件

由于 AgentLego 算法库默认使用 InternLM2-Chat-20B 模型,因此我们首先需要修改 /root/agent/agentlego/webui/modules/agents/lagent_agent.py 文件的第 105行位置,将 internlm2-chat-20b 修改为 internlm2-chat-7b,即
在这里插入图片描述

使用 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

在这里插入图片描述

启动 AgentLego WebUI

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

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

会出现这个问题,此时按照提示安装即可。
在这里插入图片描述
安装后继续运行命令。
在这里插入图片描述

使用 AgentLego WebUI

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

  • 点击上方 Agent 进入 Agent 配置页面。(如1所示)
  • 点击 Agent 下方框,选择 New Agent。(如2所示)
  • 选择 Agent Class 为 lagent.InternLM2Agent。(如3所示)
  • 输入模型 URL 为 http://127.0.0.1:23333 。(如4所示)
  • 输入 Agent name,自定义即可,图中输入了 internlm2。(如5所示)
  • 点击 save to 以保存配置,这样在下次使用时只需在第2步时选择 Agent 为 internlm2 后点击 load以加载就可以了。(如6所示)
  • 点击 load 以加载配置。(如7所示)

配置工具

如下图所示:
在这里插入图片描述
点击上方 Tools 页面进入工具配置页面。(如1所示)
点击 Tools 下方框,选择 New Tool 以加载新工具。(如2所示)
选择 Tool Class 为 ObjectDetection。(如3所示)
点击 save 以保存配置。(如4所示)
等待工具加载完成后,点击上方 Chat 以进入对话页面。在页面下方选择工具部分只选择 ObjectDetection 工具,为了确保调用工具的成功率,请在使用时确保仅有这一个工具启用。接下来就可以愉快地使用 Agent 了。点击右下角文件夹以上传图片,上传图片后输入指令并点击 generate 以得到模型回复。如下图所示,我们上传了 demo 图片,模型成功地调用了工具,并详细地告诉了我们图中的内容。
在这里插入图片描述

AgentLego 自定义工具

创建工具文件

首先通过 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)

注册新工具

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

自定义工具效果

在两个 terminal 中分别启动 LMDeploy 服务和 AgentLego 的 WebUI 以体验自定义的工具的效果。

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 工具后就可以开始使用了。为了确保调用工具的成功率,请在使用时确保仅有这一个工具启用。下图是一个例子。可以看到模型成功地调用了工具并得到了结果。
在这里插入图片描述
本次实验参考这个教程,有兴趣者可前往深入研究。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值