前言
端侧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. 今日小结
这一篇我们学习了:
- 会话管理优化
- 提示词优化
- 响应缓存
- 任务队列与节流
6. 下篇预告
下一篇,我们学习 端侧AI安全与隐私!