Lagent & AgentLego 智能体应用搭建-笔记

本文介绍了Lagent,一个用于构建基于大语言模型的轻量级智能体框架,以及其扩展工具包AgentLego。文章详细讲述了如何配置环境,使用Lagent创建和测试自定义工具,以及如何利用AgentLego进行多模态工具集成。重点讨论了功能调用和工具微调的重要性。
摘要由CSDN通过智能技术生成

心心念念的一章,争取这两天好好学学。在这之前,学langchain,发现开源模型跑通的事例有限,另外,langchain官网教程也有些陈旧了,有些api都挪位置了。估计今后开源对agent支持很好的时候,出一个完整的能跑通的教程估计比较抢手,一个notebook的python版,一个notebook的js版,方便前后端一键本地部署,一脚跨入agent世界

1. 概述

1.1 Lagent 是什么

Lagent 是一个轻量级开源智能体框架,旨在让用户可以高效地构建基于大语言模型的智能体。同时它也提供了一些典型工具以增强大语言模型的能力。
工具目测不如langchain上的多,天气搜索之类没有,不过python解释器好几个,不知道差别是啥

1.2 AgentLego 是什么

AgentLego 是一个提供了多种开源工具 API 的多模态工具包,有个 AgentLego 算法库。
相当于某个api包,自己基于Lagent搞工具,相当于再封装api包。

1.3 两者的关系

在这里插入图片描述

1.4 环境配置

又搞了一个12.2的虚拟机,进去一愣,看来是挂载的存储没换,配置换了。这个很贴心👍
在这里插入图片描述
安装依赖略。

2. Lagent:轻量级智能体框架

用lmdeploy启动7b模型作为api server
在这里插入图片描述
启动lagent例子
在这里插入图片描述

ssh -CNg -L 7860:127.0.0.1:7860 root@ssh.intern-ai.org.cn -p 45263

本地观察
居然报错

  File "/root/agent/lagent/lagent/llms/lmdepoly_wrapper.py", line 422, in stream_chat
    resp += text['choices'][0]['text']
TypeError: string indices must be integers

在这里插入图片描述
参照https://zhuanlan.zhihu.com/p/692722440的笔记改改看看?主要是版本不同。

cd lagent && git checkout 581d9fb && pip install -e . && cd ..
cd agentlego && git checkout 7769e0d && pip install -e . && cd ..

没什么参考价值,摸索了下,打印错误debug。改模型ip,模型名称,OK?
在这里插入图片描述
没执行?换回原来的模型部署。
在这里插入图片描述
总算ok了。

3.2 Lagent 自定义工具完成测试

2.1 创建工具文件

Lagent 中关于工具部分的介绍文档位于 https://lagent.readthedocs.io/zh-cn/latest/tutorials/action.html
使用 Lagent 自定义工具主要分为以下几步:

  1. 继承 BaseAction 类 实现简单工具的 run 方法;
  2. 或者实现工具包内每个子工具的功能 简单工具的 run 方法可选被tool_api 装饰;
  3. 工具包内每个子工具的功能都需要被 tool_api 装饰
    看着其实和langchain里的比较像。至少@tool_api的使用差不多。
    /root/agent/lagent/lagent/actions/weather.py
import json
import os
import requests
from typing import Optional, Type

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):
    """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 = 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:
        """一个天气查询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 = 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.
        
        Args:
            results (dict): The weather content from QWeather API
                in 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_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()
        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 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()

2.2 获取 API KEY

这块略,基本都差不多。估计agent今后如果流行起来,应该可以搞个api代理服务,这样可以省掉一堆的api_key注册了,刚需。

2.3 体验自定义工具效果

记得修改internlm2_weather_web_demo.py里的模型ip为127.0.0.1:23333
在这里插入图片描述
显然示例代码没有langchain的简洁明了,虽然langchain封装的多,确实例子看起来简洁多了。不过debug应该容易一点。
看internlm2_weather_web_demo.py的代码,大体上 Internlm2Agent封装agent,Internlm2Protocol封装类似toolset。不过还是需要internlm2-chat-7b本身能够知道输入“请查询北京的天气”,会输出一个json指令,调用agent,然后将agent的结果返回。很多开源的模型function_call支持的很弱,有少数几个专门针对function_call做过增强,internlm2-chat-7b看起来还行,换提示词试试。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
看来微调定向性比较强,不够通用。

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

1. 直接使用 AgentLego

cd /root/agent
wget http://download.openmmlab.com/agentlego/road.jpg
conda activate agent
pip install openmim==0.3.9
mim install mmdet==3.3.0

/root/agent/direct_use.py

import re

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

执行结果
在这里插入图片描述

2 作为智能体工具使用

2.1 修改相关文件

/root/agent/agentlego/webui/modules/agents/lagent_agent.py 文件的第 105行位置,将 internlm2-chat-20b 修改为 internlm2-chat-7b

2.2 使用 LMDeploy 部署(同之前,略)
2.3 启动 AgentLego WebUI
conda activate agent
cd /root/agent/agentlego/webui
python one_click.py

操作比较复杂,1、配置agent,2、配置tools。3、回到chat,选tool中的 ObjectDetection,
上传图片,输入提示:请检测图中物体
在这里插入图片描述
粗略看了一下oneclick.py代码。gradio的界面比较特别,这个对于python程序员友好,对我这种前端码农很不友好。看起来gradio也不像jsp那样复杂,主打一个index.html页面,其它都是资源,路由忽略。内部还可以模块化,居然js,css也有hash。虽然是重复造轮子,但就是用户很多。还是得跟着市场走。

3. 用 AgentLego 自定义工具

AgentLego 构建自己的自定义工具文档
唉,其实还是基于langchain搞的。不过langchain版本这么多,不知道有些import的包过时禁用了没有😂
在这里插入图片描述
自定义工具类似:MagicMaker 是汇聚了优秀 AI 算法成果的免费 AI 视觉素材生成与创作平台。主要提供图像生成、图像编辑和视频生成三大核心功能,全面满足用户在各种应用场景下的视觉素材创作需求。

3.1 创建工具文件

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

import json
import requests

import numpy as np

from agentlego.types import Annotated, ImageIO, Info
from agentlego.utils import require
from .base import BaseTool


class 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 = 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}')

    def apply(self,
              keywords: Annotated[str,
                                  Info('A series of Chinese keywords separated by comma.')]
        ) -> ImageIO:
        import cv2
        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'}
        )
        image_url = response.json()['data']['imgUrl']
        image_response = requests.get(image_url)
        image = cv2.cvtColor(cv2.imdecode(np.frombuffer(image_response.content, np.uint8), cv2.IMREAD_COLOR),cv2.COLOR_BGR2RGB)
        return ImageIO(image)
3.2 注册新工具

修改 /root/agent/agentlego/agentlego/tools/init.py 文件
将 MagicMakerImageGeneration 通过 from .magicmaker_image_generation import MagicMakerImageGeneration 导入到了文件中,并且将其加入了 all 列表中。
在这里插入图片描述

3.3 体验自定义工具效果

类似上一节步骤,模型相同,
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
出图10秒。magicmaker.openxlab.org.cn看来和早起的stableDiffusion差不多。现在应该1-2秒出图比较合适。

比较顺利,AgentLego使用体验优于Lagent。这个更接近于今后做产品的交互。

4、Agent 工具能力微调

1. OpenAI Function Calling

在这里插入图片描述

1.2 数据格式

对话

messages = [
    {
        "role": "user",
        "content": "What's the weather like in San Francisco, Tokyo, and Paris?"
    }
]

工具描述

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    }
]

2. 基于 XTuner 的 Agent 工具能力微调

这块估计也是未来大模型的一个关键功能,目前常见的评测不包含function call能力。一般7B的指令跟随做的不够好,上面天气问题换一种说法就不太正常了。很有可能未来大模型那些基础评测本身不那么重要,反而是function call的指令跟随很重要。对于toB的企业,只要在系统提示里面将一些工具提示出来,后面就能正确提取参数调用工具返回,并能多回合重试的话,那个想象空间就很大了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值