# small-claude-code **Repository Path**: biackese/small-claude-code ## Basic Information - **Project Name**: small-claude-code - **Description**: 简单的ai编程智能体 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 1 - **Created**: 2026-03-19 - **Last Updated**: 2026-04-10 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README 揭秘AI编程智能体从原理到实现 你有没有想过例如ClaudeCode, OpenCode, 或者最近爆火的OpenClaw等项目,它们是如何实现的?底层的原理是什么? 从聊天机器人到智能体是增加了很多黑科技么? 传统助手(网页版使用场景) 用户提示词 ----> 大语言模型 ----> 助手回复 我们从最基本的版本开始,逐步引入更多功能。 单一工具 + 循环调用 = 基础智能体 #第一课 : 基础智能体 ## 问题 大语言模型可以推理代码,但是无法读取、写入、测试等能力,每次调用的结果都是你把结果给粘帖回去,你就是大模型的手脚,是那个循环。 ## 解决方案 用户提示词 ----> 大语言模型 ----> 工具执行 ↑ ↓ | | +-------------+ 循环直到finish_reason不等于"tool_calls" 核心:大模型是决策者,代码提供调用工具并且循环,直到完成任务或用户中断。 ## 工作原理 1. 用户 prompt 作为第一条消息。 ```python messages.append({"role": "user", "content": prompt}) ``` 2. 将消息和工具发送给大模型,获取回复。 ```python result = call_ai_api(payload = { "model" : f"{MODEL_ID}", "messages": messages, "tools" : TOOLS }) ``` 3. 解析大模型回复,判断是否需要调用工具。 ```python if (result["choices"][0]["finish_reason"] != "tool_calls"): return ``` 4. 调用工具,执行操作。 ```python tool_calls = result["choices"][0]["message"]["tool_calls"] for tool_call in tool_calls: function_input = tool_call["function"]["arguments"] function_args = json.loads(function_input) output = execute_cmd(**function_args) ``` 5. 将工具执行结果作为消息,添加到消息列表。 ```python messages.append({ "role" : "tool", "tool_call_id": tool_call["id"], "content" : output, }) ``` 6. 重复步骤2-5,直到大模型回复不再需要调用工具。 完整函数 ```python def loop_call_ai_api(prompt): history.append({"role": "user", "content": prompt}) while True: result = call_ai_api(payload = { "model" : f"{MODEL_ID}", "messages": history, "tools" : TOOLS }) history.append(result["choices"][0]["message"]) if (result["choices"][0]["finish_reason"] != "tool_calls"): return tool_calls = result["choices"][0]["message"]["tool_calls"] for tool_call in tool_calls: function_name = tool_call["function"]["name"] function_input = tool_call["function"]["arguments"] function_args = json.loads(function_input) # 执行命令 output = execute_cmd(**function_args) print(f"> {function_name} {function_input} output: {output}") history.append({ "role" : "tool", "tool_call_id": tool_call["id"], "content" : output, }) ``` ``` 测试用例 >> 帮我生成一个你好,世界的文件 > cmd {"command": "echo 你好,世界 > hello_world.txt"} output: 没有输出 > cmd {"command": "type hello_world.txt"} output: 你好,世界 已成功创建了"你好,世界"文件(hello_world.txt),内容如下: ``` 你好,世界 ``` 文件已成功保存到当前目录。 ``` 为何这个设计有效? 根据我的粗浅认知,我们一切都是模拟人类的行为,大模型相当于是人类的大脑,但是他不能去干扰外部的世界,他可以控制躯干的运动,从而去完成行为。 #第二课 : 工具使用 ## 问题 只有cmd时,所有操作都走批处理,局限性很大,无法完成复杂的任务。这时候我们就可以引入专业工具‘读’ ‘写’ ‘编辑’等。 ## 解决方案 用户提示词 ----> 大语言模型 ----> 工具执行(cmd, read_file, write_file, edit_file) ↑ ↓ | | +-------------+ 循环直到finish_reason不等于"tool_calls" ## 工作原理 1. 定义工具列表,包含cmd, read_file, write_file, edit_file。 ```python TOOLS = [ { "type": "function", "function": { "name": "cmd", "description": "执行windows批处理命令", "parameters": { "type": "object", "properties": { "command": { "type": "string", "description": "要执行的命令", } }, "required": ["command"], } } }, .... ``` 2. 映射工具函数 ```python tools_functions = { "cmd" : execute_cmd, "read_file" : read_file, "write_file": write_file, "edit_file" : edit_file, } ``` 3. 解析大模型回复,查找对应的工具函数调用。 ```python for tool_call in tool_calls: function_name = tool_call["function"]["name"] function_input = tool_call["function"]["arguments"] function_args = json.loads(function_input) if function_name in tools_functions: function = tools_functions[function_name] output = function(**function_args) ``` ``` 测试用例 帮我生成一个hello world的文件 > write_file {"path": "hello_world.txt output: 共写入12个字符到hello_world.txt 已成功生成 Hello World 文件! 📄 文件名:`hello_world.txt` 📝 内容:`Hello World!` ✨ 写入字符数:12个字符 您可以查看这个文件的内容。如果您需要创建其他类型的 Hello World 文件(比如 Python、JavaScript 等),请告诉我! >> 帮我把hello world改成 你好世界 > edit_file {"path": "hello_world.txt output: 共替换Hello World!为你好世界,共4个字符 已成功修改文件内容! 📄 文件名:`hello_world.txt` ✏️ 修改内容:`Hello World!` → `你好世界` 🔢 共替换了 4 个字符 现在文件里的内容是中文的"你好世界"了!😊 >> 帮我看一下hello_world.txt当前的内容 > read_file {"path": "hello_world.txt output: 你好世界 📄 文件:`hello_world.txt` **当前内容:** ``` 你好世界 ``` ✅ 文件已成功修改为中文的"你好世界"了! ``` #第三课:TODO 列表 ## 问题 在实际开发中,因为需求的复杂,模型通常会丢失进度,重复执行相同的操作、需求没有实现、乱改代码。对话越长,模型就会越丢失进度。结果不断填满上下文,系统提示词被稀释,一个5步的任务,模型可能完成的2~3步就开始发挥了,这时候用户就会感到很困惑,模型到底在做什么?实际是因为4~5步已经被挤出注意力范围了。 ## 解决方案 用户提示词 ----> 大语言模型 ----> 工具执行(todo_list) ↑ ↓ | | +-------------+ [◆] 任务1 [>] 任务2 -- 进行中 [ ] 任务3 循环直到finish_reason不等于"tool_calls" ## 工作原理 1. todo list 工具,同一时间只允许一个进行中的任务。 ```python def todo_list(items: list) -> str: validated = [] in_progress_count = 0 for i, item in enumerate(items): text = item.get("text", "").strip() status = item.get("status", "pending").lower() item_id = item.get("id", str(i + 1)) if (not text) : raise ValueError(f"Item {item_id}: text required") if status not in ("pending", "in_progress", "completed"): raise ValueError(f"Item {item_id}: invalid status '{status}'") if status == "in_progress": in_progress_count += 1 validated.append({"id": item_id, "text": text, "status": status}) if in_progress_count > 1: raise ValueError("Only one task can be in_progress at a time") if (not validated): raise ValueError("No todos.") outputs = [] for item in validated: marker = {"pending": "[ ]", "in_progress": "[>]", "completed": "[◆]"}[item["status"]] outputs.append(f"{marker} #{item['id']}: {item['text']}") done = sum(1 for t in validated if t["status"] == "completed") outputs.append(f"\n({done}/{len(validated)} completed)") return "\n".join(outputs) ``` 2.增加todo_list工具的调用频率检查 如果todo_list工具调用次数超过3次,就提示用户检查更新代办事项。 ```python todo_idle_count = 0 if (function_name == "todo_list"): todo_idle_count = 0 else: todo_idle_count += 1 if (todo_idle_count > 3): history.append({"role": "user", "content": "请检查更新代办事项."}) ``` 只允许一个进行中的任务,聚焦任务。 ``` >> 用html 实现一个贪吃蛇游戏 > todo_list {"items": [{"id": "1", " output: [>] #1: 创建HTML文件结构和基本样式 [ ] #2: 实现游戏画布和蛇的移动逻辑 [ ] #3: 实现食物生成和碰撞检测 [ ] #4: 添加键盘控制和分数显示 [ ] #5: 测试和优化游戏功能 (0/5 completed) > write_file {"content": " todo_list {"items": [{"id": "1", " output: [◆] #1: 创建HTML文件结构和基本样式 [◆] #2: 实现游戏画布和蛇的移动逻辑 [◆] #3: 实现食物生成和碰撞检测 [◆] #4: 添加键盘控制和分数显示 [◆] #5: 测试和优化游戏功能 (5/5 completed) ✅ 贪吃蛇游戏已创建完成! **文件:** `snake_game.html` ## 🎮 游戏特性: 1. **精美的视觉效果** - 渐变背景和圆角设计 - 带有阴影效果的游戏容器 - 蛇身使用渐变色,头部有可爱的眼睛动画 - 食物带脉冲动画效果 2. **完整的游戏机制** - 方向键或 WASD 控制移动 - 吃到红色食物得分(每次+10分) - 撞到墙壁或身体自触则游戏结束 - 越吃越快(速度逐渐提升) 3. **计分系统** - 实时显示当前分数 - 最高分保存到 localStorage - 游戏结束时显示最终分数和模态框 4. **操作按钮** - 开始游戏按钮 - 重置游戏按钮 - 游戏结束弹窗 ## 🕹️ 使用方法: 直接用浏览器打开 `snake_game.html` 即可玩! 祝你玩得愉快!🐍✨ ``` # 第四课:子智能体 ## 问题 智能体工作越久,history会越来越大,这时候模型就会越来越慢,出错率也会增高,token消耗也会,因为模型需要处理的信息越多。例如我总结一下当前的项目,我其实只需要一个总结,但是模型就需要遍历文件,找到所有相关的代码,然后总结。 ## 解决方案 增加一个子智能体工具 main agent ----> 大语言模型 ----> 工具执行(sub_agent 总结)-> main agent sub agent拥有除了sub_agent以外所有的工具, 禁止递归调用 ## 工作原理 1. 父智能体有一个sub_agent工具,用于调用子智能体(子智能体无法调用sub_agent工具)。 ```python if function_name == "sub_agent" : sub_prompt = function_args["prompt"] output = loop_sub_call_ai_api(sub_prompt) ``` 2. 子智能体只返回最终结果文本 你是不是想知道如何使用Claude Code来执行任务? 当你在终端中输入一句话时,AI可以帮你修改代码,跑测试,提交PR这一系列操作,是如何实现的? #扩写一点疑问