手写一个 mini coding agent:
要哪些 tool,edit 冲突怎么处理?
先弄清楚:每个概念是什么
- Agent loop
- harness 反复调 model、执行它发的 tool call 的循环(见 agent 与 MCP 和 LLM harness)。
- edit tool
- 精确字符串替换,把一段 old string 换成 new string。
- Optimistic concurrency
- 不加锁,写的时候才检查文件有没有被别人动过。像共享文档提示“版本冲突,请刷新”。
看图:一个 loop 加三个 tool
30 秒回答
The core is a loop around three tools: read a file, edit it by replacing an exact string, and run a shell command. Each turn the model either answers or asks for a tool; the harness runs it and appends the result, errors included, so the model can correct itself. Edit requires that the file was read first and fails if it changed since then. That's optimistic concurrency: compare a hash before writing, and re-read on a mismatch. Commands run in a sandbox with a timeout and truncated output.
Agent loop 的最小实现
def run_agent(task, tools, max_steps=50):
messages = [{"role": "user", "content": task}]
for _ in range(max_steps):
reply = llm(messages, tool_schemas(tools))
messages.append(reply)
if not reply.tool_calls: # 不再要 tool,任务结束
return reply.content
for call in reply.tool_calls:
try:
out = tools[call.name](**call.args)
except Exception as e: # 报错也还给 model,让它改
out = f"error: {e}"
messages.append({"role": "tool", "id": call.id, "content": out})
return "stopped: max steps reached"
edit tool 怎么防覆写
| 版本 | 做法 | 还剩的问题 |
|---|---|---|
| v1 整文件重写 | model 输出整份新文件覆盖 | 费 token;用户刚改的内容被冲掉 |
| v2 字符串替换 | 只改 old string 那一处,找不到就报错 | read 之后文件被别人改过,model 还按旧内容改 |
| v3 加 hash 检查 | 先 read 才能 edit;写之前重算 hash,和 read 时不一样就报错,让 model 重读 | 冲突频繁时要反复重读 |
v3 就是 optimistic concurrency。蚂蚁那场面试里,候选人先答比较 diff,面试官追问为什么不比较 hash,并说 Codex 就是这样做的。这一点只有他的说法作依据。
read 和 bash 要管住什么
| Tool | 要管住什么 |
|---|---|
| read | 大文件先用 search 定位,再用 offset 和 limit 只读命中的一段(见 文件放不进 context) |
| bash | 在 sandbox 里跑;加 timeout;输出太长就截断 |
再加一个 search tool,按文件名或内容找文件。读默认放行,写和执行按规则确认(见 agent 权限)。
必答点
- 三个 tool:read、edit(精确字符串替换)、bash,再加 search
- loop:harness 执行 tool call 并追加 tool result,没有 tool call 就结束
- 报错也当作 tool result 还给 model,并设 max steps
- edit 冲突:先 read 才能 edit,写前比对 hash 或 mtime,变了就让 model 重读
- bash 在 sandbox 里跑,有 timeout,输出截断
追问
比对 hash 还是 mtime?
hash 只看内容,最可靠。mtime 不用读文件,便宜,但内容没变时也可能变。
改成多节点部署要考虑什么?(虾皮原题)
会话状态放到外部存储,workspace 跟着会话走,任何节点都能接着跑。请求要幂等,重发不会多改一次文件。
来源面经原帖:蚂蚁 Agent 开发日常实习一面(read、edit、bash 的追问,面试官关于 hash 的说法)、虾皮 Data Infra 实习一面(多节点部署)、阿里合集、作业帮 Golang 实习(规则由程序执行还是写进提示词) · 1p3a 1180230 · ml-八股 08 第 37 题 · 中文平台调研笔记 1.2 节和第 2 节