编码工具界面(读取、编辑、Bash)
代码代理所需的最少工具:读取文件、编辑文件、运行 shell、运行测试。
编码工具界面(读取、编辑、Bash) 是 CoddyKit 上的免费 AI Agents 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
代码代理需要哪些工具
最低限度包括:
- read_file — 查看代码
- edit_file / write_file — 修改代码
- bash — 运行 shell 命令(测试、构建)
- search / grep — 按字符串或符号查找代码
read_file
def read_file(path: str, start_line: int = 0, end_line: int | None = None) -> str:
with open(path) as f:
lines = f.readlines()
return ''.join(lines[start_line:end_line])
# --- demo ---
with open('demo_source.py', 'w', encoding='utf-8') as f:
f.write('line0\nline1\nline2\nline3\nline4\n')
snippet = read_file('demo_source.py', start_line=1, end_line=3)
print('Lines 1-2 of demo_source.py:')
print(snippet)
按行范围读取可节省令牌
对于大型文件,只读取相关范围。与每次调用都读取整个文件相比,可以大幅节省令牌。
edit_file(字符串替换)
Anthropic 的字符串替换模式:在文件中查找唯一字符串并将其替换:
def edit_file(path: str, old_string: str, new_string: str):
contents = read_file(path)
occurrences = contents.count(old_string)
if occurrences == 0:
raise ValueError('old_string not found')
if occurrences > 1:
raise ValueError('old_string is not unique')
contents = contents.replace(old_string, new_string)
with open(path, 'w') as f:
f.write(contents)为什么使用字符串替换而不是差异
- 对模型来说比生成有效的差异语法更简单
- 迫使模型查看 REAL 代码(有助于发现幻觉)
- 遇到歧义时会报错
Claude Code 使用的就是这种格式。
write_file
用于创建新文件:
def write_file(path: str, content: str):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w') as f:
f.write(content)bash
Shell 命令——用于测试、构建和安装软件包:
def bash(command: str, timeout: int = 60) -> dict:
import subprocess
try:
result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=timeout)
return {'stdout': result.stdout[-5000:], 'stderr': result.stderr[-5000:], 'exit_code': result.returncode}
except subprocess.TimeoutExpired:
return {'error': 'timeout', 'exit_code': -1}
# --- demo ---
result = bash("echo hello from the sandboxed shell")
print(f"exit_code={result['exit_code']}")
print(f"stdout={result['stdout'].strip()!r}")
将 bash 工具置于沙箱中
NEVER 在您的主机上运行 bash。请使用 Docker / Firecracker / E2B。(请参阅之前关于沙箱的课程。)
截断过长的输出
测试失败可能会输出数 MB 的内容。请截取最后几个 KB——其中通常包含实际错误:
stderr = 'error line\n' * 1000
if len(stderr) > 5000:
stderr = '...[truncated]...' + stderr[-5000:]
print(f'Truncated stderr length: {len(stderr)}')search / grep
def grep(pattern: str, path: str = '.', file_glob: str = '**/*') -> list[str]:
matches = []
for f in glob(file_glob, recursive=True):
for i, line in enumerate(open(f)):
if re.search(pattern, line):
matches.append(f'{f}:{i+1}: {line.rstrip()}')
return matches[:50]list_files
def list_files(path: str = '.') -> list[str]:
return [p for p in glob(f'{path}/**', recursive=True) if os.path.isfile(p)][:200]可选:AST 工具
用于更深入地理解代码:
def find_function(name: str, path: str):
tree = ast.parse(open(path).read())
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name == name:
return ast.unparse(node)工具描述在这里最重要
代码代理选错工具的次数多于聊天代理。因此请在工具描述上投入额外时间:
description='Edit a file by replacing a unique string. The old_string MUST appear exactly once in the file. Reads the file first to validate. Use this for any code change in an existing file.'这就是完整的工具集
读取、编辑、写入、执行命令、搜索、列出。借助这六种工具,智能体几乎可以完成任何软件工程任务。只有在测量到确实有收益时,才添加专用工具。
编辑模式
为什么“字符串替换”编辑比“发送完整文件”编辑更安全?
回顾
读取、编辑(字符串替换)、写入、执行命令、搜索、列出。六种工具,只要描述清晰并受到沙箱保护,就足以应对几乎任何编程智能体任务。
常见问题解答
「编码工具界面(读取、编辑、Bash)」课时是免费的吗?
是的 — 「编码工具界面(读取、编辑、Bash)」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents 课程共包含 4 节课。
「编码工具界面(读取、编辑、Bash)」这节课中我会学到什么?
代码代理所需的最少工具:读取文件、编辑文件、运行 shell、运行测试。 你通过在浏览器中直接运行的动手代码来练习 AI Agents,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「编码工具界面(读取、编辑、Bash)」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents 课中编写并运行代码吗?
能。每节 AI Agents 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 代理模式:规划—执行—验证
- 编码工具界面(读取、编辑、Bash)
- 迭代式自我纠错循环
- SWE-Agent 与 OpenDevin 架构