AIGC 浏览器插件开发:Chrome 插件集成 ChatGLM3 文本生成与图像生成功能

AI 驱动代码审查实战

Claude code-review 插件深度解析,把 AI 智能审查接进 CI/CD 流水线

Chrome 插件集成 AIGC 功能开发指南

核心功能实现
  1. 文本生成(ChatGLM3 集成)
// 调用文本生成 API
async function generateText(prompt) {
  const apiEndpoint = "https://api.chatglm.cn/v3/completions";
  const payload = {
    prompt: prompt,
    max_tokens: 500,
    temperature: 0.7
  };

  const response = await fetch(apiEndpoint, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer YOUR_API_KEY"
    },
    body: JSON.stringify(payload)
  });

  return response.json();
}

  1. 图像生成功能
// 调用图像生成 API
async function generateImage(description) {
  const apiEndpoint = "https://api.imagegen.com/v1/generate";
  const payload = {
    prompt: description,
    size: "1024x1024",
    num_images: 1
  };

  const response = await fetch(apiEndpoint, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer YOUR_API_KEY"
    },
    body: JSON.stringify(payload)
  });

  return response.json();
}

插件架构设计
graph TD
    A[用户界面] --> B(内容脚本)
    B --> C[后台服务]
    C --> D{API 服务}
    D --> E[文本生成]
    D --> F[图像生成]
    E --> G[结果展示]
    F --> G

关键组件实现
  1. manifest.json 配置
{
  "manifest_version": 3,
  "name": "AIGC Assistant",
  "version": "1.0",
  "permissions": [
    "storage",
    "contextMenus",
    "scripting"
  ],
  "host_permissions": [
    "https://api.chatglm.cn/*",
    "https://api.imagegen.com/*"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  },
  "icons": {
    "128": "icon.png"
  }
}

  1. 上下文菜单集成
// background.js
chrome.contextMenus.create({
  id: "generate-text",
  title: "使用 ChatGLM3 生成文本",
  contexts: ["selection"]
});

chrome.contextMenus.create({
  id: "generate-image",
  title: "根据文本生成图像",
  contexts: ["selection"]
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "generate-text") {
    chrome.tabs.sendMessage(tab.id, {
      action: "generateText",
      text: info.selectionText
    });
  } else if (info.menuItemId === "generate-image") {
    chrome.tabs.sendMessage(tab.id, {
      action: "generateImage",
      text: info.selectionText
    });
  }
});

  1. 用户界面组件 (popup.html)
<div class="container">
  <textarea id="input-prompt" placeholder="输入提示词..."></textarea>
  <div class="button-group">
    <button id="text-gen-btn">生成文本</button>
    <button id="image-gen-btn">生成图像</button>
  </div>
  <div id="result-container">
    <div id="text-output"></div>
    <img id="image-output" style="max-width:100%">
  </div>
</div>

性能优化策略
  1. 缓存机制
// 使用 chrome.storage 缓存结果
async function getCachedResponse(key, apiCall) {
  const cache = await chrome.storage.local.get([key]);
  if (cache[key]) return cache[key];
  
  const freshData = await apiCall();
  await chrome.storage.local.set({ [key]: freshData });
  return freshData;
}

  1. 请求批处理
const requestQueue = [];
let isProcessing = false;

async function processQueue() {
  if (isProcessing || requestQueue.length === 0) return;
  
  isProcessing = true;
  const batch = requestQueue.splice(0, 5);
  const results = await Promise.all(batch.map(req => req.func()));
  
  batch.forEach((req, index) => {
    req.callback(results[index]);
  });
  
  isProcessing = false;
  processQueue();
}

function enqueueRequest(func, callback) {
  requestQueue.push({ func, callback });
  processQueue();
}

安全实践
  1. API 密钥管理
// 安全存储密钥
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === "storeKey") {
    chrome.storage.local.set({ apiKey: request.key }, () => {
      sendResponse({ status: "success" });
    });
    return true;
  }
});

  1. 内容安全策略
// manifest.json 添加
"content_security_policy": {
  "extension_pages": "script-src 'self'; object-src 'self'"
}

完整工作流
  1. 用户选择文本 → 右键菜单触发生成请求
  2. 内容脚本捕获请求 → 发送至后台服务
  3. 后台调用对应 API → 处理响应数据
  4. 结果返回至内容脚本 → 在页面展示
  5. 用户通过弹出窗口直接输入 → 同步调用 API

实现提示

  1. 使用 Promise.race() 实现请求超时控制
  2. 添加生成状态指示器(加载动画)
  3. 实现历史记录存储功能
  4. 为图像生成添加种子参数控制
  5. 使用 Web Workers 处理大型文本生成

此方案实现了完整的浏览器端 AIGC 工作流,通过合理的架构设计平衡了功能性与性能,确保用户体验流畅性。实际部署时需根据具体 API 文档调整参数格式。

AI 驱动代码审查实战

Claude code-review 插件深度解析,把 AI 智能审查接进 CI/CD 流水线

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值