本关用lagent创建智能体,使用的框架为lagent。
当前lagent使用AgentLego作为工具集
1.1 Lagent 是什么
Lagent 是一个轻量级开源智能体框架,旨在让用户可以高效地构建基于大语言模型的智能体。同时它也提供了一些典型工具以增强大语言模型的能力。
Lagent 目前已经支持了包括 AutoGPT、ReAct 等在内的多个经典智能体范式,也支持了如下工具:
- Arxiv 搜索
- Bing 地图
- Google 学术搜索
- Google 搜索
- 交互式 IPython 解释器
- IPython 解释器
- PPT
- Python 解释器
1.2 AgentLego 是什么
AgentLego 是一个提供了多种开源工具 API 的多模态工具包,旨在像是乐高积木一样,让用户可以快速简便地拓展自定义工具,从而组装出自己的智能体。通过 AgentLego 算法库,不仅可以直接使用多种工具,也可以利用这些工具,在相关智能体框架(如 Lagent,Transformers Agent 等)的帮助下,快速构建可以增强大语言模型能力的智能体。
AgentLego 目前提供了如下工具:
通用能力 | 语音相关 | 图像处理 | AIGC |
计算器 谷歌搜索 | 文本 -> 音频(TTS) 音频 -> 文本(STT) | 描述输入图像 识别文本(OCR) 视觉问答(VQA) 人体姿态估计 人脸关键点检测 图像边缘提取(Canny)深度图生成 生成涂鸦(Scribble) 检测全部目标 检测给定目标 SAM 分割一切 分割给定目标 | 文生图 图像拓展 删除给定对象 替换给定对象 根据指令修改 ControlNet 系列 根据边缘+描述生成 根据深度图+描述生成 根据姿态+描述生成 根据涂鸦+描述生成 ImageBind 系列 音频生成图像 热成像生成图像 音频+图像生成图像 音频+文本生成图像 |
经过上面的介绍,我们可以发现,Lagent 是一个智能体框架,而 AgentLego 与大模型智能体并不直接相关,而是作为工具包,在相关智能体的功能支持模块发挥作用。
两者之间的关系可以用下图来表示:
环境配置
首先环境配置上我们需要新建agent目录并配置conda环境(这里我已经配置成功了)
mkdir -p /root/agent studio-conda -t agent -o pytorch-2.1.2 # 非internstudio环境下使用以下代码 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和lagentlego
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 ..
安装其他依赖
在这一步中,我们将会安装其他将要用到的依赖库,如 LMDeploy,可以执行如下命令:
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自定义工具
touch /root/agent/lagent/lagent/actions/weather.py
首先通过命令创建工具文件,这里我以天气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中获取对应的api_key
在/root/agent/Tutorial/agent/internlm2_weather_web_demo.py下修改代码,将ArxivSearch传入工具列表即可。
然后用两个终端分别启动Web_Demo和LMDeploy两个服务。
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=在2.2节获取的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 端口号
最后登录本地地址即可使用自己定制的agent了