标签 编译器 下的文章

代码Agent没有护城河?我用Go标准库和DeepSeek证明给你看!

本文永久链接 – https://tonybai.com/2025/04/18/reproduce-thorsten-balls-code-agent

大家好,我是Tony Bai。

人工智能Agent风头正劲,但构建它们真的那么难吗?本文深入解读Thorsten Ball 的“皇帝新衣”论,并通过一个 Go 标准库 + OpenAI Compatible API + DeepSeek的实战复现,揭示代码编辑 Agent 的核心简洁性,探讨真正的挑战与机遇。

引言:AI Agent 的神秘光环与现实

近来,AI Agent(人工智能代理)无疑是技术圈最炙手可热的话题之一。从能自主编码的软件工程师,到能规划执行复杂任务的智能助手,Agent 展现出的潜力令人兴奋。但与此同时,它们往往被一层神秘的光环笼罩,许多人觉得构建一个真正能工作的 Agent,尤其是能与代码交互、编辑文件的 Agent,必然涉及极其复杂的技术和深不可测的“炼金术”。

事实果真如此吗?Agent 的核心真的那么难以企及吗?

戳破泡沫:Thorsten Ball 的“皇帝新衣”论

著名开发者、“Writing A Compiler In Go”和“Writing An Interpreter In Go”两本高质量大作的作者Thorsten Ball最近发表了一篇振聋发聩的文章——《How To Build An Agent》(如何构建一个Agent),副标题更是直言不讳:“The Emperor Has No Clothes”(皇帝没有穿衣服)。

Thorsten 的核心观点非常清晰:构建一个功能齐全、能够编辑代码的 Agent,其核心原理并不神秘,甚至可以说没有所谓的“护城河”。他认为,那些看似神奇的 Agent(自动编辑文件、运行命令、从错误中恢复、尝试不同策略)背后并没有什么惊天秘密。

核心不过是:一个强大的大语言模型 (LLM) + 一个循环 (Loop) + 足够的上下文额度 (Tokens) + 工具调用 (Tools)

而那些让Agent产品(如Cursor等)令人印象深刻、甚至上瘾的特性,更多来自于务实的工程实践和大量的“体力活” (Elbow Grease)——UI 设计、编辑器集成、错误处理、提示词工程、工具链优化等等。

为了证明核心逻辑的简单性,Thorsten 在文章中手把手地用不到 400 行 Go 代码,基于Anthropic Claude模型和其Go SDK,实现了一个具备基本代码编辑能力的Agent Demo。这个Demo 包含了三个关键的工具:

  • read_file: 读取文件内容。
  • list_files: 列出目录内容。
  • edit_file: 编辑文件内容——令人惊讶的是,这个核心的编辑功能,其实现方式极其基础,仅仅是基于字符串替换

就是这样一个看似“简陋”的Agent,却能在实验中成功完成创建JavaScript文件、修改代码逻辑、解码字符串等任务,展现了自主规划和调用工具的能力。

不止于理论:我们用标准库 + OpenAI Compatible API + DeepSeek复现并验证!

Thorsten 的文章和示例极具启发性。但为了进一步验证其观点的普适性(其实主要是我没有Claude的API key)——即这种 Agent 的核心逻辑是否独立于特定的 LLM 提供商或 SDK——我们进行了一项挑战:

在不使用任何第三方 LLM SDK 的情况下,仅依靠Go标准库 (net/http, encoding/json 等),将 Thorsten 的示例移植到使用通用的 OpenAI Compatible API(主要是Chat Completions API)。

这意味着我们需要:

  • 手动构建 HTTP 请求。
  • 处理 API 认证 (Bearer Token)。
  • 定义匹配 OpenAI API 格式的 Go 结构体。
  • 处理 JSON 的序列化与反序列化。
  • 实现 OpenAI 的工具调用 (Tool Calling) 规范,包括函数定义、参数传递和结果返回。

经过一番努力,我们成功了!这个纯标准库版本的 Go Agent 不仅编译通过,而且完美地复现了 Thorsten 文章中的所有实验,无论是文件读写、列表,还是代码创建与修改,其行为和效果与原版几乎一致。

这有力地证明了:代码 Agent 的核心交互范式(请求 -> LLM 思考/工具调用 -> 执行工具 -> 返回结果 -> LLM 再思考…)确实是通用的,不依赖于特定的 SDK 或 API 提供商。 掌握了底层的 HTTP 通信和 API 协议规范,用任何语言、任何网络库都可以构建类似的核心。

亲手体验:一步步复现你的代码编辑Agent

理论和别人的成功固然鼓舞人心,但亲手实践才能带来最真切的感受。“纸上得来终觉浅,绝知此事要躬行”。下面,我们将结合关键代码片段,指导你一步步复现这个使用 Go 标准库和 OpenAI Compatible API 构建的代码编辑 Agent 实验。

(注意:你需要准备一个 OpenAI API Key 或其他兼容 OpenAI API 的服务商提供的 Key 和 Endpoint,我这里使用的是兼容OpenAI API的DeepSeek的deepseek-chat大模型。此外,这里展示的是关键代码片段,完整代码请参考code-editing-agent-deepseek)

准备工作:

  1. 环境配置: 确保安装 Go 环境。设置环境变量 OPENAI_API_KEY,以及可选的 OPENAI_API_BASE (兼容 API 地址) 和 OPENAI_MODEL (模型名称,如 gpt-4o, gpt-3.5-turbo, 或其他兼容模型,比如deepseek-chat等)。
  2. 获取并运行代码: 将完整的 main.go 代码保存到 code-editing-agent 目录,执行 go mod tidy 下载依赖。
  3. 设置环境变量(见下面),然后运行 go run main.go 启动 Agent。你应该看到程序启动并等待你的输入。
$export OPENAI_API_KEY=<your_deepseek_api_key>
$export OPENAI_API_BASE=https://api.deepseek.com
$export OPENAI_MODEL=deepseek-chat

实验 0:基础对话 (验证连接)

  • 目标: 验证 Agent 与 LLM API 的基本连接和对话流程是否正常,此时不涉及工具调用。
  • 关键代码 (简化流程): Agent 的核心 Run 方法会接收用户输入,将其添加到 conversation 历史中,然后调用 callOpenAICompletion,最后处理并打印 AI 的文本回复。
// Simplified flow within Agent.Run for basic chat
func (a *Agent) Run(ctx context.Context) error {
    // ... setup ...
    conversation := []OpenAIChatCompletionMessage{ /* system prompt */ }
    for { // Outer loop for user input
        // ... get userInput from console ...
        conversation = append(conversation, OpenAIChatCompletionMessage{Role: "user", Content: userInput})

        // --- Call API ---
        resp, err := a.callOpenAICompletion(ctx, conversation)
        if err != nil {
            fmt.Printf("\u001b[91mAPI Error\u001b[0m: %s\n", err.Error())
            continue // Let user try again
        }
        if len(resp.Choices) == 0 { /* handle no choices */ continue }

        assistantMessage := resp.Choices[0].Message
        conversation = append(conversation, assistantMessage) // Add response to history

        // --- Print Text Response ---
        if assistantMessage.Content != "" {
            fmt.Printf("\u001b[93mAI\u001b[0m: %s\n", assistantMessage.Content)
        }

        // --- Tool Handling Logic would go here, but skipped for basic chat ---
        // In a basic chat without tool calls, the inner loop (if any) breaks immediately.

    } // End of outer loop
    return nil
}
  • 解释: 这一步主要测试 callOpenAICompletion 函数能否成功打包对话历史、发送 HTTP 请求到 API 端点、接收有效的文本响应,并由 Run 方法将其打印出来。
  • 步骤:

    1. 在 You: 提示符后输入:

      You: Hey! I'm Tony! How are you?

    2. 观察 AI 是否能正常回复,确认 API 连接。

  • Agent输出:

$./agent
Chat with AI (use 'ctrl-c' to quit)
You: Hey! I'm Tony! How are you?
AI: Hi Tony! I'm just a program, so I don't have feelings, but I'm here and ready to help you with anything you need. How can I assist you today?

实验 1 & 2:read_file 工具 (读取文件)

  • 目标: 测试 Agent 调用 read_file 工具读取指定文件内容的能力。
  • 关键代码:

工具定义 (ReadFileDefinition): 告诉AI 有一个名为 read_file 的工具,它需要一个path参数,并描述了其功能。

type ReadFileInput struct { // Defines the input structure for the tool
    Path string json:"path" jsonschema_description:"The relative path..." jsonschema:"required"
}

var ReadFileDefinition = ToolDefinition{
    Name:        "read_file",
    Description: "Read the contents of a given relative file path...",
    InputSchema: GenerateSchema[ReadFileInput](), // Generates {"type": "object", "properties": {"path": {"type": "string", ...}}, "required": ["path"]}
    Function:    ReadFile,                          // Links to the Go function below
}

工具执行函数 (ReadFile): 这个 Go 函数接收 AI 提供的参数(文件路径),并使用标准库 os.ReadFile 实际执行文件读取。

func ReadFile(input json.RawMessage) (string, error) {
    readFileInput := ReadFileInput{}
    err := json.Unmarshal(input, &readFileInput) // Parse the JSON arguments from AI
    if err != nil || readFileInput.Path == "" { /* handle parse error or missing path */ }

    content, err := os.ReadFile(readFileInput.Path) // Use Go standard library to read file
    if err != nil { /* handle file read error */ }

    return string(content), nil // Return file content as a string
}
  • 解释: 当用户请求涉及文件内容时,AI 会根据 ReadFileDefinition 的描述,决定调用 read_file 工具,并提供 path 参数。Agent 的 Run 循环捕获到这个工具调用请求,找到对应的 ReadFile 函数,传入参数并执行。函数读取文件后返回内容字符串,这个字符串会被包装成 role: tool 的消息发送回给 AI,AI 再根据文件内容生成最终答复。
  • 步骤 (实验 1 – secret-file.txt):
    1. 准备: 创建 secret-file.txt 文件,内容为“what animal is the most disagreeable because it always says neigh?”
    2. 输入: buddy, help me solve the riddle in the secret-file.txt file
    3. 观察: AI 回复 -> Tool Call: read_file({“path”:”secret-file.txt”}) -> AI 给出谜底。
    4. Agent输出:
You: buddy, help me solve the riddle in the secret-file.txt file
Tool Call: list_files({})
Tool Call: read_file({"path":"secret-file.txt"})
AI: The answer to the riddle is a **horse**, because it always says "neigh" (which sounds like "nay," meaning disagreement). 

Let me know if you need help with anything else, Tony!
  • 步骤 (实验 2 – 读取main.go):
    1. 输入: What’s going on in main.go? Be brief!
    2. 观察: AI 回复 -> Tool Call: read_file({“path”:”main.go”}) -> AI 给出代码摘要。
    3. 模型输出:
You: What's going on in main.go? Be brief!
Tool Call: read_file({"path":"main.go"})
AI: The `main.go` file is a Go program that sets up an **AI agent** capable of interacting with the local filesystem (reading, listing, and editing files). Here's a brief breakdown:

1. **Purpose**:
   - The agent acts as a helper, responding to user requests by either providing text answers or using tools to interact with files.

2. **Key Features**:
   - **Tools**: It has three built-in tools:
     - `read_file`: Reads file contents.
     - `list_files`: Lists files/directories.
     - `edit_file`: Edits or creates files.
   - **OpenAI Integration**: Uses the OpenAI API (like GPT-4) to process user input and decide when to use tools.
   - **Interactive CLI**: Takes user input from the command line and displays responses.

3. **Workflow**:
   - The agent maintains a conversation history with the user.
   - If a tool is needed, it calls the OpenAI API, executes the tool, and updates the conversation.

4. **Dependencies**:
   - Requires an `OPENAI_API_KEY` environment variable to work with the OpenAI API.

In short, it's a **file-system assistant powered by OpenAI**, designed to help with file operations via natural language commands. Let me know if you'd like more details!

实验 3:list_files 工具

  • 目标: 测试 list_files 工具,让 AI 感知当前工作目录的文件结构。
  • 关键代码:

工具定义 (ListFilesDefinition): 定义 list_files 工具,路径参数可选。

type ListFilesInput struct { // Input structure, path is optional
    Path string json:"path,omitempty" jsonschema_description:"Optional relative path..."
}

var ListFilesDefinition = ToolDefinition{
    Name:        "list_files",
    Description: "List files and directories at a given path. If no path...",
    InputSchema: GenerateSchema[ListFilesInput](),
    Function:    ListFiles, // Links to the Go function below
}

工具执行函数 (ListFiles): 使用 filepath.WalkDir 遍历目录,并将结果格式化为 JSON 数组字符串。

func ListFiles(input json.RawMessage) (string, error) {
    // ... Parse optional path from input ...
    dir := "." // Default to current directory
    if listFilesInput.Path != "" { dir = listFilesInput.Path }

    var files []string
    err := filepath.WalkDir(dir, func(...) error { // Use standard library WalkDir
        // ... build relative path ...
        // ... append path to files slice (add "/" for directories) ...
        return nil
    })
    if err != nil { /* handle walk error */ }

    result, err := json.Marshal(files) // Return as JSON array string
    if err != nil { /* handle marshal error */ }
    return string(result), nil
}
  • 解释: AI 被问及目录内容时,会调用 list_files 工具(通常不带参数,使用默认当前目录)。Go 代码执行 ListFiles 函数,遍历目录,将文件和目录名(目录带 /)的列表打包成 JSON 字符串返回给 AI。AI 再将这个列表呈现给用户。
  • 步骤:
    1. 输入: what do you see in this directory?
    2. 观察: AI 回复 -> Tool Call: list_files({}) -> AI 列出当前目录文件。
    3. Agent输出:
You: what do you see in this directory?
Tool Call: list_files({})
AI: Here’s what’s in the current directory:  

1. **Files**:
   - `.main.go.swp` (likely a temporary swap file for `main.go`).
   - `go.mod` and `go.sum` (Go module files for dependency management).
   - `main.go` (the main Go program file).
   - `secret-file.txt` (the file with the riddle you solved earlier).  

2. **Directory**:
   - `agent/` (a subdirectory, possibly containing agent-related code or resources).  

Let me know if you'd like to explore any of these further!

实验 4 & 5:组合工具 (list_files + read_file)

  • 目标: 观察 Agent 如何自主地组合使用多个工具(先 list_files 发现文件,再 read_file 读取特定文件)来完成更复杂的任务。
  • 关键代码 (Agent 的 Run 方法中的内部循环): 这是实现多步工具调用的核心。
// Inside Agent.Run method
for { // Outer loop for user input
    // ... get user input, add to conversation ...

    for { // <--- INNER LOOP: Handles multi-turn tool calls ---
        resp, err := a.callOpenAICompletion(ctx, conversation) // Call API
        // ... handle response ...
        assistantMessage := resp.Choices[0].Message
        conversation = append(conversation, assistantMessage) // Add assistant's response

        // Check for tool calls in the response
        if len(assistantMessage.ToolCalls) == 0 {
            // No tools called by AI in this turn. Print text response (if any)
            // and break the INNER loop to wait for next user input.
            if assistantMessage.Content != "" { /* print content */ }
            break // Exit INNER loop
        }

        // --- AI requested tools, execute them ---
        toolResults := []OpenAIChatCompletionMessage{}
        for _, toolCall := range assistantMessage.ToolCalls {
            // ... find tool definition by toolCall.Function.Name ...
            // ... execute the tool's Go function with toolCall.Function.Arguments ...
            // ... prepare resultMsg (role: "tool", content: output/error) ...
            toolResults = append(toolResults, resultMsg)
        }
        conversation = append(conversation, toolResults...) // Add tool results to history

        // DO NOT BREAK! Continue the INNER loop immediately.
        // The conversation now includes the tool results,
        // so the next call to callOpenAICompletion will send them back to the AI.
    } // <--- End of INNER LOOP ---

} // End of OUTER loop
  • 解释: 关键在于内部循环 (INNER LOOP)。当 AI 的回复包含 ToolCalls 时,Agent 会:

    1. 执行所有请求的工具。
    2. 将每个工具的执行结果(成功输出或错误信息)构造成 role: “tool” 的消息。
    3. 将这些 tool 消息添加到对话历史 conversation 中。
    4. 不退出内部循环,而是立即用更新后的 conversation(现在包含了工具结果)再次调用 callOpenAICompletion。
      这样,AI 就能在其下一步的思考中“看到”刚刚执行的工具结果,并据此决定是继续调用工具、生成最终答案,还是进行其他操作。这个循环会持续到 AI 的某次响应不再包含 ToolCalls 为止。
  • 步骤 (实验 4 – Go 文件信息):

    1. 输入: Tell me about all the Go files in here. Be brief!
    2. 观察: list_files -> AI 回复 -> read_file (main.go) -> AI 回复 -> read_file (go.mod) -> AI 回复 -> AI 最终汇总。
    3. Agent输出:
You: Tell me about all the Go files in here. Be brief!
AI: Here’s a quick rundown of the Go files in the directory:

1. **`main.go`**:
   - The core program file. It sets up an **AI agent** that interacts with the local filesystem using tools (`read_file`, `list_files`, `edit_file`).
   - Integrates with the **OpenAI API** for natural language processing.
   - Handles user input via the command line.  

2. **`go.mod` & `go.sum`**:
   - **`go.mod`**: Defines the Go module (project) and its dependencies (e.g., `github.com/invopop/jsonschema` for JSON schema generation).
   - **`go.sum`**: Locks dependency versions for reproducibility.  

That’s it! The other files (like `.main.go.swp`) are temporary or non-Go files. Let me know if you want details on any specific part!

注意:这里DeepSeek模型并没有再调用read_file!与预期不相符,也许和模型的实现有关。比如模型缓存了这些文件的内容。

  • 步骤 (实验 5 – Go 版本):
    1. 输入: What go version are we using in this project?
    2. 观察: list_files -> AI 回复 -> read_file (go.mod) -> AI 回复 -> AI 最终回答 Go 版本。
    3. Agent输出:
You: What go version are we using in this project?
Tool Call: read_file({"path":"go.mod"})
AI: The project is using **Go version 1.24.0**, as specified in the `go.mod` file.  

Let me know if you'd like help with anything else!

实验 6, 7, & 8:edit_file 工具 (创建、编辑文件)

  • 目标: 测试核心的 edit_file 工具,包括文件创建(当 old_str 为空且文件不存在时)和内容修改。
  • 关键代码:

工具定义 (EditFileDefinition): 定义 edit_file 工具,包含 path, old_str, new_str 三个参数。

type EditFileInput struct {
    Path   string json:"path" jsonschema_description:"The path..." jsonschema:"required"
    OldStr string json:"old_str" jsonschema_description:"Text to search for..."
    NewStr string json:"new_str" jsonschema_description:"Text to replace with..." jsonschema:"required"
}

var EditFileDefinition = ToolDefinition{
    Name:        "edit_file",
    Description: "Make edits to a text file. Replaces ALL occurrences...",
    InputSchema: GenerateSchema[EditFileInput](),
    Function:    EditFile, // Links to the Go function below
}

工具执行函数 (EditFile 及助手 createNewFile): 处理文件创建和修改逻辑。

func EditFile(input json.RawMessage) (string, error) {
    editFileInput := EditFileInput{}
    // ... parse input path, old_str, new_str ...

    content, err := os.ReadFile(editFileInput.Path)
    if err != nil {
        // Key logic: If file doesn't exist AND old_str is empty, try creating it.
        if os.IsNotExist(err) && editFileInput.OldStr == "" {
            return createNewFile(editFileInput.Path, editFileInput.NewStr)
        }
        return "", err // Other read error
    }

    // File exists, perform replacement
    oldContent := string(content)
    newContent := strings.Replace(oldContent, editFileInput.OldStr, editFileInput.NewStr, -1) // Replace all
    // ... check if replacement happened ...

    err = os.WriteFile(editFileInput.Path, []byte(newContent), 0644) // Write back
    // ... handle write error ...
    return "OK", nil
}

// Helper to create a new file (and parent directories if needed)
func createNewFile(filePath, content string) (string, error) {
    dir := path.Dir(filePath)
    if dir != "." && dir != "" {
        // Ensure parent directories exist
        if err := os.MkdirAll(dir, 0755); err != nil { /* handle error */ }
    }
    err := os.WriteFile(filePath, []byte(content), 0644) // Write the new file
    // ... handle error ...
    return fmt.Sprintf("Successfully created file %s", filePath), nil
}
  • 解释: edit_file 是最强大的工具。AI 根据用户的意图(创建或修改)来调用它,并提供必要的参数。Go 代码的核心逻辑在于:

    • 如果 os.ReadFile 返回“文件不存在”错误,并且 AI 提供的 old_str 是空字符串,则调用 createNewFile 来创建文件,将 new_str 作为初始内容。
    • 如果文件存在,则使用 strings.Replace(替换所有匹配项)执行内容替换,并用 os.WriteFile 写回磁盘。
      这种区分处理使得一个工具能同时处理创建和编辑两种场景。
  • 步骤 (实验 6 – 创建):

    1. 输入: hey buddy, create fizzbuzz.js…
    2. 观察: (可能 list_files) -> Tool Call: edit_file({“path”:”fizzbuzz.js”,”old_str”:”",”new_str”:”…”}) -> AI 回复成功。
    3. 验证: 退出 Agent,检查 fizzbuzz.js 是否生成。
    4. Agent输出与执行结果:
You: hey buddy, create fizzbuzz.js that I can run with Nodejs and that has fizzbuzz in it and executes it
Tool Call: edit_file({"path":"fizzbuzz.js","old_str":"","new_str":"// FizzBuzz in Node.js\nfunction fizzbuzz(n) {\n  for (let i = 1; i <= n; i++) {\n    if (i % 15 === 0) console.log(\"FizzBuzz\");\n    else if (i % 3 === 0) console.log(\"Fizz\");\n    else if (i % 5 === 0) console.log(\"Buzz\");\n    else console.log(i);\n  }\n}\n\n// Execute FizzBuzz for numbers 1 to 100\nfizzbuzz(100);"})
AI: Done! I've created **`fizzbuzz.js`** with a FizzBuzz implementation that runs in Node.js. Here's what it does:  

1. **Function**:
   - `fizzbuzz(n)` prints numbers from 1 to `n`, replacing multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz".  

2. **Execution**:
   - It runs for numbers **1 to 100** by default.  

### How to Run:
node fizzbuzz.js

Let me know if you'd like any tweaks!

生成的fizzbuzz.js的文件内容如下:

$cat fizzbuzz.js
// FizzBuzz in Node.js
function fizzbuzz(n) {
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) console.log("FizzBuzz");
    else if (i % 3 === 0) console.log("Fizz");
    else if (i % 5 === 0) console.log("Buzz");
    else console.log(i);
  }
}

// Execute FizzBuzz for numbers 1 to 100
fizzbuzz(100);%

使用node运行该fizzbuzz.js的文件,输出如下:

$node fizzbuzz.js
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
... ...
97
98
Fizz
Buzz
  • 步骤 (实验 7 – 编辑):
    1. 准备: 确保 fizzbuzz.js 存在。
    2. 运行 Agent。
    3. 输入: Please edit fizzbuzz.js so that it only prints until 15
    4. 观察: read_file -> edit_file (改代码) -> (可能) edit_file (改注释) -> AI 回复成功。
    5. 验证: 退出 Agent,检查 fizzbuzz.js 是否修改。
    6. Agent输出与执行结果:
You: Please edit fizzbuzz.js so that it only prints until 15
Tool Call: edit_file({"path":"fizzbuzz.js","old_str":"// Execute FizzBuzz for numbers 1 to 100\nfizzbuzz(100);","new_str":"// Execute FizzBuzz for numbers 1 to 15\nfizzbuzz(15);"})
AI: Got it! I updated **`fizzbuzz.js`** to print FizzBuzz only up to **15** instead of 100.  

### How to Run:
node fizzbuzz.js

Now it’ll output:  

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Let me know if you'd like further changes!

查看更新后的fizzbuzz.js:

$cat fizzbuzz.js
// FizzBuzz in Node.js
function fizzbuzz(n) {
  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) console.log("FizzBuzz");
    else if (i % 3 === 0) console.log("Fizz");
    else if (i % 5 === 0) console.log("Buzz");
    else console.log(i);
  }
}

// Execute FizzBuzz for numbers 1 to 15
fizzbuzz(15);%

运行更新后的fizzbuzz.js结果如下:

$node fizzbuzz.js
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
  • 步骤 (实验 8 – 创建):
    1. 输入: Create a congrats.js script that rot13-decodes…
    2. 观察: (可能 list_files) -> Tool Call: edit_file({“path”:”congrats.js”,”old_str”:”",”new_str”:”…”}) -> AI 回复成功。
    3. 验证: 退出 Agent,检查 congrats.js 是否生成,运行 node congrats.js 确认输出。
    4. Agent输出与执行结果:
You: Create a congrats.js script that rot13-decodes the following string 'Pbatenghyngvbaf ba ohvyqvat n pbqr-rqvgvat ntrag!' and prints it
AI: Here's the plan:
1. I'll create a **`congrats.js`** script.
2. It will **ROT13-decode** the string `'Pbatenghyngvbaf ba ohvyqvat n pbqr-rqvgvat ntrag!'`.
3. The decoded result will be printed to the console.  

Let me implement this for you.
Tool Call: edit_file({"path":"congrats.js","old_str":"","new_str":"// ROT13 decoder in Node.js\nfunction rot13(str) {\n  return str.replace(/[a-zA-Z]/g, function(c) {\n    const base = c <= 'Z' ? 65 : 97;\n    return String.fromCharCode((c.charCodeAt(0) - base + 13) % 26 + base);\n  });\n}\n\n// Encoded string\nconst encoded = 'Pbatenghyngvbaf ba ohvyqvat n pbqr-rqvgvat ntrag!';\n\n// Decode and print\nconsole.log(rot13(encoded));"})
AI: Done! I've created **`congrats.js`** for you. Here's what it does:  

1. **ROT13 Decoding**:
   - The script decodes the string `'Pbatenghyngvbaf ba ohvyqvat n pbqr-rqvgvat ntrag!'` using ROT13.  

2. **Output**:
   - Running it will print the decoded message to the console.  

### How to Run:  

node congrats.js

The decoded result should appear. Let me know if you'd like to tweak anything!

查看生成的congrats.js结果如下:

$cat congrats.js
// ROT13 decoder in Node.js
function rot13(str) {
  return str.replace(/[a-zA-Z]/g, function(c) {
    const base = c <= 'Z' ? 65 : 97;
    return String.fromCharCode((c.charCodeAt(0) - base + 13) % 26 + base);
  });
}

// Encoded string
const encoded = 'Pbatenghyngvbaf ba ohvyqvat n pbqr-rqvgvat ntrag!';

// Decode and print
console.log(rot13(encoded));%

运行生成的congrats.js结果如下:

$node congrats.js
Congratulations on building a code-editing agent!

通过这些结合了代码片段和解释的步骤,你应该能更清晰地理解 Agent 在每个实验中是如何利用其被赋予的工具和核心循环机制来完成任务的。这再次印证了 Thorsten Ball 的观点:核心很简单,但组合起来却能产生强大的效果

简单背后的深思:Agent 的真正壁垒在哪?

既然核心逻辑相对简单,那是否意味着构建一个优秀的 Agent 应用就没有门槛了呢?显然不是。Thorsten Ball 的“体力活” (Elbow Grease) 一词点醒了我们:真正的挑战和壁垒,在于核心逻辑之外的大量工程细节和产品打磨。

这包括但不限于:

  • 提示词工程 (Prompt Engineering): 如何设计出精确、高效、能引导 LLM 稳定输出预期格式和进行合理工具调用的 System Prompt 和 User Prompt?
  • 工具设计与健壮性 (Tool Design & Robustness): 如何设计出功能明确、接口清晰、并且足够健壮(能处理各种边缘情况和错误输入)的工具?简单的字符串替换编辑文件显然是不够的,更复杂的场景需要更精密的工具(如 AST 操作、diff 应用等)。
  • 状态管理与长上下文: 如何有效管理 Agent 的长期记忆、任务状态、以及在 LLM 的上下文窗口限制下处理复杂的多步骤任务?
  • 错误处理与恢复: 当 LLM 理解错误、工具执行失败或外部环境变化时,Agent 如何优雅地处理错误、进行重试或寻求用户帮助?
  • 用户体验与集成 (UI/UX & Integration): 如何将 Agent 无缝集成到用户的工作流中(如 IDE 插件、命令行工具、Web 应用)?如何提供直观、高效的交互界面?
  • 性能与成本 (Performance & Cost): 如何优化 Agent 的响应速度?如何控制频繁调用 LLM API 带来的成本?
  • 安全性: 如何确保 Agent 不会执行危险操作,或者被恶意利用?工具的权限控制至关重要。

这些才是构建一个能在现实世界中可靠、高效、安全地工作的 Agent 应用时,需要投入大量时间和精力去解决的真正工程难题。未来的 Agent 应用竞争,很可能就围绕着这些方面展开。

小结:人人皆可 Agent?拥抱实践的力量

Thorsten Ball 的文章和我们的复现实验,共同揭示了一个令人兴奋的事实:理解和开始构建 AI Agent 的门槛,比许多人想象的要低得多。 其核心概念是清晰且可及的。

这并不意味着打造卓越的 Agent 产品很容易,但它确实意味着,任何具备基本编程能力和对 LLM API 有所了解的开发者,都可以动手尝试,去探索 Agent 的可能性。

不要被表面的复杂性所迷惑,正如“皇帝的新衣”所揭示的,有时最强大的能力隐藏在最简洁的原理背后。现在,轮到你去发现、去实践、去创造了。

鼓励大家亲自尝试运行和修改这个Go Agent示例,感受一下与“你自己创造的智能体”协作编码的初步体验!

想更进一步?开启你的 Go & AI 精进之旅!

本文为你揭示了构建代码 Agent 的核心简洁性,但这仅仅是冰山一角。真正的挑战在于将这些基础概念,通过扎实的工程实践,转化为可靠、高效、能在实际场景中创造价值的应用。

如果你渴望在这条激动人心的道路上走得更远、更深,希望系统性学习如何用Go构建AI原生应用,深入探索 Agent、RAG(检索增强生成)、模型集成、向量数据库应用等前沿实践,我强烈推荐我的知识星球「Gopher的AI原生应用开发第一课」。在这里,我们不只有理论探讨,更有动手实战项目、最新的技术趋势解读、活跃的高质量社群交流,以及与我的直接互动答疑。如果你对用 Go 在 AI 时代创造真正有影响力的应用充满热情,这里将是你的最佳实践场和加速器。

扫码加入「Go & AI 精进营」知识星球,开启你的 AI 原生开发之旅! 并且,体系化Go核心进阶内容:「Go原理课」、「Go进阶课」、「Go避坑课」等独家深度专栏,将帮助你夯实Go内功

img{512x368}

你的支持,是创作的最大动力!

最后,如果你觉得本文对你有启发、有帮助:

  • 【分享】 给你的朋友、同事或技术社群,一起交流探讨。
  • 【关注】 我的公众号「[ iamtonybai ]」,第一时间获取更多Go语言、AI应用、云原生和架构思考与实践的硬核干货!

感谢你的耐心阅读与宝贵支持!期待在学习的路上与你继续同行!


img{512x368}
img{512x368}

著名云主机服务厂商DigitalOcean发布最新的主机计划,入门级Droplet配置升级为:1 core CPU、1G内存、25G高速SSD,价格6$/月。有使用DigitalOcean需求的朋友,可以打开这个链接地址:https://m.do.co/c/bff6eed92687 开启你的DO主机之路。

Gopher Daily(Gopher每日新闻) – https://gopherdaily.tonybai.com

我的联系方式:

  • 微博(暂不可用):https://weibo.com/bigwhite20xx
  • 微博2:https://weibo.com/u/6484441286
  • 博客:tonybai.com
  • github: https://github.com/bigwhite
  • Gopher Daily归档 – https://github.com/bigwhite/gopherdaily
  • Gopher Daily Feed订阅 – https://gopherdaily.tonybai.com/feed

商务合作方式:撰稿、出书、培训、在线课程、合伙创业、咨询、广告合作。

自定义Hash终迎标准化?Go提案maphash.Hasher接口设计解读

本文永久链接 – https://tonybai.com/2025/04/17/standardize-the-hash-function

大家好,我是Tony Bai。

随着Go泛型的落地和社区对高性能自定义容器需求的增长,如何为用户自定义类型提供一套标准、安全且高效的Hash计算与相等性判断机制,成为了Go核心团队面临的重要议题。近日,经过Go核心开发者多轮深入探讨,编号为#70471 的提案”hash: standardize the hash function”最终收敛并被接受,为Go生态引入了全新的maphash.Hasher[T] 接口,旨在统一自定义类型的Hash实现方式。

这个旨在统一自定义类型Hash实现的提案令人期待,但我们首先需要理解,究竟是什么背景和痛点,促使Go社区必须着手解决自定义 Hash 的标准化问题呢?

1. 背景:为何需要标准化的Hash接口?

Go 1.18泛型发布之前,为自定义类型(尤其是非comparable类型)实现Hash往往需要开发者自行设计方案,缺乏统一标准。随着泛型的普及,开发者可以创建自定义的哈希表、集合等泛型数据结构,此时,一个标准的、能与这些泛型容器解耦的Hash和相等性判断机制变得至关重要。

更关键的是安全性。一个简单的func(T) uint64类型的Hash函数看似直观和易实现,但极易受到Hash 洪水攻击 (Hash Flooding DoS) 的威胁。

什么是Hash洪水攻击呢? 简单来说,哈希表通过Hash函数将键(Key)分散到不同的“桶”(Bucket)中,理想情况下可以实现快速的O(1)平均查找、插入和删除。但如果Hash函数的设计存在缺陷或过于简单(例如,不使用随机种子),攻击者就可以精心构造大量具有相同Hash值的不同键。当这些键被插入到同一个哈希表中时,它们会集中在少数几个甚至一个“桶”里,导致这个桶形成一个长链表。此时,对这个桶的操作(如查找或插入)性能会从O(1)急剧退化到O(n),消耗大量CPU时间。攻击者通过发送大量这样的冲突键,就能耗尽服务器资源,导致服务缓慢甚至完全不可用。

Go内建的map类型通过为每个map实例使用内部随机化的 Seed(种子)来初始化其Hash函数,使得攻击者无法预测哪些键会产生冲突,从而有效防御了此类攻击。hash/maphash包也提供了基于maphash.Seed的安全Hash计算方式。因此,任何标准化的自定义Hash接口都必须将基于Seed的随机化纳入核心设计,以避免开发者在不知情的情况下引入安全漏洞。

明确了标准化Hash接口的必要性,尤其是出于安全性的考量之后,Go核心团队又是如何一步步探索、权衡,最终从多种可能性中确定接口的设计方向的呢?其间的思考过程同样值得我们关注。

2. 设计演进:从简单函数到maphash.Hasher

围绕如何设计这个标准接口,Go 团队进行了广泛的讨论(相关issue: #69420, #69559, #70471)。

最初,开发者们提出的 func(T) uint64 由于无法有效防御 Hash 洪水攻击而被迅速否定。

随后,大家一致认为需要引入Seed,讨论的焦点则转向Seed的传递和使用方式:是作为函数参数(func(Seed, T) uint64)还是封装在接口或结构体中。对此,Ian Lance Taylor提出了Hasher[T]接口的雏形,包含Hash(T) uint64和Equal(T, T) bool方法,并通过工厂函数(如 MakeSeededHasher)来管理 Seed。 然而,这引发了关于Seed作用域(per-process vs per-table)和状态管理(stateless vs stateful)的进一步讨论。

Austin Clements 提出了多种接口变体,并深入分析了不同设计的利弊,包括API 简洁性、性能(间接调用 vs 直接调用)、类型推断的限制以及易用性(是否容易误用导致不安全)。

最终,为了更好地支持递归Hash(例如,一个结构体的Hash需要依赖其成员的Hash),讨论聚焦于将*maphash.Hash对象直接传递给Hash方法。maphash.Hash内部封装了Seed和Hash状态,能够方便地在递归调用中传递,简化了实现过程。

经历了对不同方案的深入探讨和关键决策(例如引入 *maphash.Hash),最终被接受并写入提案的maphash.Hasher[T] 接口究竟长什么样?它的核心设计理念又是什么呢?接下来,让我们来详细解读。

3. 最终方案:maphash.Hasher[T]接口

经过审慎评估和实际代码验证(见CL 657296CL 657297),Go团队最终接受了以下maphash.Hasher[T]接口定义:

package maphash

// A Hasher is a type that implements hashing and equality for type T.
//
// A Hasher must be stateless. Hence, typically, a Hasher will be an empty struct.
type Hasher[T any] interface {
    // Hash updates hash to reflect the contents of value.
    //
    // If two values are [Equal], they must also Hash the same.
    // Specifically, if Equal(a, b) is true, then Hash(h, a) and Hash(h, b)
    // must write identical streams to h.
    Hash(hash *Hash, value T) // 注意:这里的 hash 是 *maphash.Hash 类型
    Equal(a, b T) bool
}

该接口的核心设计理念可以归纳为如下几点:

  • Stateless Hasher: Hasher[T] 的实现本身应该是无状态的(通常是空结构体),所有状态(包括 Seed)都由传入的 *maphash.Hash 对象管理。
  • 安全保障: 通过强制使用maphash.Hash,确保了 Hash 计算过程与 Go 内建的、经过安全加固的Hash算法(如 runtime.memhash)保持一致,并天然集成了Seed 机制。
  • 递归友好: 在计算复杂类型的 Hash 时,可以直接将 *maphash.Hash 对象传递给成员类型的 Hasher,使得递归实现简洁高效。
  • 关注点分离: 将 Hash 计算 (Hash) 和相等性判断 (Equal) 分离,并与类型 T 本身解耦,提供了更大的灵活性(类似于 sort.Interface 的设计哲学)。

下面是一个maphash.Hasher的使用示例:

package main

import (
    "hash/maphash"
    "slices"
)

// 自定义类型
type Strings []string

// 为 Strings 类型实现 Hasher
type StringsHasher struct{} // 无状态

func (StringsHasher) Hash(mh *maphash.Hash, val Strings) {
    // 使用 maphash.Hash 的方法写入数据
    maphash.WriteComparable(mh, len(val)) // 先写入长度
    for _, s := range val {
        mh.WriteString(s)
    }
}

func (StringsHasher) Equal(a, b Strings) bool {
    return slices.Equal(a, b)
}

// 另一个包含自定义类型的结构体
type Thing struct {
    ss Strings
    i  int
}

// 为 Thing 类型实现 Hasher (递归调用 StringsHasher)
type ThingHasher struct{} // 无状态

func (ThingHasher) Hash(mh *maphash.Hash, val Thing) {
    // 调用成员类型的 Hasher
    StringsHasher{}.Hash(mh, val.ss)
    // 为基础类型写入 Hash
    maphash.WriteComparable(mh, val.i)
}

func (ThingHasher) Equal(a, b Thing) bool {
    // 优先比较简单字段
    if a.i != b.i {
        return false
    }
    // 调用成员类型的 Equal
    return StringsHasher{}.Equal(a.ss, b.ss)
}

// 假设有一个自定义的泛型 Set
type Set[T any, H Hasher[T]] struct {
    hash H // Hasher 实例 (通常是零值)
    seed maphash.Seed
    // ... 其他字段,如存储数据的 bucket ...
}

// Set 的 Get 方法示例
func (s *Set[T, H]) Has(val T) bool {
    var mh maphash.Hash
    mh.SetSeed(s.seed) // 使用 Set 实例的 Seed 初始化 maphash.Hash

    // 使用 Hasher 计算 Hash
    s.hash.Hash(&mh, val)
    hashValue := mh.Sum64()

    // ... 在 bucket 中根据 hashValue 查找 ...
    // ... 找到潜在匹配项 potentialMatch 后,使用 Hasher 的 Equal 判断 ...
    // if s.hash.Equal(val, potentialMatch) {
    //     return true
    // }
    // ...

    // 简化示例,仅展示调用
    _ = hashValue // 避免编译错误

    return false // 假设未找到
}

func main() {
    // 创建 Set 实例时,需要提供具体的类型和对应的 Hasher 类型
    var s Set[Thing, ThingHasher]
    s.seed = maphash.MakeSeed() // 初始化 Seed

    // ... 使用 s ...
    found := s.Has(Thing{ss: Strings{"a", "b"}, i: 1})
    println(found)
}

这个精心设计的 maphash.Hasher[T] 接口及其使用范例展示了其潜力和优雅之处。然而,任何技术方案在落地过程中都难免遇到挑战,这个新接口也不例外。它目前还面临哪些已知的问题,未来又有哪些值得期待的发展方向呢?

4. 挑战与展望

尽管 maphash.Hasher 接口设计优雅且解决了核心问题,但也存在一些已知挑战:

  • 编译器优化: 当前 Go 编译器(截至讨论时)在处理接口方法调用时,可能会导致传入的 *maphash.Hash 对象逃逸到堆上,影响性能。这是 Go 泛型和编译器优化(#48849)需要持续改进的地方,但核心团队认为不应因此牺牲接口设计的合理性。
  • 易用性: maphash.Hash 目前主要提供 Write, WriteString, WriteByte 以及泛型的 WriteComparable。对于其他基础类型(如各种宽度的整数、浮点数),可能需要更多便捷的 WriteXxx 方法来提升开发体验。
  • 生态整合: 未来 Go 标准库或扩展库中的泛型容器(如可能出现的 container/set 或 container/map 的变体)有望基于此接口构建,从而允许用户无缝接入自定义类型的 Hash 支持。

综合来看,尽管存在一些挑战需要克服,但maphash.Hasher[T]接口的提出无疑是Go泛型生态发展中的一个重要里程碑。现在,让我们对它的意义和影响做一个简要的总结。

5. 小结

maphash.Hasher[T]接口的接受是Go在泛型时代标准化核心机制的重要一步。它不仅为开发者提供了一种统一、安全的方式来为自定义类型实现 Hash 和相等性判断,也为 Go 生态中高性能泛型容器的发展奠定了坚实的基础。虽然还存在一些编译器优化和 API 便利性方面的挑战,但其核心设计的合理性和前瞻性预示着 Go 在类型系统和泛型支持上的持续进步。我们期待看到这个接口在未来Go版本中的落地,以及它为Go开发者带来的便利。

更多信息:

对于这个备受关注的 maphash.Hasher 接口提案,你怎么看?它是否满足了你对自定义类型 Hash 标准化的期待?或者你认为还有哪些挑战或改进空间?

非常期待在评论区看到你的真知灼见!


原「Gopher部落」已重装升级为「Go & AI 精进营」知识星球,快来加入星球,开启你的技术跃迁之旅吧!

我们致力于打造一个高品质的 Go 语言深度学习AI 应用探索 平台。在这里,你将获得:

  • 体系化 Go 核心进阶内容: 深入「Go原理课」、「Go进阶课」、「Go避坑课」等独家深度专栏,夯实你的 Go 内功。
  • 前沿 Go+AI 实战赋能: 紧跟时代步伐,学习「Go+AI应用实战」、「Agent开发实战课」,掌握 AI 时代新技能。
  • 星主 Tony Bai 亲自答疑: 遇到难题?星主第一时间为你深度解析,扫清学习障碍。
  • 高活跃 Gopher 交流圈: 与众多优秀 Gopher 分享心得、讨论技术,碰撞思想火花。
  • 独家资源与内容首发: 技术文章、课程更新、精选资源,第一时间触达。

衷心希望「Go & AI 精进营」能成为你学习、进步、交流的港湾。让我们在此相聚,享受技术精进的快乐!欢迎你的加入!

img{512x368}
img{512x368}
img{512x368}

著名云主机服务厂商DigitalOcean发布最新的主机计划,入门级Droplet配置升级为:1 core CPU、1G内存、25G高速SSD,价格6$/月。有使用DigitalOcean需求的朋友,可以打开这个链接地址:https://m.do.co/c/bff6eed92687 开启你的DO主机之路。

Gopher Daily(Gopher每日新闻) – https://gopherdaily.tonybai.com

我的联系方式:

  • 微博(暂不可用):https://weibo.com/bigwhite20xx
  • 微博2:https://weibo.com/u/6484441286
  • 博客:tonybai.com
  • github: https://github.com/bigwhite
  • Gopher Daily归档 – https://github.com/bigwhite/gopherdaily
  • Gopher Daily Feed订阅 – https://gopherdaily.tonybai.com/feed

商务合作方式:撰稿、出书、培训、在线课程、合伙创业、咨询、广告合作。

如发现本站页面被黑,比如:挂载广告、挖矿等恶意代码,请朋友们及时联系我。十分感谢! Go语言第一课 Go语言精进之路1 Go语言精进之路2 Go语言编程指南
商务合作请联系bigwhite.cn AT aliyun.com

欢迎使用邮件订阅我的博客

输入邮箱订阅本站,只要有新文章发布,就会第一时间发送邮件通知你哦!

这里是 Tony Bai的个人Blog,欢迎访问、订阅和留言! 订阅Feed请点击上面图片

如果您觉得这里的文章对您有帮助,请扫描上方二维码进行捐赠 ,加油后的Tony Bai将会为您呈现更多精彩的文章,谢谢!

如果您希望通过微信捐赠,请用微信客户端扫描下方赞赏码:

如果您希望通过比特币或以太币捐赠,可以扫描下方二维码:

比特币:

以太币:

如果您喜欢通过微信浏览本站内容,可以扫描下方二维码,订阅本站官方微信订阅号“iamtonybai”;点击二维码,可直达本人官方微博主页^_^:
本站Powered by Digital Ocean VPS。
选择Digital Ocean VPS主机,即可获得10美元现金充值,可 免费使用两个月哟! 著名主机提供商Linode 10$优惠码:linode10,在 这里注册即可免费获 得。阿里云推荐码: 1WFZ0V立享9折!


View Tony Bai's profile on LinkedIn
DigitalOcean Referral Badge

文章

评论

  • 正在加载...

分类

标签

归档



Statcounter View My Stats