【书生3.2】Lagent 自定义你的 Agent 智能体

1 环境准备

直接复用之前的xtuner或者llamaindex环境

# 安装其他依赖包
conda activate llamainde
pip install termcolor==2.4.0
pip install lmdeploy==0.5.2

pip install griffe==0.48 # 重要

2 启动模型

# 这里我使用的是早前下载的internlm2-chat-7b
conda activate llamainde
lmdeploy serve api_server /project/serve/xtuner/Shanghai_AI_Laboratory/internlm2-chat-7b --model-name internlm2-chat-7b

3 部署lagent

另启动一个窗口

# 创建目录以存放代码
mkdir -p /project/serve/camp3
cd /project/serve/camp3
git clone https://github.com/InternLM/lagent.git
cd lagent && git checkout 81e7ace && pip install -e . && cd ..

cd /project/serve/camp3/lagent
conda activate llamaindex
streamlit run examples/internlm2_agent_web_demo.py

4 可视化页面及配置

注意模型ip不要带http

这里用的internlm2-chat-7b, 使用工具的效果不是很直接,它会再询问一下。

在这里插入图片描述

5 自定义工具的智能体

(base) [root@localhost ~]# cd /project/serve/camp3/lagent/
(base) [root@localhost lagent]# touch lagent/actions/magicmaker.py
(base) [root@localhost lagent]# vim lagent/actions/magicmaker.py 
(base) [root@localhost lagent]# vim examples/internlm2_agent_web_demo.py 
(base) [root@localhost lagent]# 


#magicmaker.py
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}

  1. 创建magicmaker.py文件

  2. 修改 /root/agent_camp3/lagent/examples/internlm2_agent_web_demo.py 来适配我们的自定义工具。

    1. from lagent.actions import ActionExecutor, ArxivSearch, IPythonInterpreter 的下一行添加 from lagent.actions.magicmaker import MagicMaker
    2. 在第27行添加 MagicMaker()
  3. 重新启动**streamlit run examples/internlm2_agent_web_demo.py

这里与教程不一样的是,图片并没有直接展示出来,要点击才能查看

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

bug

ModuleNotFoundError: No module named 'griffe.enumerations

在这里插入图片描述

pip install griffe==0.48
### 如何将 Agent 部署到 Hugging Face 平台 为了成功地将 Agent 部署至 Hugging Face 平台,需遵循一系列特定的操作指南。Hugging Face 提供了一个名为 Spaces 的功能,允许用户轻松部署应用程序并共享给他人[^2]。 #### 创建 Hugging Face 账户和仓库 首先,在[Hugging Face 官方网站](https://huggingface.co/)注册账号,并创建一个新的 Repository 来存储即将上传的应用程序代码及相关资源文件。 #### 准备环境与依赖项配置 确保本地环境中已安装 Git 及 Python 解释器。接着克隆刚刚建立好的远程仓库到本地计算机上: ```bash git clone https://huggingface.co/spaces/<your_username>/<repo_name> cd spaces/<your_username>/<repo_name> ``` 编辑 `requirements.txt` 文件来指定项目所需的Python包版本号,这有助于保持不同运行环境下的一致性和稳定性。 #### 编写应用逻辑代码 编写或调整现有的Agent脚本使其能够独立工作于云服务器之上。对于基于Web的服务端口监听部分,建议采用 Flask 或 FastAPI 这样的轻量级框架构建RESTful API接口服务;而对于前端展示页面,则可通过集成Gradio组件快速搭建交互式的图形化操作面板[^4]。 #### 测试本地实例 在推送任何更改之前务必先验证整个系统的正常运作情况。启动虚拟环境后执行以下命令开启调试模式下的HTTP服务器进程: ```bash pip install -r requirements.txt python app.py # 假设主入口函数位于此文件内 ``` 打开浏览器访问 http://localhost:7860 地址确认一切按预期响应无误后再继续下一步骤。 #### 推送更新至远端分支 当所有准备工作都完成后就可以准备同步最新的改动记录回线上空间里去了。记得每次修改完都要及时提交变更日志以便追踪历史版本间的差异变化趋势。 ```bash git add . git commit -m "Initial deployment setup" git push origin main ``` 此时应该可以在个人主页看到新发布的Space条目链接指向刚才所设置的内容了。 #### 发布后的维护事项 发布之后还需要定期关注评论区反馈意见积极改进产品体验质量。另外也要留意官方公告通知有关政策变动可能会影响到现有架构设计的地方提前做好应对措施安排。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PythonJavaC++go

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值