open插件:-OpenManus扩展开发:自定义工具与智能体实现 - # 使用asyncio
摘要
OpenManus的强大之处不仅在于其内置功能,更在于其良好的扩展性。通过自定义工具和智能体,开发者可以根据特定需求扩展OpenManus的功能。本文将详细介绍如何开发自定义工具和智能体,包括设计原则、实现方法、最佳实践和常见问题解决,帮助开发者充分利用OpenManus的扩展能力。
正文
1. 扩展开发概述
OpenManus采用模块化设计,允许开发者通过实现标准接口来扩展其功能。主要的扩展点包括:
自定义工具:扩展智能体的能力自定义智能体:实现特定领域的智能体自定义流程:实现复杂的多智能体协作模式
#mermaid-svg-n123LpMEyuML3Jhp {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-n123LpMEyuML3Jhp .error-icon{fill:#552222;}#mermaid-svg-n123LpMEyuML3Jhp .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-n123LpMEyuML3Jhp .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-n123LpMEyuML3Jhp .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-n123LpMEyuML3Jhp .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-n123LpMEyuML3Jhp .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-n123LpMEyuML3Jhp .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-n123LpMEyuML3Jhp .marker{fill:#333333;stroke:#333333;}#mermaid-svg-n123LpMEyuML3Jhp .marker.cross{stroke:#333333;}#mermaid-svg-n123LpMEyuML3Jhp svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-n123LpMEyuML3Jhp .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-n123LpMEyuML3Jhp .cluster-label text{fill:#333;}#mermaid-svg-n123LpMEyuML3Jhp .cluster-label span{color:#333;}#mermaid-svg-n123LpMEyuML3Jhp .label text,#mermaid-svg-n123LpMEyuML3Jhp span{fill:#333;color:#333;}#mermaid-svg-n123LpMEyuML3Jhp .node rect,#mermaid-svg-n123LpMEyuML3Jhp .node circle,#mermaid-svg-n123LpMEyuML3Jhp .node ellipse,#mermaid-svg-n123LpMEyuML3Jhp .node polygon,#mermaid-svg-n123LpMEyuML3Jhp .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-n123LpMEyuML3Jhp .node .label{text-align:center;}#mermaid-svg-n123LpMEyuML3Jhp .node.clickable{cursor:pointer;}#mermaid-svg-n123LpMEyuML3Jhp .arrowheadPath{fill:#333333;}#mermaid-svg-n123LpMEyuML3Jhp .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-n123LpMEyuML3Jhp .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-n123LpMEyuML3Jhp .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-n123LpMEyuML3Jhp .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-n123LpMEyuML3Jhp .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-n123LpMEyuML3Jhp .cluster text{fill:#333;}#mermaid-svg-n123LpMEyuML3Jhp .cluster span{color:#333;}#mermaid-svg-n123LpMEyuML3Jhp div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-n123LpMEyuML3Jhp :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}
扩展架构
OpenManus扩展点
自定义工具
自定义智能体
自定义流程
BaseTool子类
BaseAgent子类
BaseFlow子类
2. 自定义工具开发
2.1 工具基类介绍
所有OpenManus工具都继承自[BaseTool](file:///D:/project/OpenManus/app/tool/base.py#L8-L32)基类,该基类定义了工具的基本结构和接口:
from app.tool.base import BaseTool
from pydantic import BaseModel, Field
from typing import Any, Dict, Optional
class BaseTool(ABC, BaseModel):
name: str
description: str
parameters: Optional[dict] = None
async def __call__(self, **kwargs) ->Any:
"""Execute the tool with given parameters."""
return await self.execute(**kwargs)
@abstractmethod
async def execute(self, **kwargs) ->Any:
"""Execute the tool with given parameters."""
def to_param(self) ->Dict:
"""Convert tool to function call format."""
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.parameters,
},
}
2.2 创建简单工具示例
让我们创建一个简单的数学计算工具:
# app/tool/calculator.py
from app.tool.base import BaseTool
from typing import Union
class CalculatorTool(BaseTool):
"""一个简单的计算器工具,支持基本数学运算"""
name: str = "calculator"
description: str = "执行基本数学运算,包括加法、减法、乘法和除法"
parameters: dict = {
"type": "object",
"properties": {
"operation": {
"type": "string",
"description": "要执行的数学运算",
"enum": ["add", "subtract", "multiply", "divide"]
},
"a": {
"type": "number",
"description": "第一个操作数"
},
"b": {
"type": "number",
"description": "第二个操作数"
}
},
"required": ["operation", "a", "b"]
}
async def execute(
self,
operation: str,
a: Union[int, float],
b: Union[int, float]
) ->str:
"""执行数学运算"""
try:
if operation == "add":
result = a + b
elif operation == "subtract":
result = a - b
elif operation == "multiply":
result = a * b
elif operation == "divide":
if b == 0:
return "错误:除数不能为零"
result = a / b
else:
return f"错误:不支持的运算 '{operation}'"
return f"计算结果: {a} {self._get_operator_symbol(operation)} {b} = {result}"
except Exception as e:
return f"计算错误: {str(e)}"
def _get_operator_symbol(self, operation: str) ->str:
"""获取运算符符号"""
symbols = {
"add": "+",
"subtract": "-",
"multiply": "*",
"divide": "/"
}
return symbols.get(operation, "?")
2.3 创建复杂工具示例
创建一个与外部API交互的工具:
# app/tool/weather_api.py
import aiohttp
import json
from app.tool.base import BaseTool
from app.config import config
class WeatherAPITool(BaseTool):
"""获取天气信息的工具"""
name: str = "weather_api"
description: str = "获取指定城市的当前天气信息"
parameters: dict = {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "要查询天气的城市名称"
},
"country": {
"type": "string",
"description": "城市所在的国家代码(可选)",
"default": "CN"
}
},
"required": ["city"]
}
async def execute(self, city: str, country: str = "CN") ->str:
"""获取天气信息"""
try:
# 从配置中获取API密钥
api_key = config.llm.get("default", {}).get("api_key")
if not api_key:
return "错误:未配置API密钥"
# 构建API请求URL
url = f"http://api.openweathermap.org/data/2.5/weather"
params = {
"q": f"{city},{country}",
"appid": api_key,
"units": "metric",
"lang": "zh_cn"
}
# 发送HTTP请求
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as response:
if response.status == 200:
data = await response.json()
return self._format_weather_response(data)
else:
return f"API请求失败,状态码: {response.status}"
except Exception as e:
return f"获取天气信息时发生错误: {str(e)}"
def _format_weather_response(self, data: dict) ->str:
"""格式化天气响应数据"""
try:
city_name = data["name"]
country = data["sys"]["country"]
temp = data["main"]["temp"]
feels_like = data["main"]["feels_like"]
humidity = data["main"]["humidity"]
description = data["weather"][0]["description"]
return (f"城市: {city_name}, {country}\n"
f"当前温度: {temp}°C (体感温度: {feels_like}°C)\n"
f"天气状况: {description}\n"
f"湿度: {humidity}%")
except KeyError as e:
return f"天气数据格式错误: 缺少字段 {e}"
2.4 工具结果处理
使用[ToolResult](file:///D:/project/OpenManus/app/tool/base.py#L35-L80)类处理工具执行结果:
# app/tool/advanced_tool.py
from app.tool.base import BaseTool, ToolResult
import asyncio
class AdvancedTool(BaseTool):
"""展示高级工具结果处理的示例工具"""
name: str = "advanced_tool"
description: str = "一个展示高级结果处理的工具"
parameters: dict = {
"type": "object",
"properties": {
"task": {
"type": "string",
"description": "要执行的任务类型",
"enum": ["simple", "with_image", "with_error"]
}
},
"required": ["task"]
}
async def execute(self, task: str) ->ToolResult:
"""执行任务并返回结构化结果"""
try:
if task == "simple":
return ToolResult(
output="这是一个简单的任务结果",
)
elif task == "with_image":
# 模拟生成图像并返回base64编码
base64_image = self._generate_dummy_image()
return ToolResult(
output="任务完成,生成了图像",
base64_image=base64_image
)
elif task == "with_error":
return ToolResult(
error="这是一个模拟的错误信息"
)
else:
return ToolResult(
error=f"不支持的任务类型: {task}"
)
except Exception as e:
return ToolResult(
error=f"执行任务时发生错误: {str(e)}"
)
def _generate_dummy_image(self) ->str:
"""生成模拟的base64图像数据"""
# 这里应该实际生成图像并编码为base64
# 为演示目的,我们返回一个简短的模拟数据
return "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
3. 自定义智能体开发
3.1 智能体基类介绍
OpenManus中的智能体基于[BaseAgent](file:///D:/project/OpenManus/app/agent/base.py#L17-L196)类,该类提供了智能体的基本功能:
from app.agent.base import BaseAgent
from pydantic import Field
class BaseAgent(BaseModel, ABC):
# 核心属性
name: str = Field(..., description="Unique name of the agent")
description: Optional[str] = Field(None, description="Optional agent description")
# 提示词
system_prompt: Optional[str] = Field(
None, description="System-level instruction prompt"
)
next_step_prompt: Optional[str] = Field(
None, description="Prompt for determining next action"
)
# 依赖
llm: LLM = Field(default_factory=LLM, description="Language model instance")
memory: Memory = Field(default_factory=Memory, description="Agent's memory store")
state: AgentState = Field(
default=AgentState.IDLE, description="Current agent state"
)
3.2 创建专用智能体示例
创建一个专门用于处理数学问题的智能体:
# app/agent/math_solver.py
from app.agent.toolcall import ToolCallAgent
from app.tool.calculator import CalculatorTool
from app.tool import ToolCollection
from pydantic import Field
class MathSolverAgent(ToolCallAgent):
"""专门解决数学问题的智能体"""
name: str = "math_solver"
description: str = "一个专门用于解决数学问题的AI智能体"
system_prompt: str = """你是一个专业的数学问题解决助手。你的任务是:
1. 理解用户提出的数学问题
2. 将复杂问题分解为简单的步骤
3. 使用计算器工具执行必要的计算
4. 提供清晰、准确的解答过程和最终答案
请记住:
- 始终展示计算过程
- 确保计算的准确性
- 使用适当的小数位数
- 在需要时提供解释说明
"""
next_step_prompt: str = "请继续解决数学问题或提供最终答案。"
max_steps: int = 15
def __init__(self, **data):
super().__init__(**data)
# 添加数学计算工具
self.available_tools = ToolCollection(
CalculatorTool()
)
3.3 创建多工具智能体示例
创建一个功能更丰富的智能体:
# app/agent/personal_assistant.py
from app.agent.manus import Manus
from app.tool import (
WebSearch,
PythonExecute,
StrReplaceEditor,
AskHuman
)
from app.tool.weather_api import WeatherAPITool
from app.tool.calculator import CalculatorTool
class PersonalAssistantAgent(Manus):
"""个人助理智能体,集成多种工具"""
name: str = "personal_assistant"
description: str = "一个功能丰富的个人助理AI智能体"
system_prompt: str = """你是一个功能全面的个人助理。你可以:
1. 回答各种问题和提供信息
2. 执行网络搜索获取最新信息
3. 进行数学计算
4. 查询天气信息
5. 编写和编辑代码
6. 修改文件内容
7. 在需要时询问用户以获得更多信息
请根据用户需求选择合适的工具,并提供有用、准确的帮助。
"""
def __init__(self, **data):
super().__init__(**data)
# 添加额外的个人助理工具
self.available_tools.add_tools(
WeatherAPITool(),
CalculatorTool()
)
4. 工具集合管理
4.1 ToolCollection类
[ToolCollection](file:///D:/project/OpenManus/app/tool/tool_collection.py#L12-L71)类用于管理多个工具:
# app/tool/tool_collection.py
from app.tool.base import BaseTool, ToolResult, ToolFailure
class ToolCollection:
"""A collection of defined tools."""
def __init__(self, *tools: BaseTool):
self.tools = tools
self.tool_map = {tool.name: tool for tool in tools}
def add_tool(self, tool: BaseTool):
"""添加单个工具到集合中"""
if tool.name in self.tool_map:
print(f"警告: 工具 {tool.name} 已存在于集合中,跳过添加")
return self
self.tools += (tool,)
self.tool_map[tool.name] = tool
return self
def add_tools(self, *tools: BaseTool):
"""添加多个工具到集合中"""
for tool in tools:
self.add_tool(tool)
return self
async def execute(
self, *, name: str, tool_input: Dict[str, Any] = None
) ->ToolResult:
"""执行指定的工具"""
tool = self.tool_map.get(name)
if not tool:
return ToolFailure(error=f"工具 {name} 不存在")
try:
result = await tool(**tool_input)
return result
except Exception as e:
return ToolFailure(error=f"执行工具时出错: {str(e)}")
4.2 动态工具管理
实现动态添加和移除工具:
# app/tool/dynamic_tool_manager.py
from app.tool.tool_collection import ToolCollection
from app.tool.base import BaseTool
import importlib
import asyncio
class DynamicToolManager:
"""动态工具管理器,支持运行时添加/移除工具"""
def __init__(self):
self.tool_collection = ToolCollection()
self.loaded_modules = {}
async def load_tool_from_module(self, module_path: str, class_name: str) ->bool:
"""从模块动态加载工具"""
try:
# 检查模块是否已加载
if module_path in self.loaded_modules:
module = self.loaded_modules[module_path]
else:
# 动态导入模块
module = importlib.import_module(module_path)
self.loaded_modules[module_path] = module
# 获取工具类
tool_class = getattr(module, class_name)
# 创建工具实例
tool_instance = tool_class()
# 添加到工具集合
self.tool_collection.add_tool(tool_instance)
print(f"成功加载工具: {tool_instance.name}")
return True
except Exception as e:
print(f"加载工具失败 {module_path}.{class_name}: {e}")
return False
async def unload_tool(self, tool_name: str) ->bool:
"""卸载指定的工具"""
if tool_name in self.tool_collection.tool_map:
# 从工具映射中移除
del self.tool_collection.tool_map[tool_name]
# 从工具列表中移除
self.tool_collection.tools = tuple(
tool for tool in self.tool_collection.tools
if tool.name != tool_name
)
print(f"成功卸载工具: {tool_name}")
return True
else:
print(f"工具不存在: {tool_name}")
return False
def get_available_tools(self) ->list:
"""获取可用工具列表"""
return list(self.tool_collection.tool_map.keys())
async def execute_tool(self, tool_name: str, **kwargs) ->str:
"""执行指定的工具"""
result = await self.tool_collection.execute(
name=tool_name,
tool_input=kwargs
)
return str(result)
5. 集成自定义扩展
5.1 在智能体中使用自定义工具
# app/agent/custom_agent.py
from app.agent.toolcall import ToolCallAgent
from app.tool import ToolCollection
from app.tool.calculator import CalculatorTool
from app.tool.weather_api import WeatherAPITool 拼多多帮助力入口
class CustomAgent(ToolCallAgent):
"""使用自定义工具的智能体示例"""
name: str = "custom_agent"
description: str = "使用自定义工具的示例智能体"
system_prompt: str = """你是一个功能丰富的AI助手,可以:
1. 执行数学计算
2. 查询天气信息
3. 回答各种问题
"""
def __init__(self, **data):
super().__init__(**data)
# 初始化工具集合
self.available_tools = ToolCollection(
CalculatorTool(),
WeatherAPITool()
)
5.2 在Flow中使用自定义智能体
# app/flow/custom_flow.py
from app.flow.planning import PlanningFlow
from app.agent.custom_agent import CustomAgent
from app.agent.math_solver import MathSolverAgent
class CustomPlanningFlow(PlanningFlow):
"""使用自定义智能体的规划流程"""
def __init__(self, **data):
# 创建自定义智能体
agents = {
"general": CustomAgent(),
"math": MathSolverAgent()
}
super().__init__(agents=agents, **data)
# 设置执行器键
self.executor_keys = ["general", "math"]
6. 扩展开发最佳实践
6.1 错误处理
# app/tool/robust_tool.py
from app.tool.base import BaseTool, ToolResult
import asyncio
from tenacity import retry, stop_after_attempt, wait_exponential
class RobustTool(BaseTool):
"""展示健壮错误处理的工具示例"""
name: str = "robust_tool"
description: str = "一个具有健壮错误处理机制的工具"
parameters: dict = {
"type": "object",
"properties": {
"operation": {
"type": "string",
"description": "要执行的操作"
}
},
"required": ["operation"]
}
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=1, max=10)
)
async def execute(self, operation: str) ->ToolResult:
"""执行操作,包含重试机制"""
try:
# 模拟可能失败的操作
result = await self._perform_operation(operation)
return ToolResult(output=result)
except Exception as e:
# 记录错误日志
print(f"工具执行失败 (尝试 {self.execute.retry.statistics['attempt_number']}): {e}")
# 如果是最后一次尝试,返回错误结果
if self.execute.retry.statistics['attempt_number'] >= 3:
return ToolResult(error=f"操作失败,已重试3次: {str(e)}")
# 否则重新抛出异常以触发重试
raise
async def _perform_operation(self, operation: str) ->str:
"""执行具体操作"""
# 模拟网络请求或其他可能失败的操作
import random
if random.random() < 0.7: # 70%的概率失败
raise Exception("模拟操作失败")
return f"操作 '{operation}' 执行成功"
6.2 性能优化
# app/tool/optimized_tool.py
from app.tool.base import BaseTool
from functools import lru_cache
import asyncio
class OptimizedTool(BaseTool):
"""展示性能优化技巧的工具"""
name: str = "optimized_tool"
description: str = "一个经过性能优化的工具"
parameters: dict = {
"type": "object",
"properties": {
"data": {
"type": "string",
"description": "要处理的数据"
}
},
"required": ["data"]
}
def __init__(self, **data):
super().__init__(**data)
# 初始化缓存
self._expensive_operation_cache = {}
async def execute(self, data: str) ->str:
"""执行优化的操作"""
# 使用缓存避免重复计算
if data in self._expensive_operation_cache:
return f"缓存结果: {self._expensive_operation_cache[data]}"
# 执行耗时操作
result = await self._expensive_operation(data)
# 缓存结果
self._expensive_operation_cache[data] = result
return result
@lru_cache(maxsize=128)
def _cached_helper_function(self, input_data: str) ->str:
"""使用LRU缓存的辅助函数"""
# 模拟耗时计算
import time
time.sleep(0.1) # 模拟计算时间
return f"处理结果: {input_data.upper()}"
async def _expensive_operation(self, data: str) ->str:
"""模拟耗时操作"""
# 使用asyncio.sleep模拟异步操作
await asyncio.sleep(0.5)
# 使用缓存的辅助函数
result = self._cached_helper_function(data)
return f"完成处理: {result}"
6.3 配置管理
# app/tool/configurable_tool.py
from app.tool.base import BaseTool
from app.config import config
from pydantic import Field
class ConfigurableTool(BaseTool):
"""可配置的工具示例"""
name: str = "configurable_tool"
description: str = "一个可根据配置调整行为的工具"
parameters: dict = {
"type": "object",
"properties": {
"action": {
"type": "string",
"description": "要执行的操作"
}
},
"required": ["action"]
}
# 工具特定配置
timeout: int = Field(default=30, description="操作超时时间(秒)")
max_retries: int = Field(default=3, description="最大重试次数")
def __init__(self, **data):
super().__init__(**data)
# 从全局配置中读取工具特定设置
tool_config = config.llm.get("configurable_tool", {})
self.timeout = tool_config.get("timeout", self.timeout)
self.max_retries = tool_config.get("max_retries", self.max_retries)
async def execute(self, action: str) ->str:
"""执行可配置的操作"""
try:
# 使用配置的参数执行操作
result = await self._perform_action(action, timeout=self.timeout)
return result
except Exception as e:
return f"操作失败: {str(e)}"
async def _perform_action(self, action: str, timeout: int) ->str:
"""执行具体操作"""
# 这里实现具体的业务逻辑
import asyncio
await asyncio.sleep(min(timeout, 5)) # 模拟操作
return f"执行操作 '{action}' 完成,超时设置: {timeout}秒"
7. 测试自定义扩展
7.1 工具测试
# tests/test_calculator_tool.py
import pytest
import asyncio
from app.tool.calculator import CalculatorTool
@pytest.fixture
def calculator_tool():
return CalculatorTool()
@pytest.mark.asyncio
async def test_calculator_add(calculator_tool):
result = await calculator_tool.execute("add", 5, 3)
assert "计算结果: 5 + 3 = 8" in result
@pytest.mark.asyncio
async def test_calculator_divide_by_zero(calculator_tool):
result = await calculator_tool.execute("divide", 10, 0)
assert "错误:除数不能为零" in result
@pytest.mark.asyncio
async def test_calculator_invalid_operation(calculator_tool):
result = await calculator_tool.execute("power", 2, 3)
assert "错误:不支持的运算" in result
7.2 智能体测试
# tests/test_custom_agent.py
import pytest
from app.agent.custom_agent import CustomAgent
@pytest.fixture
async def custom_agent():
agent = CustomAgent()
yield agent
await agent.cleanup()
@pytest.mark.asyncio
async def test_custom_agent_initialization(custom_agent):
assert custom_agent.name == "custom_agent"
assert len(custom_agent.available_tools.tools) >= 2 # 至少包含计算器和天气工具
@pytest.mark.asyncio
async def test_custom_agent_run(custom_agent):
# 简单测试智能体是否能运行
result = await custom_agent.run("你好,这是一个测试")
assert isinstance(result, str)
8. 扩展部署和分发
8.1 创建扩展包
# setup.py - 扩展包配置
from setuptools import setup, find_packages
setup(
name="openmanus-extensions",
version="1.0.0",
description="OpenManus自定义扩展包",
packages=find_packages(),
install_requires=[
"openmanus>=1.0.0",
"aiohttp>=3.8.0",
# 其他依赖
],
entry_points={
'openmanus.tools': [
'calculator = app.tool.calculator:CalculatorTool',
'weather_api = app.tool.weather_api:WeatherAPITool',
],
'openmanus.agents': [
'math_solver = app.agent.math_solver:MathSolverAgent',
'personal_assistant = app.agent.personal_assistant:PersonalAssistantAgent',
]
}
)
8.2 插件系统实现
# app/plugin_manager.py
import pkg_resources
from app.tool.base import BaseTool
from app.agent.base import BaseAgent
class PluginManager:
"""插件管理器,支持动态加载扩展"""
def __init__(self):
self.tools = {}
self.agents = {}
def load_plugins(self):
"""加载所有已安装的插件"""
# 加载工具插件
for entry_point in pkg_resources.iter_entry_points('openmanus.tools'):
try:
tool_class = entry_point.load()
tool_instance = tool_class()
self.tools[tool_instance.name] = tool_instance
print(f"加载工具插件: {tool_instance.name}")
except Exception as e:
print(f"加载工具插件失败 {entry_point.name}: {e}")
# 加载智能体插件
for entry_point in pkg_resources.iter_entry_points('openmanus.agents'):
try:
agent_class = entry_point.load()
agent_instance = agent_class()
self.agents[agent_instance.name] = agent_instance
print(f"加载智能体插件: {agent_instance.name}")
except Exception as e:
print(f"加载智能体插件失败 {entry_point.name}: {e}")
def get_tool(self, name: str) ->BaseTool:
"""获取指定名称的工具"""
return self.tools.get(name)
def get_agent(self, name: str) ->BaseAgent:
"""获取指定名称的智能体"""
return self.agents.get(name)
def list_tools(self) ->list:
"""列出所有可用工具"""
return list(self.tools.keys())
def list_agents(self) ->list:
"""列出所有可用智能体"""
return list(self.agents.keys())
总结
OpenManus的扩展开发机制为开发者提供了强大的自定义能力,主要特点包括:
标准化接口:通过继承基类实现标准化的扩展接口灵活的参数定义:使用JSON Schema定义工具参数,支持复杂数据类型完善的错误处理:提供ToolResult类统一处理成功和失败情况良好的异步支持:全面支持异步操作,提高并发性能易于测试:模块化设计便于单元测试和集成测试
通过合理使用这些扩展机制,开发者可以:
定制专用工具:针对特定领域开发专业工具构建领域智能体:实现专门处理特定任务的智能体设计复杂流程:实现多智能体协作的复杂业务流程优化系统性能:通过缓存、异步等技术优化扩展组件性能
实践建议
遵循设计原则:严格按照基类接口要求实现扩展组件完善错误处理:为所有可能的错误情况提供适当的处理机制注重性能优化:对耗时操作使用异步或缓存技术加强测试覆盖:为自定义组件编写充分的测试用例文档化接口:清晰描述自定义组件的使用方法和参数说明安全编码:对输入参数进行验证,避免安全漏洞
参考资料
OpenManus GitHub仓库Pydantic文档Python异步编程指南JSON Schema规范软件设计模式,open插件