目录
第六课 lagent & AgentLego 智能体应用搭建
【第六节】: 【Lagent & AgentLego 智能体应用搭建】
1、Agent 理论及 Lagent&AgentLego 开源产品介绍
2、Lagent 调用已有 Arxiv 论文搜索工具实战
3、Lagent 新增自定义工具实战(以查询天气的工具为例)
4、AgentLego 新增 MagicMaker 文生图工具实战
1 课程笔记
1.1 大模型的局限性、时效性(今年)、可靠性()
什么是智能体?
- 可以感知环境中的动态条件
- 能采取动作影响环境
- 能运用推理能力理解信息、解决问题、产生推断、决定动作。
Hayes Roth 1995
An Architecture for Adaptive Intelligent System
智能体包括哪些部分?
- 大脑:控制器,接受信息采取动作。
- 感知:对外部信息的感知和处理。音、视、图。
- 动作:利用并执行工具。文本检索、API、控制机械。
智能体范式
解析任务,产生新的任务。递归?
任务拆分发送给worker,最后solver接受Planer和Worker的信息进行输出。
选择工具后执行,判断是否需要执行下一个工具。
2 实践
- 创建开发机。cuda12.2、30%开发机
- 创建工作目录。root/agent
- 创建虚拟环境
- 源码安装
- git clone lagent pip
- git clone agentlego
- demo:git clone Tutorial
- 安装其他依赖
轻量级智能体框架
- 使用LMDeploy部署。(后台的服务)
- 启动lagent Web Demo。新建终端启动服务。
- ssh连接。(两个端口)
- 本地打开,填写模型ip(deploy服务)
- 插件配置:ArxivSearch
lagent自定义工具
步骤:
- 继承BaseAction
- 实现简单工具的
run方法
;或者每个工具包内的子功能
。 - 简单工具的run方法可以被
tool_api
装饰;工具包内每个子工具的功能都需要被tool_api装饰。
实践:调用和风天气api的工具(终止前面的两个服务)
- 创建文件weather.py
- 粘贴代码。
- 和风天气api。复制连接——粘贴——控制台——创建项目(免费订阅、web api、自定义key的名称)——项目管理——查看key
- 启动LMDeploy的服务。
- key的变量设置
- 启动天气服务的demo
- ssh服务映射
- 填写LMDeploy的ip地址和agent query名称
- 问答
AgentLego 组装智能体
AgentLego WebUI示例:
直接使用
- demo文件下载
- mmdet目标检测工具的安装。
- 创建目标检测文件
direct_use.py
。 - 执行推理。运行direct_use.py
AgentLego WebUI 使用
-
修改模型。20B—>7B
-
LMDeploy的部署。
-
启动agentlegoWebUI。one_click.py
-
两个服务启动后使用ssh连接到本地。
-
配置agent、agent class(LM2)、url、save to 、load
-
工具配置:新工具——目标检测——
-
chat:工具选择——目标检测
-
上传图片、检测
-
服务启动后配置工具就是搭积木的过程
agentLego自定义工具
1、继承BaseTool类
2、修改default_desc属性(工具功能描述)
3、如有需要重载setup方法(重载模块延迟加载)
4、重载apply方法(工具功能实现)
实践:调用MagicMaker的api实现文生图。
- 新建工具文件——粘贴工具源码。
- 在
__init__
文件中注册工具。(导包、__all__
列表) - 启动deploy
- 启动
one_click.py
- 本地使用
- webUI界面设置换上面一致。
3 作业
- 完成 Lagent Web Demo 使用,并在作业中上传截图。文档可见 Lagent Web Demo
- 完成 AgentLego 直接使用部分,并在作业中上传截图。文档可见 直接使用 AgentLego。
- 完成 AgentLego WebUI 使用,并在作业中上传截图。文档可见 AgentLego WebUI。
- 使用 Lagent 或 AgentLego 实现自定义工具并完成调用,并在作业中上传截图。文档可见:
基础配置
-
创建开发机。cuda12.2、30%开发机
-
创建工作目录。root/agent
mkdir -p /root/agent
-
创建虚拟环境
studio-conda -t agent -o pytorch-2.1.2
-
源码安装
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 ..
-
安装其他依赖
pip install lmdeploy==0.3.0
-
Tutorial
cd /root/agent git clone -b camp2 https://gitee.com/internlm/Tutorial.git
3.1 Lagent 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
-
启动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
-
ssh连接。(两个端口)
ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p <port>
-
本地打开,填写模型ip(deploy服务)
http://localhost:7860/
-
插件配置:ArxivSearch。
请帮我搜索 InternLM2 Technical Report
127.0.0.1:23333
3.2 AgentLego 直接使用
目标检测
-
demo文件下载
cd /root/agent wget http://download.openmmlab.com/agentlego/road.jpg
-
mmdet目标检测工具的安装。目标检测工具是基于 mmdet (MMDetection) 算法库中的 RTMDet-Large 模型。
# conda activate agent pip install openmim==0.3.9 mim install mmdet==3.3.0
-
创建目标检测文件
direct_use.py
。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)
-
执行推理。运行direct_use.py
python /root/agent/direct_use.py
3.3 AgentLego WebUI
目标检测WebUI
-
修改模型。20B—>7B
-
/root/agent/agentlego/webui/modules/agents/lagent_agent.py 文件的
第 105行位置
,将internlm2-chat-20b
修改为internlm2-chat-7b
-
model_name='internlm2-chat-7b'
-
-
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
-
启动agentlegoWebUI。one_click.py
# conda activate agent cd /root/agent/agentlego/webui python one_click.py
-
两个服务启动后使用ssh连接到本地。
ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p <服务器端口号>
-
Agent
配置agent、agent class(LM2)、url(127.0.0.1:23333
)、save to 、load -
Tools
配置:新工具——目标检测—— -
chat
工具选择——目标检测 -
上传图片、检测
请检测图中的物体
-
3.4 Lagent 或 AgentLego 实现自定义工具
天气查询
-
创建文件weather.py
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。复制连接——粘贴——控制台——创建项目(免费订阅、web api、自定义key的名称)——项目管理——查看key
-
链接: https://dev.qweather.com/docs/api/
-
-
启动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
-
key的变量设置
export WEATHER_API_KEY=API KEY
-
启动天气服务的demo
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服务映射
ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p <xxx端口号>
-
填写LMDeploy的ip地址和agent query名称
127.0.0.1:23333
-
问答。
请帮我查询合肥的天气
课程
【视频地址】:https://www.bilibili.com/video/BV1Xt4217728/
【课程文档】:https://github.com/InternLM/Tutorial/tree/camp2/agent
【课程作业】:https://github.com/InternLM/Tutorial/blob/camp2/agent/homework.md