backend-api-test-doc-tool-manager.md
3.98 KB
接口测试文档 — tool-manager
1. 模块概览
| 字段 | 值 |
|---|---|
| 模块名称 | tool-manager |
| 模块说明 | 工具管理器 — 注册/调用工具,支持分组、激活/停用、OpenAI兼容Schema |
| 路由前缀 | 无(非HTTP接口,Service组件) |
| 数据库表 | 无 |
| 外部依赖 | 无 |
2. 组件列表
| 序号 | 方法 | 说明 |
|---|---|---|
| 1 | register_tool(func, name, group, description) |
注册工具函数 |
| 2 | register(group) |
装饰器方式注册 |
| 3 | call_tool({"name": ..., "input": ...}) |
调用工具 |
| 4 | get_tool_schemas() |
获取激活工具的OpenAI兼容Schema |
| 5 | reset_equipped_tools(**groups) |
重置工具组激活状态 |
| 6 | groups |
工具组字典 |
3. 组件详细说明
3.1 工具注册
方式一:函数调用
tm.register_tool(get_weather, name="custom", group="admin", description="自定义描述")
方式二:装饰器
@tm.register(group="vision")
def analyze_image(image_url: str) -> str:
"""分析图片内容"""
...
规则:
-
basic组默认激活,其他组默认未激活 - 自动从函数签名生成
input_schema(OpenAI function calling 格式) - 自动提取 docstring 作为 description
3.2 工具调用
输入:
{"name": "add", "input": {"a": 1, "b": 2}}
输出:
- 成功:
{"result": 3} - 未注册:
{"error": "未注册..."} - 组未激活:
{"error": "未激活..."} - 执行异常:
{"error": "...boom..."}
3.3 Schema生成
格式:OpenAI function calling 兼容
{
"type": "function",
"function": {
"name": "search",
"description": "搜索知识库",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string"}, "limit": {"type": "integer"}},
"required": ["query"]
}
}
}
规则:仅返回激活组(默认basic)的工具Schema
3.4 分组管理
-
basic组默认存在且激活 -
reset_equipped_tools(basic=False, vision=True)切换激活组
4. 测试场景
4.1 工具注册
| 序号 | 场景名称 | 预期结果 |
|---|---|---|
| 1 | 函数注册 | 名称/description/group正确 |
| 2 | 自定义name/group/description | 覆盖默认值 |
| 3 | 装饰器注册 | group="vision"未激活, input_schema含参数 |
4.2 工具调用
| 序号 | 场景名称 | 预期结果 |
|---|---|---|
| 1 | 调用成功 | {"result": 3} |
| 2 | 工具未注册 | {"error": "未注册"} |
| 3 | 组未激活 | {"error": "未激活"} |
| 4 | 执行异常 | {"error": 含"boom"} |
4.3 Schema生成
| 序号 | 场景名称 | 预期结果 |
|---|---|---|
| 1 | 仅返回激活组 | 1个schema(basic组) |
| 2 | 空管理器 | [] |
| 3 | OpenAI兼容格式 | type/function/parameters结构正确 |
4.4 分组管理
| 序号 | 场景名称 | 预期结果 |
|---|---|---|
| 1 | 切换激活组 | reset后vision激活,basic停用 |
| 2 | 默认组 | basic存在且激活 |
5. 对应测试代码
测试文件:backend/tests/test_tool_manager.py
| 测试类 | 测试方法 | 对应场景 |
|---|---|---|
| TestToolManagerRegister | test_register_function | 4.1-1 |
| TestToolManagerRegister | test_register_with_custom_name_and_group | 4.1-2 |
| TestToolManagerRegister | test_register_decorator | 4.1-3 |
| TestToolManagerCall | test_call_tool_success | 4.2-1 |
| TestToolManagerCall | test_call_tool_not_found | 4.2-2 |
| TestToolManagerCall | test_call_tool_inactive_group | 4.2-3 |
| TestToolManagerCall | test_call_tool_execution_error | 4.2-4 |
| TestToolManagerSchemas | test_get_tool_schemas_only_active_groups | 4.3-1 |
| TestToolManagerSchemas | test_get_tool_schemas_empty | 4.3-2 |
| TestToolManagerSchemas | test_schema_format_openai_compatible | 4.3-3 |
| TestToolManagerGroups | test_reset_equipped_tools | 4.4-1 |
| TestToolManagerGroups | test_default_groups | 4.4-2 |