【InternLM 实战营第二期笔记】Lagent AgentLego 智能体应用搭建

理论知识

Lagent 是什么

Lagent 是一个轻量级开源智能体框架,旨在让用户可以高效地构建基于大语言模型的智能体。同时它也提供了一些典型工具以增强大语言模型的能力。

Lagent 目前已经支持了包括 AutoGPT、ReAct 等在内的多个经典智能体范式,也支持了如下工具:

  • Arxiv 搜索
  • Bing 地图
  • Google 学术搜索
  • Google 搜索
  • 交互式 IPython 解释器
  • IPython 解释器
  • PPT
  • Python 解释器

AgentLego 是什么

AgentLego 是一个提供了多种开源工具 API 的多模态工具包,旨在像是乐高积木一样,让用户可以快速简便地拓展自定义工具,从而组装出自己的智能体。通过 AgentLego 算法库,不仅可以直接使用多种工具,也可以利用这些工具,在相关智能体框架(如 Lagent,Transformers Agent 等)的帮助下,快速构建可以增强大语言模型能力的智能体。

两者关系

Lagent 是一个智能体框架,而 AgentLego 与大模型智能体并不直接相关,而是作为工具包,在相关智能体的功能支持模块发挥作用。

实践部分

准备环境

拉取环境

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

安装其他依赖

pip install lmdeploy==0.3.0

克隆Tutorial

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

Lagent:轻量级智能体框架

Lagent Web Demo

启动api server

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

cd /root/agent/lagent/examples
streamlit run internlm2_agent_web_demo.py --server.address 127.0.0.1 --server.port 7860

用 Lagent 自定义工具

创建工具文件

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

文件内容:

import json
import os
import requests
from typing import Optional, Typefrom lagent.actions.base_action import BaseAction, tool_api
from lagent.actions.parser import BaseParser, JsonParser
from lagent.schema import ActionReturn, ActionStatusCodeclass 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 = keyself.location_query_url = 'https://geoapi.qweather.com/v2/city/lookup'self.weather_query_url = 'https://devapi.qweather.com/v7/weather/now'@tool_apidef 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 = responsetool_return.state = ActionStatusCode.HTTP_ERRORelif status_code == 200:parsed_res = self._parse_results(response)tool_return.result = [dict(type='text', content=str(parsed_res))]tool_return.state = ActionStatusCode.SUCCESSelse:tool_return.errmsg = str(status_code)tool_return.state = ActionStatusCode.API_ERRORreturn tool_returndef _parse_results(self, results: dict) -> str:"""Parse the weather results from QWeather API.Args:results (dict): The weather content from QWeather APIin 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_codetry: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 weathertry: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 KEY

https://dev.qweather.com/docs/api/后,点击右上角控制台获取key

体验自定义工具效果

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
cd /root/agent/Tutorial/agent
streamlit run internlm2_weather_web_demo.py --server.address 127.0.0.1 --server.port 7860

查询结果

AgentLego:组装智能体“乐高”

直接使用 AgentLego

下载demo

cd /root/agent
wget http://download.openmmlab.com/agentlego/road.jpg

安装依赖

pip install openmim==0.3.9
mim install mmdet==3.3.0

创建文件

touch /root/agent/direct_use.py

文件内容:

import reimport 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

运行结果

Inference ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━   
truck (345, 428, 528, 599), score 83
car (771, 510, 837, 565), score 81
car (604, 518, 677, 569), score 75
person (866, 503, 905, 595), score 74
person (287, 513, 320, 596), score 74
person (964, 501, 999, 604), score 72
person (1009, 503, 1047, 602), score 69
person (259, 510, 279, 575), score 65
car (1074, 524, 1275, 691), score 64
person (993, 508, 1016, 597), score 62
truck (689, 483, 764, 561), score 62
bicycle (873, 551, 903, 602), score 60
person (680, 523, 699, 567), score 55
bicycle (968, 551, 996, 609), score 53
bus (826, 482, 930, 560), score 52
bicycle (1011, 551, 1043, 617), score 51

作为智能体工具使用

修改相关文件

文件路径:

/root/agent/agentlego/webui/modules/agents/lagent_agent.py

文件的第 105行位置,将 internlm2-chat-20b 修改为 internlm2-chat-7b

使用 LMDeploy 部署

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

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

连接

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

使用 AgentLego WebUI

接下来在本地的浏览器页面中打开 http://localhost:7860 以使用 AgentLego WebUI。首先来配置 Agent,如下图所示。

  1. 点击上方 Agent 进入 Agent 配置页面。
  2. 点击 Agent 下方框,选择 New Agent。
  3. 选择 Agent Class 为 lagent.InternLM2Agent。
  4. 输入模型 URL 为 http://127.0.0.1:23333 。
  5. 输入 Agent name,自定义即可,图中输入了 internlm2。
  6. 点击 save to 以保存配置,这样在下次使用时只需在第2步时选择 Agent 为 internlm2 后点击 load 以加载就可以了。
  7. 点击 load 以加载配置。

运行结果

用 AgentLego 自定义工具

创建工具文件

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

文件内容

import json
import requestsimport numpy as npfrom agentlego.types import Annotated, ImageIO, Info
from agentlego.utils import require
from .base import BaseToolclass 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 = styleelse:raise ValueError(f'The style must be one of {self.styles_option}')if aspect_ratio in self.aspect_ratio_options:self.aspect_ratio = aspect_ratioelse: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 cv2response = 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.imdecode(np.frombuffer(image_response.content, np.uint8), cv2.IMREAD_COLOR)return ImageIO(image)

注册新工具

接下来修改 /root/agent/agentlego/agentlego/tools/__init__.py 文件,将我们的工具注册在工具列表中。如下所示,我们将 MagicMakerImageGeneration 通过 from .magicmaker_image_generation import MagicMakerImageGeneration 导入到了文件中,并且将其加入了 __all__ 列表中。

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', 'MagicMakerImageGeneration'
]

体验自定义工具效果

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

启动

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/2106.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

主流微前端框架对比与选择策略

微前端是一种架构风格,旨在将大型前端应用程序拆分为多个独立的模块,这些模块可以独立开发、测试和部署。主流的微前端框架有以下几种: Single-SPA:Single-SPA 是一个超级父级框架,可以与其他前端框架集成,…

linux环境变量设置

windows环境变量设置步骤: 右键"我的电脑"高级设置环境变量编辑"用户变量"或者"系统变量" linux下环境变量的设置步骤: 修改/etc/profile添加如下格式条目: export MAVEN_HOME/usr/local/apache-maven-3.6…

C语言指针+-整数、指针-指针、指针关系运算、指针和数组、二级指针、指针数组

文章目录 前言一、指针 - 整数二、指针 - 指针三、指针的关系运算四、指针和数组五、二级指针六、指针数组指针数组可以将几个一维数组模拟成二维数组 总结 前言 C语言指针整数、指针-指针、指针关系运算、指针和数组、二级指针、指针数组等介绍,还包括指针数组将几…

武汉大学博士,华为上班5年多,月薪多少。。。

最近,一位来自武汉大学的博士研究生透露了自己在华为公司工作五年后的薪酬情况。 据他透露,他在2018年加入华为时的月薪为2.4万,随着时间的推移,到了2023年,他的月薪已经增长至4.4万!此外,他还透…

工作后的自我介绍

您好,我叫Li,毕业于双一流**大学软件工程专业。 在大学期间通过四级,获得计算机C语言二级证书、科技立项奖(词频统计)、国家励志奖学金、优秀学生奖学金、优秀团干部、新生奖学金等。在校主修的课程有C、Java、数据结…

AI时代的GPU集群网络算力分析

浅谈GPU集群网络、集群规模和集群算力 引言在生成式AI(GenAI)和大模型时代,不仅需要关注单个GPU卡的算力,更要关注GPU集群的总有效算力。单个GPU卡的有效算力可以通过该卡的峰值算力来测算,例如,对于Nvidia…

class093 贪心经典题目专题5【左程云算法】

class093 贪心经典题目专题5【左程云算法】 前言版权推荐class093 贪心经典题目专题5最后 前言 2024-4-23 14:01:18 以下内容源自《【左程云算法】》 仅供学习交流使用 版权 禁止其他平台发布时删除以下此话 本文首次发布于CSDN平台 作者是CSDN日星月云 博客主页是https://…

网络工程师----第十一天

OSPF: 对称加密算法: 也称为私钥加密或单密钥算法,是一种加密方式,其中加密和解密使用相同的密钥。这种算法的优点包括加密解密速度快、计算量小,适用于大量数据的加密。然而,它的缺点是密钥的安全性难以保…

SEHLL脚本编程---- Nginx日志分析6-统计每分钟的请求数

描述 假设Nginx的日志存储在nowcoder.txt里,内容如下: 192.168.1.20 - - [21/Apr/2020:14:12:49 0800] "GET /1/index.php HTTP/1.1" 404 490 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefo…

深度相机(3D相机)

传统的RGB彩色相机称为2D相机, 只能得到2D的图像信息, 无法得到物体与相机的距离信息,也就是深度信息。 顾名思义, 深度相机除了获取2D信息,还能得到深度信息,也叫RGBD相机, 或3D相机。 顺便提…

被删除的照片和视频能找回吗?如何恢复手机删除的照片和视频?

手机里的照片和视频是我们记录生活的每一个瞬间,也是工作学习等场合经常用到的东西,一旦不慎丢失,将对我们造成很大损失。那么我们该如何恢复手机删除的照片和视频呢?通过掌握正确的恢复方法,能够最大程度地保护手机中…

网络常识!!!

网络常识!!! 一:网络的发展史二:关键的概念三:IP地址四:端口号二级目录二级目录二级目录二级目录三级目录 一:网络的发展史 从游戏方面发展历程进行理解: 从单机游戏-----游戏支持局域网对战-------游戏支持广域网对战-------移动端 (1)局域网对战:在同一个网吧里,不同的游戏…

2016年新华三杯复赛实验试题

2016年新华三杯复赛实验试题 拓扑图 配置需求 考生根据以下配置需求在 HCL 中的设备上进行相关配置。 以太网接口配置 将 S1、S2 的以太网接口 G1/0/1 至 G1/0/16 的模式用命令 combo enable copper 激活为电口。 虚拟局域网 为了减少广播,需要规划并配置 VLA…

Seurat -- Introduction to scRNA-seq integration 跟随学习记录

文章目录 数据是如何转换的原始ifnb数据对象Splits object后的数据对象数据对象构建完成后的标准流程Normalization后的数据对象scale 后的数据对象 不同的样本进行整合JoinLayers干了什么 数据是如何转换的 seurat object 中assays R N A l a y e r s RNAlayers RNAlayersco…

新的全息技术突破计算障碍

一种突破性的方法利用基于Lohmann透镜的衍射模型实时创建计算机生成全息图(CGH),在保持3D可视化质量的同时,大大降低了计算负荷要求。 全息显示为制作逼真的三维图像提供了一条令人兴奋的途径,这种图像给人以连续深度…

在 Slurm 上运行 Jupyter

1. 背景介绍 现在的大模型训练越来越深入每个组了,大规模集群系统也应用的愈发广泛。一般的slurm系统提交作业分为2种,一种是srun,这种所见即所得的申请方式一般适用于短期的调试使用,大概一般允许的时间从几个小时到1天左右&…

【Camera Sensor Driver笔记】七、点亮指南之Flash

<flashDriverData> flashName adp1660 flash 名称 flashDriverType I2C PMIC / I2C &#xff08;PMIC为平台的&#xff0c;eg&#xff1a;flashname&#xff1a;pmic flashDriverType&#xff1a;PMIC&#xff09; <powerUpSe…

flutter 设置启屏页 flutter_native_splash 坑记录

flutter_native_splash | Flutter packageCustomize Flutters default white native splash screen with background color and splash image. Supports dark mode, full screen, and more.https://pub.dev/packages/flutter_native_splash 发现一直白屏 原因是 代码中 下面…

图书租赁系统

网上出版的电子书只有购买服务&#xff0c;如果也有租赁服务就好了。例如&#xff0c;读者可以租个1个小时&#xff0c;1个小时到期&#xff0c;读者就不能阅读该书。 图中借阅结束时间是2024-04-23 13:36:29&#xff0c;到期后该书就会从列表中消失。 BookOrderMapper.xml &…

Python与设计模式之适配器的使用方法

适配器模式&#xff1a;将一个类的接口转换成客户希望的另一个接口&#xff0c;适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作 主要有两个实现方式&#xff1a; 1.使用继承--类适配器 2.使用组合--对象适配器 适用场景 1.想使用一个已经存在的类&a…