6-LAgent & AgentLego 智能体应用搭建
LAgent和AgentLego是书生·浦语的智能体框架,本次实践搭建智能体框架并实践相应插件场景。
为什么要有智能体以及什么是智能体
LLM存在一定的局限性,包括:
- 幻觉:模型因为训练数据的不能全覆盖性,导致模型可能会生成虚拟信息
- 时效性:用于模型训练的数据过时了,无法反馈最新的趋势和信息等。
- 可靠性:当模型遇到复杂任务式,可能出现错误输出,无法被信任
智能体定义
智能体能够感知环境中的动态条件,进而能采取动作影响环境,同时能够运用推理能力理解信息、解决问题、生成推断、决定的动作。
智能体的范式:AutoGPT、ReWoo、ReAct
Lagent和LAgentLego
Lagent 是一个轻量级开源智能体框架,旨在让用户可以高效地构建基于大语言模型的智能体。同时它也提供了一些典型工具以增强大语言模型的能力。
Lagent 目前已经支持了包括 AutoGPT、ReAct 等在内的多个经典智能体范式,也支持了如下工具:
- Arxiv 搜索
- Bing 地图
- Google 学术搜索
- Google 搜索
- 交互式 IPython 解释器
- IPython 解释器
- PPT
- Python 解释器
AgentLego 是一个提供了多种开源工具 API 的多模态工具包,旨在像是乐高积木一样,让用户可以快速简便地拓展自定义工具,从而组装出自己的智能体。通过 AgentLego 算法库,不仅可以直接使用多种工具,也可以利用这些工具,在相关智能体框架(如 Lagent,Transformers Agent 等)的帮助下,快速构建可以增强大语言模型能力的智能体。
AgentLego 目前提供了如下工具:
LAgent和AgentLego关系
实践
仍然是在internstudio上实践,使用50% A100
https://studio.intern-ai.org.cn/console/instance
创建虚拟环境
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
本次实践使用lmdeploy来部署LLM,所以要安装lmdeploy
pip install lmdeploy==0.3.0
下载教程
cd /root/agent
git clone -b camp2 https://gitee.com/internlm/Tutorial.git
实践1-运行Lagent
部署llm,启动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
启动WEB-ui
conda activate agent
cd /root/agent/lagent/examples
streamlit run internlm2_agent_web_demo.py --server.address 127.0.0.1 --server.port 7860
打开本地的cmd,做下端口映射,具体的-p参数根据实际调整
访问WEB
模型IP设置成127.0.0.1:23333,插件选择ArxivSearch
对话提问
实践2-自定义LAgent工具
API key准备
这里我们使用天气查询API,为了获得稳定的天气查询服务,我们首先要获取 API KEY。首先注册用户,打开 https://dev.qweather.com/docs/api/ 后,点击右上角控制台,进入控制台,在项目管理中创建项目;然后查看并复制KEY,备用。
自定义工具准备
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()
启动api
如果实践的API没停止,请先停止
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
启动web-ui
# 设置API key环境变量,取值为前面获取到的
export WEATHER_API_KEY=XX
# 比如 export WEATHER_API_KEY=xxcg
conda activate agent
cd /root/agent/Tutorial/agent
streamlit run internlm2_weather_web_demo.py --server.address 127.0.0.1 --server.port 7860
web-ui访问
可以利用前面的端口映射通道来访问:
其中的插件选择weatherquery
实践3-AgentLego
下载demo数据
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
脚本准备
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)
命令执行
python /root/agent/direct_use.py
目标检测结果
实践4-作为智能体运行
修改使用的模型
由于 AgentLego 算法库默认使用 InternLM2-Chat-20B 模型,因此我们首先需要修改 /root/agent/agentlego/webui/modules/agents/lagent_agent.py 文件的第 105行位置,将 internlm2-chat-20b 修改为 internlm2-chat-7b,即
启动API
使用lmdeploy来部署7b模型
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
### 启动web-ui
另外开一个终端,执行如下启动,执行的时候会先安装一些组件,会发现运行会报错,缺少langchain_community组件
conda activate agent
cd /root/agent/agentlego/webui
python one_click.py
执行
pip install -U langchain-community
后,再运行启动脚本,正常运行:
### 访问WEB-UI并配置agent
使用之前实验建立的端口映射通道访问web-ui
保存后,点击load后,如下:
save后如下:
对话
点击chat页签,选择tools为ObjectDectection ,点击右下角文件夹以上传图片,上传图片后输入指令并点击 generate 以得到模型回复。模型成功地调用了工具,并详细地告诉了我们图中的内容。
实践5-自定义AgentLego工具
准备工具脚本
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)
注册工具
vi /root/agent/agentlego/agentlego/tools/init.py,增加如下红框的内容:
运行模型
运行前,确保前面实验的模型运行已经停止,可以杀掉,或者直接复用也可。
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
运行WEB-UI
conda activate agent
cd /root/agent/agentlego/webui
python one_click.py
访问和设置WEB-UI
使用前面实验的端口映射通道来访问WEB-UI,其中agent使用前面设置的即可。
TOOLS选择MagicMakerImageGeneration:
和模型对话
同样在chat页签选择MagicMakerImageGeneration 工具后,输入“请生成一副山水画”等命令,模型将生成图。
结语
通过本次实验,熟悉了lagent和agentlego的使用和自定义工具功能,进一步体会了书生·浦语工具链的强大。