MiniClawd - 新手学习版
约 1564 字大约 5 分钟
2026-03-07
新手学习版 - TypeScript 精简版,剥离 90% 非核心包,保留核心逻辑,代码清晰易读,适合学习和教学。
核心特性
极简依赖
- 仅保留核心依赖包
- 剥离 90% 非必要包
- 依赖树清晰
- 易于理解
代码清晰
- 注释详细
- 结构简单
- 逻辑直观
- 适合学习
教学友好
- 循序渐进的示例
- 详细的文档说明
- 概念解释清楚
- 适合新手入门
可扩展性
- 模块化设计
- 易于添加功能
- 插件机制简单
- 二次开发友好
快速开始
安装
# 克隆仓库
git clone https://github.com/FoundDream/miniclawd.git
cd miniclawd
# 安装依赖(非常快)
npm install
# 构建
npm run build
# 启动
npm start配置
创建 .env 文件:
# API 配置
ANTHROPIC_API_KEY=your_api_key
# 基础配置
PORT=3000
LOG_LEVEL=info第一次运行
# 启动服务
npm start
# 发送第一条消息
curl -X POST http://localhost:3000/chat \
-H "Content-Type: application/json" \
-d '{"message": "Hello, AI!"}'项目结构
miniclawd/
├── src/
│ ├── core/ # 核心逻辑
│ │ ├── agent.ts # Agent 主类
│ │ ├── llm.ts # LLM 调用
│ │ └── tools.ts # 工具系统
│ ├── memory/ # 记忆系统
│ │ └── simple.ts # 简单记忆实现
│ ├── server/ # HTTP 服务器
│ │ └── index.ts # 服务器入口
│ └── index.ts # 主入口
├── examples/ # 示例代码
│ ├── basic.ts # 基础使用
│ ├── tools.ts # 工具使用
│ └── memory.ts # 记忆使用
├── docs/ # 文档
│ ├── architecture.md # 架构说明
│ ├── tutorial.md # 教程
│ └── api.md # API 文档
└── package.json核心代码解析
Agent 主类
// src/core/agent.ts
export class Agent {
private llm: LLM;
private tools: Tool[];
private memory: Memory;
constructor(config: AgentConfig) {
this.llm = new LLM(config.apiKey);
this.tools = [];
this.memory = new SimpleMemory();
}
/**
* 处理用户消息
* 这是 Agent 的核心方法
*/
async chat(message: string): Promise<string> {
// 1. 从记忆中获取上下文
const context = await this.memory.getContext();
// 2. 构建提示词
const prompt = this.buildPrompt(message, context);
// 3. 调用 LLM
const response = await this.llm.generate(prompt);
// 4. 检查是否需要使用工具
if (this.needsTool(response)) {
const toolResult = await this.executeTool(response);
return this.chat(toolResult); // 递归调用
}
// 5. 保存到记忆
await this.memory.save(message, response);
return response;
}
/**
* 注册工具
*/
registerTool(tool: Tool): void {
this.tools.push(tool);
}
}LLM 调用
// src/core/llm.ts
export class LLM {
private apiKey: string;
private baseURL = 'https://api.anthropic.com/v1';
constructor(apiKey: string) {
this.apiKey = apiKey;
}
/**
* 生成响应
* 这是与 Claude API 交互的核心方法
*/
async generate(prompt: string): Promise<string> {
const response = await fetch(`${this.baseURL}/messages`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': this.apiKey,
'anthropic-version': '2023-06-01',
},
body: JSON.stringify({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
messages: [{
role: 'user',
content: prompt,
}],
}),
});
const data = await response.json();
return data.content[0].text;
}
}工具系统
// src/core/tools.ts
export interface Tool {
name: string;
description: string;
execute: (params: any) => Promise<any>;
}
/**
* 工具执行器
*/
export class ToolExecutor {
private tools: Map<string, Tool> = new Map();
register(tool: Tool): void {
this.tools.set(tool.name, tool);
}
async execute(toolName: string, params: any): Promise<any> {
const tool = this.tools.get(toolName);
if (!tool) {
throw new Error(`Tool ${toolName} not found`);
}
return await tool.execute(params);
}
}
// 示例工具:获取当前时间
export const getCurrentTime: Tool = {
name: 'get_current_time',
description: '获取当前时间',
execute: async () => {
return new Date().toISOString();
},
};简单记忆
// src/memory/simple.ts
export class SimpleMemory {
private messages: Array<{
role: 'user' | 'assistant';
content: string;
timestamp: Date;
}> = [];
/**
* 保存对话
*/
async save(userMessage: string, assistantMessage: string): Promise<void> {
this.messages.push({
role: 'user',
content: userMessage,
timestamp: new Date(),
});
this.messages.push({
role: 'assistant',
content: assistantMessage,
timestamp: new Date(),
});
// 只保留最近 10 条消息
if (this.messages.length > 10) {
this.messages = this.messages.slice(-10);
}
}
/**
* 获取上下文
*/
async getContext(): Promise<string> {
return this.messages
.map(m => `${m.role}: ${m.content}`)
.join('\n');
}
}学习路径
第一步:理解基础
// examples/basic.ts
import { Agent } from './src/core/agent';
async function main() {
// 1. 创建 Agent
const agent = new Agent({
apiKey: process.env.ANTHROPIC_API_KEY!,
});
// 2. 发送消息
const response = await agent.chat('你好!');
console.log(response);
}
main();第二步:添加工具
// examples/tools.ts
import { Agent, Tool } from './src/core/agent';
// 定义一个简单的工具
const weatherTool: Tool = {
name: 'get_weather',
description: '获取天气信息',
execute: async (params: { city: string }) => {
// 这里可以调用真实的天气 API
return `${params.city}的天气是晴天`;
},
};
async function main() {
const agent = new Agent({
apiKey: process.env.ANTHROPIC_API_KEY!,
});
// 注册工具
agent.registerTool(weatherTool);
// 使用工具
const response = await agent.chat('北京的天气怎么样?');
console.log(response);
}
main();第三步:使用记忆
// examples/memory.ts
import { Agent } from './src/core/agent';
async function main() {
const agent = new Agent({
apiKey: process.env.ANTHROPIC_API_KEY!,
});
// 第一轮对话
await agent.chat('我叫张三');
// 第二轮对话 - Agent 会记住你的名字
const response = await agent.chat('我叫什么名字?');
console.log(response); // "你叫张三"
}
main();教学文档
架构说明
MiniClawd 采用简单的三层架构:
- 核心层 (core): Agent、LLM、Tools
- 记忆层 (memory): 对话历史管理
- 服务层 (server): HTTP API 接口
关键概念
ReAct 循环
用户输入 → LLM 思考 → 需要工具?
↓ 是
执行工具 → 获取结果 → 继续思考
↓ 否
返回响应工具调用流程
// 1. LLM 决定使用工具
"我需要使用 get_weather 工具查询北京天气"
// 2. 解析工具调用
const toolCall = {
name: 'get_weather',
params: { city: '北京' }
};
// 3. 执行工具
const result = await tool.execute(toolCall.params);
// 4. 将结果返回给 LLM
"工具返回:北京的天气是晴天"
// 5. LLM 生成最终响应
"北京今天是晴天"适用场景
学习 AI Agent
- 理解 Agent 工作原理
- 学习 LLM 集成
- 掌握工具调用机制
教学演示
- 课堂教学示例
- 技术分享
- 概念验证
快速原型
- 快速验证想法
- 最小可行产品
- 功能演示
与其他版本对比
vs 官方版
- 官方版功能完整但复杂,MiniClawd 简单易懂
- 官方版依赖多,MiniClawd 依赖少
- MiniClawd 专为学习设计
vs Nanobot
- Nanobot 使用 Python,MiniClawd 使用 TypeScript
- Nanobot 更极简,MiniClawd 更适合学习
- MiniClawd 保留了更多官方版的结构
扩展示例
添加自定义工具
// 创建一个计算器工具
const calculatorTool: Tool = {
name: 'calculator',
description: '执行数学计算',
execute: async (params: { expression: string }) => {
// 注意:实际使用时需要安全的表达式求值
return eval(params.expression);
},
};
agent.registerTool(calculatorTool);持久化记忆
import fs from 'fs/promises';
class FileMemory extends SimpleMemory {
private filePath = './memory.json';
async save(userMessage: string, assistantMessage: string): Promise<void> {
await super.save(userMessage, assistantMessage);
await fs.writeFile(this.filePath, JSON.stringify(this.messages));
}
async load(): Promise<void> {
const data = await fs.readFile(this.filePath, 'utf-8');
this.messages = JSON.parse(data);
}
}相关链接
- GitHub: FoundDream/miniclawd
- 教程: 完整教程
- 视频讲解: B站视频
- 问题反馈: Issues
贡献
欢迎改进教学内容和示例!
# 克隆仓库
git clone https://github.com/FoundDream/miniclawd.git
# 安装依赖
npm install
# 运行示例
npm run example:basic
npm run example:tools
npm run example:memory许可证
MIT License - 详见 LICENSE