Lagent 自定义你的 Agent 智能体

ops/2024/10/20 5:27:06/
aidu_pl">

任务:使用 Lagent 自定义一个智能体,并使用 Lagent Web Demo 成功部署与调用

复现过程

1、根据教材部署环境。https://github.com/InternLM/Tutorial/blob/camp3/docs/L2/Lagent/readme.md

2、启动Lagent Web Demo 和LMDeploy api_server,注意,Lagent Web Demo的model要填实际的model name。

conda activate agent_camp3
lmdeploy serve api_server /share/new_models/Shanghai_AI_Laboratory/internlm2_5-7b-chat --model-name internlm2_5-7b-chat
cd /root/agent_camp3/lagent
conda activate agent_camp3
streamlit run examples/internlm2_agent_web_demo.py

在这里插入图片描述

3、制作新的插件magicmaker和weatherquery

在这里插入图片描述
代码如下:

import json
import requestsfrom lagent.actions.base_action import BaseAction, tool_api
from lagent.actions.parser import BaseParser, JsonParser
from lagent.schema import ActionReturn, ActionStatusCodeclass MagicMaker(BaseAction):styles_option = ['dongman',  # 动漫'guofeng',  # 国风'xieshi',   # 写实'youhua',   # 油画'manghe',   # 盲盒]aspect_ratio_options = ['16:9', '4:3', '3:2', '1:1','2:3', '3:4', '9:16']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}')@tool_apidef generate_image(self, keywords: str) -> dict:"""Run magicmaker and get the generated image according to the keywords.Args:keywords (:class:`str`): the keywords to generate imageReturns::class:`dict`: the generated image* image (str): path to the generated image"""try: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'})except Exception as exc:return ActionReturn(errmsg=f'MagicMaker exception: {exc}',state=ActionStatusCode.HTTP_ERROR)image_url = response.json()['data']['imgUrl']return {'image': image_url}
import json
import requestsfrom lagent.actions.base_action import BaseAction, tool_api
from lagent.actions.parser import BaseParser, JsonParser
from lagent.schema import ActionReturn, ActionStatusCodeclass WeatherQuery(BaseAction):adcode = '370102'def __init__(self, adcode='370102'):super().__init__()self.adcode = adcode@tool_apidef weather_query(self, keywords: str) -> dict:"""Run weatherquery and get the weather information according to the keywords.Args:keywords (:class:`str`): the keywords to query weather information. such as address.Returns::class:`dict`: the generated image* image (str): path to the generated image* province: the province of address* city: the city of address* adcode: city code of the address* weather: weather detail information* temperature: temperature of the address* winddirection: wind's direction* windpower: wind's power* humidity: humidity information* reporttime: report timestamp, example: 2024-08-15 16:01:03* temperature_float: temperature informations with float. such as 30.0* humidity_float: humidity information with float format. such as 63.0"""try:# Use Address info to get adcodeurl_get_address = 'https://restapi.amap.com/v3/geocode/geo?key=c7f6ae7c9a1bf1bc4ef72eaa36fc1d83&address=' + keywordsaddr_rsp = requests.get(url=url_get_address)adcode = addr_rsp.json()['geocodes'][0]['adcode']# Query weather info with adcodeurl_weather_query = 'https://restapi.amap.com/v3/weather/weatherInfo?key=c7f6ae7c9a1bf1bc4ef72eaa36fc1d83&city=' + adcoderesponse = requests.get(url=url_weather_query)except Exception as exc:return ActionReturn(errmsg=f'WeatherQuery exception: {exc}',state=ActionStatusCode.HTTP_ERROR)result = response.json()['lives'][0]return {'result': result}

4、然后修改internlm2_agent_web_demo.py,添加红框部分。

在这里插入图片描述

5、再启动webdemo后,测试成功

在这里插入图片描述
在这里插入图片描述


http://www.ppmy.cn/ops/118072.html

相关文章

c++模拟真人鼠标轨迹算法

一.鼠标轨迹算法简介 鼠标轨迹底层实现采用 C / C语言,利用其高性能和系统级访问能力,开发出高效的鼠标轨迹模拟算法。通过将算法封装为 DLL(动态链接库),可以方便地在不同的编程环境中调用,实现跨语言的兼…

Splashtop 在2024年 CybersecAsia 读者之选奖项评选中荣获新星奖

2024年9月26日 新加坡 安全远程访问和支持解决方案领域的领先企业 Splashtop 在第五届 CybersecAsia 读者之选奖项评选中荣获新星奖。该奖项的评选人员包括首席信息安全官、技术领袖和网络安全从业者,旨在表彰亚太地区网络安全领袖在行业中发挥的关键作用、取得的创…

OpenHarmony(鸿蒙南向)——平台驱动开发【PIN】

往期知识点记录: 鸿蒙(HarmonyOS)应用层开发(北向)知识点汇总 鸿蒙(OpenHarmony)南向开发保姆级知识点汇总~ 持续更新中…… 概述 功能简介 PIN即管脚控制器,用于统一管理各SoC的…

pytorch ----【输入张量.data.size()/输入张量.size()】的使用

import torch test_data torch.randn(1, 12, 32, 32) batchsize, num_channels, height, width test_data.data.size() 在提供的代码中,test_data 是一个形状为 (1, 12, 32, 32) 的随机张量,表示一个批次(batch)中有 1 张图像&…

数据治理003-数据域

数据仓库是面向主题(数据综合、归类并进行分析利用的抽象)的应用。 数据仓库模型设计除横向的分层外,通常也需要根据业务情况进行纵向划分数据域。数据域是联系较为紧密的数据主题的集合,通常是根据业务类别、数据来源、数据用途…

some 牛课题

D-Cidoai的字符集合_牛客练习赛128 (nowcoder.com) #include "bits/stdc.h" #define int long long using namespace std; int fa[100000000]; int sz[100000000]; int find(int n) {if(n!fa[n])fa[n]find(fa[n]);return fa[n]; } map<string,int>mp; signed …

ArcGIS Desktop使用入门(三)常用工具条——拓扑(上篇:地图拓扑)

系列文章目录 ArcGIS Desktop使用入门&#xff08;一&#xff09;软件初认识 ArcGIS Desktop使用入门&#xff08;二&#xff09;常用工具条——标准工具 ArcGIS Desktop使用入门&#xff08;二&#xff09;常用工具条——编辑器 ArcGIS Desktop使用入门&#xff08;二&#x…

H.264与H.265

在使用海康平台做涉嫌头配置时&#xff0c;有H.264和H.265。大家可能搞不清楚两者的区别&#xff0c;下边我们来看一下H.264和H.265的区别。 H.264与H.265的区别 压缩效率&#xff1a; H.264&#xff1a;由于算法优化&#xff0c;H.264可以在低于1Mbps的速度下实现标清数字图像…