使用 Claude Code + 国内模型(MiniMax / Kimi Code)
- 人力有限:小团队往往 3-10 人,开发者身兼数职
- 需求多样:前后端、运维、架构都要懂
- 迭代快速:没有大厂的冗余资源,必须高效
| 场景 | 传统方式 | AI Agent 方式 |
|---|---|---|
| 代码审查 | 人工耗时 30min+ | AI 自动分析,5min 出结果 |
| 单元测试 | 手工编写耗时 | 自动生成 + 补充边界 |
| Bug 定位 | 逐行 debug | 结合日志 + 代码上下文智能定位 |
| 文档生成 | 事后补文档 | 代码即文档,实时同步 |
| 重构建议 | 依赖经验 | 基于模式识别的结构化建议 |
让开发者从重复劳动中解放,专注于创造性工作
Claude Code (主控) + MiniMax/Kimi Code (国产补充)
| 特性 | Claude Code | MiniMax | Kimi Code |
|---|---|---|---|
| 定位 | 代码智能助手 | 多模态 + 长文本 | 代码专项优化 |
| 优势 | 全球最佳代码能力 | 中文理解强、国内合规 | 代码补全快 |
| 适用 | 复杂逻辑、架构设计 | 中文文档、本土化 | 日常编码辅助 |
| 成本 | API 计费 | API 计费 | API 计费 |
┌─────────────────────────────────────────────────────────────┐
│ 用户界面 (CLI / Web) │
├─────────────────────────────────────────────────────────────┤
│ Agent 编排层 (LangChain/自研) │
├──────────────────────┬──────────────────────────────────────┤
│ Claude Code │ 国内模型集群 │
│ (主力推理) │ ┌──────────┐ ┌──────────┐ │
│ │ │ MiniMax │ │Kimi Code │ │
│ │ └──────────┘ └──────────┘ │
├──────────────────────┴──────────────────────────────────────┤
│ 工具层 (Git / 文件系统 / 执行环境) │
└─────────────────────────────────────────────────────────────┘
- 运行时:Node.js 20+ / Python 3.11+
- Agent 框架:LangChain.js / LangChain (Python)
- 模型客户端:OpenAI 兼容 API 适配
- 版本控制:Git
- 部署:Docker + Docker Compose
src/
├── agent/ # Agent 核心
│ ├── orchestrator.ts # 任务编排器
│ ├── planner.ts # 任务规划
│ └── executor.ts # 执行器
├── models/ # 模型抽象层
│ ├── base.ts # 基础接口
│ ├── claude.ts # Claude Code 适配
│ ├── minimax.ts # MiniMax 适配
│ └── kimi.ts # Kimi Code 适配
├── tools/ # 工具集
│ ├── file.ts # 文件操作
│ ├── git.ts # Git 操作
│ ├── terminal.ts # 命令执行
│ └── search.ts # 代码搜索
├── memory/ # 记忆层
│ ├── short-term.ts # 会话记忆
│ └── long-term.ts # 项目知识
└── index.ts # 入口
用户输入 → 意图识别 → 任务分解 → 模型推理 → 工具执行 → 结果验证 → 反馈输出
- 模型无关抽象:通过接口隔离具体模型实现
- 工具可扩展:新增工具不影响核心逻辑
- 记忆分层:短期记忆(会话)+长期记忆(项目上下文)
- 容错机制:单模型失败时自动切换备选
- 访问 Anthropic Console
- 创建账号并获取 API Key
- 注意:Claude Code 需要 Plus 会员才能使用高级功能
- 访问 MiniMax 开放平台
- 注册企业/个人账号
- 创建 API Key,注意模型选择(推荐
abab6.5s)
- 访问 Kimi API 开放平台
- 注册并获取 API Key
- 推荐模型:
kimi-code-v5
# 1. 克隆模板
git clone https://github.com/your-team/ai-agent-starter.git
cd ai-agent-starter
# 2. 安装依赖
npm install
# 3. 配置环境变量
cp .env.example .env
# 编辑 .env 填入你的 API Keys
# 4. 验证安装
npm run build
npm test# .env
# Claude Code (主力模型)
ANTHROPIC_API_KEY=sk-ant-xxxxx
# MiniMax (中文理解)
MINIMAX_API_KEY=xxxxx
MINIMAX_GROUP_ID=xxxxx
# Kimi Code (代码辅助)
KIMI_API_KEY=xxxxx
# 可选配置
DEFAULT_MODEL=claude
FALLBACK_MODEL=minimax
LOG_LEVEL=info创建 src/models/base.ts:
// 模型接口抽象
export interface ModelConfig {
apiKey: string;
baseUrl?: string;
model: string;
maxTokens?: number;
temperature?: number;
}
export interface Message {
role: 'system' | 'user' | 'assistant';
content: string;
}
export interface CompletionResponse {
content: string;
usage?: {
promptTokens: number;
completionTokens: number;
totalTokens: number;
};
}
export abstract class BaseModel {
protected config: ModelConfig;
constructor(config: ModelConfig) {
this.config = config;
}
abstract complete(messages: Message[]): Promise<CompletionResponse>;
// 默认实现,可被覆盖
async completeWithRetry(
messages: Message[],
retries = 3
): Promise<CompletionResponse> {
for (let i = 0; i < retries; i++) {
try {
return await this.complete(messages);
} catch (error) {
if (i === retries - 1) throw error;
await this.delay(1000 * Math.pow(2, i)); // 指数退避
}
}
throw new Error('Max retries reached');
}
protected delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
}创建 src/models/claude.ts:
import { BaseModel, ModelConfig, Message, CompletionResponse } from './base';
export class ClaudeModel extends BaseModel {
private baseUrl = 'https://api.anthropic.com/v1';
constructor(config: ModelConfig) {
super(config);
}
async complete(messages: Message[]): Promise<CompletionResponse> {
const response = await fetch(`${this.baseUrl}/messages`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': this.config.apiKey,
'anthropic-version': '2023-06-01',
},
body: JSON.stringify({
model: this.config.model || 'claude-3-5-sonnet-20241022',
max_tokens: this.config.maxTokens || 4096,
messages: messages.filter(m => m.role !== 'system'),
system: messages.find(m => m.role === 'system')?.content,
}),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Claude API error: ${error}`);
}
const data = await response.json();
return {
content: data.content[0].text,
usage: data.usage,
};
}
}创建 src/models/minimax.ts:
import { BaseModel, ModelConfig, Message, CompletionResponse } from './base';
export class MiniMaxModel extends BaseModel {
private baseUrl = 'https://api.minimax.chat/v1';
constructor(
config: ModelConfig,
private groupId: string
) {
super(config);
}
async complete(messages: Message[]): Promise<CompletionResponse> {
const response = await fetch(
`${this.baseUrl}/text/chatcompletion_v2?GroupId=${this.groupId}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.config.apiKey}`,
},
body: JSON.stringify({
model: this.config.model || 'abab6.5s',
max_tokens: this.config.maxTokens || 4096,
messages: this.formatMessages(messages),
}),
}
);
if (!response.ok) {
const error = await response.text();
throw new Error(`MiniMax API error: ${error}`);
}
const data = await response.json();
return {
content: data.choices[0].message.content,
usage: data.usage,
};
}
// MiniMax 消息格式处理
private formatMessages(messages: Message[]) {
return messages.map(m => ({
role: m.role === 'system' ? 'system' :
m.role === 'user' ? 'user' : 'assistant',
content: m.content,
}));
}
}创建 src/models/index.ts:
import { BaseModel } from './base';
import { ClaudeModel } from './claude';
import { MiniMaxModel } from './minimax';
import { KimiModel } from './kimi';
export type ModelType = 'claude' | 'minimax' | 'kimi';
export interface ModelFactoryConfig {
type: ModelType;
apiKey: string;
model?: string;
groupId?: string; // MiniMax 需要
}
export function createModel(config: ModelFactoryConfig): BaseModel {
const baseConfig = {
apiKey: config.apiKey,
model: config.model,
maxTokens: 4096,
temperature: 0.7,
};
switch (config.type) {
case 'claude':
return new ClaudeModel(baseConfig);
case 'minimax':
if (!config.groupId) {
throw new Error('MiniMax requires groupId');
}
return new MiniMaxModel(baseConfig, config.groupId);
case 'kimi':
return new KimiModel(baseConfig);
default:
throw new Error(`Unknown model type: ${config.type}`);
}
}
export { BaseModel, ClaudeModel, MiniMaxModel, KimiModel } from './index';创建 src/tools/file.ts:
import * as fs from 'fs/promises';
import * as path from 'path';
export class FileTool {
async read(filePath: string): Promise<string> {
try {
return await fs.readFile(filePath, 'utf-8');
} catch (error) {
throw new Error(`Failed to read ${filePath}: ${error}`);
}
}
async write(filePath: string, content: string): Promise<void> {
await fs.mkdir(path.dirname(filePath), { recursive: true });
await fs.writeFile(filePath, content, 'utf-8');
}
async list(dirPath: string, recursive = false): Promise<string[]> {
const entries = await fs.readdir(dirPath, { withFileTypes: true });
const files: string[] = [];
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isFile()) {
files.push(fullPath);
} else if (entry.isDirectory() && recursive) {
const subFiles = await this.list(fullPath, true);
files.push(...subFiles);
}
}
return files;
}
async search(dirPath: string, pattern: string): Promise<string[]> {
const files = await this.list(dirPath, true);
const results: string[] = [];
for (const file of files) {
const content = await this.read(file);
if (content.includes(pattern)) {
results.push(file);
}
}
return results;
}
}创建 src/agent/orchestrator.ts:
import { BaseModel, Message } from '../models';
import { FileTool } from '../tools/file';
import { GitTool } from '../tools/git';
import { TerminalTool } from '../tools/terminal';
export interface AgentContext {
task: string;
workingDir: string;
history: Message[];
}
export class AgentOrchestrator {
private model: BaseModel;
private tools: {
file: FileTool;
git: GitTool;
terminal: TerminalTool;
};
constructor(model: BaseModel) {
this.model = model;
this.tools = {
file: new FileTool(),
git: new GitTool(),
terminal: new TerminalTool(),
};
}
async execute(context: AgentContext): Promise<string> {
// 1. 分析任务
const plan = await this.plan(context);
// 2. 执行计划
const results = await this.executePlan(plan, context);
// 3. 验证结果
const verified = await this.verify(results);
return verified ? this.summarize(results) : this.recover(results);
}
private async plan(context: AgentContext): Promise<string[]> {
const messages: Message[] = [
{
role: 'system',
content: `你是一个代码助手。根据用户任务,制定执行计划。
可用工具:file_read, file_write, git_status, terminal_run
请用 JSON 数组格式返回步骤,每个步骤描述要做什么。`,
},
{
role: 'user',
content: context.task,
},
];
const response = await this.model.complete(messages);
return JSON.parse(response.content);
}
private async executePlan(plan: string[], context: AgentContext): Promise<any[]> {
const results = [];
for (const step of plan) {
const messages: Message[] = [
{
role: 'system',
content: `执行步骤:${step}
当前目录:${context.workingDir}
请选择合适的工具并执行。`,
},
];
const response = await this.model.complete(messages);
// 解析工具调用并执行
const toolCall = this.parseToolCall(response.content);
const result = await this.executeTool(toolCall);
results.push({ step, result });
}
return results;
}
private parseToolCall(response: string): { tool: string; args: any } {
// 简化版:实际应该用更严格的解析
try {
return JSON.parse(response);
} catch {
return { tool: 'terminal_run', args: { command: response } };
}
}
private async executeTool(call: { tool: string; args: any }): Promise<any> {
switch (call.tool) {
case 'file_read':
return this.tools.file.read(call.args.path);
case 'file_write':
return this.tools.file.write(call.args.path, call.args.content);
case 'git_status':
return this.tools.git.status(call.args.repo);
case 'terminal_run':
return this.tools.terminal.run(call.args.command, call.args.cwd);
default:
throw new Error(`Unknown tool: ${call.tool}`);
}
}
private async verify(results: any[]): Promise<boolean> {
// 简化的验证逻辑
return results.every(r => r.result !== undefined);
}
private async recover(results: any[]): Promise<string> {
// 错误恢复逻辑
return 'Some steps failed, please check the results.';
}
private async summarize(results: any[]): Promise<string> {
return results.map(r => `✓ ${r.step}: ${JSON.stringify(r.result)}`).join('\n');
}
}创建 src/index.ts:
import { createModel } from './models';
import { AgentOrchestrator } from './agent/orchestrator';
async function main() {
const args = process.argv.slice(2);
const task = args.join(' ');
if (!task) {
console.error('请提供任务描述');
process.exit(1);
}
// 从环境变量获取配置
const modelType = process.env.DEFAULT_MODEL || 'claude';
const apiKey = getApiKey(modelType);
const model = createModel({
type: modelType as any,
apiKey,
model: getModelName(modelType),
});
const agent = new AgentOrchestrator(model);
console.log('🤖 正在执行任务:', task);
const result = await agent.execute({
task,
workingDir: process.cwd(),
history: [],
});
console.log('\n✅ 执行结果:');
console.log(result);
}
function getApiKey(type: string): string {
const keys: Record<string, string> = {
claude: process.env.ANTHROPIC_API_KEY!,
minimax: process.env.MINIMAX_API_KEY!,
kimi: process.env.KIMI_API_KEY!,
};
return keys[type];
}
function getModelName(type: string): string {
const models: Record<string, string> = {
claude: 'claude-3-5-sonnet-20241022',
minimax: 'abab6.5s',
kimi: 'kimi-code-v5',
};
return models[type];
}
main().catch(console.error);// src/models/router.ts
export class ModelRouter {
private models: Map<string, BaseModel> = new Map();
private primary: string;
private fallback: string;
constructor(config: { primary: string; fallback: string; models: Map<string, BaseModel> }) {
this.primary = config.primary;
this.fallback = config.fallback;
this.models = config.models;
}
async complete(messages: Message[]): Promise<CompletionResponse> {
const primaryModel = this.models.get(this.primary);
try {
return await primaryModel!.complete(messages);
} catch (error) {
console.warn(`Primary model failed, trying fallback: ${this.fallback}`);
const fallbackModel = this.models.get(this.fallback);
return await fallbackModel!.complete(messages);
}
}
// 智能路由:根据任务类型选择模型
selectModel(taskType: 'code' | 'document' | 'analysis'): string {
switch (taskType) {
case 'code':
return 'claude';
case 'document':
return 'minimax';
case 'analysis':
return 'kimi';
default:
return this.primary;
}
}
}// src/memory/short-term.ts
export class ShortTermMemory {
private messages: Message[] = [];
private maxSize: number;
constructor(maxSize = 20) {
this.maxSize = maxSize;
}
add(message: Message): void {
this.messages.push(message);
if (this.messages.length > this.maxSize) {
this.messages.shift();
}
}
getMessages(): Message[] {
return [...this.messages];
}
clear(): void {
this.messages = [];
}
// 压缩历史(保留关键信息)
compress(): void {
// 实现摘要压缩逻辑
if (this.messages.length > this.maxSize / 2) {
const summary = this.summarize(this.messages);
this.messages = [
{ role: 'system', content: `Summary: ${summary}` },
...this.messages.slice(-this.maxSize / 2),
];
}
}
private summarize(messages: Message[]): string {
// 简化版:返回消息数量
return `${messages.length} messages in conversation`;
}
}// src/tools/permissions.ts
export interface ToolPermission {
tool: string;
allowed: boolean;
requiresApproval?: boolean;
}
export class ToolPermissionManager {
private permissions: Map<string, ToolPermission> = new Map([
{ tool: 'file_read', allowed: true } as any,
{ tool: 'file_write', allowed: true, requiresApproval: true } as any,
{ tool: 'git_commit', allowed: true, requiresApproval: true } as any,
{ tool: 'terminal_run', allowed: false } as any,
{ tool: 'delete', allowed: false } as any,
]);
canExecute(tool: string): { allowed: boolean; requiresApproval: boolean } {
const perm = this.permissions.get(tool);
return {
allowed: perm?.allowed ?? false,
requiresApproval: perm?.requiresApproval ?? false,
};
}
approve(tool: string): void {
const perm = this.permissions.get(tool);
if (perm) {
this.permissions.set(tool, { ...perm, allowed: true });
}
}
}# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist/ ./dist/
COPY .env.example .env
EXPOSE 3000
CMD ["node", "dist/index.js"]# docker-compose.yml
version: '3.8'
services:
agent:
build: .
ports:
- "3000:3000"
env_file:
- .env
volumes:
- ./workspace:/app/workspace
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3// src/utils/logger.ts
export class AgentLogger {
private logs: Array<{
timestamp: Date;
level: 'info' | 'warn' | 'error';
message: string;
context?: any;
}> = [];
log(level: 'info' | 'warn' | 'error', message: string, context?: any): void {
const entry = { timestamp: new Date(), level, message, context };
this.logs.push(entry);
// 控制台输出
console[level](`[${entry.timestamp.toISOString()}] ${message}`, context || '');
// 生产环境可以发送到日志服务
if (process.env.NODE_ENV === 'production') {
this.sendToRemote(entry);
}
}
getLogs(filter?: { level?: string; since?: Date }): any[] {
let filtered = this.logs;
if (filter?.level) {
filtered = filtered.filter(l => l.level === filter.level);
}
if (filter?.since) {
filtered = filtered.filter(l => l.timestamp > filter.since!);
}
return filtered;
}
private sendToRemote(entry: any): void {
// 发送到日志服务(如 Prometheus, Loki, DataDog)
}
}
export const logger = new AgentLogger();// src/utils/rate-limiter.ts
export class RateLimiter {
private requests: Map<string, number[]> = new Map();
private limit: number;
private windowMs: number;
constructor(limit: number, windowMs: number) {
this.limit = limit;
this.windowMs = windowMs;
}
check(key: string): boolean {
const now = Date.now();
const timestamps = this.requests.get(key) || [];
// 清理过期的时间戳
const validTimestamps = timestamps.filter(t => now - t < this.windowMs);
if (validTimestamps.length >= this.limit) {
return false;
}
validTimestamps.push(now);
this.requests.set(key, validTimestamps);
return true;
}
reset(key: string): void {
this.requests.delete(key);
}
}// 好的系统提示词示例
const systemPrompt = `
你是一个专业的代码助手,专注于帮助小团队高效完成任务。
## 核心原则
1. 代码优先:优先提供可运行的代码解决方案
2. 安全第一:绝不执行未经确认的危险操作
3. 清晰解释:用简单易懂的语言解释技术决策
## 工作流程
1. 理解需求 → 2. 制定计划 → 3. 执行验证 → 4. 总结结果
## 输出格式
- 代码块必须标注语言
- 复杂操作需要用户确认
- 定期汇报进度
`;//统一的错误处理
export class AgentError extends Error {
constructor(
message: string,
public code: string,
public recoverable: boolean = false
) {
super(message);
this.name = 'AgentError';
}
}
// 使用
try {
await agent.execute(context);
} catch (error) {
if (error instanceof AgentError) {
if (error.recoverable) {
// 自动恢复
console.log('Attempting recovery...');
} else {
// 报告给用户
console.error(`Fatal error: ${error.message}`);
}
}
}// src/__tests__/agent.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { AgentOrchestrator } from '../agent/orchestrator';
import { ClaudeModel } from '../models/claude';
describe('AgentOrchestrator', () => {
let agent: AgentOrchestrator;
let mockModel: any;
beforeEach(() => {
mockModel = {
complete: vi.fn().mockResolvedValue({
content: JSON.stringify(['file_read', 'git_status']),
}),
};
agent = new AgentOrchestrator(mockModel as any);
});
it('should execute simple task', async () => {
const result = await agent.execute({
task: '查看当前 git 状态',
workingDir: '/test',
history: [],
});
expect(result).toBeDefined();
expect(mockModel.complete).toHaveBeenCalled();
});
it('should handle model errors gracefully', async () => {
mockModel.complete = vi.fn().mockRejectedValue(new Error('API Error'));
await expect(
agent.execute({ task: 'test', workingDir: '/', history: [] })
).rejects.toThrow();
});
});| 场景 | 推荐模型 | 原因 |
|---|---|---|
| 复杂架构设计 | Claude Code | 代码理解最强 |
| 中文文档撰写 | MiniMax | 中文语义理解好 |
| 快速代码补全 | Kimi Code | 响应速度快 |
| 生产环境 | Claude + MiniMax 双备 | 稳定性优先 |
- 按需切换模型:简单任务用便宜的模型
- 缓存常用结果:相同输入不重复调用
- 设置预算上限:API 费用告警
- 压缩上下文:减少 token 消耗
// 成本控制示例
const costTracker = {
dailyLimit: 10, // 美元
spent: 0,
track(usage: any) {
const cost = (usage.totalTokens / 1000) * 0.003; // 估算
this.spent += cost;
if (this.spent > this.dailyLimit) {
throw new Error('Daily budget exceeded');
}
}
};- 沙盒执行:代码在隔离环境运行
- 权限分级:危险操作需要人工确认
- 审计日志:所有操作可追溯
- 敏感信息过滤:API Key 等不上传
- 使用 JSON Schema 验证
- 提供 fallback 解析
- 要求模型输出特定格式
// 强制结构化输出
const structuredPrompt = `
请按以下 JSON 格式返回结果,不要有其他内容:
{
"action": "read|write|execute",
"target": "文件路径或命令",
"reason": "为什么这样做"
}
`;欢迎提交 Issue 和 PR!
- Fork 本仓库
- 创建特性分支 (
git checkout -b feature/xxx) - 提交更改 (
git commit -m 'Add xxx') - 推送分支 (
git push origin feature/xxx) - 提 PR
MIT License - 欢迎商业使用!
本文档由 AI Agent 生成并持续维护