前言
上一篇我们学会了基础使用,这一篇深入学习Prompt API的所有细节!
1. Prompt API完整架构
1.1 API类型
| API | 功能 |
|---|---|
window.ai.assistant |
通用助手(文本生成) |
window.ai.languageModel |
语言模型 |
window.ai.summarizer |
文本摘要 |
window.ai.translator |
翻译 |
window.ai.writer |
写作辅助 |
1.2 能力检测
javascript
// 检测所有AI能力
async function checkAllCapabilities() {
const results = {};
// 助手能力
if ('ai' in window && window.ai.assistant) {
results.assistant = await window.ai.assistant.capabilities();
}
// 语言模型
if ('ai' in window && window.ai.languageModel) {
results.languageModel = await window.ai.languageModel.capabilities();
}
// 摘要器
if ('ai' in window && window.ai.summarizer) {
results.summarizer = await window.ai.summarizer.capabilities();
}
console.log('所有AI能力:', results);
return results;
}
2. 核心API详解
2.1 创建会话
javascript
// 完整的会话创建选项
const sessionOptions = {
systemPrompt: '你是一个专业的AI助手。',
temperature: 0.7, // 创造性:0-1,0更确定,1更随机
topK: 40, // 候选词数量
topP: 0.9, // nucleus sampling
maxOutputTokens: 1024, // 最大输出长度
contextWindow: 4096 // 上下文窗口大小
};
const session = await window.ai.assistant.create(sessionOptions);
2.2 提示方式
方式1:普通提示
javascript
const result = await session.prompt('什么是React Hooks?');
方式2:流式提示(推荐)
javascript
// 流式输出,打字机效果
async function streamPrompt(prompt) {
const stream = session.promptStreaming(prompt);
let fullText = '';
for await (const chunk of stream) {
fullText += chunk;
updateUI(fullText); // 实时更新UI
}
return fullText;
}
方式3:多轮对话
javascript
// 会话会自动保留上下文!
await session.prompt('我叫张三');
await session.prompt('我叫什么名字?'); // 回答:张三
2.3 会话管理
javascript
class AISessionManager {
constructor() {
this.session = null;
}
async getSession() {
if (!this.session) {
this.session = await window.ai.assistant.create({
systemPrompt: '你是一个专业的助手。'
});
}
return this.session;
}
// 销毁会话,释放资源
destroy() {
if (this.session) {
this.session.destroy();
this.session = null;
}
}
}
// 使用
const manager = new AISessionManager();
const session = await manager.getSession();
3. 提示工程(Prompt Engineering)
3.1 系统提示词模式
javascript
// 模式1:角色设定
const ROLE_PROGRAMMER = `你是一个经验丰富的前端开发专家,精通React、Vue、TypeScript。
风格:简洁、准确、有示例
语言:中文
`;
// 模式2:任务说明
const TASK_WRITING = `你的任务是帮助用户写作和润色。
要求:
1. 保持原意
2. 让语言更流畅
3. 不要添加额外内容
`;
// 模式3:输出格式
const FORMAT_JSON = `请用JSON格式输出,格式如下:
{
"success": true,
"data": {
"title": "",
"content": ""
}
}
只返回JSON,不要其他内容。
`;
3.2 少样本学习(Few-Shot Learning)
javascript
const FEW_SHOT_PROMPT = `请判断情感是积极还是消极。
示例:
输入:这个电影很好看!
输出:积极
输入:这东西太差了
输出:消极
输入:今天天气真不错
输出:`;
3.3 思维链(Chain-of-Thought)
javascript
const COT_PROMPT = `解决这个问题,请一步步思考。
问题:小明有5个苹果,给了小红2个,又买了3个,现在有几个?
思考:
1. 初始数量:5个
2. 给出2个后:5-2=3个
3. 又买了3个:3+3=6个
答案:6个
`;
4. 其他专用API
4.1 摘要API
javascript
async function summarizeText(text) {
if (!window.ai.summarizer) return;
const summarizer = await window.ai.summarizer.create({
type: 'key-points', // 或 'summary'
format: 'plain-text'
});
const result = await summarizer.summarize(text);
return result;
}
// 使用
const text = '很长的文章...';
const summary = await summarizeText(text);
console.log('摘要:', summary);
4.2 翻译API
javascript
async function translateText(text, from, to) {
if (!window.ai.translator) return;
const translator = await window.ai.translator.create({
sourceLanguage: from,
targetLanguage: to
});
const result = await translator.translate(text);
return result;
}
// 使用
const translated = await translateText('Hello world', 'en', 'zh');
console.log('翻译结果:', translated);
5. 完整的工具类封装
javascript
class ChromeAI {
constructor(options = {}) {
this.assistant = null;
this.options = {
systemPrompt: '你是一个AI助手。',
temperature: 0.7,
...options
};
}
async init() {
if (!('ai' in window)) {
throw new Error('Chrome AI不可用');
}
this.assistant = await window.ai.assistant.create(this.options);
}
// 普通生成
async generate(prompt) {
return await this.assistant.prompt(prompt);
}
// 流式生成
async *generateStream(prompt) {
const stream = this.assistant.promptStreaming(prompt);
for await (const chunk of stream) {
yield chunk;
}
}
// 快速生成(带超时)
async generateWithTimeout(prompt, timeout = 30000) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
return await this.assistant.prompt(prompt, {
signal: controller.signal
});
} finally {
clearTimeout(timeoutId);
}
}
// 销毁
destroy() {
if (this.assistant) {
this.assistant.destroy();
this.assistant = null;
}
}
}
// 使用示例
const ai = new ChromeAI({
systemPrompt: '你是一个专业的前端助手。'
});
await ai.init();
const result = await ai.generate('解释什么是React Hooks');
6. 今日小结
这一篇我们学习了:
- Prompt API完整架构
- 会话创建和管理
- 提示工程技巧
- 其他专用API(摘要、翻译)
- 完整的工具类封装
7. 下篇预告
下一篇,我们进入实战:端侧文本生成!