学习笔记:书生·浦语实战营第二期第六课

目录

1. 相关视频和文档

2. 视频学习笔记

2.1 智能体相关背景

2.2 Lagent & AgentLego的介绍

3. 课后作业

3.1 体验Lagent 轻量级智能体框架:论文查询功能

3.2 用 Lagent 自定义工具:实时查询天气

3.3 体验AgentLego组装智能体“乐高”:目标检测

3.4 AgentLego作为智能体工具使用(web版目标检测)

3.5 用 AgentLego 自定义工具:图像生成


1. 相关视频和文档

2. 视频学习笔记

2.1 智能体相关背景

为什么要有智能体?

  • 大模型具有局限性:① 幻觉:模型可能会生成虚假信息,与现实不符或脱节;② 时效性:模型训练数据过时,无法反映最新趋势和信息;③ 可靠性:面对复杂任务时,可能频发错误输出现象,影响信任度

什么是智能体?

  • 定义:可以感知环境中的动态条件,能采取动作影响环境,能运用推理能力理解信息、解决问题、产生推断、决定动作
  • 组成部分:① 大脑:作为控制器,承担记忆、思考和决策任务,接受来自感知模块的信息,并采取相应动作;② 感知:对外部环境的多模态信息进行感知和处理,包括但不限于图像、音频、视频、传感器等;③ 动作:利用并执行工具以影响环境,工具可能包括文本的检索、调用相关 API、操控机械臂等
  • 经典范式:AutoGPT,ReWoo,ReAct 
AutoGPTReWooReAct

2.2 Lagent & AgentLego的介绍

Lagent 是一个轻量级开源智能体框架,旨在让用户可以高效地构建基于大语言模型的智能体。支持多种智能体范式,如 AutoGPT,ReWoo,ReAct,也支持多种工具,如谷歌搜索、Python解释器等

AgentLego 是一个多模态工具包,可以像乐高积木一样快速简便地拓展自定义工具,从而组装出自己的智能体,支持多个智能体框架,如Lagent、LangChain、 Transformers Agents,提供大量视觉、多模态领域前沿算法

Lagent 和 AgentLego 的关系?

3. 课后作业

3.1 体验Lagent 轻量级智能体框架:论文查询功能

目标:体验此框架在 arxiv 上搜索论文的能力

3.1.1 创建开发机及配置环境

开发机创建过程可以参考 学习笔记:书生·浦语实战营第二期第二课-CSDN博客 的3.1.1部分,注意本次实验需要30% A100,镜像为 Cuda12.2-conda。进入开发机,在 Terminal 中创建环境(需要时间,耐心等待)

mkdir -p /root/agent
studio-conda -t agent -o pytorch-2.1.2

安装 Lagent 和 AgentLego

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

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

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

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

3.1.3 启动并使用 Lagent Web Demo

新建一个 vscode 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 完全启动后,需要在本地进行端口映射,可参考 学习笔记:书生·浦语实战营第二期第二课-CSDN博客 的3.2.3部分

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

3.1.4 在本地浏览器打开 http://localhost:7860,先输入模型 IP :127.0.0.1:23333,再按下回车键确认,插件选择 ArxivSearch,让模型获得在 arxiv 上搜索论文的能力,测试结果如下:

使用体验:在教程的demo中输入的问题是““请帮我搜索 InternLM2 Technical Report”,模型能较好地给出回答,在本次实验中,笔者输入的问题是“请搜索最新的关于乳腺癌的论文”,模型的回答就有点......一方面会觉得,如果要给出论文名之后,模型才能完成搜索,那和去官网上搜索好像没有太大差别,另一方面是去官网上输入关键词,能自动推荐一系列相关的文章,但是在这个demo中,给了提示范围,模型只给出了如何搜索论文的建议,并不会给出一系列论文并做一些简单介绍

3.2 用 Lagent 自定义工具:实时查询天气

目标:实现调用“和风天气 ”API 的工具以完成实时天气查询的功能

3.2.1 创建开发机及配置环境(已在3.1.1部分完成)

** 注意:确保 3.1 中的 LMDeploy 服务以及 Web Demo 服务已经停止(即 terminal 已关闭),否则在这部分的实验中会出现 CUDA Out of Memory 或是端口已占用的情况

3.2.2 创建weather.py文件,并填入内容

先在 vscode terminal 中执行下面这句代码,创建文件

touch /root/agent/lagent/lagent/actions/weather.py

打开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()

3.2.3 获取 API KEY

为获得稳定的天气查询服务,需要获取 开发文档 | 和风天气开发服务  的API KEY,打开上述链接,点击右上角控制台,然后会提示需要注册,添加邮箱和手机号码等,完成后再按下图步骤操作

创建完成后,点击“返回项目管理”,按下图所示步骤操作

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

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

export WEATHER_API_KEY=获取到的和风天气的key
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 完全启动后,需要在本地进行端口映射(如果3.1部分的端口映射还没关闭,这里可以继续使用),可参考 学习笔记:书生·浦语实战营第二期第二课-CSDN博客 的3.2.3部分

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

3.2.5 在本地浏览器打开 http://localhost:7860,先输入模型 IP :127.0.0.1:23333,输入完成后按下回车键确认,插件选择 WeatherQuery,测试结果如下:

3.3 体验AgentLego组装智能体“乐高”:目标检测

3.3.1 在terminal中输入命令下载相关文件和依赖包(需要时间,耐心等待)

cd /root/agent
wget http://download.openmmlab.com/agentlego/road.jpg
conda activate agent
pip install openmim==0.3.9
mim install mmdet==3.3.0

3.3.2 创建direct_use.py文件,并填入内容

先在 vscode terminal 中执行下面这句代码,创建文件

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)

3.3.3 运行direct_use.py文件

在 vscode terminal 中执行下面的代码,运行文件(需要时间,耐心等待)

conda activate agent
python /root/agent/direct_use.py

推理完成后,就可以看到一张名为 road_detection_direct.jpg 的图片,对比原图与检测结果:

3.4 AgentLego作为智能体工具使用(web版目标检测)

3.4.1 修改相关文件

 AgentLego 算法库默认使用 InternLM2-Chat-20B 模型,本实验需要修改 /root/agent/agentlego/webui/modules/agents/lagent_agent.py 文件的第 105行,将 internlm2-chat-20b 修改为 internlm2-chat-7b 并保存

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

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

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

本地端口映射,可参考 学习笔记:书生·浦语实战营第二期第二课-CSDN博客 的3.2.3部分

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

3.4.3 在本地浏览器打开 http://localhost:7860,先对进行配置,再进行测试

agent 的配置过程(第⑦步完成之后会显示 Successfully loaded Crohcirtep):

tool 的配置过程(第④步完成之后会显示 Loaded ObjectDetection):

配置完成后,点击左上角的“chat”进行测试:

3.5 用 AgentLego 自定义工具:图像生成

3.5.1 创建相关文件,并填入内容(记得关闭3.4的terminal)

先在 vscode terminal 中执行下面这句代码,创建文件

touch /root/agent/agentlego/agentlego/tools/magicmaker_image_generation.py

打开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.5.2 修改 /root/agent/agentlego/agentlego/tools/__init__.py 文件并保存

3.5.3 使用LMDeploy部署 (与3.4.2的步骤一致,故此处不再赘述)

3.5.4  在本地浏览器打开 http://localhost:7860,先对进行配置,再进行测试

agent 的配置过程可参考3.4.3部分,也可直接选择3.4部分创建的agent,创建完成之后点击load

tool 的配置过程(第④步完成之后会显示 Loaded MagicMakerImageGeneration):

配置完成后,点击左上角的“chat”进行测试:

  • 46
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值