译皇帝的新装:仅用 200 行代码复现 Claude 核心编程能力

原文:https://www.mihaileric.com/The-Emperor-Has-No-Clothes/

作者:Mihail Eric 工程师、研究员、教育家。

《皇帝的新装》封面

如今的 AI 代码助手用起来简直如同魔法一般。你哪怕用些驴唇不对马嘴、逻辑勉强通顺的英文描述需求,它们也能读懂你的文件、修改你的项目,还能写出可直接运行的可用代码。

但真相是:这类工具的核心原理根本算不上什么魔法,大约只需 200 行通俗易懂、逻辑直白的 Python 代码即可实现。

接下来,我们就从零开始,亲手打造一个能实际工作的编码智能体(Code Agent)。

核心思维模型

在编写任何代码之前,我们先搞清楚:当你使用一款编码智能体时,背后实际发生的到底是什么。它的本质,不过是你与一个「带有工具箱的强大大语言模型(LLM)」进行的一场对话而已。

  1. 你 发送指令消息(新建一个文件,里面写一个 hello world 函数)
  2. LLM 判断出完成该需求需要调用工具,随后返回一个结构化的工具调用指令(也可能是多个工具调用指令)
  3. 你的程序 在本地实际执行该工具调用(如真正创建文件)
  4. 执行结果被回传给 LLM
  5. LLM基于该上下文信息继续执行操作或给出最终回应

这就是完整的工作循环。LLM 实际上从不直接操作你的文件系统。它只是提出执行某些操作的请求,然后由你的代码来具体实现这些操作。

三大必备工具

我们构建的编码智能体本质上只需要三种核心能力:

  • 读取文件:让 LLM 能够查看你的代码
  • 列出文件:让 LLM 能够浏览你的项目结构
  • 编辑文件:让它能够执行创建和修改代码的指令

仅此而已。 像 Claude Code 这样的生产级智能体确实拥有更多功能(如 grep、bash、网页搜索等),但我们将看到,仅这三个工具就足以实现超乎想象的实用功能了。

搭建基础框架

我们从导入基础模块和初始化 API 客户端开始。我在这里选用的是 Anthropic 的接口,这套代码同样适配市面上所有的大语言模型服务商。

import inspect
import json
import os

import anthropic
from dotenv import load_dotenv
from pathlib import Path
from typing import Any, Dict, List, Tuple

load_dotenv()

claude_client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

定义一些终端颜色常量,用于提升输出的可读性:

YOU_COLOR = "\u001b[94m"
ASSISTANT_COLOR = "\u001b[93m"
RESET_COLOR = "\u001b[0m"

再定义一个文件路径解析工具(如将相对路径 file.py 解析为完整的绝对路径 /Users/you/project/file.py):

def resolve_abs_path(path_str: str) -> Path:
    """
    file.py -> /Users/you/project/file.py
    """
    path = Path(path_str).expanduser()
    if not path.is_absolute():
        path = (Path.cwd() / path).resolve()
    return path

实现核心工具

请注意你需要为工具函数撰写详尽完整的文档注释(docstrings),因为 LLM 会依据这些注释内容,分析判断在对话过程中应该调用哪一个工具函数。关于这一点的重要性,下文会展开详细说明。

工具一:读取文件

最简单的工具。接收文件名参数,返回文件内容:

def read_file_tool(filename: str) -> Dict[str, Any]:
    """
    Gets the full content of a file provided by the user.
    :param filename: The name of the file to read.
    :return: The full content of the file.
    """
    full_path = resolve_abs_path(filename)
    print(full_path)
    with open(str(full_path), "r") as f:
        content = f.read()
    return {
        "file_path": str(full_path),
        "content": content
    }

我们让这个函数返回字典(dictionary)格式的数据,原因是:LLM 需要一份「发生了什么」的结构化上下文信息。

译注: LLM 擅长「理解结构化数据」,但极不擅长「解析无格式的纯文本」;返回字典,是让 LLM 能「精准、无歧义、不出错」理解执行结果的唯一方式

工具二:列出文件

通过列出目录内容来实现导航功能:

def list_files_tool(path: str) -> Dict[str, Any]:
    """
    Lists the files in a directory provided by the user.
    :param path: The path to a directory to list files from.
    :return: A list of files in the directory.
    """
    full_path = resolve_abs_path(path)
    all_files = []
    for item in full_path.iterdir():
        all_files.append({
            "filename": item.name,
            "type": "file" if item.is_file() else "dir"
        })
    return {
        "path": str(full_path),
        "files": all_files
    }

工具三:编辑文件

这是最复杂的工具,但其逻辑依然简单明了。它主要处理两种情况:

  • 创建新文件,当old_str为空
  • 修改替换文本,通过定位old_str并将其替换为new_str
def edit_file_tool(path: str, old_str: str, new_str: str) -> Dict[str, Any]:
    """
    Replaces first occurrence of old_str with new_str in file. If old_str is empty,
    create/overwrite file with new_str.
    :param path: The path to the file to edit.
    :param old_str: The string to replace.
    :param new_str: The string to replace with.
    :return: A dictionary with the path to the file and the action taken.
    """
    full_path = resolve_abs_path(path)
    if old_str == "":
        full_path.write_text(new_str, encoding="utf-8")
        return {
            "path": str(full_path),
            "action": "created_file"
        }
    original = full_path.read_text(encoding="utf-8")
    if original.find(old_str) == -1:
        return {
            "path": str(full_path),
            "action": "old_str not found"
        }
    edited = original.replace(old_str, new_str, 1)
    full_path.write_text(edited, encoding="utf-8")
    return {
        "path": str(full_path),
        "action": "edited"
    }

这里的通用约定规则:传入的old_str为空字符串时,代表「创建该文件」。反之(传入非空的old_str),则执行文本的查找与替换操作。专业的 IDE 会在匹配不到目标文本时,增加复杂的容错兜底逻辑,但目前这个简单的实现足以满足需求。

工具注册表

我们需要一种通过名称来查找工具的机制:

TOOL_REGISTRY = {
    "read_file": read_file_tool,
    "list_files": list_files_tool,
    "edit_file": edit_file_tool
}

让 LLM 了解我们的工具

LLM 需要知道存在哪些工具以及如何调用它们。我们将基于工具函数的「函数签名」和「文档注释」,动态生成这份工具说明信息,提供给 LLM 参考。

def get_tool_str_representation(tool_name: str) -> str:
    tool = TOOL_REGISTRY[tool_name]
    return f"""
    Name: {tool_name}
    Description: {tool.__doc__}
    Signature: {inspect.signature(tool)}
    """

def get_full_system_prompt():
    tool_str_repr = ""
    for tool_name in TOOL_REGISTRY:
        tool_str_repr += "TOOL\n===" + get_tool_str_representation(tool_name)
        tool_str_repr += f"\n{'='*15}\n"
    return SYSTEM_PROMPT.format(tool_list_repr=tool_str_repr)

接下来是系统提示词(System Prompt):

SYSTEM_PROMPT = """
You are a coding assistant whose goal it is to help us solve coding tasks.
You have access to a series of tools you can execute. Here are the tools you can execute:

{tool_list_repr}

When you want to use a tool, reply with exactly one line in the format: 'tool: TOOL_NAME({{JSON_ARGS}})' and nothing else.
Use compact single-line JSON with double quotes. After receiving a tool_result(...) message, continue the task.
If no tool is needed, respond normally.
"""

这是最核心的秘诀:我们仅仅是告诉 LLM 「这是你可用的工具,这是调用它们的格式」,至于什么时候调用、以及如何组合使用这些工具,全靠 LLM 自己去推理和解决。

解析工具调用

当 LLM 返回响应内容时,我们需要检测判断它是否在要求我们执行某个工具函数:

def extract_tool_invocations(text: str) -> List[Tuple[str, Dict[str, Any]]]:
    """
    Return list of (tool_name, args) requested in 'tool: name({...})' lines.
    The parser expects single-line, compact JSON in parentheses.
    """
    invocations = []
    for raw_line in text.splitlines():
        line = raw_line.strip()
        if not line.startswith("tool:"):
            continue
        try:
            after = line[len("tool:"):].strip()
            name, rest = after.split("(", 1)
            name = name.strip()
            if not rest.endswith(")"):
                continue
            json_str = rest[:-1].strip()
            args = json.loads(json_str)
            invocations.append((name, args))
        except Exception:
            continue
    return invocations

简单的文本解析。 查找以tool:开头的行,提取函数名和 JSON 格式的入参。

LLM 请求封装

做一个对 LLM API 调用的轻量级封装:

def execute_llm_call(conversation: List[Dict[str, str]]):
    system_content = ""
    messages = []

    for msg in conversation:
        if msg["role"] == "system":
            system_content = msg["content"]
        else:
            messages.append(msg)

    response = claude_client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=2000,
        system=system_content,
        messages=messages
    )
    return response.content[0].text

智能体循环

现在我们将所有部分整合串联起来。这就是整个程序中魔法发生的地方:

def run_coding_agent_loop():
    print(get_full_system_prompt())
    conversation = [{
        "role": "system",
        "content": get_full_system_prompt()
    }]
    while True:
        try:
            user_input = input(f"{YOU_COLOR}You:{RESET_COLOR}:")
        except (KeyboardInterrupt, EOFError):
            break
        conversation.append({
            "role": "user",
            "content": user_input.strip()
        })
        while True:
            assistant_response = execute_llm_call(conversation)
            tool_invocations = extract_tool_invocations(assistant_response)
            if not tool_invocations:
                print(f"{ASSISTANT_COLOR}Assistant:{RESET_COLOR}: {assistant_response}")
                conversation.append({
                    "role": "assistant",
                    "content": assistant_response
                })
                break
            for name, args in tool_invocations:
                tool = TOOL_REGISTRY[name]
                resp = ""
                print(name, args)
                if name == "read_file":
                    resp = tool(args.get("filename", "."))
                elif name == "list_files":
                    resp = tool(args.get("path", "."))
                elif name == "edit_file":
                    resp = tool(args.get("path", "."),
                                args.get("old_str", ""),
                                args.get("new_str", ""))
                conversation.append({
                    "role": "user",
                    "content": f"tool_result({json.dumps(resp)})"
                })

其结构如下:

  1. 外层循环: 获取用户输入,将其加入对话历史。

  2. 内层循环: 调用 LLM,检查是否需要调用工具。

    • 如果不需要工具,则打印响应并跳出内层循环。

    • 如果需要工具,则执行它们,将结果加入对话历史,然后再次循环。

内层循环会持续进行,直到 LLM 返回一个不请求任何工具的响应为止。这使得智能体能够链式执行多个工具调用(例如,读取一个文件,然后编辑它,最后确认编辑结果)。

运行它

if __name__ == "__main__":
    run_coding_agent_loop()

现在,你可以进行如下对话:

  • > You: Make me a new file called hello.py and implement hello world in it

智能体调用 edit_file 函数,参数为 path="hello.py", old_str="", new_str="print('Hello World')"

  • > Assistant: Done! Created hello.py with a hello world implementation.

或者进行多步骤交互:

  • > You: Edit hello.py and add a function for multiplying two numbers

智能体先调用read_file查看当前文件内容,随后调用edit_file来添加该函数。

  • > Assistant: Added a multiply function to hello.py.

我们构建的版本 vs. 生产级工具

我们的代码大约只有 200 行。而像 Claude Code 这样的生产级工具,额外增加了:

  • 更完善的错误处理和回退机制
  • 流式响应以提供更好的 UX(用户体验)
  • 更智能的上下文管理(如对长文件进行摘要总结等)
  • 更多工具(如运行命令、搜索代码库等)
  • 破坏性操作的审批流程

但核心循环(Core Loop)呢?它正是我们这里所构建的。LLM 决定做什么,你的代码去执行,结果再反馈回去。这就是其完整的架构。

亲自上手尝试吧

完整的源代码大约 200 行。你可以将其中的 LLM 提供商换成您偏好的服务,调整系统提示,或通过添加更多工具函数作为练习。你一定会惊叹:这套极简的模式,竟能实现如此强大的能力。

以上本文内容节选自作者斯坦福大学讲座《现代 AI 软件工程》课程的第一模块,点击此处查看课程详情。

网友评论 (0)

暂无评论,快来抢沙发吧~

发表评论

目录