新手搭建做网站临沂网站建设吧
2026/4/16 18:15:58 网站建设 项目流程
新手搭建做网站,临沂网站建设吧,dede自定义网站地图,html5 手机网站开发叫才【CSDN 编者按】当 Claude Code、Devin 这些 AI 编程工具被神话成“下一代程序员”时#xff0c;很多人以为背后是某种高不可攀的黑科技。但本文作者用不到 200 行 Python 代码#xff0c;亲手拆解了一个最小可用的 Coding Agent#xff0c;让开发者可以直观地看到#xff…【CSDN 编者按】当 Claude Code、Devin 这些 AI 编程工具被神话成“下一代程序员”时很多人以为背后是某种高不可攀的黑科技。但本文作者用不到 200 行 Python 代码亲手拆解了一个最小可用的 Coding Agent让开发者可以直观地看到所谓“会读代码、会改项目”的智能体本质只是一个围绕 LLM 的工具调用循环。原文链接https://www.mihaileric.com/The-Emperor-Has-No-Clothes/作者 | Mihail Eric 翻译 | 郑丽媛出品 | CSDNIDCSDNnews现在的 AI 编程助手用起来简直像魔法。你随口用几句不太通顺的英语描述需求它就能自动读代码、改项目、写出能跑的功能模块。Claude Code、Cursor、Devin看起来都像是掌握了某种神秘黑科技。但真相是这些工具的核心一点也不神秘——不到 200 行的 Python 代码就能复刻一个可用的 AI 编程 Agent。下面让我们从零开始亲手实现一个「会改代码的 LLM」。先搞懂核心逻辑Coding Agent 到底在干什么在写代码前先搞清楚你在用 Claude Code 时后台究竟发生了什么本质上它就是大语言模型LLM 工具库的对话循环具体步骤只有五步1你发送指令比如“创建一个包含 hello world 函数的新文件”2LLM 分析指令后判断需要调用工具并返回结构化的工具调用请求可以是单次或多次调用3你的本地程序执行这个工具调用比如真的创建文件4工具执行结果被回传给 LLM5LLM 结合结果继续处理直到完成任务整个过程里LLM 自始至终都没有直接操作你的文件系统它只负责下达指令真正干活的是你写的本地代码。核心三件套实现 Agent 只需要 3 个工具一个能用的代码助手底层只需要三个核心功能再多的功能都只是锦上添花1读取文件让 LLM 能查看你现有代码的内容2列出文件帮 LLM 理清项目的目录结构实现 “导航”3编辑文件让 LLM 能创建新文件、修改已有代码没错就是这么简单。像 Claude Code 这样的商用产品还会额外集成 grep 检索、bash 命令执行、网页搜索等功能但对我们来说这三个工具就足够实现核心能力了。第一步搭建基础框架我们从最基础的导入和 API 客户端开始。我这里用的是 Anthropic但换成其他 LLM 供应商的 SDK 也完全适用。import inspectimport jsonimport os import anthropicfrom dotenv import load_dotenvfrom pathlib import Pathfrom typing import Any, Dict, List, Tuple load_dotenv()claude_client anthropic.Anthropic(api_keyos.environ[ANTHROPIC_API_KEY])为了让终端输出的内容更易区分我们定义几个颜色常量YOU_COLOR \u001b[94mASSISTANT_COLOR \u001b[93mRESET_COLOR \u001b[0m再写一个工具函数用来解析并返回文件的绝对路径避免因相对路径导致的找不到文件问题def resolve_abs_path(path_str: str) - Path: path Path(path_str).expanduser() if not path.is_absolute(): path (Path.cwd() / path).resolve() return path第二步实现三大核心工具注意工具函数的文档字符串docstring一定要写清楚LLM 会根据这些描述判断该调用哪个工具、怎么传参——这是让 Agent 能正常工作的关键。工具 1读取文件内容功能最简单的工具传入文件名返回文件的完整内容。def read_file_tool(filename: str) - Dict[str, Any]: full_path resolve_abs_path(filename) with open(str(full_path), r) as f: content f.read() return { file_path: str(full_path), content: content }返回字典格式是为了给 LLM 传递结构化的执行结果方便它理解。工具 2列出目录下的文件帮 LLM 搞清楚项目结构实现“导航”功能。def list_files_tool(path: str) - Dict[str, Any]: 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 }工具 3编辑文件创建 修改这是三个工具里最复杂的一个但逻辑依然清晰它主要处理两种场景当old_str参数为空时创建新文件当old_str参数不为空时替换文件中第一次出现的old_str为new_strdef edit_file_tool(path: str, old_str: str, new_str: str) - Dict[str, Any]: full_path resolve_abs_path(path) if old_str : full_path.write_text(new_str, encodingutf-8) return {path: str(full_path), action: created_file} original full_path.read_text(encodingutf-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, encodingutf-8) return {path: str(full_path), action: edited}商用 IDE 的代码助手会有更复杂的容错逻辑但这个极简版本足以验证核心原理。第三步注册工具让 LLM 能找到它们我们需要一个“工具注册表”把工具名称和对应的函数绑定起来方便后续调用。TOOL_REGISTRY { read_file: read_file_tool, list_files: list_files_tool, edit_file: edit_file_tool }第四步给 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_reprtool_str_repr)然后定义核心的系统提示词模板这是整个 Agent 的 “灵魂”你不是教 LLM 怎么写代码而是教它怎么调用现实世界的工具。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第六步封装 LLM 调用逻辑写一个简单的封装函数负责把对话历史传给 LLM并获取回复。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( modelclaude-sonnet-4-20250514, max_tokens2000, systemsystem_content, messagesmessages ) return response.content[0].text第七步组装核心循环让 Agent 跑起来这一步是把前面所有的模块串起来实现 Agent 的核心工作流也是“魔法”发生的地方。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: ftool_result({json.dumps(resp)}) })这个主循环的逻辑可以拆解为两层外层循环获取用户输入添加至对话内容内层循环调用大型语言模型检测工具调用需求→若无需工具输出响应并终止内层循环→若需工具执行工具操作将结果添加至对话内容循环继续。内层循环持续进行直至 LLM 响应时不再请求任何工具。这使 Agent 能够串联多个工具调用例如读取文件→编辑文件→确认编辑。最后一步启动程序加上主函数入口运行我们的代码助手if __name__ __main__: run_coding_agent_loop()现在你就可以进行这样的对话了你创建一个名为 hello.py 的新文件并在其中实现Hello World功能AI 助手调用 edit_file 函数参数为 pathhello.pyold_strnew_strprint(Hello World)AI 助手完成已创建包含 Hello World 实现的 hello.py 文件。或者还可以进行多步骤交互你编辑 hello.py 并添加一个乘法函数AI 助手调用 read_file 查看当前内容再调用 edit_file 添加函数AI 助手已在 hello.py 中添加乘法函数我们的极简版 vs 商用版 Claude Code我们的代码只有200 行左右但已经实现了代码助手的核心逻辑。商用产品 Claude Code 之所以更强大是因为它在这个基础上做了这些优化1更完善的错误处理比如文件权限不足、路径不存在时的容错逻辑2流式输出让回复内容实时显示提升用户体验3智能上下文管理比如自动摘要长文件避免 Token 超限4更丰富的工具集比如执行 shell 命令、搜索代码库、调用外部 API5安全校验流程比如修改重要文件前需要用户确认防止误操作但核心工作流完全一致LLM 决策 → 本地工具执行 → 结果反馈 → 继续决策。所以动手试试吧完整源代码我放在这里了https://drive.google.com/file/d/1YtpKFVG13DHyQ2i3HOtwyVJOV90nWeL2/view?pli1这不到 200 行的代码只是一个起点你还可以对其轻松扩展换成其他 LLM 供应商的 API调整系统提示词并可作为练习添加更多工具。你会发现看似高大上的 AI 代码助手底层原理其实一点都不神秘。推荐阅读11天狂写10万行代码13年Rust老兵与Claude联手从零造了一门新语言全网380万人围观连代码都不看4个月“烧掉”30亿Token不懂编程的他却做出了50个产品……开发网站被欠薪Web开发者怒删客户官网只留三行催款留言先付钱才能访问网站

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询