侧边栏壁纸
  • 累计撰写 56 篇文章
  • 累计创建 5 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Trae Agent 源码深入研究

温馨提示:
部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

项目: bytedance/trae-agent
版本: 0.1.0
许可证: MIT
技术报告: arXiv:2507.23370


目录

  1. 项目概述
  2. 整体架构
  3. 目录结构
  4. 主要模块说明
  5. 关键类与函数
  6. 依赖关系
  7. 配置系统
  8. 工具系统
  9. LLM 多提供商支持
  10. 轨迹记录系统
  11. Docker 模式
  12. 评估系统
  13. 项目运行方式
  14. 开发与测试

1. 项目概述

Trae Agent 是一个基于大语言模型(LLM)的通用软件工程任务代理。它提供强大的 CLI 接口,能够理解自然语言指令,并使用多种工具和 LLM 提供商执行复杂的软件工程工作流。

核心特性:

  • Lakeview: 为代理步骤提供简洁的摘要
  • 多 LLM 支持: OpenAI、Anthropic、Doubao、Azure、OpenRouter、Ollama、Google Gemini
  • 丰富工具生态: 文件编辑、Bash 执行、顺序思维、代码知识图谱等
  • 交互模式: 对话式界面用于迭代开发
  • 轨迹记录: 详细记录所有代理动作,用于调试和分析
  • 灵活配置: 基于 YAML 的配置,支持环境变量覆盖
  • Docker 支持: 可在隔离容器中执行任务

2. 整体架构

2.1 分层架构图

┌──────────────────────────────────────────────────────────────┐
│                       CLI 层 (cli.py)                        │
│            click 命令组: run / interactive / show-config     │
└──────────────────────────┬───────────────────────────────────┘
                           │
┌──────────────────────────▼───────────────────────────────────┐
│                    代理编排层 (Agent)                         │
│  ┌─────────────┐  发现/初始化   ┌──────────────────────┐    │
│  │ Agent Facade│ ──────────────►│     TraeAgent        │    │
│  │  (agent.py) │                │  (trae_agent.py)     │    │
│  └─────────────┘                │         │            │    │
│                                 └─────────│────────────┘    │
│                                           │                 │
│                          ┌────────────────▼──────────────┐  │
│                          │       BaseAgent               │  │
│                          │    (base_agent.py)            │  │
│                          │  execute_task() / _run_llm    │  │
│                          └───────────────────────────────┘  │
└──────────────────────────┬───────────────────────────────────┘
                           │
         ┌─────────────────┼─────────────────────┐
         ▼                 ▼                     ▼
┌────────────────┐ ┌──────────────┐ ┌──────────────────────┐
│   工具系统      │ │  LLM 客户端  │ │     配置与工具层      │
│ (tools/)       │ │(llm_clients/)│ │                      │
│                │ │              │ │  - config.py         │
│ - BashTool     │ │ - OpenAI     │ │  - trajectory_       │
│ - TextEditor   │ │ - Anthropic  │ │    recorder.py       │
│ - JSONEditTool │ │ - Google     │ │  - mcp_client.py     │
│ - Sequential   │ │ - Azure      │ │  - cli/              │
│   Thinking     │ │ - Doubao     │ │  - prompt/           │
│ - TaskDone     │ │ - Ollama     │ │                      │
│ - CKGTool      │ │ - OpenRouter │ │                      │
│ - MCPTool      │ │              │ │                      │
└────────────────┘ └──────────────┘ └──────────────────────┘

2.2 核心执行流程

用户输入任务
    │
    ▼
CLI (click) → 解析参数 → 加载配置 (Config.create)
    │
    ▼
Agent Facade → 创建 TraeAgent 实例
    │
    ├── 初始化 LLM 客户端 (LLMClient)
    ├── 注册工具 (ToolExecutor)
    ├── 设置轨迹记录器 (TrajectoryRecorder)
    └── 可选: 初始化 MCP 客户端
    │
    ▼
BaseAgent.execute_task()
    │
    ├── while step_number <= max_steps:
    │   │
    │   ├── 1. LLM 请求 (_run_llm_step)
    │   │   ├── LLMClient.chat(messages, tools)
    │   │   └── 返回 LLMResponse
    │   │
    │   ├── 2. 检查任务完成 (llm_indicates_task_completed)
    │   │   ├── 是 → 验证补丁 → 完成
    │   │   └── 否 → 继续
    │   │
    │   ├── 3. 工具调用 (_tool_call_handler)
    │   │   ├── ToolExecutor.parallel_tool_call() 或
    │   │   └── ToolExecutor.sequential_tool_call()
    │   │
    │   ├── 4. 结果反思 (reflect_on_result)
    │   │
    │   └── 5. 记录步骤 (TrajectoryRecorder)
    │
    ▼
返回 AgentExecution (包含所有步骤、结果、Token 消耗)

3. 目录结构

trae-agent/
├── trae_agent/                          # 主源码包
│   ├── __init__.py                      # 包入口,导出核心类
│   ├── cli.py                           # CLI 入口 (click 命令组)
│   ├── agent/                           # 代理核心
│   │   ├── __init__.py
│   │   ├── agent.py                     # Agent Facade 类
│   │   ├── base_agent.py                # BaseAgent 抽象基类
│   │   ├── trae_agent.py                # TraeAgent 具体实现
│   │   ├── agent_basics.py              # 数据模型定义
│   │   └── docker_manager.py            # Docker 容器管理
│   ├── tools/                           # 工具系统
│   │   ├── __init__.py                  # 工具注册表 (tools_registry)
│   │   ├── base.py                      # Tool/ToolExecutor/ToolCall 基类
│   │   ├── bash_tool.py                 # Bash 命令执行工具
│   │   ├── edit_tool.py                 # 文本编辑器工具
│   │   ├── json_edit_tool.py            # JSON 编辑工具
│   │   ├── sequential_thinking_tool.py  # 顺序思维工具
│   │   ├── task_done_tool.py            # 任务完成标记工具
│   │   ├── ckg_tool.py                  # 代码知识图谱工具
│   │   ├── ckg/                         # CKG 子模块
│   │   │   ├── base.py
│   │   │   └── ckg_database.py
│   │   ├── mcp_tool.py                  # MCP 工具封装
│   │   ├── edit_tool_cli.py             # 独立 CLI 编辑工具 (PyInstaller)
│   │   ├── json_edit_tool_cli.py        # 独立 CLI JSON 编辑工具 (PyInstaller)
│   │   └── docker_tool_executor.py      # Docker 模式工具执行器
│   ├── utils/                           # 工具模块
│   │   ├── __init__.py
│   │   ├── config.py                    # YAML 配置管理
│   │   ├── constants.py                 # 常量定义
│   │   ├── legacy_config.py             # 旧版 JSON 配置兼容
│   │   ├── trajectory_recorder.py       # 轨迹记录器
│   │   ├── mcp_client.py                # MCP 客户端
│   │   ├── cli/                         # CLI 用户界面
│   │   │   ├── __init__.py
│   │   │   ├── cli_console.py           # 控制台抽象 (ConsoleFactory)
│   │   │   ├── console_simple.py        # 简单控制台实现
│   │   │   ├── console_rich.py          # Rich 控制台实现
│   │   │   ├── lakeview.py              # Lakeview 摘要生成
│   │   │   └── textual_app.py           # Textual TUI 应用
│   │   └── llm_clients/                 # LLM 多提供商客户端
│   │       ├── __init__.py
│   │       ├── llm_basics.py            # LLM 基础数据结构
│   │       ├── llm_client.py            # LLMClient 门面类
│   │       ├── base_client.py           # BaseLLMClient 抽象基类
│   │       ├── openai_client.py         # OpenAI 客户端
│   │       ├── anthropic_client.py      # Anthropic 客户端
│   │       ├── google_client.py         # Google Gemini 客户端
│   │       ├── azure_client.py          # Azure OpenAI 客户端
│   │       ├── doubao_client.py         # 豆包客户端
│   │       ├── ollama_client.py         # Ollama 本地模型客户端
│   │       └── openrouter_client.py     # OpenRouter 客户端
│   └── prompt/                          # 提示词模板
│       ├── __init__.py
│       └── agent_prompt.py              # 系统提示词
├── evaluation/                          # SWE-bench 评估
│   ├── run_evaluation.py                # 评估运行入口
│   ├── setup.sh                         # 环境准备脚本
│   ├── swe_bench_evaluator.py           # SWE-bench 评估器
│   ├── swe_bench_live_evaluator.py      # SWE-bench-Live 评估器
│   ├── multi_swe_bench_evaluator.py     # Multi-SWE-bench 评估器
│   ├── utils.py                         # 评估工具函数
│   ├── patch_selection/                 # 补丁选择模块
│   │   ├── selector.py
│   │   ├── run_evaluation.py
│   │   ├── trae_selector/
│   │   │   ├── selector_agent.py
│   │   │   ├── selector_evaluation.py
│   │   │   ├── sandbox.py
│   │   │   ├── utils.py
│   │   │   └── tools/
│   │   └── README.md
│   └── README.md
├── server/                              # HTTP 服务 (开发中)
│   └── Readme.md
├── tests/                               # 测试套件
│   ├── test_cli.py
│   ├── agent/test_trae_agent.py
│   ├── tools/
│   │   ├── test_bash_tool.py
│   │   ├── test_edit_tool.py
│   │   ├── test_json_edit_tool.py
│   │   ├── test_mcp_tool.py
│   │   └── test_ckg_tool.py
│   └── utils/
│       ├── test_config.py
│       ├── test_mcp_client.py
│       ├── test_google_client.py
│       ├── test_ollama_client_utils.py
│       └── test_openrouter_client_utils.py
├── docs/                                # 文档
│   ├── tools.md
│   ├── TRAJECTORY_RECORDING.md
│   ├── roadmap.md
│   └── legacy_config.md
├── trae_config.yaml.example             # 示例配置文件
├── pyproject.toml                       # Python 项目配置
├── Makefile                             # 构建自动化
├── README.md                            # 项目 README
├── CODE_WIKI.md                         # 本文件
└── LICENSE                              # MIT 许可证

4. 主要模块说明

4.1 CLI 层 (trae_agent/cli.py)

CLI 层使用 click 库构建,提供三个核心命令:

命令功能关键参数
run执行单个任务--provider, --model, --working-dir, --max-steps, Docker 相关参数
interactive启动交互式会话--provider, --model, --console-type
show-config显示当前配置--config-file, --provider
tools列出可用工具

关键函数:

  • resolve_config_file() — 向后兼容解析配置文件(YAML 优先,回退到 JSON)
  • check_docker() — 检查 Docker CLI 和守护进程状态
  • build_with_pyinstaller() — 为 Docker 模式构建独立工具二进制文件

4.2 代理编排层 (trae_agent/agent/agent.py)

Agent 类是一个 Facade,负责:

  • 根据 agent_type 创建具体的 Agent 实例(当前仅支持 trae_agent
  • 管理轨迹记录器(自动生成文件名或使用用户指定路径)
  • 初始化 MCP 工具
  • 编排 CLI 控制台和代理执行的异步任务
class Agent:
    async def run(self, task, extra_args, tool_names):
        self.agent.new_task(task, extra_args, tool_names)  # 初始化任务
        await self.agent.initialise_mcp()                   # 发现 MCP 工具
        execution = await self.agent.execute_task()         # 执行任务
        await self.agent.cleanup_mcp_clients()              # 清理 MCP
        return execution

4.3 基础代理 (trae_agent/agent/base_agent.py)

BaseAgent 是抽象基类,定义了代理的核心执行循环:

核心执行循环 (execute_task):

while step_number <= max_steps:
    1. _run_llm_step → LLM 生成响应
       ├── LLMClient.chat(messages, model_config, tools)
       └── 返回 LLMResponse (内容 + 工具调用)
    2. 检测任务完成 (llm_indicates_task_completed)
       ├── 是: 验证 (is_task_completed) → 标记 COMPLETED
       └── 否: 执行工具调用
    3. _tool_call_handler
       ├── 并行/串行执行工具
       ├── 反射 (reflect_on_result)
       └── 返回新消息
    4. _finalize_step → 记录轨迹

生命周期状态 (AgentStepState):

  • THINKING — LLM 正在生成响应
  • CALLING_TOOL — 正在执行工具
  • REFLECTING — 反思工具结果
  • COMPLETED — 步骤完成
  • ERROR — 步骤出错

4.4 TraeAgent 实现 (trae_agent/agent/trae_agent.py)

TraeAgent 继承 BaseAgent,是专门用于软件工程任务的具体实现:

关键特性:

  • 使用 task_done 工具调用作为任务完成信号(而非文本匹配)
  • 支持 must_patch 模式:要求生成非空的 Git patch
  • 支持 MCP (Model Context Protocol) 工具发现
  • 提供 get_git_diff() 生成项目变更的补丁
  • 提供 remove_patches_to_tests() 过滤测试文件变更

系统提示词 (TRAE_AGENT_SYSTEM_PROMPT):

  • 7 步工作流:理解问题 → 探索代码 → 复现 Bug → 调试诊断 → 实现修复 → 验证测试 → 总结

4.5 工具系统 (trae_agent/tools/)

工具系统采用策略模式,所有工具继承自 Tool 抽象基类,通过 tools_registry 注册。

tools_registry: dict[str, type[Tool]] = {
    "bash": BashTool,
    "str_replace_based_edit_tool": TextEditorTool,
    "json_edit_tool": JSONEditTool,
    "sequentialthinking": SequentialThinkingTool,
    "task_done": TaskDoneTool,
    "ckg": CKGTool,
}

每个工具必须实现:

  • get_name() — 工具名称
  • get_description() — 工具描述(给 LLM 看)
  • get_parameters() — 参数定义(用于生成 JSON Schema)
  • execute(arguments) — 异步执行逻辑

ToolExecutor 负责工具调度,支持并行和串行执行模式。

4.6 LLM 客户端 (trae_agent/utils/llm_clients/)

LLM 客户端采用门面模式 + 策略模式:

LLMClient (门面)
  │
  ├── OpenAIClient      ← openai SDK
  ├── AnthropicClient   ← anthropic SDK
  ├── GoogleClient      ← google-genai SDK
  ├── AzureClient       ← openai SDK (Azure endpoint)
  ├── DoubaoClient      ← openai SDK (豆包 endpoint)
  ├── OllamaClient      ← ollama SDK
  └── OpenRouterClient  ← openai SDK (OpenRouter endpoint)

所有客户端实现继承 BaseLLMClient 抽象基类,统一通过 LLMClient.chat() 调用。


5. 关键类与函数

5.1 数据模型类

文件说明
LLMMessagellm_basics.pyLLM 消息:role + content + tool_call + tool_result
LLMResponsellm_basics.pyLLM 响应:content + usage + tool_calls
LLMUsagellm_basics.pyToken 消耗统计(支持累加)
ToolCalltools/base.py工具调用:name + call_id + arguments
ToolResulttools/base.py工具执行结果:call_id + success + result/error
ToolParametertools/base.py工具参数定义:name + type + description
ToolExecResulttools/base.py工具执行中间结果:output + error
AgentStepagent_basics.py代理步骤:step_number + state + tool_calls + llm_response
AgentExecutionagent_basics.py完整执行:task + steps + final_result + success + total_tokens
AgentStateagent_basics.py执行状态枚举: IDLE / RUNNING / COMPLETED / ERROR
AgentStepStateagent_basics.py步骤状态枚举: THINKING / CALLING_TOOL / REFLECTING / COMPLETED / ERROR

5.2 配置数据类

文件说明
Configconfig.py顶层配置,包含 lakeview / model_providers / models / trae_agent
TraeAgentConfigconfig.pyTraeAgent 配置,继承 AgentConfig
AgentConfigconfig.py基础代理配置:max_steps / model / tools / mcp
ModelConfigconfig.py模型配置:model / temperature / top_p / max_tokens / parallel_tool_calls
ModelProviderconfig.py模型提供商配置:api_key / provider / base_url
MCPServerConfigconfig.pyMCP 服务器配置:command / args / url / headers / env
LakeviewConfigconfig.pyLakeview 摘要配置

5.3 关键函数

函数所在类/模块说明
Config.create()Config从 YAML 文件或字符串创建配置对象
Config.resolve_config_values()Config按 CLI > ENV > Config 优先级解析配置
resolve_config_value()config.py 模块函数通用配置值解析(优先级: CLI > ENV > Config)
BaseAgent.execute_task()BaseAgent核心执行循环
BaseAgent._run_llm_step()BaseAgentLLM 请求与响应处理
BaseAgent._tool_call_handler()BaseAgent工具调用分发与结果处理
BaseAgent.llm_indicates_task_completed()BaseAgent检测任务完成信号
TraeAgent.new_task()TraeAgent创建新任务,组装初始消息
TraeAgent.get_git_diff()TraeAgent获取 Git diff 补丁
TraeAgent.discover_mcp_tools()TraeAgent发现并注册 MCP 工具
ToolExecutor.parallel_tool_call()ToolExecutor并行执行多个工具调用
ToolExecutor.sequential_tool_call()ToolExecutor串行执行多个工具调用
Tool.get_input_schema()Tool生成 OpenAI 兼容的 JSON Schema
LLMClient.chat()LLMClient统一聊天接口,内部路由到具体客户端
TrajectoryRecorder.start_recording()TrajectoryRecorder开始记录轨迹
TrajectoryRecorder.record_agent_step()TrajectoryRecorder记录代理步骤
TrajectoryRecorder.finalize_recording()TrajectoryRecorder完成记录并保存

6. 依赖关系

6.1 核心依赖 (pyproject.toml)

openai>=1.86.0              # OpenAI / Azure / Doubao / OpenRouter API
anthropic>=0.54.0,<=0.60.0  # Anthropic Claude API
google-genai>=1.24.0        # Google Gemini API
ollama>=0.5.1              # 本地 Ollama 模型
click>=8.0.0               # CLI 框架
asyncclick>=8.0.0          # 异步 CLI 框架
pydantic>=2.0.0            # 数据验证
pyyaml>=6.0.2              # YAML 配置解析
python-dotenv>=1.0.0       # .env 文件加载
rich>=13.0.0               # 终端富文本
textual>=0.50.0            # TUI 框架
tree-sitter==0.21.3        # 代码解析
tree-sitter-languages==1.10.2  # 语言解析器
ruff>=0.12.4               # Python 代码检查/格式化
mcp==1.12.2                # Model Context Protocol
jsonpath-ng>=1.7.0         # JSONPath 查询
socksio>=1.0.0             # SOCKS 代理支持
typing-extensions>=4.0.0   # 类型扩展
pyinstaller==6.15.0        # Docker 模式二进制构建

6.2 可选依赖

依赖用途
testpytest, pytest-asyncio, pytest-mock, pytest-cov, pre-commit测试
evaluationdatasets, docker, pexpect, unidiffSWE-bench 评估

6.3 模块依赖关系图

cli.py
  ├── agent/agent.py
  │   ├── agent/base_agent.py
  │   │   ├── tools/__init__.py → tools/base.py → tools/*_tool.py
  │   │   │   └── tools/docker_tool_executor.py
  │   │   │       └── agent/docker_manager.py
  │   │   ├── utils/llm_clients/llm_client.py
  │   │   │   └── utils/llm_clients/base_client.py
  │   │   │       ├── openai_client.py / anthropic_client.py / ...
  │   │   │       └── utils/llm_clients/llm_basics.py (LLMMessage, LLMResponse)
  │   │   ├── utils/trajectory_recorder.py
  │   │   ├── utils/cli/cli_console.py
  │   │   └── utils/config.py
  │   │       └── utils/legacy_config.py
  │   └── agent/trae_agent.py
  │       ├── prompt/agent_prompt.py
  │       └── utils/mcp_client.py
  └── utils/config.py

7. 配置系统

7.1 配置优先级

命令行参数 > 配置文件 > 环境变量 > 默认值

7.2 YAML 配置结构 (trae_config.yaml)

agents:
  trae_agent:
    enable_lakeview: true
    model: trae_agent_model
    max_steps: 200
    tools:
      - bash
      - str_replace_based_edit_tool
      - sequentialthinking
      - task_done

model_providers:
  anthropic:
    api_key: sk-ant-xxx
    provider: anthropic
  openai:
    api_key: sk-xxx
    provider: openai
    base_url: https://openrouter.ai/api/v1  # 可选

models:
  trae_agent_model:
    model_provider: anthropic
    model: claude-sonnet-4-20250514
    max_tokens: 4096
    temperature: 0.5
    top_p: 0.9
    top_k: 40
    max_retries: 1
    parallel_tool_calls: true

mcp_servers:  # 可选
  playwright:
    command: npx
    args: ["@playwright/mcp@0.0.27"]

lakeview:  # 可选 (Agent 步骤摘要)
  model: lakeview_model

7.3 环境变量支持

环境变量用途
OPENAI_API_KEY / OPENAI_BASE_URLOpenAI 配置
ANTHROPIC_API_KEY / ANTHROPIC_BASE_URLAnthropic 配置
GOOGLE_API_KEY / GOOGLE_BASE_URLGoogle Gemini 配置
OPENROUTER_API_KEY / OPENROUTER_BASE_URLOpenRouter 配置
DOUBAO_API_KEY / DOUBAO_BASE_URL豆包配置
TRAE_CONFIG_FILE配置文件路径(默认 trae_config.yaml

8. 工具系统

8.1 内置工具一览

工具名称注册键功能
str_replace_based_edit_toolstr_replace_based_edit_toolTextEditorTool文件查看、创建、字符串替换、插入
bashbashBashTool在持久 Bash 会话中执行命令
sequential_thinkingsequentialthinkingSequentialThinkingTool分步思考、分支推理
json_edit_tooljson_edit_toolJSONEditTool使用 JSONPath 精确编辑 JSON
task_donetask_doneTaskDoneTool标记任务完成
ckgckgCKGTool代码知识图谱查询
MCP 工具(动态注册)MCPTool通过 MCP 协议的外部工具

8.2 BashTool 详解

  • 功能: 在持久化 Bash 会话中执行命令
  • 参数: command (命令字符串), is_interactive (是否交互), restart (重启会话)
  • 超时: 120 秒
  • 特性: 支持背景进程、会话重启、输出截断

8.3 TextEditorTool 详解

  • 命令: view (查看), create (创建), str_replace (替换), insert (插入)
  • 路径要求: 必须使用绝对路径
  • 特性: 自动行号显示、目录浏览、大文件行范围查看

8.4 JSONEditTool 详解

  • 命令: view, set, add, remove
  • 路径: 使用 JSONPath 表达式 (如 $.users[0].name)
  • 特性: 语法验证、格式化保留、详细信息错误提示

8.5 SequentialThinkingTool 详解

  • 参数: thought (当前思考), thought_number, total_thoughts, next_thought_needed
  • 高级: is_revision (修订), revises_thought (修订目标), branch_from_thought (分支)
  • 特性: 支持思考分支、动态调整思考数量、历史追踪

8.6 CKGTool 详解

  • 功能: 查询函数定义、类定义、类方法、代码调用关系
  • 数据库: 使用 tree-sitter 构建代码 AST 索引
  • 优势: 快速定位代码结构,无需逐文件搜索

8.7 MCPTool 详解

  • 功能: 封装 MCP 协议定义的外部工具
  • 集成: 通过 MCPClient 连接 MCP 服务器,自动发现工具
  • 传输: 支持 stdio、SSE、Streamable HTTP、WebSocket

8.8 DockerToolExecutor 详解

  • 功能: 根据工具类型决定在本地还是 Docker 容器内执行
  • Docker 化工具: bash, str_replace_based_edit_tool, json_edit_tool
  • 内部: 使用 PyInstaller 构建独立二进制,复制到容器内执行

9. LLM 多提供商支持

9.1 架构

LLMClient 充当门面,根据 LLMProvider 枚举选择具体的客户端实现:

class LLMProvider(Enum):
    OPENAI = "openai"
    ANTHROPIC = "anthropic"
    AZURE = "azure"
    OLLAMA = "ollama"
    OPENROUTER = "openrouter"
    DOUBAO = "doubao"
    GOOGLE = "google"

9.2 BaseLLMClient 抽象基类

所有客户端实现的统一接口:

方法说明
chat(messages, model_config, tools)发送聊天请求并获取响应
supports_tool_calling(model_config)检查是否支持工具调用
set_trajectory_recorder(recorder)关联轨迹记录器
set_chat_history(messages)设置聊天历史

9.3 客户端实现差异

客户端SDK工具调用模式特殊参数
OpenAIClientopenaitool_choice: autostrict: true (JSON Schema)
AnthropicClientanthropictool_choicethinking (扩展思考), top_k
GoogleClientgoogle-genai函数声明candidate_count
AzureClientopenai同 OpenAImax_completion_tokens (o3/gpt-5)
DoubaoClientopenai同 OpenAI豆包特有 base_url
OllamaClientollama同 OpenAI本地模型
OpenRouterClientopenai同 OpenAI多模型路由

10. 轨迹记录系统

10.1 核心类: TrajectoryRecorder

位置: trae_agent/utils/trajectory_recorder.py

数据流:

BaseAgent.execute_task()
  ├── TrajectoryRecorder.start_recording()
  ├── 循环中:
  │   ├── LLMClient.chat() → TrajectoryRecorder.record_llm_interaction()
  │   ├── BaseAgent._record_handler() → TrajectoryRecorder.record_agent_step()
  │   └── TrajectoryRecorder.update_lakeview() (如果启用了 Lakeview)
  └── TrajectoryRecorder.finalize_recording()

10.2 JSON 轨迹文件结构

{
  "task": "任务描述",
  "start_time": "2025-06-12T22:05:46",
  "end_time": "2025-06-12T22:06:15",
  "provider": "anthropic",
  "model": "claude-sonnet-4-20250514",
  "max_steps": 200,
  "success": true,
  "final_result": "任务完成总结",
  "execution_time": 28.69,
  "llm_interactions": [ /* 每次 LLM 请求/响应 */ ],
  "agent_steps": [ /* 每个代理步骤:状态、工具调用、结果 */ ]
}

10.3 保存机制

  • 默认保存到 trajectories/trajectory_YYYYMMDD_HHMMSS.json
  • 每步操作后自动保存(非仅在结束时)
  • 目录自动创建

11. Docker 模式

11.1 支持的 Docker 操作

CLI 参数说明
--docker-image从指定镜像创建新容器
--docker-container-id附加到已有容器
--dockerfile-path从 Dockerfile 构建镜像
--docker-image-file从 tar 归档加载镜像
--docker-keep完成后是否保留容器(默认保留)

11.2 架构

本地环境                           Docker 容器
┌──────────────┐               ┌─────────────────────┐
│  TraeAgent   │               │  Bash session       │
│  LLM Client  │               │  Edit tools         │
│  ToolExecutor├──────┬───────►│  JSON edit tools    │
│              │      │        │  Workspace files    │
└──────────────┘      │        └─────────────────────┘
                      │
               ┌──────▼──────────┐
               │ DockerToolExecutor │
               │  路由容器工具调用   │
               └─────────────────┘

11.3 DockerToolExecutor 详解

  • 维护一个 original_executor(用于本地工具)和 docker_manager
  • 容器内工具使用 PyInstaller 构建为独立二进制
  • 自动将工具二进制和 workspace 目录挂载到容器

11.4 DockerManager

位置: trae_agent/agent/docker_manager.py

  • 容器生命周期管理: start(), stop(), exec_command()
  • 支持从多种来源创建容器(镜像名、容器 ID、Dockerfile、tar 文件)
  • 工作目录映射和工具目录同步

12. 评估系统

12.1 支持的基准

基准说明数据集
SWE-bench真实 Python 仓库 GitHub IssueSWE-bench_Verified, SWE-bench_Lite, SWE-bench
SWE-bench-Live实时 Issue 解决基准lite, verified, full
Multi-SWE-bench多语言 Issue 解决基准flash, mini (Java/TS/JS/Go/Rust/C/C++)

12.2 评估流程

1. 环境准备 (setup.sh)
   ├── 克隆 benchmark 仓库
   ├── 安装 benchmark harness
   └── 安装评估依赖

2. 执行评估 (run_evaluation.py)
   ├── 模式: expr (仅生成), eval (仅评估), e2e (端到端)
   ├── 为每个实例:
   │   ├── 拉取 Docker 镜像
   │   ├── 构建 Trae Agent 制品 (trae-agent.tar)
   │   ├── 在容器中运行 Trae Agent
   │   └── 收集生成的 patch
   └── 使用 benchmark harness 评估 patch

12.3 评估输出结构

results/{benchmark}_{dataset}_{run_id}/
├── predictions.json     # 生成的 patch 集合
├── results.json         # 评估结果
└── {instance_id}/
    ├── problem_statement.txt
    ├── {instance_id}.patch
    ├── {instance_id}.json   # 轨迹文件
    └── ...

13. 项目运行方式

13.1 环境要求

13.2 安装

git clone https://github.com/bytedance/trae-agent.git
cd trae-agent
uv sync --all-extras
source .venv/bin/activate

13.3 配置

cp trae_config.yaml.example trae_config.yaml
# 编辑 trae_config.yaml,填入 API Key 和模型配置

13.4 基本命令

# 执行单次任务
trae-cli run "创建一个 Python hello world 脚本"

# 查看配置
trae-cli show-config

# 交互模式
trae-cli interactive

# 指定提供商和模型
trae-cli run "修复 main.py 中的 bug" --provider anthropic --model claude-sonnet-4-20250514

# Docker 模式
trae-cli run "运行测试" --docker-image python:3.12 --working-dir /path/to/project

# 保存轨迹
trae-cli run "调试认证模块" --trajectory-file debug_session.json

13.5 交互模式命令

命令功能
任意任务描述执行该任务
status显示代理信息和配置
help显示帮助
clear清屏
exit / quit退出会话

14. 开发与测试

14.1 开发环境

make install-dev        # 创建 venv 并安装所有依赖
make pre-commit-install # 安装 pre-commit 钩子

14.2 测试

make test               # 运行所有测试(跳过外部服务测试)
make uv-test            # 通过 uv 运行测试

# 手动运行
uv run pytest tests/ -v --tb=short

14.3 代码规范

make fix-format         # ruff 自动格式化
make pre-commit-run     # 运行 pre-commit 检查

14.4 测试结构

tests/
├── test_cli.py                    # CLI 逻辑测试
├── agent/test_trae_agent.py       # TraeAgent 测试
├── tools/
│   ├── test_bash_tool.py          # Bash 工具测试
│   ├── test_edit_tool.py          # 编辑工具测试
│   ├── test_json_edit_tool.py     # JSON 编辑工具测试
│   ├── test_mcp_tool.py           # MCP 工具测试
│   └── test_ckg_tool.py           # CKG 工具测试
└── utils/
    ├── test_config.py             # 配置解析测试
    ├── test_mcp_client.py         # MCP 客户端测试
    ├── test_google_client.py      # Google 客户端测试
    ├── test_ollama_client_utils.py # Ollama 工具函数测试
    └── test_openrouter_client_utils.py # OpenRouter 工具函数测试

14.5 Makefile 目标

目标说明
install-dev创建 venv + 安装所有依赖
uv-sync安装所有依赖(包括 test/evaluation)
uv-test运行所有测试
uv-pre-commit运行 pre-commit 钩子
fix-formatruff 格式化和修复
clean清理构建产物和缓存

文档版本: v1.0
生成日期: 2026-05-30
基于提交: 最新 main 分支

0

评论区