书生浦语第二期实战营——第六课_lagent & AgentLego

本文介绍了如何使用Lagent和AgentLego框架开发智能体,包括理论概念、工具定制、实战演练如调用外部API(如天气查询)和使用MMDetection进行目标检测,以及通过WebUI进行应用搭建。教程涵盖了从环境配置到部署和实际操作的详细步骤。
摘要由CSDN通过智能技术生成

第六课 lagent & AgentLego 智能体应用搭建

【第六节】: 【Lagent & AgentLego 智能体应用搭建】
1、Agent 理论及 Lagent&AgentLego 开源产品介绍
2、Lagent 调用已有 Arxiv 论文搜索工具实战
3、Lagent 新增自定义工具实战(以查询天气的工具为例)
4、AgentLego 新增 MagicMaker 文生图工具实战

1 课程笔记

1.1 大模型的局限性、时效性(今年)、可靠性()

什么是智能体?

  • 可以感知环境中的动态条件
  • 能采取动作影响环境
  • 能运用推理能力理解信息、解决问题、产生推断、决定动作。

Hayes Roth 1995

An Architecture for Adaptive Intelligent System

在这里插入图片描述

智能体包括哪些部分?

  • 大脑:控制器,接受信息采取动作。
  • 感知:对外部信息的感知和处理。音、视、图。
  • 动作:利用并执行工具。文本检索、API、控制机械。

在这里插入图片描述

智能体范式

在这里插入图片描述

在这里插入图片描述

解析任务,产生新的任务。递归?

在这里插入图片描述

任务拆分发送给worker,最后solver接受Planer和Worker的信息进行输出。

在这里插入图片描述

选择工具后执行,判断是否需要执行下一个工具。

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

2 实践

在这里插入图片描述

  1. 创建开发机。cuda12.2、30%开发机
  2. 创建工作目录。root/agent
  3. 创建虚拟环境
  4. 源码安装
    • git clone lagent pip
    • git clone agentlego
    • demo:git clone Tutorial
  5. 安装其他依赖

轻量级智能体框架

  1. 使用LMDeploy部署。(后台的服务)
  2. 启动lagent Web Demo。新建终端启动服务。
  3. ssh连接。(两个端口)
  4. 本地打开,填写模型ip(deploy服务)
  5. 插件配置:ArxivSearch

lagent自定义工具

步骤:

  1. 继承BaseAction
  2. 实现简单工具的run方法;或者每个工具包内的子功能
  3. 简单工具的run方法可以被tool_api装饰;工具包内每个子工具的功能都需要被tool_api装饰。

实践:调用和风天气api的工具(终止前面的两个服务)

  1. 创建文件weather.py
  2. 粘贴代码。
  3. 和风天气api。复制连接——粘贴——控制台——创建项目(免费订阅、web api、自定义key的名称)——项目管理——查看key
  4. 启动LMDeploy的服务。
  5. key的变量设置
  6. 启动天气服务的demo
  7. ssh服务映射
  8. 填写LMDeploy的ip地址和agent query名称
  9. 问答

AgentLego 组装智能体

AgentLego WebUI示例:

在这里插入图片描述

直接使用

  1. demo文件下载
  2. mmdet目标检测工具的安装。
  3. 创建目标检测文件direct_use.py
  4. 执行推理。运行direct_use.py

AgentLego WebUI 使用

  1. 修改模型。20B—>7B

  2. LMDeploy的部署。

  3. 启动agentlegoWebUI。one_click.py

  4. 两个服务启动后使用ssh连接到本地。

    1. 配置agent、agent class(LM2)、url、save to 、load

    2. 工具配置:新工具——目标检测——

    3. chat:工具选择——目标检测

    4. 上传图片、检测

服务启动后配置工具就是搭积木的过程

agentLego自定义工具

1、继承BaseTool类

2、修改default_desc属性(工具功能描述)

3、如有需要重载setup方法(重载模块延迟加载)

4、重载apply方法(工具功能实现)

实践:调用MagicMaker的api实现文生图。

  1. 新建工具文件——粘贴工具源码。
  2. __init__文件中注册工具。(导包、__all__列表)
  3. 启动deploy
  4. 启动one_click.py
  5. 本地使用
  6. webUI界面设置换上面一致。

3 作业

  1. 完成 Lagent Web Demo 使用,并在作业中上传截图。文档可见 Lagent Web Demo
  2. 完成 AgentLego 直接使用部分,并在作业中上传截图。文档可见 直接使用 AgentLego

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

基础配置

  1. 创建开发机。cuda12.2、30%开发机

  2. 创建工作目录。root/agent

      mkdir -p /root/agent
    
  3. 创建虚拟环境

    studio-conda -t agent -o pytorch-2.1.2
    

    在这里插入图片描述

  4. 源码安装

    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 ..
    
  5. 安装其他依赖

    pip install lmdeploy==0.3.0
    

    在这里插入图片描述

  6. Tutorial
    cd /root/agent
    git clone -b camp2 https://gitee.com/internlm/Tutorial.git
    

3.1 Lagent Web Demo

查技术报告

  1. 使用LMDeploy部署。(后台的服务)

    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
    

    在这里插入图片描述

  2. 启动lagent Web Demo。新建终端启动服务。

    conda activate agent
    cd /root/agent/lagent/examples
    streamlit run internlm2_agent_web_demo.py --server.address 127.0.0.1 --server.port 7860
    

    在这里插入图片描述

  3. ssh连接。(两个端口)

    ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p <port>
    

    在这里插入图片描述

  4. 本地打开,填写模型ip(deploy服务)

    http://localhost:7860/

  5. 插件配置:ArxivSearch。请帮我搜索 InternLM2 Technical Report 127.0.0.1:23333

    在这里插入图片描述

    在这里插入图片描述

3.2 AgentLego 直接使用

目标检测

  1. demo文件下载

    cd /root/agent
    wget http://download.openmmlab.com/agentlego/road.jpg
    
  2. mmdet目标检测工具的安装。目标检测工具是基于 mmdet (MMDetection) 算法库中的 RTMDet-Large 模型。

    # conda activate agent
    pip install openmim==0.3.9
    mim install mmdet==3.3.0
    
  3. 创建目标检测文件direct_use.pytouch /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)
    
  4. 执行推理。运行direct_use.py

    python /root/agent/direct_use.py

    在这里插入图片描述

3.3 AgentLego WebUI

目标检测WebUI

  1. 修改模型。20B—>7B

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

    2. model_name='internlm2-chat-7b'
      

      在这里插入图片描述

  2. LMDeploy的部署。

    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
    
  3. 启动agentlegoWebUI。one_click.py

    # conda activate agent
    cd /root/agent/agentlego/webui
    python one_click.py
    
  4. 两个服务启动后使用ssh连接到本地。

    ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p <服务器端口号>

    1. Agent 配置agent、agent class(LM2)、url(127.0.0.1:23333)、save to 、load

    2. Tools 配置:新工具——目标检测——

    3. chat 工具选择——目标检测

    4. 上传图片、检测请检测图中的物体

      在这里插入图片描述

      在这里插入图片描述

      在这里插入图片描述

      在这里插入图片描述

3.4 Lagent 或 AgentLego 实现自定义工具

天气查询

  1. 创建文件weather.py

    touch /root/agent/lagent/lagent/actions/weather.py

  2. 粘贴代码。

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

    在这里插入图片描述

  3. 和风天气api。复制连接——粘贴——控制台——创建项目(免费订阅、web api、自定义key的名称)——项目管理——查看key

    1. 链接: https://dev.qweather.com/docs/api/

      在这里插入图片描述

      在这里插入图片描述

      在这里插入图片描述

  4. 启动LMDeploy的服务。

    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
    
  5. key的变量设置

    export WEATHER_API_KEY=API KEY
    
  6. 启动天气服务的demo

    conda activate agent
    cd /root/agent/Tutorial/agent
    streamlit run internlm2_weather_web_demo.py --server.address 127.0.0.1 --server.port 7860
    
  7. ssh服务映射

    ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p <xxx端口号>
    
  8. 填写LMDeploy的ip地址和agent query名称 127.0.0.1:23333

  9. 问答。请帮我查询合肥的天气

    在这里插入图片描述

课程
【视频地址】:https://www.bilibili.com/video/BV1Xt4217728/
【课程文档】:https://github.com/InternLM/Tutorial/tree/camp2/agent
【课程作业】:https://github.com/InternLM/Tutorial/blob/camp2/agent/homework.md

  • 12
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值