扩展-Trae Agent 深度技术分析字节跳动开源的 LLM 驱动软件工程 AI AgentGitHub: https://github.com/bytedance/trae-agent目录1. 项目概述2. 架构设计3. 核心组件4. 实现原理5. 工具系统6. 使用示例7. 执行轨迹格式8. 与竞品对比9. 依赖与环境10. 适用场景与局限1. 项目概述Trae Agent 是字节跳动开源的LLM 驱动通用软件工程 Agent专为自动解决复杂编程任务而设计包括 GitHub issue 修复、代码重构、单元测试生成等。核心定位与 Cursor、Claude Code 等闭源 AI 编码助手不同Trae Agent 强调研究友好的透明化架构完全开源易于修改和扩展模块化设计便于进行消融研究Ablation Study详细的执行轨迹记录支持学术研究支持 7 主流 LLM 提供商解决的问题问题类别具体描述代码理解与导航在大型陌生代码库中快速定位相关文件和函数问题重现自动创建复现脚本验证 bug 存在性根因分析通过代码分析和调试找出 bug 根本原因修复实现精准、最小化的代码修改解决问题验证与测试执行完整测试套件防止回归执行可视化完整的轨迹记录便于理解 Agent 决策过程2. 架构设计整体架构┌─────────────────────────────────────────────────────────┐ │ CLI Interface │ │ (trae_agent/cli.py) │ │ 命令行参数解析 / 配置文件处理(YAML/JSON) / Docker支持 │ └──────────────────────────┬──────────────────────────────┘ │ ┌──────────────────────────▼──────────────────────────────┐ │ Config Layer │ │ (trae_agent/utils/config.py) │ │ ModelProvider / ModelConfig / TraeAgentConfig │ └──────────────────────────┬──────────────────────────────┘ │ ┌──────────────────────────▼──────────────────────────────┐ │ Agent Core (BaseAgent) │ │ (trae_agent/agent/base_agent.py) │ │ 消息管理 / LLM调用编排 / 工具调用管理 / 步骤追踪 │ └──────────┬───────────────┬──────────────────────────────┘ │ │ │ ┌──────▼──────┐ ┌──────▼──────┐ ┌────────▼────────┐ │ Tool Caller │ │ LLM Client │ │ Trajectory │ │ │ │ (多厂商适配) │ │ Recorder │ └──────┬──────┘ └──────┬──────┘ └─────────────────┘ │ │ ┌──────┴───────┐ ┌────┴───────────────────────────┐ │ 工具集合 │ │ Providers │ │ - bash │ │ OpenAI / Anthropic / Google │ │ - edit │ │ Azure / Ollama / Doubao │ │ - json_edit │ │ OpenRouter │ │ - thinking │ └────────────────────────────────┘ │ - MCP tools │ └──────────────┘目录结构trae-agent/ ├── trae_agent/ │ ├── agent/ │ │ ├── base_agent.py # Agent 核心执行循环 │ │ └── trae_agent.py # SWE 专用 Agent 实现 │ ├── tools/ │ │ ├── bash_tool.py # Shell 命令执行 │ │ ├── edit_tool.py # 文件编辑工具 │ │ ├── json_edit_tool.py # JSON 精确编辑 │ │ ├── sequential_thinking_tool.py # 结构化思考 │ │ ├── task_done_tool.py # 完成标记 │ │ └── mcp_tool.py # MCP 工具集成 │ ├── utils/ │ │ ├── config.py # 配置管理 │ │ ├── llm_client.py # LLM 多厂商适配 │ │ └── trajectory_recorder.py # 执行轨迹记录 │ └── cli.py # CLI 入口 ├── docs/ │ └── roadmap.md ├── pyproject.toml └── trae_config.yaml # 示例配置3. 核心组件3.1 BaseAgent — 执行引擎Agent 核心类实现完整的执行状态机状态机设计Agent 生命周期: INITIALIZING → RUNNING → COMPLETED ↓ ERROR 单步状态: THINKING → CALLING_TOOL → REFLECTING → COMPLETED ↓ ERROR关键方法方法职责execute_task()主执行循环管理 Agent 状态机_run_llm_step()单个 LLM 推理步骤_tool_call_handler()工具调用和结果处理_finalize_step()步骤完成和记录3.2 TraeAgent — SWE 专用实现继承 BaseAgent针对软件工程任务增强MCP 服务发现与动态初始化Git diff 生成和补丁管理--must-patch模式定制化系统提示词TRAE_AGENT_SYSTEM_PROMPT测试目录过滤防止误修改测试文件3.3 LLMClient — 多厂商适配器采用工厂模式统一接口对接 7 个 LLM 提供商classLLMProvider(Enum):OPENAIopenaiANTHROPICanthropicAZUREazureOLLAMAollamaOPENROUTERopenrouterDOUBAOdoubao# 字节跳动豆包GOOGLEgoogle# Google Gemini配置优先级CLI 参数 配置文件 环境变量 默认值3.4 TrajectoryRecorder — 执行轨迹记录完整记录 Agent 每一步的执行细节LLM 请求 / 响应对含 token 用量Agent 步骤和状态转换工具调用和执行结果完整元数据时间戳、模型配置、任务描述4. 实现原理4.1 Agent 主执行循环asyncdefexecute_task(self)-AgentExecution:executionAgentExecution(taskself._task,steps[])whilestep_numberself._max_steps:stepAgentStep(step_numberstep_number,stateAgentStepState.THINKING)# 1. LLM 推理messagesawaitself._run_llm_step(step,messages,execution)# 2. 记录步骤awaitself._finalize_step(step,messages,execution)# 3. 检查完成ifexecution.agent_stateAgentState.COMPLETED:breakstep_number1awaitself._close_tools()awaitself.cleanup_mcp_clients()returnexecution4.2 LLM 推理步骤asyncdef_run_llm_step(self,step,messages,execution):# 调用 LLMllm_responseself._llm_client.chat(messages,self._model_config,self._tools)# 检查任务完成标记ifself.llm_indicates_task_completed(llm_response):ifself._is_task_completed(llm_response):execution.successTruereturnmessages# 处理工具调用ifllm_response.tool_calls:returnawaitself._tool_call_handler(llm_response.tool_calls,step)4.3 工具执行策略支持并行和顺序两种调用模式ifself._model_config.parallel_tool_calls:tool_resultsawaitself._tool_caller.parallel_tool_call(tool_calls)else:tool_resultsawaitself._tool_caller.sequential_tool_call(tool_calls)# 将结果追加到消息历史fortool_resultintool_results:messages.append(LLMMessage(roleuser,tool_resulttool_result))# 可选生成 Agent 反思reflectionself.reflect_on_result(tool_results)ifreflection:messages.append(LLMMessage(roleassistant,contentreflection))4.4 MCP 工具动态发现asyncdefinitialise_mcp(self):awaitself.discover_mcp_tools()ifself.mcp_tools:self._tools.extend(self.mcp_tools)# 动态扩展工具集asyncdefdiscover_mcp_tools(self):forname,configinself.mcp_servers_config.items():mcp_clientMCPClient()awaitmcp_client.connect_and_discover(name,config,self.mcp_tools,self._llm_client.provider.value)5. 工具系统内置工具工具名称功能关键特性bashShell 命令执行持久化会话、120s 超时、精确错误码捕获str_replace_based_edit_tool文件编辑view/create/str_replace/insert 操作json_edit_toolJSON 精确编辑JSONPath 表达式定位修改sequential_thinking结构化思考支持分支、修正、5-25 步深度思考task_done完成标记触发 Agent 停止循环Bash 工具的会话管理class_BashSession:_timeout:float120.0# 默认超时秒数_sentinel:str,,,,bash-command-exit-__ERROR_CODE__-banner,,,,asyncdefrun(self,command:str)-ToolExecResult:# 发送命令 → Sentinel 等待完成 → 提取输出和错误码returnToolExecResult(outputoutput,errorerror,error_codeerror_code)状态在命令间持久保持支持 Unix 和 Windows。文件编辑工具操作view - 显示文件内容或目录结构支持行范围 create - 创建新文件文件已存在则报错 str_replace - 精确字符串替换必须唯一匹配包括空白符 insert - 在指定行后插入文本JSON 编辑工具示例# JSONPath 表达式示例$.users[0].name# 第一个用户名$.config.database.host# 嵌套属性$.items[*].price# 所有项目价格$..key# 递归搜索顺序思考工具参数{thought:当前思考内容,thought_number:3,total_thoughts:10,next_thought_needed:True,is_revision:False,# 是否修正前一个思考branch_id:branch_a# 多分支探索标识}6. 使用示例安装pipinstalltrae-agent# 或从源码安装gitclone https://github.com/bytedance/trae-agentcdtrae-agentpipinstall-e.环境变量配置exportANTHROPIC_API_KEYyour-keyexportOPENAI_API_KEYyour-keyexportGOOGLE_API_KEYyour-key基础命令# 执行任务trae-cli runCreate a hello world Python script# 查看当前配置trae-cli show-config# 交互模式REPLtrae-cli interactive指定 LLM 提供商# OpenAI GPT-4otrae-cli runFix the bug in main.py\--provideropenai\--modelgpt-4o# Anthropic Claudetrae-cli runAdd unit tests for utils.py\--provideranthropic\--modelclaude-sonnet-4-20250514# Google Geminitrae-cli runOptimize the sorting algorithm\--providergoogle\--modelgemini-2.5-flash# 本地 Ollama 模型trae-cli runAdd comments to this file\--providerollama\--modelqwen3# OpenRouter统一接入多 providertrae-cli runReview this code\--provideropenrouter\--modelanthropic/claude-3-5-sonnet高级选项# 指定工作目录trae-cli runAdd tests for auth module\--working-dir /path/to/project# 保存执行轨迹trae-cli runDebug authentication flow\--trajectory-file debug_session.json# 强制生成代码补丁SWE 模式trae-cli runFix login bug from issue #42\--must-patch# Docker 隔离执行指定镜像trae-cli runRun tests in isolated env\--docker-image python:3.12\--working-dir ./workspace# Docker使用 Dockerfile 构建trae-cli runDebug authentication\--dockerfile-path ./workspace/Dockerfile# Docker附加到已有容器trae-cli runUpdate API endpoints\--docker-container-id 91998a56056c配置文件trae_config.yamlagents:trae_agent:enable_lakeview:truemodel:trae_agent_modelmax_steps:200tools:-bash-str_replace_based_edit_tool-sequentialthinking-task_done# MCP 服务配置可选allow_mcp_servers:-playwrightmcp_servers:playwright:command:npxargs:-playwright/mcp0.0.27model_providers:anthropic:api_key:${ANTHROPIC_API_KEY}provider:anthropicopenai:api_key:${OPENAI_API_KEY}provider:openaimodels:trae_agent_model:model_provider:anthropicmodel:claude-sonnet-4-20250514max_tokens:4096temperature:0.5top_p:1.0max_retries:10parallel_tool_calls:true7. 执行轨迹格式每次运行生成一个 JSON 文件包含完整执行记录{task:Fix the authentication bug,start_time:2025-06-12T22:05:46.433797,end_time:2025-06-12T22:06:15.123456,provider:anthropic,model:claude-sonnet-4-20250514,max_steps:20,llm_interactions:[{timestamp:2025-06-12T22:05:47.000000,input_messages:[...],response:{content:Ill analyze the authentication code...,finish_reason:end_turn,usage:{input_tokens:150,output_tokens:75,cache_read_input_tokens:0},tool_calls:[...]}}],agent_steps:[{step_number:1,state:thinking,tool_calls:[...],tool_results:[...],reflection:null,error:null}],success:true,final_result:Fixed JWT token expiry validation in auth.py,execution_time:28.69}轨迹文件可用于分析 Agent 决策过程统计 Token 使用量和成本进行消融研究和对比实验接入 MLOps 平台Wandb / MLFlow8. 与竞品对比特性Trae AgentClaude CodeCursor开源✓ MIT✓ 开源✗ 闭源研究友好✓ 专为研究设计✓ 中等✗ 生产优先完整执行轨迹✓ JSON 详细记录有限✗多 LLM 支持✓ 7 提供商主要 Anthropic✓ 多个Docker 隔离✓ 完整支持✗✗MCP 集成✓ 完整支持✓ 部分✗消融研究✓ 易于修改组件✗✗交互模式✓ REPL✓✓商业成熟度研究阶段生产可用生产优先Trae Agent 最大差异点是目前唯一专门为 AI Agent 学术研究设计的开源框架完整的执行轨迹记录和高度模块化使其成为研究工具调用、Agent 决策、多步推理的理想平台。9. 依赖与环境# 核心依赖pyproject.toml python 3.11 anthropic 0.54.0,0.60.0 openai 1.86.0 google-genai 1.24.0 ollama 0.5.1 mcp 1.12.2 # Model Context Protocol pydantic 2.0.0 pyyaml 6.0.2 tree-sitter 0.21.3 # 代码解析 tree-sitter-languages 1.10.2 # 多语言支持 textual 0.50.0 # TUI 界面 pyinstaller 6.15.0 # Docker 工具打包10. 适用场景与局限最适合的场景GitHub issue 自动化修复SWE-bench 类任务代码审查与重构单元测试自动生成文档批量更新Bug 根因分析不太适合的场景实时交互式编码推荐 Cursor / Claude CodeGUI 应用开发缺乏 UI 预览交互式调试会话缺乏实时反馈未来路线图阶段功能SDK 开发无头接口、流式轨迹记录沙箱环境隔离任务执行、并行任务支持轨迹分析MLOps 集成Wandb / MLFlow工具扩展Jupyter 支持、MCP 标准化多 Agent 编排Agent 协作、工作流模式*分析基于 trae-agent v0.1.0