文字編輯器工具
為 Claude 提供 Anthropic 定義的文字編輯器工具,以檢視、建立和編輯檔案,並處理其 view、str_replace、create 和 insert 命令。
Claude 可以使用 Anthropic 結構描述的文字編輯器工具(text editor tool)來檢視和修改文字檔案,協助您除錯、修正並改善您的程式碼或其他文字文件。這讓 Claude 能夠直接與您的檔案互動,提供實際操作的協助,而不僅僅是建議變更。
關於模型支援,請參閱工具參考。
何時使用文字編輯器工具
以下是一些使用文字編輯器工具的範例情境:
- 程式碼除錯: 讓 Claude 識別並修正您程式碼中的錯誤,從語法錯誤到邏輯問題。
- 程式碼重構: 讓 Claude 透過有針對性的編輯來改善您的程式碼結構、可讀性和效能。
- 文件產生: 請 Claude 為您的程式碼庫新增 docstring、註解或 README 檔案。
- 測試建立: 讓 Claude 根據其對實作的分析,為您的程式碼建立單元測試。
使用文字編輯器工具
使用 Messages API 將文字編輯器工具(名為 str_replace_based_edit_tool)提供給 Claude。
您可以選擇性地指定 max_characters 參數,以控制檢視大型檔案時的截斷行為。
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
tools=[
{
"type": "text_editor_20250728",
"name": "str_replace_based_edit_tool",
"max_characters": 10000,
}
],
messages=[
{
"role": "user",
"content": "There's a syntax error in my primes.py file. Can you help me fix it?",
}
],
)
print(response)請依照以下方式使用文字編輯器工具:
為 Claude 提供文字編輯器工具和使用者提示
- 在您的 API 請求中包含文字編輯器工具
- 提供可能需要檢查或修改檔案的使用者提示,例如「您能修正我程式碼中的語法錯誤嗎?」
Claude 使用工具檢查檔案或目錄
- Claude 評估需要查看的內容,並使用
view命令檢查檔案內容或列出目錄內容 - API 回應將包含一個帶有
view命令的tool_use內容區塊
- Claude 評估需要查看的內容,並使用
執行 view 命令並回傳結果
- 從 Claude 的工具使用請求中擷取檔案或目錄路徑
- 讀取檔案內容或列出目錄內容
- 如果工具設定中指定了
max_characters參數,請將檔案內容截斷至該長度 - 透過以包含
tool_result內容區塊的新user訊息繼續對話,將結果回傳給 Claude
Claude 使用工具修改檔案
- 檢查檔案或目錄後,Claude 可能會使用
str_replace等命令進行變更,或使用insert在特定行號新增文字。 - 如果 Claude 使用
str_replace命令,Claude 會建構一個格式正確的工具使用請求,其中包含舊文字以及用來取代它的新文字
- 檢查檔案或目錄後,Claude 可能會使用
執行編輯並回傳結果
- 從 Claude 的工具使用請求中擷取檔案路徑、舊文字和新文字
- 在檔案中執行文字取代
- 將結果回傳給 Claude
Claude 提供其分析和說明
- 在檢查並可能編輯檔案後,Claude 會完整說明其發現的內容以及所做的變更
文字編輯器工具命令
文字編輯器工具支援多個用於檢視和修改檔案的命令:
view
view 命令允許 Claude 檢查檔案的內容或列出目錄的內容。它可以讀取整個檔案或特定範圍的行。
參數:
command:必須為 "view"path:要檢視的檔案或目錄的路徑view_range(選用):由兩個整數組成的陣列,指定要檢視的起始和結束行號。行號從 1 開始計算,結束行為 -1 表示讀取至檔案結尾。此參數僅適用於檢視檔案,不適用於目錄。
檢視檔案的範例:
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "str_replace_based_edit_tool",
"input": {
"command": "view",
"path": "primes.py"
}
}檢視目錄的範例:
{
"type": "tool_use",
"id": "toolu_02B19r91rw91mr917835mr9",
"name": "str_replace_based_edit_tool",
"input": {
"command": "view",
"path": "src/"
}
}str_replace
str_replace 命令允許 Claude 將檔案中的特定字串取代為新字串。這用於進行精確的編輯。
參數:
command:必須為 "str_replace"path:要修改的檔案路徑old_str:要取代的文字(必須完全相符,包括空白和縮排)new_str:要插入以取代舊文字的新文字
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "str_replace_based_edit_tool",
"input": {
"command": "str_replace",
"path": "primes.py",
"old_str": "for num in range(2, limit + 1)",
"new_str": "for num in range(2, limit + 1):"
}
}create
create 命令允許 Claude 以指定的內容建立新檔案。
參數:
command:必須為 "create"path:應建立新檔案的路徑file_text:要寫入新檔案的內容
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "str_replace_based_edit_tool",
"input": {
"command": "create",
"path": "test_primes.py",
"file_text": "import unittest\nimport primes\n\nclass TestPrimes(unittest.TestCase):\n def test_is_prime(self):\n self.assertTrue(primes.is_prime(2))\n self.assertTrue(primes.is_prime(3))\n self.assertFalse(primes.is_prime(4))\n\nif __name__ == '__main__':\n unittest.main()"
}
}insert
insert 命令允許 Claude 在檔案中的特定位置插入文字。
參數:
command:必須為 "insert"path:要修改的檔案路徑insert_line:要在其後插入文字的行號(0 表示檔案開頭)insert_text:要插入的文字
{
"type": "tool_use",
"id": "toolu_01A09q90qw90lq917835lq9",
"name": "str_replace_based_edit_tool",
"input": {
"command": "insert",
"path": "primes.py",
"insert_line": 0,
"insert_text": "\"\"\"Module for working with prime numbers.\n\nThis module provides functions to check if a number is prime\nand to generate a list of prime numbers up to a given limit.\n\"\"\"\n"
}
}範例:使用文字編輯器工具修正語法錯誤
此範例示範 Claude 如何使用文字編輯器工具修正 Python 檔案中的語法錯誤。
首先,您的應用程式為 Claude 提供文字編輯器工具以及修正語法錯誤的提示:
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],
messages=[
{
"role": "user",
"content": "There's a syntax error in my primes.py file. Can you help me fix it?",
}
],
)
print(response)Claude 首先使用文字編輯器工具檢視檔案:
{
"id": "msg_01XAbCDeFgHiJkLmNoPQrStU",
"model": "claude-opus-5",
"stop_reason": "tool_use",
"role": "assistant",
"content": [
{
"type": "text",
"text": "I'll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue."
},
{
"type": "tool_use",
"id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
"name": "str_replace_based_edit_tool",
"input": {
"command": "view",
"path": "primes.py"
}
}
]
}接著,您的應用程式應讀取檔案並將其內容回傳給 Claude:
response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],
messages=[
{
"role": "user",
"content": "There's a syntax error in my primes.py file. Can you help me fix it?",
},
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "I'll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue.",
},
{
"type": "tool_use",
"id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
"name": "str_replace_based_edit_tool",
"input": {"command": "view", "path": "primes.py"},
},
],
},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01AbCdEfGhIjKlMnOpQrStU",
"content": '1: def is_prime(n):\n2: """Check if a number is prime."""\n3: if n <= 1:\n4: return False\n5: if n <= 3:\n6: return True\n7: if n % 2 == 0 or n % 3 == 0:\n8: return False\n9: i = 5\n10: while i * i <= n:\n11: if n % i == 0 or n % (i + 2) == 0:\n12: return False\n13: i += 6\n14: return True\n15: \n16: def get_primes(limit):\n17: """Generate a list of prime numbers up to the given limit."""\n18: primes = []\n19: for num in range(2, limit + 1)\n20: if is_prime(num):\n21: primes.append(num)\n22: return primes\n23: \n24: def main():\n25: """Main function to demonstrate prime number generation."""\n26: limit = 100\n27: prime_list = get_primes(limit)\n28: print(f"Prime numbers up to {limit}:")\n29: print(prime_list)\n30: print(f"Found {len(prime_list)} prime numbers.")\n31: \n32: if __name__ == "__main__":\n33: main()',
}
],
},
],
)
print(response)Claude 識別出語法錯誤,並使用 str_replace 命令修正它:
{
"id": "msg_01VwXyZAbCdEfGhIjKlMnO",
"model": "claude-opus-5",
"stop_reason": "tool_use",
"role": "assistant",
"content": [
{
"type": "text",
"text": "I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you."
},
{
"type": "tool_use",
"id": "toolu_01PqRsTuVwXyZAbCdEfGh",
"name": "str_replace_based_edit_tool",
"input": {
"command": "str_replace",
"path": "primes.py",
"old_str": " for num in range(2, limit + 1)",
"new_str": " for num in range(2, limit + 1):"
}
}
]
}接著,您的應用程式應進行編輯並回傳結果:
response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
tools=[{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}],
messages=[
# 先前的訊息……
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you.",
},
{
"type": "tool_use",
"id": "toolu_01PqRsTuVwXyZAbCdEfGh",
"name": "str_replace_based_edit_tool",
"input": {
"command": "str_replace",
"path": "primes.py",
"old_str": " for num in range(2, limit + 1)",
"new_str": " for num in range(2, limit + 1):",
},
},
],
},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01PqRsTuVwXyZAbCdEfGh",
"content": "Successfully replaced text at exactly one location.",
}
],
},
],
)
print(response)最後,Claude 提供修正的完整說明:
{
"id": "msg_01IjKlMnOpQrStUvWxYzAb",
"model": "claude-opus-5",
"stop_reason": "end_turn",
"role": "assistant",
"content": [
{
"type": "text",
"text": "I've fixed the syntax error in your primes.py file. The issue was in the `get_primes` function at line 19. There was a missing colon (:) at the end of the for loop line.\n\nHere's what I changed:\n\nFrom:\n```python\nfor num in range(2, limit + 1)\n```\n\nTo:\n```python\nfor num in range(2, limit + 1):\n```\n\nIn Python, a colon is required at the end of statements that start a new code block, such as for loops, if statements, function definitions, etc. Without the colon, Python raises a syntax error because it doesn't know where the code block begins.\n\nYour code should now run correctly. The function will properly generate a list of prime numbers up to the specified limit."
}
]
}實作文字編輯器工具
文字編輯器工具是以無結構描述(schema-less)工具的形式實作的。使用此工具時,您不需要像其他工具一樣提供輸入結構描述;該結構描述已內建於 Claude 的模型中,且無法修改。
對於 Claude 4 及更新的模型,工具類型為 type: "text_editor_20250728"。
初始化您的編輯器實作
建立輔助函式來處理檔案操作,例如讀取、寫入和修改檔案。請考慮實作備份功能,以便從錯誤中復原。
處理編輯器工具呼叫
建立一個函式,根據命令類型處理來自 Claude 的工具呼叫:
def handle_editor_tool(tool_call): input_params = tool_call.input command = input_params.get("command", "") file_path = input_params.get("path", "") if command == "view": # 讀取並回傳檔案內容 pass elif command == "str_replace": # 取代檔案中的文字 pass elif command == "create": # 建立新檔案 pass elif command == "insert": # 在指定位置插入文字 pass實作安全措施
新增驗證和安全檢查:
- 驗證檔案路徑以防止目錄遍歷
- 在進行變更前建立備份
- 妥善處理錯誤
- 實作權限檢查
處理 Claude 的回應
從 Claude 的回應中擷取並處理工具呼叫:
# 處理 Claude 回應中的工具使用 for content in response.content: if content.type == "tool_use": # 根據指令執行工具 result = handle_editor_tool(content) # 將結果回傳給 Claude tool_result = { "type": "tool_result", "tool_use_id": content.id, "content": result, }
處理錯誤
使用文字編輯器工具時,可能會發生各種錯誤。以下是處理這些錯誤的指引:
如果 Claude 嘗試檢視或修改不存在的檔案,請在 tool_result 中回傳適當的錯誤訊息:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "Error: File not found",
"is_error": true
}
]
}如果 Claude 的 str_replace 命令在檔案中比對到多個位置,請回傳適當的錯誤訊息:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "Error: Found 3 matches for replacement text. Please provide more context to make a unique match.",
"is_error": true
}
]
}如果 Claude 的 str_replace 命令未比對到檔案中的任何文字,請回傳適當的錯誤訊息:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "Error: No match found for replacement. Please check your text and try again.",
"is_error": true
}
]
}如果在建立、讀取或修改檔案時發生權限問題,請回傳適當的錯誤訊息:
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": "toolu_01A09q90qw90lq917835lq9",
"content": "Error: Permission denied. Cannot write to file.",
"is_error": true
}
]
}遵循實作最佳實務
當要求 Claude 修正或修改程式碼時,請具體說明需要檢查哪些檔案或需要解決哪些問題。清楚的上下文有助於 Claude 識別正確的檔案並進行適當的變更。
較無幫助的提示:「您能修正我的程式碼嗎?」
較佳的提示:「我的 primes.py 檔案中有一個語法錯誤導致它無法執行。您能修正它嗎?」
在需要時清楚指定檔案路徑,尤其是當您處理多個檔案或位於不同目錄中的檔案時。
較無幫助的提示:「檢閱我的輔助檔案」
較佳的提示:「您能檢查我的 utils/helpers.py 檔案是否有任何效能問題嗎?」
在您的應用程式中實作備份系統,在允許 Claude 編輯檔案之前建立檔案副本,尤其是針對重要或正式環境的程式碼。
def backup_file(file_path):
"""Create a backup of a file before editing."""
backup_path = f"{file_path}.backup"
if os.path.exists(file_path):
with open(file_path, "r") as src, open(backup_path, "w") as dst:
dst.write(src.read())str_replace 命令要求要取代的文字必須完全相符。您的應用程式應確保舊文字恰好只有一個相符項目,否則應提供適當的錯誤訊息。
def safe_replace(file_path, old_text, new_text):
"""Replace text only if there's exactly one match."""
with open(file_path, "r") as f:
content = f.read()
count = content.count(old_text)
if count == 0:
return "Error: No match found"
elif count > 1:
return f"Error: Found {count} matches"
else:
new_content = content.replace(old_text, new_text)
with open(file_path, "w") as f:
f.write(new_content)
return "Successfully replaced text"在 Claude 對檔案進行變更後,請透過執行測試或檢查程式碼是否仍如預期運作來驗證變更。
def verify_changes(file_path):
"""Run tests or checks after making changes."""
try:
# 對於 Python 檔案,檢查語法錯誤
if file_path.endswith(".py"):
import ast
with open(file_path, "r") as f:
ast.parse(f.read())
return "Syntax check passed"
except Exception as e:
return f"Verification failed: {str(e)}"定價與 token 用量
文字編輯器工具採用與其他搭配 Claude 使用的工具相同的定價結構。它依據您所使用的 Claude 模型,遵循標準的輸入與輸出 token 定價。
除了基本 token 之外,文字編輯器工具還需要以下額外的輸入 token:
| 工具 | 額外輸入 token |
|---|---|
text_editor_20250429 (Claude 4.x) | 700 個 token |
如需有關工具定價的更詳細資訊,請參閱工具使用定價。
將文字編輯器工具與其他工具整合
您可以將文字編輯器工具與其他 Claude 工具一起使用。組合工具時,請確保您:
- 將工具版本與您使用的模型相匹配
- 將請求中包含的所有工具的額外 token 用量納入考量
變更記錄
| 日期 | 版本 | 變更 |
|---|---|---|
| 2025 年 7 月 28 日 | text_editor_20250728 | 發布更新版的文字編輯器工具,修正了一些問題並新增選用的 max_characters 參數。除此之外與 text_editor_20250429 完全相同。 |
| 2025 年 4 月 29 日 | text_editor_20250429 | 發布適用於 Claude 4 的文字編輯器工具。此版本移除了 undo_edit 命令,但保留所有其他功能。工具名稱已更新,以反映其基於 str_replace 的架構。 |
| 2025 年 3 月 13 日 | text_editor_20250124 | 推出獨立的文字編輯器工具文件。此版本針對 Claude Sonnet 3.7 進行了最佳化,但功能與前一版本完全相同。 |
| 2024 年 10 月 22 日 | text_editor_20241022 | 文字編輯器工具隨 Claude Sonnet 3.5 首次發布(已淘汰;請參閱模型棄用)。透過 view、create、str_replace、insert 和 undo_edit 命令提供檢視、建立和編輯檔案的功能。 |
後續步驟
以下是一些以更便利、更強大的方式使用文字編輯器工具的構想:
- 與您的開發工作流程整合:將文字編輯器工具建置到您的開發工具或 IDE 中
- 建立程式碼審查系統:讓 Claude 審查您的程式碼並進行改善
- 建置除錯助手:建立一個系統,讓 Claude 能協助您診斷並修正程式碼中的問題
- 實作檔案格式轉換:讓 Claude 協助您將檔案從一種格式轉換為另一種格式
- 自動化文件:設定工作流程,讓 Claude 自動為您的程式碼撰寫文件
文字編輯器工具讓 Claude 能夠直接處理您的程式碼庫,支援從除錯到自動化文件的各種工作流程。
Was this page helpful?