- 闯关任务:使用 Lagent 自定义一个智能体,并使用 Lagent Web Demo 成功部署与调用。
1.Lagent介绍
Lagent 是一个轻量级开源智能体框架,旨在让用户可以高效地构建基于大语言模型的智能体。同时它也提供了一些典型工具以增强大语言模型的能力。
其中,Action动作,也被称为工具,提供了一套LLM驱动的智能体用来与真实世界交互并执行复杂任务的函数。有两种类型的工具:(1)简单工具: 只提供一个API接口供调用;(2)工具包: 实现多个API接口,承担不同的子任务。Lagent 目前已经支持支持如下工具:
- Arxiv 搜索
- Bing 地图
- Google 学术搜索
- Google 搜索
- 交互式 IPython 解释器
- IPython 解释器
- PPT
- Python 解释器
2.Lagent自定义智能体实践
首先,建立相应的虚拟环境,安装对应依赖包,通过源码安装的方式安装 lagent:
mkdir -p /root/agent_camp3
cd /root/agent_camp3
git clone https://github.com/InternLM/lagent.git
cd lagent && git checkout 81e7ace && pip install -e . && cd ..
接下来,将使用 Lagent 的 Web Demo 来体验 InternLM2.5-7B-Chat 的智能体能力。首先,先使用 LMDeploy(后端推理框架) 部署 InternLM2.5-7B-Chat,并启动一个 API Server:
lmdeploy serve api_server /share/new_models/Shanghai_AI_Laboratory/internlm2_5-7b-chat --model-name internlm2_5-7b-chat
然后,在另一个窗口中启动 Lagent 的 Web Demo:
cd /root/agent_camp3/lagent
conda activate agent_camp3
streamlit run examples/internlm2_agent_web_demo.py
等待两个 server 都完全启动后,进行端口映射,在网页中打开Web Demo,并修改模型名称一栏为 internlm2_5-7b-chat
,修改模型 ip一栏为127.0.0.1:23333,调用该模型已启动的API。
在插件选择一栏选择 ArxivSearch
,并输入指令“帮我搜索一下 MindSearch 论文”:
接下来,基于 Lagent 自定义自己的智能体。使用 Lagent 自定义工具主要分为以下几步:
- 继承
BaseAction
类 - 实现简单工具的
run
方法;或者实现工具包内每个子工具的功能 - 简单工具的
run
方法可选被tool_api
装饰;工具包内每个子工具的功能都需要被tool_api
装饰
下面将实现一个调用 MagicMaker API 以完成文生图的功能,首先先创建工具文件/root/agent_camp3/lagent/lagent/actions/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}
最后,修改 /root/agent_camp3/lagent/examples/internlm2_agent_web_demo.py
来适配我们的自定义工具。重新启动 Web Demo,选择两个工具,输入“请帮我生成一幅山水画”:
再次输入“帮我搜索一下 MindSearch 论文”:
依然能够正常调用与对话。