Skip to content

About

小团队 AI Agent 编码实战:从 0 到 1 落地指南,使用 Claude Code + MiniMax/Kimi Code

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 

Repository files navigation

小团队 AI Agent 编码实战:从 0 到 1 落地指南

使用 Claude Code + 国内模型(MiniMax / Kimi Code)

📋 目录

  1. 为什么小团队需要 AI Agent 编码
  2. 技术栈选型
  3. 架构设计
  4. 环境准备
  5. 核心实现步骤
  6. 集成与优化
  7. 部署与运维
  8. 最佳实践
  9. 常见问题

1. 为什么小团队需要 AI Agent 编码

1.1 现状与挑战

  • 人力有限:小团队往往 3-10 人,开发者身兼数职
  • 需求多样:前后端、运维、架构都要懂
  • 迭代快速:没有大厂的冗余资源,必须高效

1.2 AI Agent 能做什么

场景 传统方式 AI Agent 方式
代码审查 人工耗时 30min+ AI 自动分析,5min 出结果
单元测试 手工编写耗时 自动生成 + 补充边界
Bug 定位 逐行 debug 结合日志 + 代码上下文智能定位
文档生成 事后补文档 代码即文档,实时同步
重构建议 依赖经验 基于模式识别的结构化建议

1.3 核心价值

让开发者从重复劳动中解放,专注于创造性工作


2. 技术栈选型

2.1 为什么选择这个组合

Claude Code (主控) + MiniMax/Kimi Code (国产补充)
特性 Claude Code MiniMax Kimi Code
定位 代码智能助手 多模态 + 长文本 代码专项优化
优势 全球最佳代码能力 中文理解强、国内合规 代码补全快
适用 复杂逻辑、架构设计 中文文档、本土化 日常编码辅助
成本 API 计费 API 计费 API 计费

2.2 推荐架构

┌─────────────────────────────────────────────────────────────┐
│                      用户界面 (CLI / Web)                    │
├─────────────────────────────────────────────────────────────┤
│                      Agent 编排层 (LangChain/自研)            │
├──────────────────────┬──────────────────────────────────────┤
│   Claude Code        │         国内模型集群                   │
│   (主力推理)         │   ┌──────────┐  ┌──────────┐        │
│                      │   │ MiniMax  │  │Kimi Code │        │
│                      │   └──────────┘  └──────────┘        │
├──────────────────────┴──────────────────────────────────────┤
│                      工具层 (Git / 文件系统 / 执行环境)        │
└─────────────────────────────────────────────────────────────┘

2.3 技术选型清单

  • 运行时:Node.js 20+ / Python 3.11+
  • Agent 框架:LangChain.js / LangChain (Python)
  • 模型客户端:OpenAI 兼容 API 适配
  • 版本控制:Git
  • 部署:Docker + Docker Compose

3. 架构设计

3.1 核心模块

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             # 入口

3.2 数据流

用户输入 → 意图识别 → 任务分解 → 模型推理 → 工具执行 → 结果验证 → 反馈输出

3.3 关键设计原则

  1. 模型无关抽象:通过接口隔离具体模型实现
  2. 工具可扩展:新增工具不影响核心逻辑
  3. 记忆分层:短期记忆(会话)+长期记忆(项目上下文)
  4. 容错机制:单模型失败时自动切换备选

4. 环境准备

4.1 账号与 API Key 获取

Claude Code

  1. 访问 Anthropic Console
  2. 创建账号并获取 API Key
  3. 注意:Claude Code 需要 Plus 会员才能使用高级功能

MiniMax

  1. 访问 MiniMax 开放平台
  2. 注册企业/个人账号
  3. 创建 API Key,注意模型选择(推荐 abab6.5s)

Kimi Code

  1. 访问 Kimi API 开放平台
  2. 注册并获取 API Key
  3. 推荐模型:kimi-code-v5

4.2 开发环境搭建

# 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

4.3 环境变量模板

# .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

5. 核心实现步骤

步骤 1:模型抽象层

创建 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));
  }
}

步骤 2:Claude Code 适配器

创建 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,
    };
  }
}

步骤 3:MiniMax 适配器

创建 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,
    }));
  }
}

步骤 4:模型工厂

创建 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';

步骤 5:工具层实现

创建 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;
  }
}

步骤 6:Agent 编排器

创建 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');
  }
}

步骤 7:CLI 入口

创建 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);

6. 集成与优化

6.1 模型路由策略

// 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;
    }
  }
}

6.2 记忆层实现

// 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`;
  }
}

6.3 工具权限控制

// 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 });
    }
  }
}

7. 部署与运维

7.1 Docker 部署

# 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

7.2 监控与日志

// 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();

7.3 速率限制

// 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);
  }
}

8. 最佳实践

8.1 提示词工程

// 好的系统提示词示例
const systemPrompt = `
你是一个专业的代码助手,专注于帮助小团队高效完成任务。

## 核心原则
1. 代码优先:优先提供可运行的代码解决方案
2. 安全第一:绝不执行未经确认的危险操作
3. 清晰解释:用简单易懂的语言解释技术决策

## 工作流程
1. 理解需求 → 2. 制定计划 → 3. 执行验证 → 4. 总结结果

## 输出格式
- 代码块必须标注语言
- 复杂操作需要用户确认
- 定期汇报进度
`;

8.2 错误处理

//统一的错误处理
 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}`);
    }
  }
}

8.3 测试策略

// 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();
  });
});

9. 常见问题

Q1: 如何选择主模型?

场景 推荐模型 原因
复杂架构设计 Claude Code 代码理解最强
中文文档撰写 MiniMax 中文语义理解好
快速代码补全 Kimi Code 响应速度快
生产环境 Claude + MiniMax 双备 稳定性优先

Q2: API 成本如何控制?

  1. 按需切换模型:简单任务用便宜的模型
  2. 缓存常用结果:相同输入不重复调用
  3. 设置预算上限:API 费用告警
  4. 压缩上下文:减少 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');
    }
  }
};

Q3: 如何保证代码安全?

  1. 沙盒执行:代码在隔离环境运行
  2. 权限分级:危险操作需要人工确认
  3. 审计日志:所有操作可追溯
  4. 敏感信息过滤:API Key 等不上传

Q4: 模型返回格式不稳定怎么办?

  1. 使用 JSON Schema 验证
  2. 提供 fallback 解析
  3. 要求模型输出特定格式
// 强制结构化输出
const structuredPrompt = `
请按以下 JSON 格式返回结果,不要有其他内容:
{
  "action": "read|write|execute",
  "target": "文件路径或命令",
  "reason": "为什么这样做"
}
`;

📚 扩展阅读


🤝 贡献指南

欢迎提交 Issue 和 PR!

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/xxx)
  3. 提交更改 (git commit -m 'Add xxx')
  4. 推送分支 (git push origin feature/xxx)
  5. 提 PR

📄 许可证

MIT License - 欢迎商业使用!


本文档由 AI Agent 生成并持续维护

About

小团队 AI Agent 编码实战:从 0 到 1 落地指南,使用 Claude Code + MiniMax/Kimi Code

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors