综合 Chrome AI:颠覆网页开发的全新黑科技

2024-11-19 09:46:54 +0800 CST views 1365

Chrome AI 简介

我们来看看一个浏览器 AI 的实际应用示例:

示例代码解读

async function askAi(question) {
	if (!question) return "你倒是输入问题啊"

	// 检查模型是否已下载(模型只需下载一次,就可以供所有网站使用)
	const canCreate = await window.ai.canCreateTextSession()

	if (canCreate !== "no") {
		// 创建一个会话进程
		const session = await window.ai.createTextSession()
  
		// 向 AI 提问
		const result = await session.prompt(question)
	  
		// 销毁会话
		session.destroy()
		
		return result
	}	
	
	return "模型都还没下载好,你问个蛋蛋"
}

askAi("玩梗来说,世界上最好的编程语言是啥").then(console.log)
// 打印: **Python 语言:程序员的快乐源泉!**

可以看到,这些浏览器原生 AI 接口挂载在 window.ai 对象下,无需调用外部 API,直接使用本地模型。这使得开发者可以自由地将 AI 智能融入网页的各个环节,如实时翻译。

未来,这个 AI 标准接口不仅限于 Chrome 和 PC 端,其他浏览器也会跟进,移动设备上的浏览器同样可以运行本地模型。

Chrome AI 接口文档

下面展示 Chrome AI 的接口文档,代码使用 TypeScript 编写并附有注释:

declare global {
  interface Window {
    readonly ai: AI;
  }

  interface AI {
    /**
     * 判断模型是否准备好了
     * @example
     * ```js
     * const availability = await window.ai.canCreateTextSession()
     * if (availability === 'readily') {
     *  console.log('模型已经准备好了')
     * } else if (availability === 'after-download') {
     *  console.log('模型正在下载中')
     * } else {
     *  console.log('模型还没下载')
     * }
     * ```
     */
    canCreateTextSession(): Promise<AIModelAvailability>;

    /**
     * 创建一个文本生成会话进程
     * @param options 会话配置  
     * @example
     * ```js
     * const session = await window.ai.createTextSession({
     *  topK: 50, // 生成文本的多样性,越大越多样
     *  temperature: 0.8 // 生成文本的创造性,越大越随机
     * })
     * 
     * const text = await session.prompt('今天天气怎么样?')
     * console.log(text)
     * ```
     */
    createTextSession(options?: AITextSessionOptions): Promise<AITextSession>;

    /**
     * 获取默认的文本生成会话配置
     * @example
     * ```js
     * const options = await window.ai.defaultTextSessionOptions()
     * console.log(options) // { topK: 50, temperature: 0.8 }
     * ```
     */
    defaultTextSessionOptions(): Promise<AITextSessionOptions>;
  }

  /**
   * AI模型的可用性状态
   * - `readily`:模型已经准备好了
   * - `after-download`:模型正在下载中
   * - `no`:模型还没下载
   */
  type AIModelAvailability = 'readily' | 'after-download' | 'no';

  interface AITextSession {
    /**
     * 询问 AI 问题,返回 AI 的回答
     * @param input 输入文本
     * @example
     * ```js
     * const session = await window.ai.createTextSession()
     * const text = await session.prompt('今天天气怎么样?')
     * console.log(text)
     * ```
     */
    prompt(input: string): Promise<string>;

    /**
     * 询问 AI 问题,以流的形式返回 AI 的回答
     * @param input 输入文本
     * @example
     * ```js
     * const session = await window.ai.createTextSession()
     * const stream = session.promptStreaming('今天天气怎么样?')
     * let result = ''
     * let previousLength = 0
     * 
     * for await (const chunk of stream) {
     *  const newContent = chunk.slice(previousLength)
     *  console.log(newContent) // AI 的每次输出
     *  previousLength = chunk.length
     *  result += newContent
     * }
     * 
     * console.log(result) // 最终的 AI 回答(完整版)
     */
    promptStreaming(input: string): ReadableStream;

    /**
     * 销毁会话
     * @example
     * ```js
     * const session = await window.ai.createTextSession()
     * session.destroy()
     * ```
     */
    destroy(): void;

    /**
     * 克隆会话
     * @example
     * ```js
     * const session = await window.ai.createTextSession()
     * const cloneSession = session.clone()
     * const text = await cloneSession.prompt('今天天气怎么样?')
     * console.log(text)
     * ```
     */
    clone(): AITextSession;
  }

  interface AITextSessionOptions {
    /**
     * 生成文本的多样性,越大越多样,正整数,没有范围
     */
    topK: number;

    /**
     * 生成文本的创造性,越大越随机,0-1 之间的小数
     */
    temperature: number;
  }
}

如何启用 Chrome AI

准备工作

  1. 下载最新的 Chrome Dev 版或 Chrome Canary 版(版本号不低于 128.0.6545.0)。
  2. 确保电脑有 22G 的可用存储空间。
  3. 需要科学上网。

启用 Gemini Nano 和 Prompt API

  1. 打开 Chrome,输入 chrome://flags/#optimization-guide-on-device-model,选择 Enable
  2. 再输入 chrome://flags/#prompt-api-for-gemini-nano,选择 Enable
  3. 重启 Chrome。

确认 Gemini Nano 是否可用

  1. F12 打开开发者工具,输入 await window.ai.canCreateTextSession()
  2. 如果返回 readily,说明已成功启用。

模型下载

  1. 输入 chrome://components,找到 Optimization Guide On Device Model,点击 Check for update,等待模型下载完成。
  2. 下载完成后,再次确认模型是否可用。

思考与展望

AI 技术的迅速发展为网页产品带来了巨大的变革可能。未来,或许会有更多的 AI 组件出现,为网页操作带来更多智能化功能。开发者应该积极拥抱这些变化,寻找新的增长点。

彩蛋

通过 window.ai.createTextSession 接口,我们可以推测未来可能会出现更多类型的 AI 模型,如文本转语音、语音转文本、文本生成图片等,敬请期待!

复制全文 生成海报 浏览器 人工智能 开发 编程 技术文档

推荐文章

前端代码规范 - Commit 提交规范
2024-11-18 10:18:08 +0800 CST
Go语言SQL操作实战
2024-11-18 19:30:51 +0800 CST
向满屏的 Import 语句说再见!
2024-11-18 12:20:51 +0800 CST
Vue中如何使用API发送异步请求?
2024-11-19 10:04:27 +0800 CST
markdown语法
2024-11-18 18:38:43 +0800 CST
Python 微软邮箱 OAuth2 认证 Demo
2024-11-20 15:42:09 +0800 CST
Vue3 组件间通信的多种方式
2024-11-19 02:57:47 +0800 CST
Vue3中如何处理组件间的动画?
2024-11-17 04:54:49 +0800 CST
Flet 构建跨平台应用的 Python 框架
2025-03-21 08:40:53 +0800 CST
CentOS 镜像源配置
2024-11-18 11:28:06 +0800 CST
12 个精选 MCP 网站推荐
2025-06-10 13:26:28 +0800 CST
程序员茄子在线接单