【书生·浦语大模型实战营】第6节笔记:Lagent & AgentLego 智能体应用搭建

本文详细介绍了如何使用Lagent框架部署和启动WebDemo,自定义工具如天气查询,并通过AgentLego进行目标检测和图像生成。同时,还涉及了如何使用MMDetection库和配置环境变量以确保服务正常运行。
摘要由CSDN通过智能技术生成

一、Lagent:轻量级智能体框架

1. Lagent Web Demo
1.1 使用 LMDeploy 部署
  • 需要使用 LMDeploy 启动的 api_server
  • 在 VSCode 的终端中执行代码以启动 api_server
1.2 启动并使用 Lagent Web Demo
  • 新建终端,执行命令启动 Lagent Web Demo。
  • 命令:cd /root/agent/lagent/examples 后 streamlit run internlm2_agent_web_demo.py --server.address 127.0.0.1 --server.port 7860
  • 等待服务启动后,进行端口映射,将 api_server 的23333端口和 Lagent Web Demo 的7860端口映射到本地。
  • 访问 http://localhost:7860 使用 Lagent Web Demo。
  • 输入模型 IP 127.0.0.1:23333,选择插件 ArxivSearch 进行论文搜索。

2. 用 Lagent 自定义工具
2.1 创建工具文件
  • 新建工具文件 /root/agent/lagent/lagent/actions/weather.py,实现天气查询功能。
  • 工具类 WeatherQuery 继承自 BaseAction,使用 tool_api 装饰器。
2.2 获取 API KEY
2.3 体验自定义工具效果
  • 确保之前的 LMDeploy 服务和 Web Demo 服务已停止。
  • 设置环境变量 WEATHER_API_KEY 为之前获取的 API KEY。
  • 激活 Conda 环境,运行 streamlit 启动 Web Demo。
  • 进行端口映射,输入模型地址,选择工具,开始体验。

代码示例

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

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)
        self.key = os.environ.get('WEATHER_API_KEY', key)
        if self.key is None:
            raise ValueError('Please set Weather API key either in the environment as WEATHER_API_KEY or pass it as `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:
        """A weather query API. Can query weather information based on the city name."""
        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."""
        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()
        if len(city_code_response.json()['location']) == 0:
            return 1, '未查询到城市'
        city_code = city_code_response.json()['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()

(演示效果) 

注意事项
  • 确保在运行新服务前停止旧服务,避免 CUDA 内存不足或端口占用问题。
  • 使用环境变量 WEATHER_API_KEY 来设置天气 API 的密钥。

二、AgentLego:组装智能体“乐高”

1. 直接使用 AgentLego
  • 下载 demo 文件至 /root/agent 目录。
  • 安装目标检测工具所需依赖,基于 mmdet (MMDetection) 算法库中的 RTMDet-Large 模型。
  • 安装 mim 后通过 mim 安装 mmdet。
  • 创建 direct_use.py 用于直接使用目标检测工具,代码示例包括加载工具、应用工具、可视化结果。

2. 作为智能体工具使用
2.1 修改相关文件
  • 修改 /root/agent/agentlego/webui/modules/agents/lagent_agent.py 文件以更换模型大小。
2.2 使用 LMDeploy 部署
  • 使用 LMDeploy 启动 api_server。
2.3 启动 AgentLego WebUI
  • 在 /root/agent/agentlego/webui 目录下启动 WebUI。
2.4 使用 AgentLego WebUI
  • 通过浏览器访问 http://localhost:7860 使用 WebUI。
  • 配置 Agent 和工具,使用 ObjectDetection 工具进行图片上传和模型调用。

3. 用 AgentLego 自定义工具
3.1 创建工具文件
  • 创建 magicmaker_image_generation.py 文件,实现调用 MagicMaker API 进行图像生成的工具。
3.2 注册新工具
  • 修改 /root/agent/agentlego/agentlego/tools/__init__.py 文件,将新工具注册到工具列表。
3.3 体验自定义工具效果
  • 启动 LMDeploy 服务和 AgentLego WebUI,使用 MagicMakerImageGeneration 工具。

 

注意事项
  • 确保 LMDeploy 服务和 Web Demo 服务在体验自定义工具前已停止,避免 CUDA Out of Memory 或端口占用问题。
附加信息

  • 25
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值