nano所有文档的整合版 喂给AI或者自己看都可以 LanguageModel 与 Prompt API 开发指南目录概述LanguageModel 基础2.1 检查模型可用性2.2 创建会话2.3 模型参数2.4 模型提前准备优化冷启动Prompt API 使用3.1 基本 Prompt3.2 流式输出安全渲染3.3 多模态输入3.4 结构化输出会话管理4.1 初始提示4.2 上下文窗口4.3 克隆会话4.4 销毁会话性能优化5.1 结果缓存机制用户体验技巧6.1 动画过渡6.2 人工延迟6.3 导航历史与撤销硬件要求1. 概述Prompt API是 Chrome 内置 AI 的核心接口允许开发者向Gemini Nano模型发送自然语言请求。LanguageModel是 Prompt API 的具体实现提供会话管理和提示交互能力。核心优势特性说明隐私保护数据本地处理不上传云端低延迟本地推理响应迅速离线可用模型下载后无需网络多模态支持文本、图像、音频输入2. LanguageModel 基础2.1 检查模型可用性constavailabilityawaitLanguageModel.availability({expectedInputs:[{type:text,languages:[en]}],expectedOutputs:[{type:text,languages:[en]}],})// 返回: available | downloading | unavailable2.2 创建会话constsessionawaitLanguageModel.create({monitor(m){m.addEventListener(downloadprogress,(e){console.log(下载进度:${e.loaded*100}%)})},})2.3 模型参数扩展程序专用constparamsawaitLanguageModel.params()// { defaultTopK: 3, maxTopK: 128, defaultTemperature: 1, maxTemperature: 2 }constsessionawaitLanguageModel.create({temperature:params.defaultTemperature*1.2,topK:params.defaultTopK,})2.4 模型提前准备优化冷启动原理在用户触发 AI 功能前提前初始化会话避免冷启动延迟。最佳实践// ✅ 推荐页面加载时或用户首次交互时初始化letaiSessionnull// 页面加载完成后立即准备模型document.addEventListener(DOMContentLoaded,async(){// 等待用户交互必需consthandleFirstInteractionasync(){if(!aiSession){aiSessionawaitLanguageModel.create({initialPrompts:[{role:system,content:You are a helpful assistant.}],})}document.removeEventListener(click,handleFirstInteraction)}// 监听用户首次点击document.addEventListener(click,handleFirstInteraction,{once:true})})// 后续使用时会话已就绪asyncfunctiongetAIResponse(prompt){if(!aiSession){aiSessionawaitLanguageModel.create()}returnaiSession.prompt(prompt)}注意对于 Prompt API应在准备好initialPrompts后再调用create()因为初始提示只能在会话创建时设置。3. Prompt API 使用3.1 基本 PromptconstsessionawaitLanguageModel.create()constresultawaitsession.prompt(Write a poem about the sea)console.log(result)3.2 流式输出安全渲染安全注意所有 LLM 输出都应视为不可信内容需要进行清理。import*assmdfromstreaming-markdown// 设置 Sanitizer APIconstsanitizernewSanitizer({allowElements:[p,br,strong,em,a],allowAttributes:{href:[a]},})// 创建离屏缓冲区避免闪烁constbuffernewDocumentFragment()constparsersmd.parser_new(buffer)// 流式处理conststreamsession.promptStreaming(Write a detailed article)letchunksforawait(constchunkofstream){chunkschunk smd.parser_write(parser,chunk)// 使用 Sanitizer API 安全渲染constcleanFragmentsanitizer.sanitize(buffer)outputContainer.replaceChildren(cleanFragment)}关键要点使用 Sanitizer API 清理输出使用流式 Markdown 解析器如 streaming-markdown在离屏缓冲区构建 DOM避免闪烁不要直接设置innerHTML存在注入风险3.3 多模态输入支持文本、图像、音频输入constsessionawaitLanguageModel.create({expectedInputs:[{type:text,languages:[en]},{type:image},{type:audio}],expectedOutputs:[{type:text,languages:[en]}],})// 图像输入constresponseawaitsession.prompt([{role:user,content:[{type:text,value:Describe this image:},{type:image,value:imageBlob},],},])3.4 结构化输出使用 JSON Schema 约束响应格式constschema{type:object,properties:{rating:{type:number,minimum:0,maximum:5},summary:{type:string},},required:[rating,summary],}constresultawaitsession.prompt(Rate this product and summarize it,{responseConstraint:schema,})constparsedJSON.parse(result)4. 会话管理4.1 初始提示constsessionawaitLanguageModel.create({initialPrompts:[{role:system,content:You are a helpful assistant.},{role:user,content:What is the capital of France?},{role:assistant,content:Paris},],})4.2 上下文窗口console.log(已使用:${session.contextUsage}/${session.contextWindow})session.addEventListener(contextoverflow,(){console.log(上下文窗口溢出历史记录将被删除)})4.3 克隆会话// 创建基准会话constbaseSessionawaitLanguageModel.create({initialPrompts:[{role:system,content:You are a technical editor.}],})// 克隆用于并行任务consttask1awaitbaseSession.clone()consttask2awaitbaseSession.clone()// 并行执行const[result1,result2]awaitPromise.all([task1.prompt(Review this code...),task2.prompt(Summarize this article...),])// 完成后销毁克隆会话task1.destroy()task2.destroy()4.4 销毁会话session.destroy()5. 性能优化5.1 结果缓存机制核心思想将重复查询的结果存储起来避免重复推理。classAICache{constructor(){this.TTL_MS3600000// 1小时有效期this.CACHE_PREFIXai_cache_}asyncgetResponse(prompt,forceRefreshfalse){// 标准化输入constqueryprompt.trim().toLowerCase()constcacheKey${this.CACHE_PREFIX}${this._hash(query)}// 检查缓存if(!forceRefresh){constcachedthis._getFromCache(cacheKey)if(cached)return{result:cached,source:cache}}// 运行推理constsessionawaitLanguageModel.create()constresultawaitsession.prompt(prompt)session.destroy()// 存储到缓存this._saveToCache(cacheKey,result)return{result,source:fresh}}_hash(str){lethash0for(leti0;istr.length;i){hash(hash5)-hashstr.charCodeAt(i)hashhashhash}returnMath.abs(hash)}_getFromCache(key){try{constdatalocalStorage.getItem(key)if(!data)returnnullconst{value,expiry}JSON.parse(data)if(Date.now()expiry){localStorage.removeItem(key)returnnull}returnvalue}catch{returnnull}}_saveToCache(key,value){try{// 检查存储空间if(!this._hasEnoughSpace()){this._cleanupOldest()}localStorage.setItem(key,JSON.stringify({value,expiry:Date.now()this.TTL_MS,}),)}catch{// 存储失败时静默处理}}_hasEnoughSpace(){constusednewBlob(Object.values(localStorage)).sizereturnused4*1024*1024// 4MB 限制}_cleanupOldest(){letoldestKeynullletoldestExpiryInfinityfor(leti0;ilocalStorage.length;i){constkeylocalStorage.key(i)if(key.startsWith(this.CACHE_PREFIX)){constdatalocalStorage.getItem(key)try{const{expiry}JSON.parse(data)if(expiryoldestExpiry){oldestExpiryexpiry oldestKeykey}}catch{}}}if(oldestKey)localStorage.removeItem(oldestKey)}}// 使用示例constcachenewAICache()constresultawaitcache.getResponse(Write a poem)console.log(来源:${result.source})6. 用户体验技巧6.1 动画过渡为 AI 生成的内容添加平滑过渡效果/* CSS */.ai-result{opacity:0;transform:translateY(10px);animation:fadeIn 0.3s ease-out forwards;}keyframesfadeIn{to{opacity:1;transform:translateY(0);}}// 流式输出时的渐进动画constcontainerdocument.querySelector(.ai-result)conststreamsession.promptStreaming(Write an essay)forawait(constchunkofstream){container.textContentchunk}6.2 人工延迟对于快速响应的任务添加短暂延迟让用户感知处理过程asyncfunctiongetAIResponse(prompt){conststartTimeDate.now()constresultawaitsession.prompt(prompt)// 确保至少显示 1 秒的加载状态constelapsedDate.now()-startTimeif(elapsed1000){awaitnewPromise((resolve)setTimeout(resolve,1000-elapsed))}returnresult}6.3 导航历史与撤销classAIHistoryManager{constructor(){this.history[]this.currentIndex-1}addEntry(prompt,response){// 清除当前位置之后的历史this.historythis.history.slice(0,this.currentIndex1)this.history.push({prompt,response,timestamp:Date.now()})this.currentIndex}undo(){if(this.currentIndex0){this.currentIndex--returnthis.history[this.currentIndex]}returnnull}redo(){if(this.currentIndexthis.history.length-1){this.currentIndexreturnthis.history[this.currentIndex]}returnnull}getCurrent(){returnthis.history[this.currentIndex]||null}}// 使用示例consthistorynewAIHistoryManager()// 保存结果history.addEntry(Write a poem,poemResult)// 撤销/重做constprevioushistory.undo()constnexthistory.redo()7. 硬件要求要求说明操作系统Windows 10/11、macOS 13、Linux、Chromebook Plus存储空间至少 22GB 可用空间GPU4GB VRAMCPU≥16GB RAM≥4核网络仅用于初始模型下载参考链接Prompt API 官方文档TypeScript 类型定义会话管理最佳实践文档版本2025年9月