开发者指南
418 字约 1 分钟
2025-02-04
本指南介绍如何开发和扩展 AgentFlow Sandbox。
扩展方式
AgentFlow 提供两种扩展方式:
1. 轻量级 API 工具
使用 @register_api_tool 装饰器注册简单的 API 工具:
from sandbox.server.backends.tools import register_api_tool
@register_api_tool("my_tool", config_key="my_config")
async def my_tool(query: str, **config) -> Dict[str, Any]:
api_key = config.get("api_key")
# 调用外部 API
return {"result": "..."}特点:
- ❌ 不需要继承任何类
- ❌ 不需要 Session 管理
- ✅ 配置从
apis.xxx自动注入 - ✅ 适合调用外部 API
2. 重量级 Backend
继承 Backend 基类创建复杂后端:
from sandbox.server.backends.base import Backend
from sandbox.server.core.decorators import tool
class MyBackend(Backend):
name = "my"
description = "My Custom Backend"
async def warmup(self) -> None:
# 预热资源
pass
async def initialize(self, worker_id: str, config: Dict) -> Dict:
# 创建 Session
return {"resource": ...}
@tool("my:action")
async def action(self, param: str, session_info: Dict) -> Dict:
return {"result": "..."}特点:
- ✅ 支持生命周期管理(warmup, shutdown, initialize, cleanup)
- ✅ 支持 Session 管理
- ✅ 适合需要持久状态的后端
Backend 类型
| 类型 | 方法 | 适用场景 | 示例 |
|---|---|---|---|
| 共享资源 | warmup(), shutdown() | 全局共享资源 | RAG |
| Session 资源 | initialize(), cleanup() | Worker 独立资源 | VM, Bash |
| 混合 | 全部四个 | 共享 + Session | Browser |
决策树
需要预热或 Session 吗?
│
├── 否 → 轻量级 API 工具
│ └── @register_api_tool
│
└── 是 → 重量级 Backend
│
│ 需要全局共享资源?
│
├── 是 → 实现 warmup() / shutdown()
│
└── 需要 Worker 独立资源?
│
└── 是 → 实现 initialize() / cleanup()快速参考
| 我要开发... | 选择 | 装饰器 | Session |
|---|---|---|---|
| 调用外部 API | 轻量级工具 | @register_api_tool | ❌ |
| 共享模型/连接池 | Backend + warmup | @tool | ❌ |
| 每用户独立实例 | Backend + initialize | @tool | ✅ |
| 混合模式 | Backend + 全部方法 | @tool | ✅ |