如何构建一个代理
or: The Emperor Has No Clothes
或者:皇帝的新装
Thorsten Ball, April 15, 2025
Thorsten Ball, 2025年4月15日
It’s not that hard to build a fully functioning, code-editing agent.
构建一个完全功能的代码编辑代理并不难。
It seems like it would be. When you look at an agent editing files, running commands, wriggling itself out of errors, retrying different strategies - it seems like there has to be a secret behind it.
这似乎是这样。当你看到一个代理编辑文件、运行命令、从错误中挣脱、重试不同策略时——似乎背后一定有一个秘密。
There isn’t. It’s an LLM, a loop, and enough tokens. It’s what we’ve been saying on the podcast from the start. The rest, the stuff that makes Amp so addictive and impressive? Elbow grease.
没有。这是一个 LLM,一个循环,以及足够的令牌。这就是我们从一开始就在 播客 上所说的。其余的,让 Amp 如此上瘾和令人印象深刻的东西?就是努力。
But building a small and yet highly impressive agent doesn’t even require that. You can do it in less than 400 lines of code, most of which is boilerplate.
但构建一个小而又令人印象深刻的代理甚至不需要那样。你可以在不到 400 行代码的情况下做到这一点,其中大部分是样板代码。
I’m going to show you how, right now. We’re going to write some code together and go from zero lines of code to “oh wow, this is… a game changer.”
我现在就要向你展示如何做到这一点。我们将一起编写一些代码,从零行代码到“哦哇,这真是……一个游戏规则改变者。”
I urge you to follow along. No, really. You might think you can just read this and that you don’t have to type out the code, but it’s less than 400 lines of code. I need you to feel how little code it is and I want you to see this with your own eyes in your own terminal in your own folders.
我 敦促 你跟着一起做。不,真的。你可能认为你可以只阅读这些,而不必输入代码,但这不到 400 行代码。我需要你 感受 这段代码有多少,我希望你在自己的终端和文件夹中亲眼看到这一点。
Here’s what we need:
我们需要的是:
Pencils out!
拿出铅笔!
Let’s dive right in and get ourselves a new Go project set up in four easy commands:
让我们直接开始,轻松用四个命令设置一个新的 Go 项目:
mkdir code-editing-agent
cd code-editing-agent
go mod init agent
touch main.go
Now, let’s open main.go
and, as a first step, put a skeleton of things we need in it:
现在,让我们打开 main.go
,作为第一步,放入我们需要的框架:
package main import ( "bufio" "context" "fmt" "os" "github.com/anthropics/anthropic-sdk-go"
) func main() { client := anthropic.NewClient() scanner := bufio.NewScanner(os.Stdin) getUserM...