字節開源的 AI Coding Agent —— Trae Agent 深入淺出
1. 項目概述
從 Cursor 到 Trae,從 claude code 到 gemini cli,AI Coding 都是火熱的戰場,現在字節開源了新的 trae-agent(https://github.com/bytedance/trae-agent),我們來一探究竟。
Trae Agent is an LLM-based agent for general purpose software engineering tasks. It provides a powerful CLI interface that can understand natural language instructions and execute complex software engineering workflows using various tools and LLM providers.
Trae Agent 是一個基於大語言模型 (LLM) 的軟件工程 Agent,提供強大的命令行界面,能夠理解自然語言指令並使用各種工具執行復雜的軟件工程工作流。
1.1 核心特性
-
多 LLM 支持 :支持 OpenAI 和 Anthropic 官方 API
-
豐富的工具生態系統 :文件編輯、Bash 執行、順序思考等
-
交互模式 :提供對話式界面進行迭代開發
-
軌跡記錄 :詳細記錄所有 Agent 操作,便於調試和分析
-
靈活配置 :基於 JSON 的配置,支持環境變量
-
Lakeview :爲 Agent 步驟提供簡短而精確的摘要
2. 系統架構
2.1 核心組件
代碼結構
Trae Agent
├── Agent系統 (Agent)
│ ├── 基礎Agent (Base Agent)
│ └── Trae Agent (Trae Agent)
├── LLM 客戶端 (LLM Client)
│ ├── OpenAI 客戶端
│ └── Anthropic 客戶端
├── 工具系統 (Tools)
│ ├── 工具基類 (Tool)
│ ├── 工具執行器 (ToolExecutor)
│ ├── 文本編輯工具 (TextEditorTool)
│ ├── Bash 工具 (BashTool)
│ ├── 順序思考工具 (SequentialThinkingTool)
│ └── 任務完成工具 (TaskDoneTool)
├── 軌跡記錄 (Trajectory Recording)
│ └── 軌跡記錄器 (TrajectoryRecorder)
└── 命令行界面 (CLI)
└── CLI 控制檯 (CLIConsole)
2.2 運行流程
- 任務初始化 :
-
創建 TraeAgent 實例
-
設置軌跡記錄器
-
調用 new_task() 初始化任務和工具
- 執行循環 :
-
調用 execute_task() 開始執行循環
-
向 LLM 發送消息並獲取響應
-
解析 LLM 響應中的工具調用
-
執行工具調用並獲取結果
-
對結果進行反思
-
將結果和反思發送回 LLM
-
重複直到任務完成或達到最大步驟數
- 任務完成 :
-
檢測任務是否完成
-
記錄最終結果
-
完成軌跡記錄
工具調用流程
- 工具調用解析 :
-
從 LLM 響應中提取工具調用
-
驗證工具名稱和參數
- 工具執行 :
-
查找對應的工具實例
-
調用工具的 execute() 方法
-
捕獲執行結果或錯誤
- 結果處理 :
-
將工具執行結果轉換爲 ToolResult
-
將結果發送回 LLM
3. 核心組件詳解
3.1 Agent 系統
3.1.1 基礎 Agent (Base Agent)
Agent 類是所有 Agent 的基類,定義了 Agent 的基本行爲和接口:
-
初始化 :設置 LLM 客戶端、工具、配置參數等
-
任務執行 :實現了 execute_task() 方法,這是 Agent 執行任務的核心循環
-
狀態管理 :跟蹤 Agent 執行步驟、狀態轉換等
-
工具調用 :處理 LLM 生成的工具調用並執行
-
反思機制 :對工具執行結果進行反思
3.1.2 Trae Agent (Trae Agent)
TraeAgent 類繼承自 Agent ,專門用於軟件工程任務:
-
任務初始化 :實現了 new_task() 方法,初始化工具和任務參數
-
軌跡記錄 :設置和管理軌跡記錄器
-
任務完成檢測 :增強的任務完成檢測邏輯
-
補丁生成 :支持代碼補丁生成和驗證
查看 agent 系統,通常都是要看看提示詞的,這裏也不例外:
def get_system_prompt(self) -> str:
"""Get the system prompt for TraeAgent."""
return """You are an expert AI software engineering agent.
Your primary goal is to resolve a given GitHub issue by navigating the provided codebase, identifying the root cause of the bug, implementing a robust fix, and ensuring your changes are safe and well-tested.
Follow these steps methodically:
1. Understand the Problem:
- Begin by carefully reading the user's problem description to fully grasp the issue.
- Identify the core components and expected behavior.
2. Explore and Locate:
- Use the available tools to explore the codebase.
- Locate the most relevant files (source code, tests, examples) related to the bug report.
3. Reproduce the Bug (Crucial Step):
- Before making any changes, you **must** create a script or a test case that reliably reproduces the bug. This will be your baseline for verification.
- Analyze the output of your reproduction script to confirm your understanding of the bug's manifestation.
4. Debug and Diagnose:
- Inspect the relevant code sections you identified.
- If necessary, create debugging scripts with print statements or use other methods to trace the execution flow and pinpoint the exact root cause of the bug.
5. Develop and Implement a Fix:
- Once you have identified the root cause, develop a precise and targeted code modification to fix it.
- Use the provided file editing tools to apply your patch. Aim for minimal, clean changes.
6. Verify and Test Rigorously:
- Verify the Fix: Run your initial reproduction script to confirm that the bug is resolved.
- Prevent Regressions: Execute the existing test suite for the modified files and related components to ensure your fix has not introduced any new bugs.
- Write New Tests: Create new, specific test cases (e.g., using `pytest`) that cover the original bug scenario. This is essential to prevent the bug from recurring in the future. Add these tests to the codebase.
- Consider Edge Cases: Think about and test potential edge cases related to your changes.
7. Summarize Your Work:
- Conclude your trajectory with a clear and concise summary. Explain the nature of the bug, the logic of your fix, and the steps you took to verify its correctness and safety.
**Guiding Principle:** Act like a senior software engineer. Prioritize correctness, safety, and high-quality, test-driven development.
# GUIDE FOR HOW TO USE "sequential_thinking" TOOL:
- Your thinking should be thorough and so it's fine if it's very long. Set totalThoughts to at least 5, but setting it up to 25 is fine as well. You'll need more total thoughts when you are considering multiple possible solutions or root causes for an issue.
- Use this tool as much as you find necessary to improve the quality of your answers.
- You can run bash commands (like tests, a reproduction script, or 'grep'/'find' to find relevant context) in between thoughts.
- The sequential_thinking tool can help you break down complex problems, analyze issues step-by-step, and ensure a thorough approach to problem-solving.
- Don't hesitate to use it multiple times throughout your thought process to enhance the depth and accuracy of your solutions.
If you are sure the issue has been solved, you should call the `task_done` to finish the task."""
翻譯下:
您是一名專業的AI軟件工程Agent。
您的首要目標是通過分析提供的代碼庫,定位問題根源,實施穩健修復方案,並確保更改安全可靠且經過充分測試,從而解決指定的GitHub issue。
請嚴格遵循以下步驟:
理解問題
仔細閱讀用戶問題描述,全面理解issue細節
確定核心組件和預期行爲
探索定位
使用工具探索代碼庫
定位與問題報告最相關的文件(源碼/測試/示例)
復現Bug(關鍵步驟)
在修改前**必須**創建可穩定復現bug的腳本/測試用例,作爲驗證基準
分析復現腳本輸出,確認對bug表現形式的理解
調試診斷
檢查已識別的相關代碼段
必要時通過調試腳本(如print語句)追蹤執行流,精確定位bug根源
開發實施修復
確定根源後,編寫精準的代碼修改方案
使用文件編輯工具應用補丁,力求改動最小化、代碼整潔
嚴格驗證測試
驗證修復:運行初始復現腳本確認bug已解決
預防迴歸:執行修改文件及相關組件的現有測試套件,確保未引入新問題
編寫新測試:創建覆蓋原始bug場景的新測試用例(如pytest),防止問題復發
邊緣案例:考慮並測試與改動相關的潛在邊界情況
總結工作
清晰簡明地總結:解釋bug本質、修復邏輯、驗證正確性與安全性的步驟
核心原則:以高級軟件工程師的準則行動,優先保證正確性、安全性和高質量的測試驅動開發。
sequential_thinking工具使用指南
思考深度優先:保持徹底思考,允許長篇幅分析(建議totalThoughts設爲5-25條)
多場景適用:當需評估多種解決方案或問題根源時,應增加思考條數
靈活調用:可在思考間隙執行bash命令(如運行測試/復現腳本/grep/find檢索)
核心價值:該工具可幫助分解複雜問題、逐步分析,確保解決方案的深度與準確性
多次調用:在整個思考過程中可反覆使用以提升解決方案質量
任務完成:確認問題解決後,請調用task_done結束任務。
R1 來評價下:
- 結構化清晰
-
7 步流程覆蓋軟件工程全生命週期(理解→定位→復現→修復→驗證→總結)
-
強制要求先復現後修復(第 3 步),符合專業開發規範
- 質量導向
-
強調測試驅動(6 步驗證佔整體 40% 權重)
-
要求編寫新測試預防迴歸,體現工程嚴謹性
- 工具鏈整合
-
明確 sequential_thinking 工具的使用邏輯(支持長鏈思考 + bash 命令穿插)
-
提供 AI 行爲邊界(如 task_done 結束條件)
- 風險控制
-
要求最小化代碼改動(降低意外風險)
-
邊緣案例測試條款覆蓋防禦性編程思想
3.2 LLM 客戶端
LLMClient 類是與 LLM 提供商交互的主要接口:
-
多提供商支持 :支持 OpenAI、Anthropic 和 Azure
-
聊天接口 :提供統一的 chat() 方法與 LLM 交互
-
工具調用支持 :檢查模型是否支持工具調用
-
軌跡記錄集成 :自動記錄 LLM 交互
3.3 工具系統
3.3.1 工具基類 (Tool)
Tool 是所有工具的抽象基類:
-
接口定義 :定義了工具名稱、描述、參數和執行方法
-
參數架構 :提供參數定義和驗證
-
JSON 定義 :生成工具的 JSON 定義,用於 LLM 工具調用
3.3.2 工具執行器 (ToolExecutor)
ToolExecutor 負責管理和執行工具調用:
-
工具註冊 :維護可用工具的映射
-
執行工具調用 :處理工具調用並返回結果
-
並行 / 順序執行 :支持並行或順序執行多個工具調用
3.3.3 文本編輯工具 (TextEditorTool)
TextEditorTool 提供文件操作功能:
-
查看文件 :顯示文件內容或目錄列表
-
創建文件 :創建新文件
-
替換文本 :在文件中替換文本
-
插入文本 :在特定行插入文本
3.3.4 Bash 工具 (BashTool)
BashTool 允許執行 Bash 命令:
-
命令執行 :在 Bash shell 中執行命令
-
會話管理 :維護持久的 Bash 會話
-
超時處理 :處理長時間運行的命令
3.4 軌跡記錄
3.4.1 軌跡記錄器 (TrajectoryRecorder)
TrajectoryRecorder 記錄 Agent 執行的詳細軌跡:
-
LLM 交互記錄 :記錄所有 LLM 請求和響應
-
Agent 步驟記錄 :記錄 Agent 執行步驟、狀態和結果
-
工具調用記錄 :記錄工具調用和結果
-
JSON 序列化 :將軌跡數據保存爲 JSON 文件
3.5 命令行 CLI
命令行界面提供了與 Trae Agent 交互的主要方式:
-
任務執行 : run 命令執行單個任務
-
交互模式 : interactive 命令啓動交互式會話
-
工具列表 : tools 命令顯示可用工具
-
配置顯示 : show-config 命令顯示當前配置
4. 配置系統
4.1 配置文件
Trae Agent 使用 JSON 配置文件 (trae_config.json) 進行配置:
{
"default_provider": "anthropic",
"max_steps": 20,
"model_providers": {
"openai": {
"api_key": "your_openai_api_key",
"model": "gpt-4o",
"max_tokens": 128000,
"temperature": 0.5,
"top_p": 1
},
"anthropic": {
"api_key": "your_anthropic_api_key",
"model": "claude-sonnet-4-20250514",
"max_tokens": 4096,
"temperature": 0.5,
"top_p": 1,
"top_k": 0
}
}
}
4.2 配置優先級
配置值的解析遵循以下優先級:
-
命令行參數(最高)
-
環境變量
-
配置文件值
-
默認值(最低)
5. 使用指南
5.1 安裝
git clone <repository-url>
cd trae-agent
uv sync
5.2 基本用法
5.2.1 執行任務
trae-cli run "創建一個計算斐波那契數列的Python腳本"
5.2.2 交互模式
trae-cli interactive
6. 擴展與定製
6.1 添加新工具
要添加新工具,需要:
-
創建繼承自 Tool 的新類
-
實現必要的方法: get_name() , get_description() , get_parameters() , execute()
-
在 tools/init.py 中註冊工具
6.2 自定義 Agent 行爲
要自定義 Agent 行爲,可以:
-
繼承 Agent 或 TraeAgent 類
-
重寫相關方法,如 execute_task() , reflect_on_result() , is_task_completed()
7. 結論
Trae Agent 是一個功能強大、靈活且可擴展的 LLM AI Codinbg Agent 框架,對想研究 AI Coding 的同學來說,可以作爲一個學習範例。
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/R2JXNlAUtfZX6-J8ThftVw