Gemini CLI源码解析:Agent与上下文管理实现细节

gemini-cli 从开源至今仅一个多月,已经收获接近65K Star,作为第一个开源的通用命令行智能体工具,在开源社区贡献者的参与下,现如今功能已经非常完善。本文将对源码进行解析,学习其中优秀Agent的设计思路,将重点关注主控Agent以及上下文管理的实现,对于其他部分不在本文的讨论范围之内。

主控 Agent 循环实现

核心架构

gemini-cli 的 Agent 循环主要由以下几个核心组件构成:

  1. GeminiClient (client.ts) - 主控制器
  2. Turn (turn.ts) - 单轮对话管理
  3. CoreToolScheduler (coreToolScheduler.ts) - 工具调用调度
  4. LoopDetectionService (loopDetectionService.ts) - 循环检测

主循环流程

typescript 复制代码
// 主要入口点在 GeminiClient.sendMessageStream
async sendMessageStream(prompt: string, prompt_id?: string): Promise<AsyncGenerator<ServerGeminiStreamEvent>> {
  // 1. 会话轮次限制检查
  if (this.turnCount >= this.MAX_TURNS) {
    throw new Error(`Maximum turns (${this.MAX_TURNS}) reached`);
  }

  // 2. 聊天历史压缩
  const compressed = await this.tryCompressChat(prompt_id);
  
  // 3. 循环检测
  const loopDetected = await this.loopDetectionService.checkForLoop(...);
  
  // 4. 创建 Turn 实例并执行
  const turn = new Turn(this.chat, this.coreToolScheduler, ...);
  return turn.run();
}

循环检测机制

在主循环过程中,系统实现了双重循环检测机制,确保系统不会陷入无限的工具调用或内容生成循环:

  • 资源保护 :避免消耗过多的 API 调用次数和计算资源

  • 用户体验 :及时通知用户并停止无效的处理过程

  • 会话恢复 :用户可以重新发起新的请求,循环检测状态会在新的prompt_id开始时重置

1. 内容块分析检测

一个基本的内容检测方法,用于快速检测内容块是否存在重复。基本原理如下:

  • 固定大小滑动窗口 :使用CONTENT_CHUNK_SIZE = 100 字符的固定大小块

  • SHA256 哈希算法 :对每个文本块计算哈希值进行高效比较

  • 位置追踪 :记录相同哈希值出现的所有位置索引

  • 距离分析 :当相同块出现 CONTENT_LOOP_THRESHOLD = 10 次时,计算平均距离

  • 循环判定 :如果平均距离 ≤ 1.5 × 块大小,则判定为循环

typescript 复制代码
class LoopDetectionService {
  private static readonly CHUNK_SIZE = 100; // 固定块大小
  private static readonly MIN_REPETITIONS = 3; // 最小重复次数
  private contentHashes: Map<string, number[]> = new Map();
  
  analyzeContentChunksForLoop(content: string): boolean {
    const chunks = this.createFixedSizeChunks(content, this.CHUNK_SIZE);
    
    for (let i = 0; i < chunks.length; i++) {
      const hash = this.hashContent(chunks[i]);
      
      if (!this.contentHashes.has(hash)) {
        this.contentHashes.set(hash, []);
      }
      
      const positions = this.contentHashes.get(hash)!;
      positions.push(i);
      
      // 检查是否有足够的重复
      if (positions.length >= this.MIN_REPETITIONS) {
        const intervals = this.calculateIntervals(positions);
        if (this.hasConsistentPattern(intervals)) {
          return true; // 检测到循环
        }
      }
    }
    
    return false;
  }
  
  private createFixedSizeChunks(content: string, size: number): string[] {
    const chunks: string[] = [];
    for (let i = 0; i <= content.length - size; i += size) {
      chunks.push(content.substring(i, i + size));
    }
    return chunks;
  }
  
  private hashContent(content: string): string {
    // 使用简单的哈希算法
    let hash = 0;
    for (let i = 0; i < content.length; i++) {
      const char = content.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash; // 转换为32位整数
    }
    return hash.toString();
  }
}

2. LLM智能检测

试用LLM结合上下文判断是否出现内容循环,设置条件如下:

  • 触发条件 :在第 30 轮后开始,每隔 3-15 轮检查一次

  • 上下文分析 :提取最近 20 轮对话历史

  • 语义理解 :使用 Gemini Flash 模型分析对话模式

  • 置信度评估 :返回0~1.0的循环置信度分数

  • 动态调整 :根据置信度调整下次检查间隔

typescript 复制代码
class LoopDetectionService {
  private static readonly DEFAULT_CHECK_INTERVAL = 5; // 默认检查间隔
  private static readonly HIGH_CONFIDENCE_THRESHOLD = 0.8;
  private static readonly MEDIUM_CONFIDENCE_THRESHOLD = 0.6;
  
  async checkForLoopWithLLM(history: ChatMessage[]): Promise<LoopCheckResult> {
    const recentHistory = history.slice(-10); // 取最近10条消息
    
    const prompt = this.buildLoopDetectionPrompt(recentHistory);
    const response = await this.llmClient.generateContent(prompt);
    
    const result = this.parseLoopDetectionResponse(response);
    
    // 根据置信度调整下次检查间隔
    if (result.confidence >= this.HIGH_CONFIDENCE_THRESHOLD) {
      this.nextCheckInterval = 2; // 高置信度,更频繁检查
    } else if (result.confidence >= this.MEDIUM_CONFIDENCE_THRESHOLD) {
      this.nextCheckInterval = 3; // 中等置信度
    } else {
      this.nextCheckInterval = this.DEFAULT_CHECK_INTERVAL; // 低置信度,正常间隔
    }
    
    return result;
  }
  
  private buildLoopDetectionPrompt(history: ChatMessage[]): string {
    return `
      分析以下对话历史,判断AI助手是否陷入了非生产性的循环状态:
      
      ${history.map(msg => `${msg.role}: ${msg.content}`).join('\n')}
      
      请评估:
      1. 是否存在重复的响应模式
      2. 是否在执行相同的无效操作
      3. 是否缺乏实质性进展
      
      返回JSON格式:{"isLoop": boolean, "confidence": number, "reason": string}
    `;
  }
}

Turn 类详细实现

Turn 类是单轮对话的核心管理器,负责处理流式响应和工具调用:

typescript 复制代码
class Turn {
  private pendingToolCalls: ToolCall[] = [];
  
  async *run(): AsyncGenerator<ServerGeminiStreamEvent> {
    // 处理响应流
    for await (const response of this.chat.sendMessageStream(this.prompt)) {
      // 处理 thought 部分
      if (response.thought) {
        yield { type: GeminiEventType.Thought, content: response.thought };
      }
      
      // 处理文本内容
      if (response.text) {
        yield { type: GeminiEventType.Content, content: response.text };
      }
      
      // 处理函数调用
      if (response.functionCalls) {
        for (const call of response.functionCalls) {
          this.handlePendingFunctionCall(call);
        }
      }
    }
    
    // 处理待处理的工具调用
    if (this.pendingToolCalls.length > 0) {
      yield* this.handleToolCalls();
    }
  }
  
  private handlePendingFunctionCall(call: FunctionCall): void {
    this.pendingToolCalls.push({
      id: generateId(),
      name: call.name,
      params: call.args
    });
  }
}

上下文管理实现

内存管理策略

gemini-cli 采用 纯内存 + 文件系统的混合存储方案, 不依赖数据库 :

  1. 内存存储: 会话期间的上下文保存在内存中,如:聊天历史、工具调用状态、循环检测状态等

  2. 文件系统持久化: 长期记忆通过文件系统存储,如:用户记忆、项目上下文等

  3. 智能压缩: 动态压缩聊天历史以控制token使用

聊天历史压缩机制

typescript 复制代码
// 压缩触发条件和参数
static readonly COMPRESSION_TOKEN_THRESHOLD = 0.7;  // 70% token 使用率触发压缩
static readonly COMPRESSION_PRESERVE_THRESHOLD = 0.3; // 保留 30% 最新历史
static readonly MAX_TURNS = 100; // 最大会话轮次

async tryCompressChat(prompt_id?: string): Promise<boolean> {
  const history = this.getChat().getHistory(true);
  const originalTokenCount = countTokens(history, this.model);
  const limit = tokenLimit(this.model);
  
  // 检查是否需要压缩
  if (originalTokenCount > this.COMPRESSION_TOKEN_THRESHOLD * limit) {
    // 计算保留的历史记录数量
    const preserveIndex = this.findIndexAfterFraction(
      history, 
      this.COMPRESSION_PRESERVE_THRESHOLD
    );
    
    // 生成摘要并更新历史
    const summary = await this.sendMessage(getCompressionPrompt(), ...);
    this.getChat().updateHistory(newHistory);
    
    return true;
  }
  return false;
}

结构化的压缩提示词

Claude code类似,也是提供把需要压缩的内容提炼为几个部分,进而减少token的使用量,避免超出上下文限制:

  • overall_goal:用户的主要目标

  • key_knowledge:重要的技术知识和决策

  • file_system_state:文件系统的当前状态

  • recent_actions:最近执行的重要操作

  • current_plan:当前的执行计划

完整的prompt如下:

xml 复制代码
You are the component that summarizes internal chat history into a given structure.

When the conversation history grows too large, you will be invoked to distill the entire history into a concise, structured XML snapshot. This snapshot is CRITICAL, as it will become the agent's *only* memory of the past. The agent will resume its work based solely on this snapshot. All crucial details, plans, errors, and user directives MUST be preserved.

First, you will think through the entire history in a private <scratchpad>. Review the user's overall goal, the agent's actions, tool outputs, file modifications, and any unresolved questions. Identify every piece of information that is essential for future actions.

After your reasoning is complete, generate the final <state_snapshot> XML object. Be incredibly dense with information. Omit any irrelevant conversational filler.

The structure MUST be as follows:

<state_snapshot>
    <overall_goal>
        <!-- A single, concise sentence describing the user's high-level objective. -->
        <!-- Example: "Refactor the authentication service to use a new JWT library." -->
    </overall_goal>

    <key_knowledge>
        <!-- Crucial facts, conventions, and constraints the agent must remember based on the conversation history and interaction with the user. Use bullet points. -->
        <!-- Example:
         - Build Command: \`npm run build\`
         - Testing: Tests are run with \`npm test\`. Test files must end in \`.test.ts\`.
         - API Endpoint: The primary API endpoint is \`https://api.example.com/v2\`.
         
        -->
    </key_knowledge>

    <file_system_state>
        <!-- List files that have been created, read, modified, or deleted. Note their status and critical learnings. -->
        <!-- Example:
         - CWD: \`/home/user/project/src\`
         - READ: \`package.json\` - Confirmed 'axios' is a dependency.
         - MODIFIED: \`services/auth.ts\` - Replaced 'jsonwebtoken' with 'jose'.
         - CREATED: \`tests/new-feature.test.ts\` - Initial test structure for the new feature.
        -->
    </file_system_state>

    <recent_actions>
        <!-- A summary of the last few significant agent actions and their outcomes. Focus on facts. -->
        <!-- Example:
         - Ran \`grep 'old_function'\` which returned 3 results in 2 files.
         - Ran \`npm run test\`, which failed due to a snapshot mismatch in \`UserProfile.test.ts\`.
         - Ran \`ls -F static/\` and discovered image assets are stored as \`.webp\`.
        -->
    </recent_actions>

    <current_plan>
        <!-- The agent's step-by-step plan. Mark completed steps. -->
        <!-- Example:
         1. [DONE] Identify all files using the deprecated 'UserAPI'.
         2. [IN PROGRESS] Refactor \`src/components/UserProfile.tsx\` to use the new 'ProfileAPI'.
         3. [TODO] Refactor the remaining files.
         4. [TODO] Update tests to reflect the API change.
        -->
    </current_plan>
</state_snapshot>

总结

gemini-cli的设计思路不乏以下亮点:

  1. 循环控制 :多层安全机制确保系统稳定性,包括轮次限制和智能循环检测

  2. 上下文管理 :无数据库依赖的轻量级设计,结合智能压缩和结构化摘要,有效管理长对话历史

Manus类似,gemini-cli使用文件系统持久化长期记忆,因为文件系统就是天然的数据库,这种设计既保证了系统的可靠性和性能,又提供了良好的用户体验和扩展性。

不过,略显遗憾的是目前gemini-cli使用的仍然是单一主控Agent来控制所有交互,响应速度上会比较差;而Claude code则是多Agent架构,同时异步设计实现了高效的响应速度,并且还允许用户根据不同任务定义不同的子Agent,在性能和效率上都是断档的存在。期待后续gemini-cli和其他开源的Agent也能够实现类似的架构。

相关推荐
Wendy14411 小时前
【灰度实验】——图像预处理(OpenCV)
人工智能·opencv·计算机视觉
中杯可乐多加冰1 小时前
五大低代码平台横向深度测评:smardaten 2.0领衔AI原型设计
人工智能
无线图像传输研究探索1 小时前
单兵图传终端:移动场景中的 “实时感知神经”
网络·人工智能·5g·无线图传·5g单兵图传
大熊猫侯佩2 小时前
无需自己写半行代码:让 AI 编程智能体(Agent)化身神笔马良为我们自动仿制 App 界面
swiftui·agent·cursor
zzywxc7872 小时前
AI在编程、测试、数据分析等领域的前沿应用(技术报告)
人工智能·深度学习·机器学习·数据挖掘·数据分析·自动化·ai编程
铭keny3 小时前
YOLOv8 基于RTSP流目标检测
人工智能·yolo·目标检测
墨尘游子3 小时前
11-大语言模型—Transformer 盖楼,BERT 装修,RoBERTa 直接 “拎包入住”|预训练白话指南
人工智能·语言模型·自然语言处理
金井PRATHAMA3 小时前
主要分布于内侧内嗅皮层的层Ⅲ的网格-速度联合细胞(Grid × Speed Conjunctive Cells)对NLP中的深层语义分析的积极影响和启示
人工智能·深度学习·神经网络·机器学习·语言模型·自然语言处理·知识图谱
天道哥哥3 小时前
InsightFace(RetinaFace + ArcFace)人脸识别项目(预训练模型,鲁棒性很好)
人工智能·目标检测
幻风_huanfeng4 小时前
学习人工智能所需知识体系及路径详解
人工智能·学习