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

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

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 模型,如文本转语音、语音转文本、文本生成图片等,敬请期待!

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

推荐文章

JavaScript设计模式:适配器模式
2024-11-18 17:51:43 +0800 CST
mysql时间对比
2024-11-18 14:35:19 +0800 CST
内网穿透技术详解与工具对比
2025-04-01 22:12:02 +0800 CST
Git 常用命令详解
2024-11-18 16:57:24 +0800 CST
api远程把word文件转换为pdf
2024-11-19 03:48:33 +0800 CST
#免密码登录服务器
2024-11-19 04:29:52 +0800 CST
js常用通用函数
2024-11-17 05:57:52 +0800 CST
一个数字时钟的HTML
2024-11-19 07:46:53 +0800 CST
Go 语言实现 API 限流的最佳实践
2024-11-19 01:51:21 +0800 CST
Hypothesis是一个强大的Python测试库
2024-11-19 04:31:30 +0800 CST
OpenCV 检测与跟踪移动物体
2024-11-18 15:27:01 +0800 CST
Requests库详细介绍
2024-11-18 05:53:37 +0800 CST
前端如何优化资源加载
2024-11-18 13:35:45 +0800 CST
markdown语法
2024-11-18 18:38:43 +0800 CST
程序员茄子在线接单