6、Lagent AgentLego 智能体应用搭建(homework)

2024-04-20 08:20

本文主要是介绍6、Lagent AgentLego 智能体应用搭建(homework),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

基础作业

  • 完成 Lagent Web Demo 使用,并在作业中上传截图。文档可见 Lagent Web Demo

0 环境准备

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

1 使用 LMDeploy 部署

        由于 Lagent 的 Web Demo 需要用到 LMDeploy 所启动的 api_server,因此我们首先按照下图指示在 vscode terminal 中执行如下代码使用 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## 启动并使用 Lagent Web Demo
cd /root/agent/lagent/examples
streamlit run internlm2_agent_web_demo.py --server.address 127.0.0.1 --server.port 7860

  • 完成 AgentLego 直接使用部分,并在作业中上传截图。文档可见 直接使用 AgentLego。

        由于 AgentLego 在安装时并不会安装某个特定工具的依赖,因此我们接下来准备安装目标检测工具运行时所需依赖。

        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(大小写敏感)的方式在 /root/agent 目录下新建 direct_use.py 以直接使用目标检测工具,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)

进阶作业

  • 完成 AgentLego WebUI 使用,并在作业中上传截图。文档可见 AgentLego WebUI。

  • 使用 Lagent 或 AgentLego 实现自定义工具并完成调用,并在作业中上传截图。文档可见:
  • 用 Lagent 自定义工具

         1 创建工具文件

首先通过 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()

        2 获取 API KEY

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.1export 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 自定义工具

AgentLego 在这方面提供了较为详尽的文档,文档地址为 自定义工具 — AgentLego 0.2.0 文档 。自定义工具主要分为以下几步:

  1. 继承 BaseTool 类
  2. 修改 default_desc 属性(工具功能描述)
  3. 如有需要,重载 setup 方法(重型模块延迟加载)
  4. 重载 apply 方法(工具功能实现)

        其中第一二四步是必须的步骤。下面我们将实现一个调用 MagicMaker 的 API 以实现图像生成的工具。

        首先通过 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/AgentLego/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'
+     'BaseTool', 'make_tool', 'BingSearch', 'MagicMakerImageGeneration'
]

运行 


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

        

这篇关于6、Lagent AgentLego 智能体应用搭建(homework)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/919750

相关文章

本地搭建DeepSeek-R1、WebUI的完整过程及访问

《本地搭建DeepSeek-R1、WebUI的完整过程及访问》:本文主要介绍本地搭建DeepSeek-R1、WebUI的完整过程及访问的相关资料,DeepSeek-R1是一个开源的人工智能平台,主... 目录背景       搭建准备基础概念搭建过程访问对话测试总结背景       最近几年,人工智能技术

5分钟获取deepseek api并搭建简易问答应用

《5分钟获取deepseekapi并搭建简易问答应用》本文主要介绍了5分钟获取deepseekapi并搭建简易问答应用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需... 目录1、获取api2、获取base_url和chat_model3、配置模型参数方法一:终端中临时将加

JavaScript中的isTrusted属性及其应用场景详解

《JavaScript中的isTrusted属性及其应用场景详解》在现代Web开发中,JavaScript是构建交互式应用的核心语言,随着前端技术的不断发展,开发者需要处理越来越多的复杂场景,例如事件... 目录引言一、问题背景二、isTrusted 属性的来源与作用1. isTrusted 的定义2. 为

Python调用另一个py文件并传递参数常见的方法及其应用场景

《Python调用另一个py文件并传递参数常见的方法及其应用场景》:本文主要介绍在Python中调用另一个py文件并传递参数的几种常见方法,包括使用import语句、exec函数、subproce... 目录前言1. 使用import语句1.1 基本用法1.2 导入特定函数1.3 处理文件路径2. 使用ex

将Python应用部署到生产环境的小技巧分享

《将Python应用部署到生产环境的小技巧分享》文章主要讲述了在将Python应用程序部署到生产环境之前,需要进行的准备工作和最佳实践,包括心态调整、代码审查、测试覆盖率提升、配置文件优化、日志记录完... 目录部署前夜:从开发到生产的心理准备与检查清单环境搭建:打造稳固的应用运行平台自动化流水线:让部署像

Linux中Curl参数详解实践应用

《Linux中Curl参数详解实践应用》在现代网络开发和运维工作中,curl命令是一个不可或缺的工具,它是一个利用URL语法在命令行下工作的文件传输工具,支持多种协议,如HTTP、HTTPS、FTP等... 目录引言一、基础请求参数1. -X 或 --request2. -d 或 --data3. -H 或

在Ubuntu上部署SpringBoot应用的操作步骤

《在Ubuntu上部署SpringBoot应用的操作步骤》随着云计算和容器化技术的普及,Linux服务器已成为部署Web应用程序的主流平台之一,Java作为一种跨平台的编程语言,具有广泛的应用场景,本... 目录一、部署准备二、安装 Java 环境1. 安装 JDK2. 验证 Java 安装三、安装 mys

Python中构建终端应用界面利器Blessed模块的使用

《Python中构建终端应用界面利器Blessed模块的使用》Blessed库作为一个轻量级且功能强大的解决方案,开始在开发者中赢得口碑,今天,我们就一起来探索一下它是如何让终端UI开发变得轻松而高... 目录一、安装与配置:简单、快速、无障碍二、基本功能:从彩色文本到动态交互1. 显示基本内容2. 创建链

Mycat搭建分库分表方式

《Mycat搭建分库分表方式》文章介绍了如何使用分库分表架构来解决单表数据量过大带来的性能和存储容量限制的问题,通过在一对主从复制节点上配置数据源,并使用分片算法将数据分配到不同的数据库表中,可以有效... 目录分库分表解决的问题分库分表架构添加数据验证结果 总结分库分表解决的问题单表数据量过大带来的性能

Java汇编源码如何查看环境搭建

《Java汇编源码如何查看环境搭建》:本文主要介绍如何在IntelliJIDEA开发环境中搭建字节码和汇编环境,以便更好地进行代码调优和JVM学习,首先,介绍了如何配置IntelliJIDEA以方... 目录一、简介二、在IDEA开发环境中搭建汇编环境2.1 在IDEA中搭建字节码查看环境2.1.1 搭建步