在本节中,我们将基于 AgentLego 构建自己的自定义工具。AgentLego 在这方面提供了极具吸引力的文档,文档地址为https://agentlego.readthedocs.io/zh-cn/latest/modules/tool。 html。自定义工具主要分为以下几个部分:
- 继承BaseTool类
- 修改default_desc属性(工具功能描述)
- 如果需要,重载设置方法(重型模块延迟加载)
- 重载apply方法(工具功能实现)
其中前二四步是必须的步骤。下面我们将实现一个调用 MagicMaker 的 API 以实现图像生成的工具。
MagicMaker是汇集了优秀AI算法成果的免费AI视觉素材生成与创作平台。主要提供图像生成、图像编辑和视频生成三大核心功能,全面满足用户在各种应用场景下的素材视觉创作需求。体验更多多功能可以访问Magic Maker。
1 创建工具文件
首先通过touch /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)
2 注册新工具
接下来修改 /root/agent/agentlego/agentlego/tools/__init__.py 文件,将我们的工具注册在工具列表中。如下所示,我们通过将 MagicMakerImageGeneration from .magicmaker_image_ Generation import MagicMakerImageGeneration 导入到了文件中,并将其加入了 __all__ 列表中。
3 体验自定义工具效果
同上一章节(三)类似,我们在两个终端中分别启动 LMDeploy 服务和 AgentLego 的 WebUI 来体验我们自定义的工具的效果。
启动 api-server
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
启动webui
conda activate agent
cd /root/agent/agentlego/webui
python one_click.py
并在本地执行如下操作以进行端口映射:
ssh -CNg -L 7860:127.0.0.1:7860 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p 你的 ssh 端口号
在工具界面选择MagicMakerImageGeneration后点击保存后,回到聊天页面选择MagicMakerImageGeneration工具后就可以开始使用了。为了确保调用工具的成功率,请在使用时确保这个工具启用。下图是一个例子。可以看到模型成功地调用了工具并得到了结果。