Chrome 浏览器内置了一个小型的语言模型 Gemini Nano。该模型通过一个名为 Prompt API(LanguageModel)的 JavaScript API 提供接口供开发者使用。使用该 API 时无需 API 密钥,也无需连接到服务器或进行任何外部网络请求;模型下载完成后,所有处理都在用户的设备上完成。 此存储库介绍了如何打开它以及 API 可以做什么。它还包括端到端自动化设置和验证的脚本。

📋 资源说明
| 项目名称 | Ar9av/gemini-nano-chrome |
|---|---|
| 项目地址 | https://github.com/Ar9av/gemini-nano-chrome |
| 当前版本 | 20261001-1520 |
| Star 数量 | 218 |
| 开发语言 | JavaScript |
| 开源协议 | MIT |
| 最近更新 | 2026-10-01 |
| 下载方式 | 百度网盘(见下方下载模块) |
📖 项目详细介绍
英文 README 已全文翻译为中文
在 Chrome 浏览器中使用 Gemini Nano
Chrome 浏览器内置了一个小型的语言模型 Gemini Nano。该模型通过一个名为 Prompt API(LanguageModel)的 JavaScript API 提供接口供开发者使用。使用该 API 时无需 API 密钥,也无需连接到服务器或进行任何外部网络请求;模型下载完成后,所有处理都在用户的设备上完成。
此存储库介绍了如何打开它以及 API 可以做什么。它还包括端到端自动化设置和验证的脚本。
运行它
git clone https://github.com/Ar9av/gemini-nano-chrome.git cd gemini-nano-chrome npm start

Higher quality: docs/setup.mp4. Recorded with the model already cached; a first run spends a few minutes downloading it.
一个命令即可完成以下操作:以正确的参数配置启动 Chrome(无需手动访问 chrome://flags),启动兼容 OpenAI 的 API 服务器,提供聊天用户界面,并在新标签页中打开该界面。首次运行时会下载约 4GB 大小的模型文件,因此需要等待几分钟;之后再次执行 npm start 时,会重用相同的 Chrome 实例,启动过程会立即完成。
Chat UI: http://localhost:8123 API server: http://localhost:8788/v1/chat/completions
下面的所有内容都解释了该命令的作用以及如何直接使用每个部分,以防您想要比一个脚本提供的更多控制权。
要求
| Chrome | 138+ (Dev or Canary channel recommended; this repo was verified on 149 and 154) |
| OS | Windows 10/11, macOS 13+, Linux, or ChromeOS on a Chromebook Plus |
| Storage | 22 GB free |
| GPU | 4 GB+ VRAM, or |
| CPU | 16 GB+ RAM and 4+ cores |
| Network | Unmetered connection for the one-time ~4 GB model download |
启用它
- 打开
chrome://flags/#optimization-guide-on-device-model,并将其设置为 Enabled BypassPerfRequirement。 - 打开
chrome://flags/#prompt-api-for-gemini-nano,并将其设置为 Enabled。 - 重新启动 Chrome(标志页面上有相应的重启按钮)。
在 Chrome 154 及更高版本中,第一个标志已不再存在,第二个标志的名称变为 chrome://flags/#prompt-api。在该版本中,Prompt API 默认是开启的,因此你可能不需要使用这两个标志中的任何一个。npm start 命令可以同时兼容这两个版本的设置。
这就是所有的设置内容了。其他所有的事情都是通过 JavaScript 来实现的。
快速入门
在任何页面上打开 DevTools(开发者工具),然后运行:
const availability = await LanguageModel.availability();
console.log(availability); // "unavailable" | "downloadable" | "downloading" | "available"
const session = await LanguageModel.create();
const answer = await session.prompt("What are you, in one sentence?");
console.log(answer);
session.destroy();
第一次调用 create() 会开始模型的下载过程。availability() 方法仅用于报告模型的状态,它本身不会启动或推进下载过程。有关一个同时能够报告下载进度的版本,请参考 examples/basic-prompt.js。
聊天用户界面(Chat UI)
web/index.html 是一个独立的聊天界面,无需任何构建步骤,模型本身也不需要服务器。它直接从页面中使用 LanguageModel,整个对话过程中会保持一个会话状态,这样后续的问题就能有准确的上下文。通过运行 npm start 可以自动启动该界面;如果想单独部署它,可以按照以下步骤操作:
cd web && python3 -m http.server 8123
在 Chrome 浏览器中打开 http://localhost:8123(请确保已启用上述所有插件/标志)。首次运行时,会显示一个下载进度条,随后会出现一个带有引导提示的聊天界面。回复内容会以 Markdown 格式显示;按下 “Stop”(或 Esc) 键可以取消回复。页面底部的计数器会显示当前聊天窗口占用了多少屏幕空间,而 “New chat” 按钮可以重置聊天会话。该应用程序会自动适应用户的系统主题设置(浅色或深色)。
在某些版本的 Chrome 中,使用普通的 file:// 打开文件也是可行的,但 Prompt API 需要一个安全的上下文环境,因此通过 http://localhost 服务器来提供文件是一个更可靠的选择。
想要使用类似可安装扩展程序的聊天功能吗?无需服务器,也完全不需要运行 npm start 命令?请查看 extension/。
结构化输出
使用 responseConstraint 将响应数据限制在 JSON 规范的范围内,这样你得到的就是可解析的 JSON 数据,而不是格式随意的文本:
const session = await LanguageModel.create();
const schema = {
type: "object",
properties: {
sentiment: { type: "string", enum: ["positive", "negative", "neutral"] },
confidence: { type: "number" },
},
required: ["sentiment", "confidence"],
};
const result = await session.prompt(
'Classify the sentiment of: "This new on-device AI is shockingly fast and works offline."',
{ responseConstraint: schema }
);
JSON.parse(result); // { sentiment: "positive", confidence: 0.95 }
Full example: examples/structured-output.js.
流媒体传输(Streaming)
const session = await LanguageModel.create();
const stream = session.promptStreaming("List 3 advantages of on-device AI.");
for await (const chunk of stream) console.log(chunk);
Full example: examples/streaming.js.
兼容 OpenAI 的 API 服务器
Gemini Nano 只能在浏览器标签页中运行,因此 Python 脚本或现有的 OpenAI 客户端无法直接调用它。server/index.js 负责解决这个问题:这个小型 HTTP 服务器一方面使用 OpenAI 的聊天完成格式进行通信,另一方面通过 CDP(Chrome DevTools Protocol)来控制实际的 Chrome 标签页。
node server/index.js # listens on http://localhost:8788 PORT=8080 node server/index.js
如果在当前没有任何程序正在运行的情况下收到第一个请求,它会自动启动 Chrome 浏览器(这与 tools/enable-flags.js 的行为相同)。npm start 命令会在一个进程中同时运行这个浏览器和聊天用户界面;而如果你只需要 API 而不需要基于浏览器的聊天功能,可以直接使用 node server/index.js 命令。
| Endpoint | Behavior |
|---|---|
POST /v1/chat/completions | Standard request/response shape, stream: true for SSE |
GET /v1/models | Lists a single model, gemini-nano |
GET /health | Reports LanguageModel.availability() |
curl http://localhost:8788/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": "What are you, in one sentence?"}]
}'
这也意味着它可以与官方的 OpenAI SDKs 兼容,因为它会将请求指向本地服务器,而不是 api.openai.com。
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8788/v1", api_key="not-needed")
response = client.chat.completions.create(
model="gemini-nano",
messages=[{"role": "user", "content": "What are you, in one sentence?"}],
)
print(response.choices[0].message.content)
一个支持流式的 plain-fetch 版本正在 examples/openai-client.js 期间开发中。
response_format 与 json_schema 的组合对应于 responseConstraint,因此上述的结构化输出示例在服务器端的处理方式是相同的。
curl http://localhost:8788/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": "Classify the sentiment of: \"This works great.\""}],
"response_format": {
"type": "json_schema",
"json_schema": { "name": "sentiment", "schema": {
"type": "object",
"properties": { "sentiment": {"type": "string"}, "confidence": {"type": "number"} },
"required": ["sentiment", "confidence"]
}}
}
}'
支持什么,不支持什么
完整的消息历史记录(system/user/assistant)通过 initialPrompts 与实际的 Prompt API 会话相对应,因此多轮对话能够正确地保持上下文。除此之外:
temperature和top_k只有在两者都设置的情况下才会被生效,并且仅在非纯标志(flags-only)开发模式(如 Origin Trial 或扩展程序上下文)下起作用。在纯标志模式下,请求仍然会成功,但会使用默认的采样方式。stop序列会在客户端与流式文本进行匹配。一旦匹配成功,服务器将停止向您发送后续的令牌,但 Chrome 会继续在内部生成这些令牌,直到完成为止。usage数字来自调用前后的session.contextUsage,这是一个估算值,并非 Gemini Nano 自带分词器提供的确切令牌计数。- 如果没有图像输入,那么
max_tokens、n(多个完成结果)、/v1/completions或/v1/embeddings等选项将不可用。Gemini Nano 的 Prompt API 并不提供这些功能所需的接口。 - 每次请求都会根据您发送的消息创建一个新的会话。服务器本身不会在请求之间保留任何对话状态。
关于配置文件目录的说明
如果您已经使用自定义的 PROFILE_DIR 运行了 tools/enable-flags.js 或 tools/smoke-test.js,那么在启动服务器时也请设置相同的值。否则,服务器会创建一个新的 Chrome 用户配置文件并重新下载模型。
PROFILE_DIR=/tmp/my-profile node server/index.js
自动化设置和测试
手动通过 chrome://flags 进行设置虽然可以一次奏效,但如果需要反复测试或希望设置能够被复现,这种方法就会变得很麻烦。tools/ 目录下有两个 Node 脚本,它们可以通过 Chrome 开发工具协议(Chrome DevTools Protocol,简称 CDP)来控制实际的 Chrome 实例。npm start 和 server/index.js 都使用了同一个底层模块 tools/chrome.js 来自动启动 Chrome。
node tools/enable-flags.js # launches Chrome in a throwaway profile with both flags set node tools/smoke-test.js # triggers the download, waits for it, and runs a real prompt
enable-flags.js 会以 --user-data-dir 指向一个新的用户配置文件来启动 Chrome,这样它就不会影响到你正常的浏览器会话或设置。此外,该脚本还会使用 --remote-debugging-port 参数。接下来,它通过点击与用户手动操作相同的下拉菜单来设置各种浏览器标志(flags),这些操作是通过 Runtime.evaluate 函数来实现的。Chrome 的内部页面(如 chrome://flags 和 chrome://on-device-internals)是由 Web 组件构建的,而这些组件的内容存储在 shadow DOM 中。因此,该脚本会递归地遍历 shadow DOM 的根节点以找到相应的控制元素(即用于设置标志的界面)。
smoke-test.js 会连接到该实例,调用 LanguageModel.create(),并在等待过程中通过 chrome://on-device-internals 来获取安装进度。这样可以确保约 4 GB 大小的文件被成功下载完成,而不仅仅是看到一个“正在下载”状态的提示,而没有任何进一步的详细信息。
这两个脚本都需要 Node.js 22 及更高版本(因为使用了内置的 fetch 和 WebSocket 函数),并且不依赖任何第三方库。
# defaults to /Applications/Google Chrome.app on macOS, google-chrome on Linux CHROME_BIN=/path/to/chrome PROFILE_DIR=/tmp/my-profile node tools/enable-flags.js
已安装的内容
安装完成后,通过 chrome://on-device-internals(先通过 chrome://chrome-urls 启用内部调试页面)可以查看当前使用的设备型号:
Model Name: v3Nano Backend Type: GPU (highest quality) Folder size: ~4,072 MiB
Limits and performance
These numbers come from measuring this build directly. LanguageModel.params() isn't available here, so context window and quota behavior come from session.contextWindow / session.contextUsage and from hitting the limit and reading the error.
Context window: 9216 tokens, shared between input and output. Track usage with session.contextUsage / session.contextWindow. Going over it doesn't truncate silently:
await session.prompt(hugeText); // hugeText tokenizes to >9216 // throws QuotaExceededError: "The input is too large." // err.requested has the token count that was attempted
Generation speed: ~50 tokens/sec, measured with promptStreaming() and session.contextUsage deltas across three 300-word-essay runs (524, 525, 513 completion tokens; 47.3, 51.1, 51.5 tok/s). Short answers tend a bit higher, 56+ tok/s on a two-sentence explanation.
Time to first token: ~80-90ms once the model is warm. A prompt near the context window limit (~3000 input tokens) takes ~2.9s to first token. That's prefill time, roughly 1000 tokens/sec for processing input, much faster than the token-by-token decoding used for generating output.
Tested on:
| Machine | MacBook Pro, Apple M4 Pro |
| CPU | 14 cores (10 performance + 4 efficiency) |
| GPU | 20 cores |
| RAM | 24 GB unified memory |
| Backend | GPU, highest quality mode (chrome://on-device-internals reports this as the selected backend automatically) |
Generation speed scales with the GPU backend Chrome selects for your hardware. Lower-end devices, or devices that fall back to CPU inference, will be slower; there's no documented way to query expected throughput ahead of time short of running a prompt and timing it, the way the numbers above were produced.
Other built-in APIs
The same on-device model backs several task-specific APIs, each scoped to a narrower job than the general-purpose Prompt API:
| API | Purpose |
|---|---|
| Summarizer | Condense text into headlines, summaries, or key points |
| Writer | Generate new text from a prompt |
| Rewriter | Revise existing text per instructions |
| Proofreader | Check spelling/grammar and suggest corrections |
| Translator | Translate between languages |
| Language Detector | Identify the language of a string |
Translator and Language Detector are desktop-only; the rest share the Prompt API's platform requirements above.
Shipping this to real users
Flags only work for you, locally. For a production site, you need either:
- An Origin Trial token registered for your origin, or
- Distribution as a Chrome Extension, which gets stable access without a trial
Either way, treat the API as progressive enhancement: check availability() and provide a fallback for browsers or devices where it returns "unavailable".
Troubleshooting
LanguageModel is not defined: one of the two flags isn't set, or Chrome wasn't relaunched after setting them. Check chrome://version to confirm which flags are active.
availability() stays on "downloading" forever: expected if you never called create(). The model downloads only in response to a create() call from a JavaScript context.
LanguageModel.params is not a function: some Chrome builds don't expose this method yet, despite it appearing in the docs. Check Object.getOwnPropertyNames(LanguageModel) for what your version supports before relying on it.
chrome://on-device-internals says debugging pages are disabled: visit chrome://chrome-urls first and click "Enable internal debugging pages."
License
MIT, see LICENSE. Chrome and Gemini icons from theSVG (CC0).
📦 本次收录内容
该项目尚未发布 Release,本次收录仓库完整源码包。
📂 收录文件清单(1 项)—— 点击展开目录
- 📄 gemini-nano-chrome-20261001-1520-source.tar.gz
⬇️ 获取方式
下方下载模块即为网盘链接(提取码 d56c),游客可直接下载。网盘内按作者/项目/版本三级目录归档,包含完整源码包与作者编译好的可执行程序。
📌 本资源来自 GitHub 开源仓库,仅供学习交流使用;请遵循项目原仓库的开源协议,商业使用请自行确认授权。
本文由 GitHub 开源项目监控程序自动发布,内容同步自项目仓库 README 与 Release 说明。
技术交流与评论 (0)