DeerFlow 2.0 深度拆解:字节跳动开源 Super Agent 框架——从 Lead Agent 架构到 Docker 沙箱的生产级实战指南(2026)
2026年2月28日,DeerFlow 2.0 正式发布,迅速登顶 GitHub Trending 榜首。截至2026年8月,该项目已收获超过 50,000 颗星,Fork 数超过 6,000。这不是又一款「聊天机器人框架」,而是一个真正能干活的 Super Agent 执行底座——拥有文件系统、Docker 沙箱、长期记忆系统,可自主规划任务并调度多个子 Agent 并行工作。本文从架构原理到生产部署,深度拆解 DeerFlow 2.0 的每一个核心组件。
一、为什么 DeerFlow 值得关注?
1.1 字节跳动的工程底蕴
DeerFlow 由字节跳动技术团队打造,经历了字节内部真实业务场景的验证。这不是一个「周末项目」,而是从 2025 年 5 月首次开源 DeerFlow 1.0 后,经过近一年的社区反馈和持续迭代,于 2026 年 2 月发布彻底重写的 2.0 版本——与 v1 没有共用代码,标志着项目从「研究工具」向「超级智能体执行底座」的战略转型。
字节跳动在推荐系统、内容理解、大规模分布式系统等领域的工程能力毋庸置疑。DeerFlow 继承了这种工程基因:代码质量高、架构设计优雅、文档完善、社区活跃。更重要的是,它采用 MIT 协议开源,允许商业用途,这在「大厂开源」项目中并不多见。
1.2 真正隔离执行——Docker 沙箱是安全护城河
绝大多数 Agent 框架(包括 LangChain、AutoGPT)在执行代码时,要么依赖本地 Python 解释器(安全风险高),要么完全不支持代码执行(能力受限)。DeerFlow 的核心创新之一是引入了 Docker 沙箱执行环境:
- 隔离性:每个任务在独立容器中运行,宿主系统完全隔离
- 持久化:文件系统可挂载,任务结果可跨会话保持
- 安全性:网络访问、资源使用可精确控制
- 可扩展:支持自定义镜像,预装特定工具链
这意味着你可以放心让 Agent 执行 rm -rf、安装任意包、调用外部 API,而不必担心「删库跑路」。
1.3 Super Agent vs ChatBot:范式跃迁
传统聊天机器人的工作模式是:用户提问 → 模型生成回答 → 对话结束。这种方式适合简单问答,但面对复杂任务(如「调研竞争对手产品并生成分析报告」)时,模型只能给出泛泛而谈的建议,无法真正「干活」。
Super Agent 的核心差异在于:
| 能力维度 | ChatBot | Super Agent |
|---|---|---|
| 任务执行 | 只能建议,不能执行 | 自主规划、调用工具、执行任务 |
| 时间跨度 | 单次对话,无持久状态 | 支持小时级长时任务 |
| 资源访问 | 无文件系统、无执行环境 | 完整文件系统、沙箱执行 |
| 记忆能力 | 上下文窗口限制,无长期记忆 | 长/短期记忆系统,跨会话保持 |
| 并行能力 | 串行对话 | 多子 Agent 并行调度 |
DeerFlow 2.0 正是朝着 Super Agent 方向演进:从「深度研究框架」升级为「可处理长时程复杂任务的超级智能体执行底座」。
二、核心架构:Lead Agent + Sub-Agents + 沙箱执行
DeerFlow 2.0 的架构可以用一张图概括:
┌─────────────────────────────────────────────────────────────┐
│ 用户交互层 │
│ (Web UI / CLI / API) │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Lead Agent │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Planning │ │ Memory │ │ Tool Use │ │ Skill │ │
│ │ Engine │ │ System │ │ Manager │ │ Loader │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌─────────────────┼─────────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Sub-Agent 1 │ │ Sub-Agent 2 │ │ Sub-Agent N │
│ (Research) │ │ (Code Gen) │ │ (Deploy) │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
└─────────────────┼─────────────────┘
▼
┌─────────────────────────────────────────────────────────────┐
│ AIO Sandbox (Docker) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Browser │ │ Shell │ │ File │ │ MCP │ │
│ │ (Playwright)│ │ (Bash) │ │ System │ │ Server │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
└─────────────────────────────────────────────────────────────┘
2.1 Lead Agent:大脑中枢
Lead Agent 是 DeerFlow 的「大脑」,负责:
- 任务理解与规划:解析用户意图,拆解为子任务
- 子 Agent 调度:根据任务类型,动态生成子 Agent 并分配工作
- 结果整合:收集各子 Agent 的输出,合成最终结果
- 记忆管理:维护长短期记忆,跨会话保持上下文
Lead Agent 基于 LangGraph 1.0 构建,这是一个专门用于构建 Agent 工作流的状态机框架。相比传统的「工具调用循环」,LangGraph 提供了更精确的控制流:
from langgraph.graph import StateGraph, END
# 定义状态
class AgentState(TypedDict):
messages: List[BaseMessage]
tasks: List[Task]
results: Dict[str, Any]
memory: MemorySnapshot
# 构建工作流图
workflow = StateGraph(AgentState)
# 添加节点
workflow.add_node("understand", understand_intent)
workflow.add_node("plan", plan_tasks)
workflow.add_node("dispatch", dispatch_subagents)
workflow.add_node("aggregate", aggregate_results)
workflow.add_node("respond", generate_response)
# 定义边(控制流)
workflow.add_edge("understand", "plan")
workflow.add_edge("plan", "dispatch")
workflow.add_edge("dispatch", "aggregate")
workflow.add_edge("aggregate", "respond")
workflow.add_edge("respond", END)
# 条件分支
workflow.add_conditional_edges(
"dispatch",
should_continue,
{
"continue": "dispatch", # 继续等待子 Agent
"aggregate": "aggregate" # 所有子 Agent 完成
}
)
LangGraph 的优势在于:
- 可视化调试:工作流图可导出为 Mermaid/图片,便于理解
- 断点续传:支持 checkpoint,长时间任务可中断后恢复
- 条件分支:基于状态的动态路由,而非硬编码 if-else
- 并行执行:原生支持节点并行,提升效率
2.2 Sub-Agents:并行执行引擎
复杂任务很少能一次完成。DeerFlow 可以将任务分解,动态生成多个子 Agent 并行执行。每个子 Agent 有独立的:
- 工作目录:在沙箱中隔离
- 上下文窗口:不会被其他任务污染
- 工具集:按需加载,减少 token 消耗
- 生命周期:任务完成后自动销毁
典型的子 Agent 类型:
| Sub-Agent 类型 | 职责 | 典型工具 |
|---|---|---|
| Research Agent | 信息检索、网页抓取 | Browser, Search API, PDF Parser |
| Code Agent | 代码生成、调试 | Shell, File System, Linter |
| Data Agent | 数据分析、可视化 | Python Runtime, Pandas, Matplotlib |
| Deploy Agent | 服务部署、配置管理 | Docker CLI, Kubectl, Terraform |
并行调度示例:
用户任务:「调研竞争对手产品并生成分析报告」
Lead Agent 的规划:
Task: "调研竞争对手产品并生成分析报告"
├─ Sub-Agent 1: "收集竞争对手 A 的产品信息"
│ └─ Tools: Browser, Search API
├─ Sub-Agent 2: "收集竞争对手 B 的产品信息"
│ └─ Tools: Browser, Search API
├─ Sub-Agent 3: "收集竞争对手 C 的产品信息"
│ └─ Tools: Browser, Search API
└─ Sub-Agent 4: "整合分析并生成报告"
└─ Tools: File System, Markdown Generator
三个调研子 Agent 可并行执行,效率提升 3-5 倍。
2.3 AIO Sandbox:All-in-One 沙箱执行环境
DeerFlow 推荐使用 AIO Sandbox,这是一个将 Browser、Shell、File、MCP 和 VSCode Server 整合在单个 Docker 容器中的执行环境。
核心特性:
- 隔离性(Isolated):容器级别的完整隔离,宿主系统不受影响
- 安全性(Safe):网络访问、资源使用可精确限制
- 持久化(Persistent):文件系统可挂载到宿主,任务结果跨会话保持
- 可挂载(Mountable FS):支持 Volume 映射,便于数据交换
- 长时间运行(Long-running):支持小时级任务,不超时
沙箱配置示例:
# docker-compose.sandbox.yml
version: '3.8'
services:
sandbox:
image: agentinfra/sandbox:latest
container_name: deerflow-sandbox
ports:
- "8080:8080" # Web UI
- "8443:8443" # VSCode Server
volumes:
- ./workspace:/workspace # 持久化工作目录
- ./skills:/mnt/skills # 技能库
environment:
- SANDBOX_MEMORY_LIMIT=4G
- SANDBOX_CPU_LIMIT=2
- SANDBOX_NETWORK=restricted # 限制网络访问
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
cap_add:
- CHOWN
- SETUID
- SETGID
沙箱内的能力矩阵:
| 能力 | 实现方式 | 用途 |
|---|---|---|
| Browser | Playwright | 网页抓取、自动化测试 |
| Shell | Bash + 常用 CLI | 命令执行、包管理 |
| File System | POSIX 文件操作 | 读写文件、项目构建 |
| MCP Server | WebSocket/stdio | 工具协议对接 |
| VSCode Server | code-server | 实时代码查看/编辑 |
三、技能系统(Skills):可插拔的能力模块
DeerFlow 的核心创新之一是技能系统。每个技能是一个结构化的能力模块,包含工作流程、最佳实践和相关资源引用。
3.1 技能文件结构
一个典型的技能目录:
/mnt/skills/public/
├── deep-search/
│ └── SKILL.md
├── report-generation/
│ └── SKILL.md
├── slide-creation/
│ └── SKILL.md
├── web-page/
│ └── SKILL.md
├── deploy/
│ ├── SKILL.md
│ └── scripts/
│ └── deploy.sh
└── biotech/
└── SKILL.md
SKILL.md 格式:
# Deep Search Skill
## Description
Perform comprehensive web search with multi-source aggregation.
## Capabilities
- Multi-engine search (Google, Bing, DuckDuckGo)
- PDF/DOCX content extraction
- Duplicate removal and ranking
## Workflow
1. Parse search query
2. Execute parallel searches
3. Aggregate and deduplicate results
4. Extract key information
5. Generate summary report
## Tools Required
- browser
- search-api
- pdf-parser
## Examples
### Example 1: Research AI Trends
User: "Research the latest AI agent frameworks in 2026"
Output: Comprehensive report with citations
## Best Practices
- Always verify sources
- Prefer official documentation
- Include publication dates
3.2 技能按需加载
DeerFlow 的技能系统采用渐进式加载:只有当任务需要某项技能时,才会加载对应的 SKILL.md。这对 Token 敏感的模型非常友好:
class SkillLoader:
def __init__(self, skill_dir: str = "/mnt/skills/public"):
self.skill_dir = skill_dir
self.loaded_skills: Dict[str, Skill] = {}
def load_skill(self, skill_name: str) -> Skill:
"""按需加载技能"""
if skill_name in self.loaded_skills:
return self.loaded_skills[skill_name]
skill_path = f"{self.skill_dir}/{skill_name}/SKILL.md"
if not os.path.exists(skill_path):
raise SkillNotFoundError(f"Skill {skill_name} not found")
skill = self._parse_skill(skill_path)
self.loaded_skills[skill_name] = skill
return skill
def unload_skill(self, skill_name: str):
"""卸载不需要的技能,释放上下文"""
if skill_name in self.loaded_skills:
del self.loaded_skills[skill_name]
3.3 内置技能一览
| 技能名称 | 功能描述 | 适用场景 |
|---|---|---|
| deep-search | 多源聚合深度搜索 | 竞品调研、技术选型 |
| report-generation | 结构化报告生成 | 分析报告、周报月报 |
| slide-creation | PPT 自动生成 | 方案汇报、培训材料 |
| web-page | 网页生成与部署 | 落地页、文档站 |
| image-generation | AI 图片/视频生成 | 营销素材、原型设计 |
| deploy | 服务部署与配置 | CI/CD、环境搭建 |
3.4 自定义技能开发
创建自定义技能只需编写 SKILL.md:
# My Custom Skill: Sentiment Analysis
## Description
Analyze sentiment of customer reviews using NLP.
## Workflow
1. Collect reviews from specified source
2. Preprocess text (clean, tokenize)
3. Run sentiment model
4. Aggregate results and generate insights
## Tools Required
- python-runtime
- transformers-library
- pandas
## Code Template
\`\`\`python
from transformers import pipeline
def analyze_sentiment(texts: List[str]) -> List[dict]:
classifier = pipeline("sentiment-analysis")
results = classifier(texts)
return results
\`\`\`
## Examples
### Example 1: E-commerce Reviews
Input: List of product reviews
Output: Sentiment distribution + key themes
将 SKILL.md 放入 /mnt/skills/custom/sentiment-analysis/,DeerFlow 会自动识别并加载。
四、记忆系统:长短期记忆的工程实现
DeerFlow 2.0 引入了长短期记忆系统,解决传统 Agent 「上下文窗口限制」和「跨会话遗忘」两大痛点。
4.1 记忆系统架构
┌─────────────────────────────────────────────────────────────┐
│ Memory System │
├─────────────────────────────────────────────────────────────┤
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ Short-term │ │ Long-term │ │
│ │ Memory │ │ Memory │ │
│ │ (In-context) │ │ (Vector Store) │ │
│ └──────────────────┘ └──────────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ Working Memory │ │ Episodic Memory │ │
│ │ (Last N turns) │ │ (Session logs) │ │
│ └──────────────────┘ └──────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────┐ │
│ │ Semantic Memory │ │
│ │ (Knowledge base)│ │
│ └──────────────────┘ │
└─────────────────────────────────────────────────────────────┘
4.2 短期记忆(Short-term Memory)
短期记忆即工作记忆,保存当前对话的最近 N 轮交互:
class ShortTermMemory:
def __init__(self, max_turns: int = 10):
self.max_turns = max_turns
self.turns: deque[Turn] = deque(maxlen=max_turns)
def add_turn(self, user_input: str, agent_response: str,
tools_used: List[str] = None):
"""添加一轮对话"""
turn = Turn(
timestamp=datetime.now(),
user_input=user_input,
agent_response=agent_response,
tools_used=tools_used or [],
metadata={
"token_count": len(user_input) + len(agent_response),
"intent": self._classify_intent(user_input)
}
)
self.turns.append(turn)
def get_context(self) -> str:
"""获取上下文摘要"""
context_parts = []
for turn in self.turns:
context_parts.append(f"User: {turn.user_input}")
context_parts.append(f"Agent: {turn.agent_response[:200]}...")
return "\n".join(context_parts)
def summarize(self) -> str:
"""压缩短期记忆(当接近窗口限制时)"""
# 使用 LLM 生成摘要
summary = self.llm.summarize(self.get_context())
return summary
4.3 长期记忆(Long-term Memory)
长期记忆使用向量数据库存储,支持语义检索:
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings
class LongTermMemory:
def __init__(self, persist_dir: str = "./memory/chroma"):
self.embeddings = OpenAIEmbeddings()
self.vectorstore = Chroma(
embedding_function=self.embeddings,
persist_directory=persist_dir
)
def store_episode(self, session_id: str, task: str,
result: str, metadata: dict = None):
"""存储一次任务执行记录"""
document = f"Task: {task}\nResult: {result}"
self.vectorstore.add_texts(
texts=[document],
metadatas=[{
"session_id": session_id,
"timestamp": datetime.now().isoformat(),
**(metadata or {})
}]
)
def recall(self, query: str, k: int = 5) -> List[dict]:
"""语义检索相关记忆"""
results = self.vectorstore.similarity_search(query, k=k)
return [
{
"content": doc.page_content,
"metadata": doc.metadata,
"score": doc.metadata.get("score", 0)
}
for doc in results
]
def forget(self, session_id: str):
"""删除指定会话的记忆"""
self.vectorstore.delete(
filter={"session_id": session_id}
)
4.4 记忆增强的 Agent Prompt
def build_prompt_with_memory(user_input: str,
short_term: ShortTermMemory,
long_term: LongTermMemory) -> str:
"""构建记忆增强的 Prompt"""
# 1. 短期记忆:最近对话
recent_context = short_term.get_context()
# 2. 长期记忆:语义检索
relevant_memories = long_term.recall(user_input, k=3)
memory_context = "\n".join([
f"- {m['content']}"
for m in relevant_memories
])
# 3. 组装 Prompt
prompt = f"""
You are DeerFlow, a Super Agent with memory capabilities.
## Recent Context (Short-term Memory)
{recent_context}
## Relevant Past Experiences (Long-term Memory)
{memory_context}
## Current Task
{user_input}
## Instructions
- Use recent context for continuity
- Leverage past experiences for similar tasks
- Explain your reasoning process
- If you encounter something new, store it for future reference
"""
return prompt
五、MCP 协议支持:工具扩展的标准接口
DeerFlow 完整支持 MCP(Model Context Protocol),这是 Anthropic 提出的工具协议标准,允许 Agent 通过统一的接口调用外部工具。
5.1 MCP 协议架构
┌──────────────────┐ WebSocket/stdio ┌──────────────────┐
│ DeerFlow │ ◄───────────────────────► │ MCP Server │
│ (Client) │ │ (Tool Host) │
└──────────────────┘ └──────────────────┘
│ │
│ 1. List Tools │
│ 2. Call Tool │
│ 3. Get Result │
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ Tool Registry │ │ External APIs │
│ (Built-in) │ │ / Databases │
└──────────────────┘ └──────────────────┘
5.2 MCP Server 配置示例
// mcp_config.json
{
"mcpServers": {
"filesystem": {
"command": "mcp-server-filesystem",
"args": ["/workspace"],
"env": {}
},
"github": {
"command": "mcp-server-github",
"args": [],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
"postgres": {
"command": "mcp-server-postgres",
"args": ["postgresql://user:pass@localhost:5432/mydb"],
"env": {}
},
"brave-search": {
"command": "mcp-server-brave-search",
"args": [],
"env": {
"BRAVE_API_KEY": "${BRAVE_API_KEY}"
}
}
}
}
5.3 MCP 工具调用流程
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def call_mcp_tool(server_name: str, tool_name: str,
arguments: dict) -> dict:
"""调用 MCP 工具"""
# 1. 连接到 MCP Server
server_params = StdioServerParameters(
command=f"mcp-server-{server_name}",
args=[]
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# 2. 列出可用工具
tools = await session.list_tools()
tool_names = [t.name for t in tools.tools]
if tool_name not in tool_names:
raise ToolNotFoundError(f"Tool {tool_name} not found")
# 3. 调用工具
result = await session.call_tool(tool_name, arguments)
return {
"content": result.content,
"is_error": result.isError
}
# 使用示例
async def main():
result = await call_mcp_tool(
"github",
"search_repositories",
{"query": "deer-flow", "limit": 10}
)
print(result)
asyncio.run(main())
5.4 自定义 MCP Server 开发
from mcp.server import Server
from mcp.types import Tool, TextContent
# 创建 MCP Server
server = Server("my-custom-server")
@server.list_tools()
async def list_tools() -> list[Tool]:
return [
Tool(
name="analyze_logs",
description="Analyze log files for errors",
inputSchema={
"type": "object",
"properties": {
"log_path": {"type": "string"},
"error_pattern": {"type": "string"}
},
"required": ["log_path"]
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
if name == "analyze_logs":
log_path = arguments["log_path"]
pattern = arguments.get("error_pattern", "ERROR")
# 实际分析逻辑
with open(log_path, 'r') as f:
errors = [line for line in f if pattern in line]
return [
TextContent(
type="text",
text=f"Found {len(errors)} errors matching '{pattern}'"
)
]
六、多模型支持:不只是 OpenAI
DeerFlow 兼容所有支持 OpenAI API 格式的模型:
| 模型厂商 | 推荐模型 | 特点 |
|---|---|---|
| OpenAI | GPT-4.1, o3 | 推理能力强,工具调用稳定 |
| Anthropic | Claude 4 Sonnet | 长上下文,代码能力强 |
| DeepSeek | DeepSeek V4 Pro | MoE 架构,高性价比 |
| 字节豆包 | Doubao Pro | 中文能力强,国内访问稳定 |
| Gemini 2.5 Pro | 多模态,长上下文 | |
| 阿里通义 | Qwen3.8 | 开源可商用,中文优秀 |
| 本地模型 | Ollama + Llama 4 | 隐私保护,无 API 成本 |
6.1 模型配置
# config.yaml
llm:
provider: "openai" # openai | anthropic | deepseek | doubao | gemini | qwen | ollama
openai:
api_key: "${OPENAI_API_KEY}"
base_url: "https://api.openai.com/v1"
model: "gpt-4.1"
temperature: 0.7
max_tokens: 4096
anthropic:
api_key: "${ANTHROPIC_API_KEY}"
model: "claude-4-sonnet-20250514"
deepseek:
api_key: "${DEEPSEEK_API_KEY}"
base_url: "https://api.deepseek.com/v1"
model: "deepseek-v4-pro"
ollama:
base_url: "http://localhost:11434"
model: "llama4:70b"
# 模型路由策略
model_routing:
planning: "gpt-4.1" # 规划用强模型
execution: "deepseek-v4-pro" # 执行用高性价比模型
fallback: "claude-4-sonnet" # 降级备用
6.2 智能模型路由
class ModelRouter:
def __init__(self, config: dict):
self.config = config
self.models = {
"planning": self._init_model(config["model_routing"]["planning"]),
"execution": self._init_model(config["model_routing"]["execution"]),
"fallback": self._init_model(config["model_routing"]["fallback"])
}
def select_model(self, task_type: str, complexity: int) -> LLM:
"""根据任务类型和复杂度选择模型"""
if task_type == "planning" or complexity > 7:
return self.models["planning"]
elif task_type == "execution":
return self.models["execution"]
else:
return self.models["fallback"]
def call_with_fallback(self, prompt: str, task_type: str) -> str:
"""带降级的模型调用"""
primary = self.select_model(task_type, complexity=5)
try:
return primary.invoke(prompt)
except Exception as e:
print(f"Primary model failed: {e}, falling back...")
return self.models["fallback"].invoke(prompt)
七、本地部署实战:从零到一的生产级配置
7.1 环境准备
系统要求:
| 组件 | 最低配置 | 推荐配置 | 生产环境 |
|---|---|---|---|
| CPU | 8 核 | 16 核 | 32 核+ |
| 内存 | 16GB | 32GB | 64GB+ |
| 存储 | 50GB | 256GB NVMe | 1TB+ NVMe |
| GPU | GTX 1660 Ti | RTX 4090 | A100/A800 |
软件依赖:
# 必需软件
- Docker Desktop 24.0+ (或 Docker Engine + Docker Compose v2+)
- Git 2.40+
- Python 3.11+ (用于 CLI)
- Node.js 20+ (前端开发)
# macOS/Linux
brew install docker git python node
# Windows (WSL2)
wsl --install -d Ubuntu-22.04
# 在 WSL2 内安装 Docker
7.2 快速部署(Docker Compose)
# 1. 克隆仓库
git clone https://github.com/bytedance/deer-flow.git
cd deer-flow
# 2. 复制配置文件
cp config.example.yaml config.yaml
cp .env.example .env
# 3. 编辑配置
# config.yaml - 配置模型、沙箱、记忆系统
# .env - 配置 API Keys
# 4. 启动服务
docker compose up -d
# 5. 检查服务状态
docker compose ps
# 6. 访问 Web UI
open http://localhost:8080
7.3 配置文件详解
config.yaml 核心配置:
# DeerFlow 2.0 配置文件
# ==================== LLM 配置 ====================
llm:
provider: "openai"
openai:
api_key: "${OPENAI_API_KEY}"
model: "gpt-4.1"
temperature: 0.7
max_tokens: 4096
# ==================== 沙箱配置 ====================
sandbox:
type: "aio" # aio | simple
docker:
image: "agentinfra/sandbox:latest"
memory_limit: "4g"
cpu_limit: 2
network_mode: "bridge" # bridge | host | none
security_opt:
- "no-new-privileges:true"
volumes:
- "${PWD}/workspace:/workspace"
- "${PWD}/skills:/mnt/skills"
# ==================== 记忆配置 ====================
memory:
short_term:
max_turns: 20
compression_threshold: 3000 # tokens
long_term:
enabled: true
backend: "chroma" # chroma | pinecone | weaviate
persist_dir: "./memory/chroma"
embedding_model: "text-embedding-3-small"
# ==================== 技能配置 ====================
skills:
directories:
- "/mnt/skills/public"
- "/mnt/skills/custom"
auto_load: false # 按需加载
# ==================== MCP 配置 ====================
mcp:
config_path: "./mcp_config.json"
timeout: 60 # seconds
# ==================== 日志配置 ====================
logging:
level: "INFO"
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
file: "./logs/deerflow.log"
.env 环境变量:
# LLM API Keys
OPENAI_API_KEY=sk-xxx
ANTHROPIC_API_KEY=sk-ant-xxx
DEEPSEEK_API_KEY=sk-xxx
DOUBAO_API_KEY=xxx
# MCP API Keys
GITHUB_TOKEN=ghp_xxx
BRAVE_API_KEY=xxx
# 可选:本地模型
OLLAMA_BASE_URL=http://localhost:11434
7.4 生产级优化建议
7.4.1 资源限制
# docker-compose.prod.yml
services:
deerflow:
image: bytedance/deerflow:2.0
deploy:
resources:
limits:
cpus: '4'
memory: 8G
reservations:
cpus: '2'
memory: 4G
environment:
- WORKER_CONCURRENCY=4
- MAX_SUBAGENTS=10
7.4.2 高可用配置
# 使用 Nginx 负载均衡
services:
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
depends_on:
- deerflow-1
- deerflow-2
- deerflow-3
deerflow-1:
image: bytedance/deerflow:2.0
environment:
- INSTANCE_ID=1
deerflow-2:
image: bytedance/deerflow:2.0
environment:
- INSTANCE_ID=2
deerflow-3:
image: bytedance/deerflow:2.0
environment:
- INSTANCE_ID=3
7.4.3 监控告警
# Prometheus + Grafana
services:
prometheus:
image: prom/prometheus:latest
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
ports:
- "9090:9090"
grafana:
image: grafana/grafana:latest
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
deerflow:
image: bytedance/deerflow:2.0
ports:
- "8080:8080"
- "9091:9091" # Metrics endpoint
八、典型应用场景与代码示例
8.1 场景一:自动化深度研究
任务:「调研 2026 年 AI Agent 框架趋势,生成分析报告」
from deerflow import DeerFlowClient
client = DeerFlowClient(base_url="http://localhost:8080")
# 创建任务
task = client.create_task(
prompt="""
调研 2026 年 AI Agent 框架的发展趋势,需要:
1. 收集主流框架(LangGraph, AutoGen, CrewAI, DeerFlow)的最新动态
2. 分析各框架的技术特点、适用场景
3. 对比性能、易用性、生态完整性
4. 生成结构化的分析报告(Markdown 格式)
""",
skills=["deep-search", "report-generation"],
sandbox_enabled=True
)
# 等待完成
result = task.wait_for_completion(timeout=3600)
print(result.output)
# 输出:完整的分析报告,包含对比表格、趋势预测、参考文献
8.2 场景二:代码生成与部署
任务:「创建一个 FastAPI 服务并部署到 Docker」
task = client.create_task(
prompt="""
创建一个 FastAPI 服务:
1. 实现 /health 健康检查端点
2. 实现 /api/users CRUD 接口
3. 使用 SQLAlchemy + SQLite
4. 编写 Dockerfile
5. 部署到本地 Docker
""",
skills=["code-generation", "deploy"],
subagents=["code", "deploy"]
)
result = task.wait_for_completion()
# 结果
# - /workspace/app/main.py - FastAPI 应用
# - /workspace/app/models.py - 数据模型
# - /workspace/Dockerfile - 容器配置
# - 服务已启动:http://localhost:8000
8.3 场景三:数据分析与可视化
任务:「分析销售数据并生成可视化仪表盘」
task = client.create_task(
prompt="""
分析 /workspace/data/sales.csv 中的销售数据:
1. 数据清洗与预处理
2. 计算关键指标(总销售额、增长率、Top 产品)
3. 生成可视化图表(使用 Plotly)
4. 创建交互式仪表盘(HTML)
""",
skills=["data-analysis", "web-page"],
files=["/workspace/data/sales.csv"]
)
result = task.wait_for_completion()
# 输出:
# - /workspace/output/analysis.ipynb - 分析 Notebook
# - /workspace/output/dashboard.html - 可视化仪表盘
九、性能优化与踩坑清单
9.1 性能优化要点
9.1.1 Token 优化
# 问题:技能一次性加载占用大量上下文
# 解决:按需加载 + 及时卸载
class OptimizedSkillLoader:
def __init__(self, max_active_skills: int = 3):
self.max_active_skills = max_active_skills
self.active_skills = OrderedDict() # LRU 缓存
def load_skill(self, skill_name: str) -> Skill:
if skill_name in self.active_skills:
# 命中缓存,移到最前
self.active_skills.move_to_end(skill_name)
return self.active_skills[skill_name]
# 加载技能
skill = self._load_from_disk(skill_name)
# 超过限制,卸载最久未用
if len(self.active_skills) >= self.max_active_skills:
oldest = next(iter(self.active_skills))
del self.active_skills[oldest]
self.active_skills[skill_name] = skill
return skill
9.1.2 并行调度优化
# 问题:子 Agent 串行执行效率低
# 解决:智能并行调度
class ParallelScheduler:
def __init__(self, max_concurrency: int = 5):
self.max_concurrency = max_concurrency
async def dispatch(self, tasks: List[Task]) -> Dict[str, Any]:
# 分析任务依赖关系
dependency_graph = self._build_dependency_graph(tasks)
# 按依赖层级分组
levels = self._topological_sort(dependency_graph)
results = {}
for level in levels:
# 同一层级任务可并行执行
batch = [
self._run_task(task)
for task in level
]
level_results = await asyncio.gather(*batch)
for task, result in zip(level, level_results):
results[task.id] = result
return results
9.1.3 记忆压缩
# 问题:长期记忆向量库膨胀,检索效率下降
# 解决:定期压缩 + 聚合
class MemoryCompressor:
def compress_memories(self, session_id: str,
similarity_threshold: float = 0.9):
# 1. 检索所有相关记忆
memories = self.vectorstore.get(
filter={"session_id": session_id}
)
# 2. 计算相似度矩阵
embeddings = self.embeddings.embed_documents(
[m.page_content for m in memories]
)
# 3. 聚合高相似度记忆
clusters = self._cluster_by_similarity(
embeddings, similarity_threshold
)
# 4. 为每个簇生成摘要
for cluster in clusters:
cluster_memories = [memories[i] for i in cluster]
summary = self._summarize_cluster(cluster_memories)
# 5. 删除原始记忆,存储摘要
for i in cluster:
self.vectorstore.delete(memories[i].id)
self.vectorstore.add_texts(
texts=[summary],
metadatas=[{
"session_id": session_id,
"type": "compressed",
"source_count": len(cluster)
}]
)
9.2 15 条生产踩坑清单
| # | 问题 | 症状 | 解决方案 |
|---|---|---|---|
| 1 | Docker 沙箱网络隔离 | 子 Agent 无法访问外网 | 配置 network_mode: bridge + 端口映射 |
| 2 | API Key 泄露 | 日志中打印敏感信息 | 使用环境变量,日志脱敏 |
| 3 | Token 超限 | 复杂任务中途失败 | 实现记忆压缩,按需加载技能 |
| 4 | 子 Agent 死锁 | 任务永不完成 | 设置全局超时,实现心跳检测 |
| 5 | 文件系统冲突 | 多 Agent 同时写同一文件 | 实现文件锁,使用独立工作目录 |
| 6 | 模型调用 429 | 高频调用被限流 | 实现指数退避重试,模型路由 |
| 7 | 记忆库膨胀 | 检索延迟 > 5s | 定期压缩,设置 TTL |
| 8 | 沙箱资源耗尽 | 容器 OOM | 配置资源限制,监控告警 |
| 9 | 技能加载失败 | 依赖包缺失 | 使用预构建镜像,pip freeze |
| 10 | 并发竞争 | 数据不一致 | 使用 Redis 分布式锁 |
| 11 | 日志丢失 | 容器重启日志消失 | 挂载日志 Volume |
| 12 | 配置热更新 | 改配置需重启 | 实现配置监听,热加载 |
| 13 | 子 Agent 结果丢失 | 子 Agent 完成但结果未返回 | 实现结果持久化,断点续传 |
| 14 | MCP 连接断开 | 工具调用失败 | 实现心跳保活,自动重连 |
| 15 | 权限不足 | 沙箱内无法执行命令 | 配置 cap_add,避免 privileged |
十、与竞品对比:DeerFlow vs OpenAI Deep Research vs OpenClaw
| 维度 | DeerFlow 2.0 | OpenAI Deep Research | OpenClaw |
|---|---|---|---|
| 开源 | ✅ MIT 协议 | ❌ 闭源 | ✅ 部分开源 |
| 沙箱执行 | ✅ Docker 完整隔离 | ❌ 无 | ✅ Docker + 本地 |
| 子 Agent 并行 | ✅ 原生支持 | ❌ 单线程 | ✅ 支持 |
| 记忆系统 | ✅ 长/短期双系统 | ❌ 无持久记忆 | ✅ 支持 |
| 技能扩展 | ✅ Markdown 技能文件 | ❌ 不支持 | ✅ Skill 系统 |
| MCP 协议 | ✅ 完整支持 | ❌ 专属协议 | ✅ 支持 |
| 多模型 | ✅ 兼容 OpenAI API 格式 | ❌ 仅 GPT 系列 | ✅ 支持 |
| 本地部署 | ✅ 完全支持 | ❌ 仅云服务 | ✅ 支持 |
| 商业使用 | ✅ MIT 协议允许 | ❌ 需订阅 | ⚠️ 部分限制 |
| 文档质量 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| 社区活跃度 | 50K+ Stars | N/A | 10K+ Stars |
| 适用场景 | 长时复杂任务 | 快速研究 | 编码辅助 |
选择建议:
- DeerFlow:需要长时复杂任务自动化、有本地部署需求、注重数据隐私
- OpenAI Deep Research:快速信息收集、不需要自定义工具、预算充足
- OpenClaw:AI 辅助编程、IDE 集成、需要 Claude Code 能力
十一、未来展望:DeerFlow 的演进方向
11.1 近期路线图(2026 Q3-Q4)
- 多模态能力增强:支持图像、视频、音频的理解与生成
- Agent 协作网络:多个 DeerFlow 实例间的任务分发与协作
- 可视化工作流编辑器:拖拽式 DAG 构建,降低使用门槛
- 企业级权限管理:RBAC、审计日志、合规报告
11.2 中期目标(2027)
- 自主学习能力:从历史任务中提取技能,自动优化工作流
- 领域专家系统:预训练的行业专用 Agent(法律、医疗、金融)
- 边缘计算支持:轻量级沙箱,适配物联网设备
- 联邦学习集成:隐私保护下的跨组织知识共享
11.3 生态愿景
DeerFlow 的终极目标是成为 AI Agent 时代的操作系统:
- 内核:Lead Agent + 沙箱执行环境
- 驱动:MCP 协议 + 工具适配层
- 应用:技能市场 + 领域解决方案
- 文件系统:持久化记忆 + 知识库
- 网络:Agent 间通信协议
总结
DeerFlow 2.0 是 2026 年最值得关注的开源 Agent 框架之一。它不是又一款「聊天机器人」,而是一个真正能干活的 Super Agent 执行底座:
核心优势:
- 架构先进:基于 LangGraph 1.0,Lead Agent + Sub-Agents + Docker 沙箱三层架构
- 能力完整:技能系统、记忆系统、MCP 协议、多模型支持一应俱全
- 工程可靠:字节跳动出品,经过真实业务验证,文档完善
- 开源友好:MIT 协议,支持商业用途,社区活跃
适用场景:
- 自动化深度研究与报告生成
- 代码生成与服务部署
- 数据分析与可视化
- 长时复杂任务自动化
快速开始:
# 一键部署
git clone https://github.com/bytedance/deer-flow.git
cd deer-flow
docker compose up -d
open http://localhost:8080
DeerFlow 代表了 AI Agent 从「对话工具」到「执行引擎」的范式跃迁。如果你正在寻找一个能真正干活的 Agent 框架,DeerFlow 值得深入探索。