Lagent & AgentLego 智能体应用搭建 第六课实战

目录

笔记部分

1. 为什么要有智能体

2. 什么是智能体

3. 智能体组成

4. 智能体范式

5. Lagent & AgentLego

6. 实战应用(见下面部分)

实战 -- 基础作业

一、环境配置:

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

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

实战 -- 进阶作业

一、完成AgentLego WebUI使用,上传截图

二、使用Lagent或AgentLego实现自定义工具并完成调用,上传截图


笔记部分

1. 为什么要有智能体

大语言模型的局限性包括:

  • 生成虚假信息:模型可能生成与现实不符的信息。

  • 数据过时:模型训练数据可能无法反映最新趋势和信息。

  • 复杂任务错误:面对复杂任务时,可能频发错误输出,影响信任度。

2. 什么是智能体

智能体具备以下特性:

  • 感知:能够感知环境中的动态条件。

  • 动作:能采取动作影响环境。

  • 推理:运用推理能力理解信息、解决问题、产生推断、决定动作。

3. 智能体组成

智能体由三个主要部分组成:

  • 大脑:作为控制器,负责记忆、思考和决策,接受感知模块的信息并采取相应动作。

  • 感知:感知和处理外部环境的多模态信息,如图像、音频、视频、传感器等。

  • 动作:利用工具执行动作以影响环境,工具包括文本检索、调用API、操控机械臂等。

4. 智能体范式

智能体的工作流程主要分为以下几种范式:

  • ReAct:输入→选择工具→执行工具→检查结束条件→结束
  • ReWoo:输入→计划拆分→执行计划(DAG)→检查结束条件→结束
  • AutoGPT:输入→选择工具→人工干预→执行工具→检查结束条件→结束

5. Lagent & AgentLego

  • Lagent:一个轻量级开源智能体框架,旨在高效构建基于大语言模型的智能体。支持多种智能体范式和工具(如谷歌搜索、Python解释器等)。Lagent 目前已经支持了包括 AutoGPT、ReAct 等在内的多个经典智能体范式,也支持如下工具:

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

  • AgentLego:一个提供了多种开源工具 API 的多模态工具包,旨在像乐高积木一样,可以快速简便地拓展自定义工具,支持多个智能体框架(如Lagent、LangChain、Transformers Agents),并提供大量视觉和多模态领域的前沿算法。

目前AgentLego提供了如下工具

能力语音相关图像处理AIGC
  • 计算器
  • 谷歌搜索
  • 文本 -> 音频(TTS)
  • 音频 -> 文本(STT)
  • 描述输入图像
  • 识别文本(OCR)
  • 视觉问答(VQA)
  • 人体姿态估计
  • 人脸关键点检测
  • 图像边缘提取(Canny)
  • 深度图生成
  • 生成涂鸦(Scribble)
  • 检测全部目标
  • 检测给定目标
  • SAM
    • 分割一切
    • 分割给定目标
  • 文生图
  • 图像拓展
  • 删除给定对象
  • 替换给定对象
  • 根据指令修改
  • ControlNet 系列
    • 根据边缘+描述生成
    • 根据深度图+描述生成
    • 根据姿态+描述生成
    • 根据涂鸦+描述生成
  • ImageBind 系列
    • 音频生成图像
    • 热成像生成图像
    • 音频+图像生成图像
    • 音频+文本生成图像

Lagent 和 AgentLego的关系

Lagent 是一个智能体框架,而 AgentLego 与大模型智能体并不直接相关,而是作为工具包,在相关智能体的功能支持模块发挥作用。

6. 实战应用(见下面部分)

  • 实战一:Lagent 轻量级智能体框架
    • 搭建智能体框架,实践如何利用Lagent进行智能体构建。
  • 实战二:AgentLego 组装智能体“乐高”
    • 使用AgentLego工具包,组装并扩展自定义工具,创建适合特定任务的智能体。

通过这些模块和工具,用户能高效构建和管理智能体应用,实现复杂任务的自动化和智能化处理。

实战 -- 基础作业

一、环境配置:

1、InternStudio创建开发机、conda环境

创建开发机界面选择镜像为 Cuda12.2-conda,并选择 GPU 为30% A100。

配置一个同时满足 Lagent 和 AgentLego 运行时所需依赖的环境:

  • 创建存放agent文件的目录:mkdir -p /root/agent
  • 配置conda环境:studio-conda -t agent -o pytorch-2.1.2

初始化环境成功↓

2、安装Lagent和AgentLego

两种安装方法:通过 pip 直接进行安装、从源码进行安装。

为了方便使用 Lagent 的 Web Demo 以及 AgentLego 的 WebUI,我们选择直接从源码进行安装。

源码安装的相关帮助文档:

Lagent:https://lagent.readthedocs.io/zh-cn/latest/get_started/install.html

AgentLego:https://agentlego.readthedocs.io/zh-cn/latest/get_started.html

安装命令:

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

3、安装其他依赖

安装LMDeploy:

conda activate agent
pip install lmdeploy==0.3.0

4、准备Tutorial

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

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

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

体验Lagent的Web Demo,使用Lagent自定义工具,并体验自定义工具的效果

详细文档见:Tutorial/agent/lagent.md at camp2 · InternLM/Tutorial · GitHub

1.Lagent Web Demo

1.1使用LMDeploy部署

在 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,输入并执行:

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端口映射到本地
ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p 你的 ssh 端口号

LMDeploy api_server

Lagent Web Demo 

接着在本地浏览器打开 http://localhost:7860 以使用 Lagent Web Demo。

首先输入模型 IP 为 127.0.0.1:23333,输入完成后回车键确认。

选择插件ArxivSearch,以让模型获得在 arxiv 上搜索论文的能力。

输入“请帮我搜索 InternLM2 Technical Report” 以让模型搜索书生·浦语2的技术报告

2.用Lagent自定义工具(见后面的进阶作业部分)

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

直接使用AgentLego工具,体验AgentLego的WebUI,以及基于AgentLego自定义工具并体验自定义工具的效果

详细文档见:Tutorial/agent/agentlego.md at camp2 · InternLM/Tutorial · GitHub

AgentLego 算法库既可以直接使用,也可以作为智能体工具使用。下面将分别介绍这两种使用方式。我们将以目标检测工具为例。

环境配置请见前面的“环境配置”部分

1、直接使用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

新建direct_use.py来直接使用目标检测工具:touch /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)

接下来执行direct_use.py文件来进行推理:python /root/agent/direct_use.py

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

2、作为智能体工具使用(详见下面的进阶作业一)

3、用AgentLego自定义工具

3.1 创建工具文件

3.2 注册新工具

3.3 体验自定义工具效果

四、Agent 工具能力微调

介绍OpenAI Function Calling的相关内容,使用XTuner来实现Agent工具能力的微调。

详细文档见:Tutorial/agent/finetune.md at camp2 · InternLM/Tutorial · GitHub

实战 -- 进阶作业

一、完成AgentLego WebUI使用,上传截图

详细文档见:Tutorial/agent/agentlego.md at camp2 · InternLM/Tutorial · GitHub

 2.1 修改相关文件

由于 AgentLego 算法库默认使用 InternLM2-Chat-20B 模型,需要修改为7B模型,具体如下:

修改 /root/agent/agentlego/webui/modules/agents/lagent_agent.py 文件的第 105行位置,将model_name 从 internlm2-chat-20b 修改为 internlm2-chat-7b,修改完保存。

2.2 使用LMDeploy部署

AgentLego 的 WebUI 需要用到 LMDeploy 所启动的 api_server。

使用LMDeploy启动一个api_server,首先在 vscode 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

2.3 启动AgentLego WebUI

新建一个 terminal 2以启动 AgentLego WebUI,执行如下指令

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

等待 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 端口号

2.4 使用AgentLego WebUI(见)

接下来在本地的浏览器页面中打开 http://localhost:7860 ,来使用 AgentLego WebUI

1、首先配置Agent:

进入Agent配置页面 → New Agent → Agent Class 选择lagent.InternLM2Agent,模型URL为 http://127.0.0.1:23333 ,输入自定义 Agent name → 点击 save to 保存配置 → 点击load加载配置

2、然后配置工具:

点击上方Tools进入工具配置页面 → 选New Tool加载新工具 → Tool Class 选择 ObjectDetection → 点击save保存配置。

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

接下来就可以使用Agent啦~

点击右下角文件夹以上传图片,然后输入指令“请检测图中的物体”,点击generate得到模型回复。模型成功地调用了工具,并详细地告诉了我们图中的内容(截图如下)

二、使用Lagent或AgentLego实现自定义工具并完成调用,上传截图

文档可见:Tutorial/agent/lagent.md at camp2 · InternLM/Tutorial · GitHub

或可见:Tutorial/agent/agentlego.md at camp2 · InternLM/Tutorial · GitHub

选择了基于 Lagent 自定义一个工具:

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

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

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

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

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、获取 API KEY (和风天气)

打开https://dev.qweather.com/docs/api/ ,进入控制台 → 项目管理 → 创建项目(输入项目名称,选择免费订阅、Web API,输入KEY的名称) → 创建好后查看和复制KEY

3、体验自定义工具效果

前提:需确保之前的LMDeploy服务、Web Demo服务已经停止,否则会出现 CUDA Out of Memory 或者端口已占用的情况。

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

terminal 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

terminal 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

本地端口映射操作:

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

全部OK后,打开http://127.0.0.1:7860/,输入模型地址127.0.0.1:23333,选择好工具WeatherQuery,即可开始啦~ (截图如下)

作业要求:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值