作业
- 完成 Lagent Web Demo 使用
- 完成 Lagent 自定义工具效果
- 完成 AgentLego 图片识别
- 完成 AgentLego WebUI
- AgentLego 实现自定义工具并完成调用
目标
搭建智能体Lagent与AgentLego工具并使用
一、什么是智能体
大脑:作为控制器,承担记忆、思考和决策任务。接受来自感知模块的信息,并采取相应动作。
感知:对外部环境的多模态信息进行感知和处理。包括但不限于图像、音频、视频、传感器等。
动作:利用并执行工具以影响环境。工具可能包括文本的检索、调用相关 API、操控机械臂等。
二、Lagent
一个轻量级开源智能体框架,旨在让用户可以高效地构建基于大语言模型的智能体。
支持多种智能体范式。(如 AutoGPT.ReWoo、ReAct)
支持多种工具。(如谷歌搜索、Python解释器等)
三、AgentLego
一个多模态工具包,旨在像乐高积木,可以快速简便地拓展自定义工具,从而组装出自己的智能体。支持多个智能体框架。(如 Lagent、LangChain、Transformers Agents)提供大量视觉、多模态领域前沿算法
四、Lagent Web Demo
Lagent 的 Web Demo 需要用到 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
conda activate agent
cd /root/agent/lagent/examples
streamlit run internlm2_agent_web_demo.py --server.address 127.0.0.1 --server.port 7860
(作业)完成 Lagent Web Demo 使用
五、用 Lagent 自定义工具
Lagent 自定义工具主要分为以下几步
继承 BaseAction 类
实现简单工具的 run 方法;或者实现工具包内每个子工具的功能
简单工具的 run 方法可选被 tool_api 装饰;工具包内每个子工具的功能都需要被 tool_api 装饰
创建工具文件
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()
(作业)完成 Lagent 自定义工具效果
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
六、直接使用 AgentLego
下载DEMO
cd /root/agent
wget http://download.openmmlab.com/agentlego/road.jpg
# 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
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)
(作业)完成 AgentLego 最终效果,还不错
七、作为智能体工具使用
使用internlm2-chat-7b 模型
# 修改 /root/agent/agentlego/webui/modules/agents/lagent_agent.py
def llm_internlm2_lmdeploy(cfg):
url = cfg['url'].strip()
llm = LMDeployClient(
model_name='internlm2-chat-20b',
model_name='internlm2-chat-7b',
url=url,
meta_template=INTERNLM2_META,
top_p=0.8,
top_k=100,
temperature=cfg.get('temperature', 0.7),
repetition_penalty=1.0,
stop_words=['<|im_end|>'])
return llm
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
# 启动 AgentLego WebUI
conda activate agent
cd /root/agent/agentlego/webui
python one_click.py
小插曲
提示缺少依赖包,重新安装一下在执行就可以了
配置
- 点击上方 Agent 进入 Agent 配置页面。(如①所示)
- 点击 Agent 下方框,选择 New Agent。(如②所示)
- 选择 Agent Class 为 lagent.InternLM2Agent。(如③所示)
- 输入模型 URL 为 http://127.0.0.1:23333 。(如④所示)
- 输入 Agent name,自定义即可,图中输入了 internlm2。(如⑤所示)
- 点击 save to 以保存配置,这样在下次使用时只需在第2步时选择 Agent 为 internlm2 后点击 load 以加载就可以了。(如⑥所示)
- 点击 load 以加载配置。(如⑦所示)
配置工具
- 点击上方 Tools 页面进入工具配置页面。(如①所示)
- 点击 Tools 下方框,选择 New Tool 以加载新工具。(如②所示)
- 选择 Tool Class 为 ObjectDetection。(如③所示)
- 点击 save 以保存配置。(如④所示)
加载完成后选择工具
(作业)完成 AgentLego WebUI
到网络上随便找一个图,看看效果,还是不错的。
八、用 AgentLego 自定义工具
自定义工具生成步骤
- 继承 BaseTool 类
- 修改 default_desc 属性(工具功能描述)
- 如有需要,重载 setup 方法(重型模块延迟加载)
- 重载 apply 方法(工具功能实现)
其中第一二四步是必须的步骤,实现一个调用 MagicMaker 的 API 以实现图像生成的工具
编辑脚本
# 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
from .base import BaseTool
from .calculator import Calculator
from .func import make_tool
from .image_canny import CannyTextToImage, ImageToCanny
from .image_depth import DepthTextToImage, ImageToDepth
from .image_editing import ImageExpansion, ImageStylization, ObjectRemove, ObjectReplace
from .image_pose import HumanBodyPose, HumanFaceLandmark, PoseToImage
from .image_scribble import ImageToScribble, ScribbleTextToImage
from .image_text import ImageDescription, TextToImage
from .imagebind import AudioImageToImage, AudioTextToImage, AudioToImage, ThermalToImage
from .object_detection import ObjectDetection, TextToBbox
from .ocr import OCR
from .scholar import * # noqa: F401, F403
from .search import BingSearch, GoogleSearch
from .segmentation import SegmentAnything, SegmentObject, SemanticSegmentation
from .speech_text import SpeechToText, TextToSpeech
from .translation import Translation
from .vqa import VQA
+ from .magicmaker_image_generation import MagicMakerImageGeneration
__all__ = [
'CannyTextToImage', 'ImageToCanny', 'DepthTextToImage', 'ImageToDepth',
'ImageExpansion', 'ObjectRemove', 'ObjectReplace', 'HumanFaceLandmark',
'HumanBodyPose', 'PoseToImage', 'ImageToScribble', 'ScribbleTextToImage',
'ImageDescription', 'TextToImage', 'VQA', 'ObjectDetection', 'TextToBbox', 'OCR',
'SegmentObject', 'SegmentAnything', 'SemanticSegmentation', 'ImageStylization',
'AudioToImage', 'ThermalToImage', 'AudioImageToImage', 'AudioTextToImage',
'SpeechToText', 'TextToSpeech', 'Translation', 'GoogleSearch', 'Calculator',
- 'BaseTool', 'make_tool', 'BingSearch'
+ 'BaseTool', 'make_tool', 'BingSearch', 'MagicMakerImageGeneration'
]
运行看看效果
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
(作业)AgentLego 实现自定义工具并完成调用
总结
学习了两个智能体应用是什么以及怎么使用,思考这些工具可以做些什么有价值的东西呢?对于垂直领域来说,如果是做工业,那么这些工具可以将不同的小模型汇总成一个大模型,那么是否就可以实现AI节能分析呢??