一:概述
Lagent是一个轻量级开源智能体框架,旨在让用户可以高效地构建基于大语言模型的智能体。Lagent不仅允许开发者使用Python语言编写智能体逻辑,还提供了一些典型工具来增强大语言模型的能力。通过Lagent,用户可以构建出功能强大的智能代理,应用于智能客服、智能办公、行业智能应用等多个场景。
它具有轻量级、高效推理引擎、多代理支持、易扩展性、可视化编辑的特点。
Lagent 目前已经支持了包括 AutoGPT、ReAct 等在内的多个经典智能体范式,也支持了如下工具:
它的基本结构如下图所示:
二:具体说明
<1>环境配置
1.1 开发机的创建,详细过程如下图所示:
1.2 然后打开创建好的开发机,配置Lagent环境
conda create -n agent_camp3 python=3.10 -y
# 激活环境
conda activate agent_camp3
# 安装 torch
conda install pytorch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 pytorch-cuda=12.1 -c pytorch -c nvidia -y
# 安装其他依赖包
pip install termcolor==2.4.0
pip install lmdeploy==0.5.2
通过源码安装的方式安装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 ..
pip install griffe==0.48.0
<2> Lagent Web Demo 使用
使用 Lagent 的 Web Demo 来体验 InternLM2.5-7B-Chat 的智能体能力。
首先,我们先使用 LMDeploy 部署 InternLM2.5-7B-Chat,并启动一个 API Server。
conda activate agent_camp3
lmdeploy serve api_server /share/new_models/Shanghai_AI_Laboratory/internlm2_5-7b-chat --model-name internlm2_5-7b-chat
接下来我们在另一个窗口中启动Lagent的Web Demo
在等待两个 server 都完全启动(如下图所示)后,我们在 本地 的 PowerShell 中输入如下指令来进行端口映射:
ssh -CNg -L 8501:127.0.0.1:8501 -L 23333:127.0.0.1:23333 root@ssh.intern-ai.org.cn -p <你的 SSH 端口号>
运行之后的效果如下所示,第一次跑你可能不太熟悉,然后这个端口号一定要修改好,要不然会报错,我就遇到了一个报错,报错如下所示:
ImportError: cannot import name 'AutoRegister' from 'class_registry' (/root/.conda/envs/agent_camp3/lib/python3.10/site-packages/class_registry/__init__.py)
Traceback:
File "/root/.conda/envs/agent_camp3/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/exec_code.py", line 88, in exec_func_with_error_handling
result = func()
File "/root/.conda/envs/agent_camp3/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 590, in code_to_exec
exec(code, module.__dict__)
File "/root/agent_camp3/lagent/examples/internlm2_agent_web_demo.py", line 8, in <module>
from lagent.actions import ActionExecutor, ArxivSearch, IPythonInterpreter
File "/root/agent_camp3/lagent/lagent/__init__.py", line 2, in <module>
from .actions import * # noqa: F401, F403
File "/root/agent_camp3/lagent/lagent/actions/__init__.py", line 3, in <module>
from .action_executor import ActionExecutor
File "/root/agent_camp3/lagent/lagent/actions/action_executor.py", line 4, in <module>
from .base_action import BaseAction
File "/root/agent_camp3/lagent/lagent/actions/base_action.py", line 14, in <module>
from class_registry import AutoRegister, ClassRegistry
<3>自定义Lagent智能体
使用 Lagent 自定义工具主要分为以下几步:
- 继承 类
BaseAction
- 实现简单工具的 方法;或者实现工具包内每个子工具的功能
run
- 简单工具的 方法可选被 装饰;工具包内每个子工具的功能都需要被 装饰
run
tool_api
tool_api
下面我们将实现一个调用 MagicMaker API 以完成文生图的功能。
首先,我们先来创建工具文件:
cd /root/agent_camp3/lagent
touch lagent/actions/magicmaker.py
然后,我们将下面的代码复制进入/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
- 在 的下一行添加
from lagent.actions import ActionExecutor, ArxivSearch, IPythonInterpreter
from lagent.actions.magicmaker import MagicMaker
- 在第27行添加 。
MagicMaker()
from lagent.actions import ActionExecutor, ArxivSearch, IPythonInterpreter
+ from lagent.actions.magicmaker import MagicMaker
from lagent.agents.internlm2_agent import INTERPRETER_CN, META_CN, PLUGIN_CN, Internlm2Agent, Internlm2Protocol
...
action_list = [
ArxivSearch(),
+ MagicMaker(),
]
接下来启动Web Demo来体验一下:
这个启动方式和上面一样。
注意生成的图片需要在浏览器复制访问。
发现两个请求都可以实现,可以一次选择多个插件。
下面再来几个提问:
发现这个结果并不太理想。
到此为止,这个自定义Lagent智能体就完成了!!