AI原生前端开发(018):端侧AI性能优化:模型加载、推理加速

前言

端侧AI性能很重要!这一篇学习如何让端侧AI更快!


1. 会话管理优化

javascript 复制代码
// ✅ 好的做法:保持单例会话
class AISessionManager {
  static instance = null;
  
  static async getInstance(options = {}) {
    if (!AISessionManager.instance) {
      AISessionManager.instance = await window.ai.assistant.create(options);
    }
    return AISessionManager.instance;
  }
}

// 使用
const session = await AISessionManager.getInstance({ systemPrompt: '...' });

2. 提示词优化

javascript 复制代码
// 优化提示词长度
const SYSTEM_PROMPT = `你是一个专业的AI助手。
要求:简洁、准确。
用中文回复。
`; // ✅ 简洁清晰

const BAD_PROMPT = `你是一个非常非常非常专业的AI助手,非常非常非常厉害,你要帮助用户...
...(省略1000字)
`; // ❌ 太长

3. 响应缓存

javascript 复制代码
class AICache {
  constructor(maxSize = 100) {
    this.cache = new Map();
    this.maxSize = maxSize;
  }

  get(prompt) {
    const key = this.hash(prompt);
    return this.cache.get(key);
  }

  set(prompt, response) {
    const key = this.hash(prompt);
    
    // LRU:删除旧的
    if (this.cache.size >= this.maxSize) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    
    this.cache.set(key, {
      response,
      timestamp: Date.now()
    });
  }

  hash(str) {
    return btoa(encodeURIComponent(str));
  }
}

// 使用
const cache = new AICache();

async function askAI(prompt) {
  // 先查缓存
  const cached = cache.get(prompt);
  if (cached) {
    return cached.response;
  }
  
  // 没有缓存,调用AI
  const response = await session.prompt(prompt);
  cache.set(prompt, response);
  
  return response;
}

4. 任务队列与节流

javascript 复制代码
class AIQueue {
  constructor() {
    this.queue = [];
    this.processing = false;
  }

  add(task) {
    this.queue.push(task);
    if (!this.processing) {
      this.process();
    }
  }

  async process() {
    if (this.queue.length === 0) {
      this.processing = false;
      return;
    }
    
    this.processing = true;
    const task = this.queue.shift();
    
    try {
      await task();
    } catch (error) {
      console.error('任务失败:', error);
    }
    
    this.process();
  }
}

// 使用
const aiQueue = new AIQueue();

// 节流:短时间多次输入只处理最后一个
function debounce(func, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func(...args), delay);
  };
}

5. 今日小结

这一篇我们学习了:

  1. 会话管理优化
  2. 提示词优化
  3. 响应缓存
  4. 任务队列与节流

6. 下篇预告

下一篇,我们学习 端侧AI安全与隐私!

相关推荐
shengjk124 分钟前
从一条 Bash 命令看懂 LLM Agent:为什么大模型会执行命令?
人工智能
Yuzhiyuxia1 小时前
【AI Agent面试系列】AI Agent可观测、评测、安全相关的知识点
人工智能·安全·面试
dozenyaoyida1 小时前
AI与大模型新闻日报 | 2026-11-11
人工智能·chatgpt·大模型·新闻
xsd202411182 小时前
把品牌官网做成一个 3D 世界:scroll-world
人工智能
孟健2 小时前
我用Claude Skills把出海视频月账单从$86打到了$16
人工智能·ai编程·claude
泯泷2 小时前
同样是多 Agent,为什么有的稳,有的却天天翻车?
人工智能·llm·agent
一起学安全技术2 小时前
拆大模型 06|Prompt 工程不靠玄学:上下文要当程序写
人工智能·语言模型·prompt·aigc
鸿蒙开发爱好者2 小时前
下班后做的小工具和小游戏,我把它们整理成了 WyanHub
网络·人工智能·职场和发展·个人开发
Tapdata3 小时前
被忽略的第三类上下文:Agent 进入真实业务后,还缺什么?
数据库·人工智能·架构
地平线智能驾驶开发者3 小时前
征程6|用 hrt_model_exec 看清 YOLOv5x 的输入、原始输出和后处理
人工智能·yolov5·机器视觉