当前位置: 首页 > article >正文

Lagent 自定义你的 Agent 智能体

任务:使用 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 requests

from lagent.actions.base_action import BaseAction, tool_api
from lagent.actions.parser import BaseParser, JsonParser
from lagent.schema import ActionReturn, ActionStatusCode


class 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 = 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}')
    
    @tool_api
    def 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 image

        Returns:
            :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 requests

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):
    adcode = '370102'

    def __init__(self, adcode='370102'):
        super().__init__()
        self.adcode = adcode

    @tool_api
    def 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 adcode
            url_get_address = 'https://restapi.amap.com/v3/geocode/geo?key=c7f6ae7c9a1bf1bc4ef72eaa36fc1d83&address=' + keywords
            addr_rsp = requests.get(url=url_get_address)
            adcode = addr_rsp.json()['geocodes'][0]['adcode']
            
            # Query weather info with adcode
            url_weather_query = 'https://restapi.amap.com/v3/weather/weatherInfo?key=c7f6ae7c9a1bf1bc4ef72eaa36fc1d83&city=' + adcode
            response = 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.kler.cn/news/327947.html

相关文章:

  • k8s 部署 prometheus
  • Android中级控件
  • Fivetran+Milvus:AI搜索新时代的数据迁移利器
  • 学习记录:js算法(五十):二叉树的右视图
  • 【Preference Learning】Reasoning with Language Model is Planning with World Model
  • mysql学习教程,从入门到精通,SQL 表、列别名(Aliases)(30)
  • Spring Boot框架在甘肃非遗文化网站设计中的运用
  • ubuntu配置python环境
  • 深度学习基础及技巧
  • Linux性能调优技巧
  • 汽车零部件开发流程关键阶段
  • PowerShell无法执行yarn命令
  • Qt_线程介绍与使用
  • Wpf Image 展示方式 图片处理 显示
  • 828华为云征文|华为云 Flexus X 实例初体验
  • 选择更轻松:山海鲸可视化与PowerBI的深度对比
  • MATLAB在无线通信标准与协议支持中的作用
  • 打造未来社交:区块链社交DAO的颠覆性开发之路
  • 2.1 HuggingFists系统架构(一)
  • Go 项目开发常用设计模式
  • OpenCV图像文件读写(1)检查 OpenCV 是否支持某种图像格式的读取功能函数haveImageReader()的使用
  • Python FFmpeg 安装使用教程
  • SQL第10课挑战题
  • C# 泛型使用案例_C# 泛型使用整理
  • vue 项目打包更新后,界面未刷新时js与css资源加载404,监听资源文件404后自动重新加载页面。
  • 解决 Macos下 Orbstack docker网络问题
  • 【工具-VMware Workstation-ubuntu】
  • UDP通信
  • Linux 如何检测一个程序的最大内存使用值?
  • 普通人未来还有哪些赚钱机会?