Chrome Skills重磅上线!浏览器秒变"龙虾助理",Agent帮你干活

谷歌Skills功能正式发布,将OpenClaw自动化能力深度融入Chrome浏览器


🚀 开篇暴击

Chrome浏览器迎来了重大更新!谷歌正式上线Skills功能,将OpenClaw(龙虾)的强大自动化能力直接搬进浏览器核心。

简单说:以后不用部署,打开Chrome就能享受Agent级服务!


📋 目录


一、Skills是什么?

1.1 核心定义

Skills = 高频AI指令的"技能模板"

本质: 把复杂的AI提示词打包成可复用的快捷方式

解决痛点:

  • • ❌ 以前:每次都要重复输入提示词
  • • ✅ 现在:一键调用,秒级响应

1.2 与OpenClaw对比

特性 Chrome Skills OpenClaw(龙虾)
部署方式 浏览器内置 本地部署
使用门槛 小白友好 需要技术基础
数据安全 Chrome账户体系 完全本地化
执行能力 Agent级 强Agent级

二、核心功能解析

2.1 技能管理界面

// Chrome Skills UI结构
const SkillsUI = {
  // 侧边栏面板
  sidebar: {
    skillsList: [],           // 技能列表
    searchInput: '',           // 搜索框
    categoryFilter: 'all',       // 分类筛选
    quickActions: []           // 快捷操作
  },
  
  // 技能详情面板
  skillDetail: {
    promptEditor: '',         // 提示词编辑器
    variableManager: {},       // 变量管理器
    previewPane: '',          // 预览面板
    executionLog: []          // 执行日志
  },
  
  // 快捷触发器
  quickTrigger: {
    addressBar: '/skills',      // 地址栏触发
    hotkey: 'Ctrl+Shift+S',   // 快捷键
    contextMenu: true         // 右键菜单
  }
};

2.2 技能执行引擎

import asyncio
from typing import Dict, Any

class SkillExecutionEngine:
    """技能力执行引擎"""
    
    def __init__(self):
        self.gemini_client = self._init_gemini_client()
        self.context_manager = ContextManager()
        self.tool_registry = ToolRegistry()
    
    async def execute_skill(self, skill_config: Dict[str, Any]) -> Dict[str, Any]:
        # 1. 解析变量
        variables = self._resolve_variables(skill_config)
        
        # 2. 渲染提示词
        prompt = self._render_prompt(skill_config['template'], variables)
        
        # 3. 选择执行策略
        execution_type = skill_config.get('type', 'simple')
        
        if execution_type == 'agent':
            return await self._execute_as_agent(prompt, variables)
        elif execution_type == 'multi_step':
            return await self._execute_multi_step(skill_config, variables)
        else:
            return await self._execute_simple(prompt, variables)
    
    async def _execute_as_agent(self, prompt: str, context: Dict) -> Dict[str, Any]:
        """Agent级执行"""
        # 拆解任务
        tasks = await self._decompose_task(prompt, context)
        
        # 协调执行
        results = []
        for task in tasks:
            if self._can_execute_parallel(task, context):
                result = await self._execute_task(task)
            else:
                result = await self._execute_task(task)
            
            results.append(result)
        
        # 汇总结果
        return self._aggregate_results(results)
    
    def _resolve_variables(self, config: Dict) -> Dict:
        """解析技能变量"""
        variables = {}
        for var_def in config.get('variables', []):
            var_name = var_def['name']
            var_type = var_def.get('type', 'text')
            
            # 从上下文获取值
            if var_type == 'text':
                variables[var_name] = self.context_manager.get(var_name)
            elif var_type == 'select':
                options = var_def.get('options', [])
                variables[var_name] = self._select_option(options)
            elif var_type == 'number':
                variables[var_name] = self.context_manager.get(var_name, 0)
        
        return variables
    
    def _render_prompt(self, template: str, variables: Dict) -> str:
        """渲染提示词"""
        result = template
        for key, value in variables.items():
            result = result.replace(f'{{{key}}}', str(value))
        return result

三、小白3步上手

第1步:创建第一个技能

// 创建简单的网页总结技能
const webSummarySkill = {
  id: 'web_summary_v1',
  name: '网页长文总结',
  description: '一键总结当前网页的长文章',
  
  // 提示词模板
  promptTemplate: `
    请总结当前网页的主要内容,要求:
    1. 提取核心观点(不超过3个)
    2. 总结关键信息(不超过5条)
    3. 给出简短评价(1-2句话)
    
    当前网页内容:
    {page_content}
  `,
  
  // 变量定义
  variables: [
    {
      name: 'page_content',
      type: 'text',
      description: '当前网页内容',
      required: true
    }
  ],
  
  // 执行配置
  execution: {
    type: 'simple',
    timeout: 30000,  // 30秒超时
    maxTokens: 1024
  }
};

// 注册技能
chrome.storage.local.set({
  skills: [webSummarySkill]
});

第2步:调用技能

// 在Chrome中调用技能
async function callSkill(skillId) {
  try {
    // 获取当前标签页内容
    const [tab] = await chrome.tabs.query({active: true});
    
    // 执行技能
    const result = await chrome.runtime.sendMessage({
      action: 'executeSkill',
      skillId: skillId,
      context: {
        tabId: tab.id,
        url: tab.url
      }
    });
    
    // 显示结果
    displayResult(result);
    
  } catch (error) {
    console.error('技能执行失败:', error);
    showError(error.message);
  }
}

// 显示结果面板
function displayResult(result) {
  const resultPanel = document.createElement('div');
  resultPanel.innerHTML = `
    <div class="skill-result">
      <h3>执行结果</h3>
      <div class="content">${result.content}</div>
      <div class="meta">
        <span>执行时间: ${result.executionTime}ms</span>
        <span>使用模型: ${result.model}</span>
      </div>
    </div>
  `;
  
  document.body.appendChild(resultPanel);
}

第3步:优化技能

// 添加变量支持
const enhancedSkill = {
  ...webSummarySkill,
  id: 'web_summary_v2',
  name: '智能网页总结',
  
  // 增强的变量支持
  variables: [
    {
      name: 'page_content',
      type: 'text',
      required: true
    },
    {
      name: 'summary_length',
      type: 'select',
      description: '总结长度',
      options: ['short', 'medium', 'long'],
      defaultValue: 'medium'
    },
    {
      name: 'include_quotes',
      type: 'boolean',
      description: '是否包含引用',
      defaultValue: false
    },
    {
      name: 'focus_areas',
      type: 'text',
      description: '重点关注领域',
      required: false
    }
  ],
  
  // 条件逻辑
  conditionalLogic: `
    IF include_quotes == true:
      ADD "提取关键引用"到总结要求
    IF focus_areas IS NOT EMPTY:
      ADD "重点关注{focus_areas}相关内容"到总结要求
  `
};

四、实战代码示例

4.1 产品对比技能

class ProductComparisonSkill {
  constructor() {
    this.name = '产品智能对比';
    this.version = '1.0.0';
  }
  
  async execute(context) {
    // 1. 获取当前页面产品信息
    const currentProduct = await this.extractProductInfo(context.tabId);
    
    // 2. 搜索相关产品
    const relatedProducts = await this.searchRelatedProducts(currentProduct.category);
    
    // 3. 构建对比数据
    const comparisonData = {
      base: currentProduct,
      competitors: relatedProducts
    };
    
    // 4. 调用Gemini生成对比
    const prompt = this.buildComparisonPrompt(comparisonData);
    const result = await this.callGemini(prompt);
    
    // 5. 格式化输出
    return this.formatComparison(result, comparisonData);
  }
  
  async extractProductInfo(tabId) {
    // 提取产品信息的详细实现
    const [tab] = await chrome.tabs.get(tabId);
    const results = await chrome.scripting.executeScript({
      target: { tabId },
      func: () => {
        // 页面脚本:提取产品信息
        return {
          name: document.querySelector('h1')?.textContent,
          price: document.querySelector('.price')?.textContent,
          specs: Array.from(document.querySelectorAll('.spec-item')).map(
            el => el.textContent
          )
        };
      }
    });
    
    return results[0];
  }
  
  buildComparisonPrompt(data) {
    return `
      请生成产品对比表格,包含以下产品:
      ${data.base.name}: ${JSON.stringify(data.base.specs)}
      ${data.competitors.map(p => 
        `${p.name}: ${JSON.stringify(p.specs)}`
      ).join('\n')}
      
      要求:
      1. 表格格式输出
      2. 标注优缺点
      3. 给出购买建议
    `;
  }
}

// 使用示例
const comparisonSkill = new ProductComparisonSkill();
const result = await comparisonSkill.execute({
  tabId: currentTab.id,
  context: {}
});

console.log('对比结果:', result);

4.2 代码提取技能

class CodeExtractionSkill {
  constructor() {
    this.name = '智能代码提取';
    this.version = '2.0.0';
  }
  
  async execute(context) {
    // 1. 获取页面代码
    const codeBlocks = await this.extractCodeBlocks(context.tabId);
    
    // 2. 识别代码语言
    const languages = this.detectLanguages(codeBlocks);
    
    // 3. 清理和格式化
    const cleanedCode = this.cleanCode(codeBlocks);
    
    // 4. 生成摘要
    const summary = await this.generateCodeSummary(cleanedCode, languages);
    
    // 5. 生成使用建议
    const suggestions = await this.generateUsageSuggestions(cleanedCode);
    
    return {
      code: cleanedCode,
      summary: summary,
      suggestions: suggestions,
      languages: languages
    };
  }
  
  async extractCodeBlocks(tabId) {
    const [tab] = await chrome.tabs.get(tabId);
    const results = await chrome.scripting.executeScript({
      target: { tabId },
      func: () => {
        // 查找所有代码块
        const codeBlocks = [];
        const codeElements = document.querySelectorAll('pre, code, .code-block');
        
        codeElements.forEach(el => {
          codeBlocks.push({
            code: el.textContent,
            language: el.className || 'unknown'
          });
        });
        
        return codeBlocks;
      }
    });
    
    return results[0];
  }
  
  async generateCodeSummary(code, languages) {
    const prompt = `
      请分析以下代码,生成摘要:
      
      代码内容:
      ${code.substring(0, 2000)}...
      
      识别语言:${languages.join(', ')}
      
      要求:
      1. 总结代码功能
      2. 识别关键算法
      3. 指出潜在优化点
    `;
    
    return await this.callGemini(prompt);
  }
}

// 注册和使用
chrome.runtime.onInstalled.addListener(() => {
  chrome.storage.local.set({
    skills: [new CodeExtractionSkill()]
  });
});

4.3 Agent多任务协调

class AgentCoordinator {
  constructor() {
    this.activeTasks = new Map();
    this.taskQueue = [];
    this.results = [];
  }
  
  async coordinateMultiPageTask(taskConfig) {
    // 1. 解析任务配置
    const tasks = this.parseTaskConfig(taskConfig);
    
    // 2. 执行任务队列
    for (const task of tasks) {
      await this.executeTask(task);
    }
    
    // 3. 汇总结果
    const summary = this.aggregateResults(this.results);
    
    // 4. 生成最终报告
    const finalReport = await this.generateFinalReport(summary);
    
    return finalReport;
  }
  
  async executeTask(task) {
    // 记录活动任务
    this.activeTasks.set(task.id, task);
    
    try {
      // 打开目标标签页
      if (task.openTab) {
        const tab = await chrome.tabs.create({ url: task.url });
        await this.waitForTabLoad(tab.id);
        task.tabId = tab.id;
      }
      
      // 执行页面操作
      const result = await this.performPageOperations(task);
      
      // 存储结果
      this.results.push({
        taskId: task.id,
        result: result,
        timestamp: Date.now()
      });
      
      return result;
      
    } catch (error) {
      console.error(`任务执行失败: ${task.id}`, error);
      throw error;
    } finally {
      this.activeTasks.delete(task.id);
    }
  }
  
  async performPageOperations(task) {
    const operations = task.operations || [];
    
    for (const op of operations) {
      const result = await this.executeOperation(op, task.tabId);
      this.results.push({
        operation: op.type,
        result: result
      });
    }
    
    return this.results.filter(r => r.taskId === task.id);
  }
}

// 使用示例
const coordinator = new AgentCoordinator();
const report = await coordinator.coordinateMultiPageTask({
  tasks: [
    {
      id: 'task_1',
      type: 'extraction',
      url: 'https://example.com/product1',
      operations: ['extract_price', 'extract_specs']
    },
    {
      id: 'task_2',
      type: 'extraction',
      url: 'https://example.com/product2',
      operations: ['extract_price', 'extract_specs']
    }
  ],
  aggregation: 'comparison_table'
});

console.log('多任务报告:', report);

五、开发指南

5.1 技能开发流程

需求分析

提示词设计

变量定义

逻辑实现

测试验证

打包发布

用户反馈

迭代优化

5.2 最佳实践

实践1:提示词工程
const promptEngineeringBestPractices = {
  // 1. 清晰的角色定义
  roleDefinition: `
    你是一个专业的{角色名称},具备以下能力:
    - 深度理解{领域}专业知识
    - 准确分析{任务类型}需求
    - 输出结构化结果
  `,
  
  // 2. 明确的任务描述
  taskDescription: `
    任务目标:{清晰的目标描述}
    
    输入数据:
    - {数据项1}
    - {数据项2}
    - {数据项3}
    
    输出要求:
    - 格式:{期望的输出格式}
    - 字数:{大致字数限制}
    - 重点:{需要突出的关键点}
  `,
  
  // 3. 示例引导
  fewShotExamples: `
    示例1:
    输入:{示例1输入}
    输出:{示例1输出}
    
    示例2:
    输入:{示例2输入}
    输出:{示例2输出}
  `
};
实践2:错误处理
class SkillErrorHandler {
  constructor() {
    this.errorLog = [];
    this.retryConfig = {
      maxRetries: 3,
      retryDelay: 1000,
      exponentialBackoff: true
    };
  }
  
  async executeWithRetry(skillExecution, context) {
    let lastError = null;
    
    for (let attempt = 0; attempt < this.retryConfig.maxRetries; attempt++) {
      try {
        return await skillExecution.execute(context);
        
      } catch (error) {
        lastError = error;
        
        // 记录错误
        this.logError(error, attempt);
        
        // 检查是否可重试
        if (!this.isRetryableError(error)) {
          throw error;  // 不可重试的错误,直接抛出
        }
        
        // 指数退避延迟
        const delay = this.calculateRetryDelay(attempt);
        await this.sleep(delay);
      }
    }
    
    // 所有重试都失败
    throw new SkillExecutionError(
      `技能执行失败,已重试${this.retryConfig.maxRetries}次`,
      lastError,
      this.errorLog
    );
  }
  
  isRetryableError(error) {
    const retryableErrors = [
      'NetworkError',
      'TimeoutError',
      'RateLimitError'
    ];
    
    return retryableErrors.some(
      errorType => error.name?.includes(errorType) || 
                  error.message?.includes(errorType)
    );
  }
  
  calculateRetryDelay(attempt) {
    if (this.retryConfig.exponentialBackoff) {
      return this.retryConfig.retryDelay * Math.pow(2, attempt);
    }
    return this.retryConfig.retryDelay;
  }
}

5.3 性能监控

class SkillPerformanceMonitor {
  constructor() {
    this.metrics = {
      executions: 0,
      totalDuration: 0,
      errors: 0,
      cacheHits: 0,
      cacheMisses: 0
    };
  }
  
  recordExecution(duration, success, cached) {
    this.metrics.executions++;
    this.metrics.totalDuration += duration;
    
    if (!success) {
      this.metrics.errors++;
    }
    
    if (cached) {
      this.metrics.cacheHits++;
    } else {
      this.metrics.cacheMisses++;
    }
  }
  
  getPerformanceReport() {
    const avgDuration = this.metrics.totalDuration / this.metrics.executions;
    const cacheHitRate = this.metrics.cacheHits / 
      (this.metrics.cacheHits + this.metrics.cacheMisses);
    const errorRate = this.metrics.errors / this.metrics.executions;
    
    return {
      totalExecutions: this.metrics.executions,
      averageDuration: `${avgDuration.toFixed(2)}ms`,
      cacheHitRate: `${(cacheHitRate * 100).toFixed(2)}%`,
      errorRate: `${(errorRate * 100).toFixed(2)}%`,
      recommendations: this.generateRecommendations()
    };
  }
  
  generateRecommendations() {
    const recommendations = [];
    
    // 基于指标生成优化建议
    if (this.metrics.cacheHitRate < 0.3) {
      recommendations.push('考虑增加缓存策略');
    }
    
    if (this.metrics.errorRate > 0.1) {
      recommendations.push('检查错误处理逻辑');
    }
    
    if (this.metrics.totalDuration / this.metrics.executions > 5000) {
      recommendations.push('优化提示词长度或模型选择');
    }
    
    return recommendations;
  }
}

// 性能监控使用
const monitor = new SkillPerformanceMonitor();

// 在技能执行时记录
const startTime = performance.now();
const result = await skill.execute(context);
const duration = performance.now() - startTime;

monitor.recordExecution(duration, result.success, result.cached);

// 定期查看性能报告
setInterval(() => {
  const report = monitor.getPerformanceReport();
  console.log('技能性能报告:', report);
}, 60000);  // 每分钟

六、性能优化

6.1 缓存策略

class SkillCache {
  constructor() {
    this.memoryCache = new Map();
    this.persistentCache = new Map();
    this.maxMemorySize = 100;  // 内存缓存最多100个结果
    this.maxPersistentSize = 1000;  // 持久化缓存最多1000个结果
  }
  
  async get(key) {
    // 1. 检查内存缓存
    if (this.memoryCache.has(key)) {
      const item = this.memoryCache.get(key);
      
      // 检查是否过期
      if (!this.isExpired(item)) {
        this.memoryCache.delete(key);
      } else {
        return item.data;
      }
    }
    
    // 2. 检查持久化缓存
    const persistent = await chrome.storage.local.get(key);
    if (persistent[key] && !this.isExpired(persistent[key])) {
      // 提升到内存缓存
      this.memoryCache.set(key, persistent[key]);
      return persistent[key].data;
    }
    
    return null;  // 缓存未命中
  }
  
  async set(key, data, ttl = 300000) {
    const item = {
      data: data,
      timestamp: Date.now(),
      ttl: ttl  // 5分钟默认TTL
    };
    
    // 1. 设置内存缓存
    if (this.memoryCache.size >= this.maxMemorySize) {
      this.evictOldest();
    }
    this.memoryCache.set(key, item);
    
    // 2. 设置持久化缓存
    await chrome.storage.local.set({ [key]: item });
  }
  
  isExpired(item) {
    return Date.now() > item.timestamp + item.ttl;
  }
  
  evictOldest() {
    // LRU淘汰策略
    let oldestKey = null;
    let oldestTime = Infinity;
    
    for (const [key, item] of this.memoryCache.entries()) {
      if (item.timestamp < oldestTime) {
        oldestTime = item.timestamp;
        oldestKey = key;
      }
    }
    
    if (oldestKey) {
      this.memoryCache.delete(oldestKey);
    }
  }
}

// 缓存使用示例
const cache = new SkillCache();

// 使用缓存执行技能
async function executeWithCache(skill, context) {
  const cacheKey = `skill_${skill.id}_${context.hash}`;
  
  // 尝试从缓存获取
  const cached = await cache.get(cacheKey);
  if (cached) {
    console.log('缓存命中');
    return cached;
  }
  
  // 执行技能
  const result = await skill.execute(context);
  
  // 存入缓存
  await cache.set(cacheKey, result, 60000);  // 10分钟TTL
  
  return result;
}

6.2 并发控制

class ConcurrencyController {
  constructor(maxConcurrent = 3) {
    this.maxConcurrent = maxConcurrent;
    this.activeRequests = 0;
    this.queue = [];
    this.semaphore = new Semaphore(maxConcurrent);
  }
  
  async execute(tasks) {
    const results = [];
    
    for (const task of tasks) {
      const result = await this.semaphore.acquire(async () => {
        this.activeRequests++;
        try {
          return await task.execute();
        } finally {
          this.activeRequests--;
        }
      });
      
      results.push(result);
    }
    
    return results;
  }
  
  getQueueStatus() {
    return {
      queueLength: this.queue.length,
      activeRequests: this.activeRequests,
      utilizationRate: this.activeRequests / this.maxConcurrent
    };
  }
}

class Semaphore {
  constructor(permits) {
    this.permits = permits;
    this.queue = [];
  }
  
  async acquire(callback) {
    if (this.permits > 0) {
      return new Promise((resolve) => {
        this.queue.push({ callback, resolve });
      });
    }
    
    this.permits--;
    
    try {
      const result = await callback();
      return result;
    } finally {
      this.permits++;
      
      if (this.queue.length > 0 && this.permits > 0) {
        const { callback, resolve } = this.queue.shift();
        resolve(callback());
      }
    }
  }
}

// 并发控制使用示例
const controller = new ConcurrencyController(3);  // 最多3个并发请求

const tasks = [
  executeSkill1(),
  executeSkill2(),
  executeSkill3(),
  executeSkill4(),
  executeSkill5()
];

const results = await controller.execute(tasks);
console.log('并发执行结果:', results);

七、总结与展望

Chrome Skills的发布,标志着浏览器AI化的重要里程碑:

技术价值:

  1. 1. 降低Agent使用门槛
    • • 无需本地部署
    • • 开箱即用
    • • 预置技能库
  2. 2. 推动浏览器进化
    • • 从信息工具到智能平台
    • • Agent级自动化能力
    • • 多模态交互体验
  3. 3. 促进生态繁荣
    • • 开发者参与
    • • 技能共享
    • • 社区共建

开发建议:

  1. 1. 从简单开始
    • • 先创建基础技能
    • • 逐步增加复杂度
    • • 积累最佳实践
  2. 2. 注重用户体验
    • • 响应速度优化
    • • 错误处理完善
    • • 反馈机制清晰
  3. 3. 关注安全与隐私
    • • 权限最小化原则
    • • 数据加密存储
    • • 用户可控

Logo

小龙虾开发者社区是 CSDN 旗下专注 OpenClaw 生态的官方阵地,聚焦技能开发、插件实践与部署教程,为开发者提供可直接落地的方案、工具与交流平台,助力高效构建与落地 AI 应用

更多推荐