当前位置: 首页 > news >正文

外国排版网站企业名录2019企业黄页

外国排版网站,企业名录2019企业黄页,视频网站开发要多少钱,海南省住房和城乡建设部网站gemini-cli 从开源至今仅一个多月,已经收获接近65K Star,作为第一个开源的通用命令行智能体工具,在开源社区贡献者的参与下,现如今功能已经非常完善。本文将对源码进行解析,学习其中优秀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) - 循环检测

主循环流程

// 主要入口点在 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 × 块大小,则判定为循环

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的循环置信度分数

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

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 类是单轮对话的核心管理器,负责处理流式响应和工具调用:

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使用

聊天历史压缩机制

// 压缩触发条件和参数
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如下:

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也能够实现类似的架构。

http://www.dtcms.com/a/585450.html

相关文章:

  • 微信小程序开发实战:图片转 Base64 全解析
  • 秒杀-订单创建消费者CreateOrderConsumer
  • 单层前馈神经网络的万能逼近定理
  • C# 如何捕获键盘按钮和组合键以及KeyPress/KeyDown/KeyUp事件之间的区别
  • Windows系统不关闭防火墙,允许某个端口的访问怎么设置?
  • UniApp 多个异步开关控制教程
  • 邯郸哪家公司做企业网站比较专业中国制造网是干什么的
  • 做视频网站把视频放在哪里wordpress建站用什么意思
  • ASP.NET Core Web 应用SQLite数据连接显示(1)
  • 网易门户网站建设网站建设及发布的流程
  • 基于python的jlink单片机自动化批量烧录工具
  • 从三路快排到内省排序:探索工业级排序算法的演进
  • CPP 学习笔记 语法总结
  • Qt 跨平台 2048 游戏开发完整教程 (含源码)
  • SortScope 排序算法可视化
  • 组件库引入
  • 手写Spring第25弹:Spring JdbcTemplate深度解析:数据操作如此简单
  • 《Python 小程序编写系列》(第一部):从零开始写一个猜数字游戏
  • 【完整源码+数据集】草莓数据集,yolov8草莓成熟度检测数据集 3207 张,草莓成熟度数据集,目标检测草莓识别算法系统实战教程
  • 英特尔网站开发框架视频教学互动网站建设
  • DeepSeek-OCR实战(01):基础运行环境搭建-RockyLinux
  • 测开学习DAY26
  • VBA经典应用69例应用9:读取工作表中个数不定的数据
  • 网站建设策划书5000字蚂蚁网站建设
  • 【Janet】比较运算符
  • 05 kafka 如何存储较大数据记录
  • 使用Unity ASE插件设置数值不会生效的问题
  • 【ZeroRange WebRTC】WebRTC 信令安全:实现原理与应用(深入指南)
  • 关于Flutter与Qt for python 的一些技术、开源、商用等问题
  • 国外免费建站网站不用下载设计师培训心得