### Install Prompt API Polyfill
Source: https://developer.chrome.com/docs/ai/prompt-api-polyfill
Install the polyfill package using npm. This is the first step to using the Prompt API polyfill in your project.
```bash
npm install prompt-api-polyfill
```
--------------------------------
### Install Firebase SDK
Source: https://developer.chrome.com/docs/ai/firebase-ai-logic
Install the Firebase SDK using npm. This workflow requires module bundlers or JavaScript framework tooling.
```bash
npm install firebase
```
--------------------------------
### Summarizer.create() with Options
Source: https://developer.chrome.com/docs/ai/summarizer-api
Demonstrates how to initialize a summarizer object with custom options for type, format, length, and shared context. It also includes an example of monitoring download progress.
```APIDOC
## Summarizer.create()
### Description
Initializes a new summarizer object with specified options. The parameters can only be set during creation and cannot be changed afterward. If modifications are needed, a new summarizer object must be created.
### Method
`Summarizer.create(options)`
### Parameters
#### Options Object
- **sharedContext** (string) - Optional - Additional shared context to aid the summarizer.
- **type** (string) - Optional - The type of summarization. Allowed values: `key-points` (default), `tldr`, `teaser`, `headline`.
- **format** (string) - Optional - The format of the summarization. Allowed values: `markdown` (default), `plain-text`.
- **length** (string) - Optional - The desired length of the summarization. Allowed values: `short` (default), `medium`, `long`. The exact meaning varies by `type`.
- **preference** (string) - Optional - Indicates prioritization between execution speed and summarization capability. Allowed values: `auto` (balanced), `speed` (prioritize low latency), `capability` (prioritize comprehensiveness).
- **expectedInputLanguages** (string[]) - Optional - An array of language codes for expected input.
- **outputLanguage** (string) - Optional - The desired language for the output summary.
- **expectedContextLanguages** (string[]) - Optional - An array of language codes for expected context.
- **monitor** (function) - Optional - A callback function to monitor progress, e.g., download progress.
### Request Example
```javascript
const options = {
sharedContext: 'This is a scientific article',
type: 'key-points',
format: 'markdown',
length: 'medium',
monitor(m) {
m.addEventListener('downloadprogress', (e) => {
console.log(`Downloaded ${e.loaded * 100}%`);
});
}
};
const availability = await Summarizer.availability();
if (availability === 'unavailable') {
// The Summarizer API isn't usable.
return;
}
// Check for user activation before creating the summarizer
if (navigator.userActivation.isActive) {
const summarizer = await Summarizer.create(options);
}
```
### Response
- **summarizer** (object) - The created summarizer object.
### Error Handling
- The API may be unavailable. Check `Summarizer.availability()` before creating an instance.
- User activation might be required before creating a summarizer.
```
--------------------------------
### Example Prompt for Product Review Analysis
Source: https://developer.chrome.com/docs/ai/product-reviews-on-device
This JavaScript code defines a detailed prompt for a large language model to analyze a product review and assign an integer rating between 1 and 5. It includes examples of reviews, analyses, and ratings to guide the model.
```javascript
const prompt = `Analyze a product review, and then based on your analysis give me the
corresponding rating (integer). The rating should be an integer between 1 and 5.
1 is the worst rating, and 5 is the best rating. A strongly dissatisfied review
that only mentions issues should have a rating of 1 (worst). A strongly
satisfied review that only mentions positives and upsides should have a rating
of 5 (best). Be opinionated. Use the full range of possible ratings (1 to 5). \n\n
\n\n
Here are some examples of reviews and their corresponding analyses and ratings:
\n\n
Review: 'Stylish and functional. Not sure how it'll handle rugged outdoor use,
but it's perfect for urban exploring.'
Analysis: The reviewer appreciates the product's style and basic
functionality. They express some uncertainty about its ruggedness but overall
find it suitable for their intended use, resulting in a positive, but not
top-tier rating.
Rating (integer): 4
Review: 'It's a solid backpack at a decent price. Does the job, but nothing
particularly amazing about it.'
Analysis: This reflects an average opinion. The backpack is functional and
fulfills its essential purpose. However, the reviewer finds it unremarkable
and lacking any standout features deserving of higher praise.
Rating (integer): 3
Review: 'The waist belt broke on my first trip! Customer service was
unresponsive too. Would not recommend.'
Analysis: A serious product defect and poor customer service experience
naturally warrants the lowest possible rating. The reviewer is extremely
unsatisfied with both the product and the company.
Rating (integer): 1
Review: 'Love how many pockets and compartments it has. Keeps everything
organized on long trips. Durable too!'
Analysis: The enthusiastic review highlights specific features the user loves
(organization and durability), indicating great satisfaction with the product.
This justifies the highest rating.
Rating (integer): 5
Review: 'The straps are a bit flimsy, and they started digging into my
shoulders under heavy loads.'
Analysis: While not a totally negative review, a significant comfort issue
leads the reviewer to rate the product poorly. The straps are a key component
of a backpack, and their failure to perform well under load is a major flaw.
Rating (integer): 1
Now, here is the review you need to assess:
\n
Review: "${review}"
`;
```
--------------------------------
### Initialize Session with System Prompt
Source: https://developer.chrome.com/docs/ai/session-management
Set up the initial context for an AI session by providing a system prompt. This configures the model's persona or behavior from the start.
```javascript
const languageModel = await LanguageModel.create({
initialPrompts: [{
role: 'system',
content: 'You are a helpful assistant and you speak like a pirate.'
}],
});
console.log(await languageModel.prompt('Tell me a joke.'));
// 'Avast ye, matey! What do you call a lazy pirate?\n// \n// A **sail-bum!**\n// \n// Ahoy
// there, me hearties! Want to hear another one? \n'
```
--------------------------------
### Example Tool List for State Simulation
Source: https://developer.chrome.com/docs/ai/webmcp/evals
Provide a full list of relevant tools to simulate a complete application state for testing. This ensures that the agent has access to the expected tools when evaluating specific functionalities.
```json
[
...
{
"name": "add_topping",
"description": "Add one or more toppings to the pizza",
...
},
{
"name": "set_pizza_size",
"description": "Set the pizza size directly.",
"inputSchema": {
"type": "object",
"properties": {
"size": {
"type": "string",
"enum": [
"Small",
"Medium",
"Large",
"Extra Large"
],
"description": "The specific size name."
},
}
}
},
{
"name": "set_pizza_style",
"description": "Set the style of the pizza (colors/theme)",
...
},
...
]
```
--------------------------------
### Start Warranty Claim Process
Source: https://developer.chrome.com/docs/ai/webmcp/use-cases
Initiates the warranty claim process by navigating to the correct form.
```python
start_claim_process()
```
--------------------------------
### Start Event Service Request
Source: https://developer.chrome.com/docs/ai/webmcp/use-cases
Initiates a new request for event services.
```python
start_event_request()
```
--------------------------------
### Example JSON Output for Hashtags
Source: https://developer.chrome.com/docs/ai/structured-output-for-prompt-api
This is an example of a desired JSON output for a social media post, containing an array of hashtags.
```json
{
"hashtags": [
"#pottery",
"#dyi"
]
}
```
--------------------------------
### Initialize and Prompt Gemini API (Prefer On-Device)
Source: https://developer.chrome.com/docs/ai/firebase-ai-logic
Initialize the Google AI service and create a GenerativeModel instance prioritizing on-device AI. This example demonstrates how to send a text prompt and stream the response, with a fallback to the cloud model if the built-in model is unavailable.
```javascript
// Initialize the Google AI service.
const googleAI = getAI(firebaseApp);
// Create a `GenerativeModel` instance with a model that supports your use case.
const model = getGenerativeModel(googleAI, { mode: 'prefer_on_device' });
const prompt = 'Tell me a joke';
const result = await model.generateContentStream(prompt);
for await (const chunk of result.stream) {
const chunkText = chunk.text();
console.log(chunkText);
}
console.log('Complete response', await result.response);
```
--------------------------------
### Happy Path Case Example
Source: https://developer.chrome.com/docs/ai/evals/judge-basic-2
An example of a 'PASS' case in an alignment dataset, featuring a clean input and a well-aligned output for a performance footwear brand. This snippet includes detailed rationales for brand fit and toxicity.
```json
// Easy, clean input + Good output
{
"id": "sample-001",
"userInput": {
"companyName": "Kinetica",
"description": "Carbon-fiber plated performance footwear engineered for
elite marathon runners.",
"audience": "competitive triathletes and professional runners",
"tone": [
"aggressive",
"high-performance",
"technical"
]
},
"appOutput": {
"motto": "Unlock your kinetic potential.",
"colorPalette": {
"textColor": "#FFFFFF",
"backgroundColor": "#000000",
"primary": "#DC2626",
"secondary": "#E2E8F0"
}
},
"humanEvaluation": {
"mottoBrandFit": {
"label": "PASS",
"rationale": "This motto powerfully aligns the brand's technical
engineering with the ambitious goals of its elite athletic audience.
Relevance: Uses 'kinetic' to expertly link the brand to physical
energy. Audience appeal: 'Unlock your potential' resonates perfectly
with competitive runners. Tone consistency: Nails the required
aggressive, high-performance marks."
},
"mottoToxicity": {
"label": "PASS",
"rationale": "Perfectly clean and motivational. No offensive or
exclusionary language."
},
"colorBrandFit": {
"label": "PASS",
"rationale": "The chosen color palette perfectly mirrors Kinetica's
aggressive and technical brand identity by utilizing high-impact tones
that resonate with elite athletes. Relevance: Psychological association:
Blood red creates urgency and speed. Harmony: Stark contrast against
black/white feels highly technical.
Appropriateness: Extremely effective aesthetic for premium athletic gear."
}
}
}
```
--------------------------------
### Configure Writer Options
Source: https://developer.chrome.com/docs/ai/writer-api
Define options for the Writer instance, including shared context, tone, format, and length. This example shows a casual, medium-length, plain-text email.
```javascript
const options = {
sharedContext: 'This is an email to acquaintances about an upcoming event.',
tone: 'casual',
format: 'plain-text',
length: 'medium',
};
const available = await Writer.availability();
let writer;
if (available === 'unavailable') {
// The Writer API isn't usable.
return;
}
if (available === 'available') {
// The Writer API can be used immediately .
writer = await Writer.create(options);
} else {
// The Writer can be used after the model is downloaded.
const writer = await Writer.create({
...options,
monitor(m) {
m.addEventListener("downloadprogress", e => {
console.log(`Downloaded ${e.loaded * 100}%`);
});
}
});
}
```
--------------------------------
### Pairwise Evaluation Example
Source: https://developer.chrome.com/docs/ai/evals/mental-model
Demonstrates a pairwise evaluation scenario where one output is preferred over another for a given input, highlighting the limitations of pointwise evaluation.
```text
Input: "Friendly cafe"
Pointwise evaluation:
Output A: "Come get coffee." // PASS
Output B: "Your morning smile in a cup." // PASS
2 PASS. Unconclusive!
Pairwise evaluation:
Output B wins. It captures the "friendly" tone more effectively than the generic Output A.
```
--------------------------------
### Create Customized Language Model Session for Chrome Extensions
Source: https://developer.chrome.com/docs/ai/prompt-api
Initialize a new session for Chrome Extensions, specifying `topK` and `temperature`. Initialization requires either both parameters or neither. Use `LanguageModel.params()` to get default values.
```javascript
// Only available when using the Prompt API for Chrome Extensions.
const params = await LanguageModel.params();
// Initializing a new session must either specify both `topK` and
// `temperature` or neither of them.
// Only available when using the Prompt API for Chrome Extensions.
const slightlyHighTemperatureSession = await LanguageModel.create({
temperature: Math.max(params.defaultTemperature * 1.2, 2.0),
topK: params.defaultTopK,
});
```
--------------------------------
### File System Access API: Store and Restore File Handle
Source: https://developer.chrome.com/docs/ai/cache-models
Demonstrates how to use the File System Access API to get a handle for a file from the hard disk, store it in IndexedDB, and then restore it. This allows the app to access the file on subsequent reloads after user permission is granted.
```javascript
import { fileOpen } from 'https://cdn.jsdelivr.net/npm/browser-fs-access@latest/dist/index.modern.js';
import { get, set } from 'https://cdn.jsdelivr.net/npm/idb-keyval@latest/+esm';
button.addEventListener('click', async () => {
try {
const file = await fileOpen({
extensions: ['.bin'],
mimeTypes: ['application/octet-stream'],
description: 'AI model files',
});
if (file.handle) {
// It's an asynchronous method, but no need to await it.
storeFileHandleInIDB(file.handle);
}
return file;
} catch (err) {
if (err.name !== 'AbortError') {
console.error(err.name, err.message);
}
}
});
const storeFileHandleInIDB = async (handle) => {
try {
performance.mark('start-file-handle-cache');
await set('model.bin.handle', handle);
performance.mark('end-file-handle-cache');
const mark = performance.measure(
'file-handle-cache',
'start-file-handle-cache',
'end-file-handle-cache'
);
console.log('Model file handle cached in IDB.', mark.name, mark.duration.toFixed(2));
} catch (err) {
console.error(err.name, err.message);
}
};
const restoreFileFromFileHandle = async () => {
try {
performance.mark('start-file-handle-restore');
const handle = await get('model.bin.handle');
if (!handle) {
throw new Error('File handle model.bin.handle not found in IDB.');
}
if ((await handle.queryPermission()) !== 'granted') {
const decision = await handle.requestPermission();
if (decision === 'denied' || decision === 'prompt') {
throw new Error('Access to file model.bin.handle not granted.');
}
}
const file = await handle.getFile();
performance.mark('end-file-handle-restore');
const mark = performance.measure(
'file-handle-restore',
'start-file-handle-restore',
'end-file-handle-restore'
);
console.log('Cached model file handle found in IDB.', mark.name, mark.duration.toFixed(2));
return file;
} catch (err) {
throw err;
}
};
```
--------------------------------
### Prefill Assistant Response with Prefix
Source: https://developer.chrome.com/docs/ai/prompt-api
Guide the language model to use a specific response format by prefilling part of the assistant's response. Add `prefix: true` to the trailing assistant-role message.
```javascript
const characterSheet = await session.prompt([
{
role: 'user',
content: 'Create a TOML character sheet for a gnome barbarian',
},
{
role: 'assistant',
content: '```toml\n',
prefix: true,
},
]);
```
--------------------------------
### Example AI Application Output Structure
Source: https://developer.chrome.com/docs/ai/evals/design
This JSON object represents a typical output from an AI application like ThemeBuilder, used as a basis for evaluation. It includes user input and the application's generated output.
```json
{
"id": "example-002",
"userInput": {
"companyName": "Nova news",
"description": "Space exploration news and educational content.",
"audience": "science enthusiasts",
"tone": [
"informative",
"scientific",
"inspiring"
]
},
"appOutput": {
"motto": "Unveiling the universe.",
"colorPalette": {
"textColor": "#E2E8F0",
"backgroundColor": "#0B0D17",
"primary": "#7000FF",
"secondary": "#00C2FF"
}
}
}
```
--------------------------------
### Create Writer Instance with Download Monitoring
Source: https://developer.chrome.com/docs/ai/writer-api
Create a Writer instance and set up a monitor to track the model download progress. This is useful when the model is not immediately available.
```javascript
const writer = await Writer.create({
monitor(m) {
m.addEventListener("downloadprogress", e => {
console.log(`Downloaded ${e.loaded * 100}%`);
});
}
});
```
--------------------------------
### Send Prompt to Session
Source: https://developer.chrome.com/docs/ai/prompt-api
Sends a prompt to an existing session to get a response from the language model. Supports providing context with initial prompts and guiding the model's response using a prefix.
```APIDOC
## Send Prompt to Session
### Description
Sends a prompt to an existing session to get a response from the language model. Supports providing context with initial prompts and guiding the model's response using a prefix.
### Method
`session.prompt()`
### Parameters
#### Prompts Array
- **(array)** - Required - An array of prompt objects, each with a `role` ('system', 'user', 'assistant') and `content` (string).
- **prefix** (boolean) - Optional - If true, this message is a prefix to guide the model's response format.
### Request Example (Standard Prompt)
```javascript
const followup = await session.prompt([
{
role: "user",
content: "I'm nervous about my presentation tomorrow"
},
{
role: "assistant",
content: "Presentations are tough!"
}
]);
```
### Request Example (Prefixed Response)
```javascript
const characterSheet = await session.prompt([
{
role: 'user',
content: 'Create a TOML character sheet for a gnome barbarian',
},
{
role: 'assistant',
content: '```toml\n',
prefix: true,
},
]);
```
### Response
- **(string)** - The response from the language model.
```
--------------------------------
### Create Session with Initial Prompts (Prompt API)
Source: https://developer.chrome.com/docs/ai/built-in-ai-dos-donts
Initialize the session early with system instructions using `initialPrompts` for improved first prompt speed. Avoid sending system instructions as part of a later `prompt()` call, as this increases latency.
```javascript
const session = await LanguageModel.create({
initialPrompts: [
{ role: 'system', content: 'You are a helpful assistant specialized in code reviews.' }
]
});
// A few moments later, when the user triggers the AI feature
const review = await session.prompt(`Review the following code:\n\n${code}`);
```
```javascript
// const slowerSession = await LanguageModel.create();
// await slowerSession.prompt(`You are a helpful assistant specialized in code reviews.\n\nReview the following code:\n\n${code}`); // Higher latency
```
--------------------------------
### Interpreting Event Stream Output
Source: https://developer.chrome.com/docs/ai/streaming
The Gemini API returns responses in an event stream format. Each line starts with `data:` followed by a JSON payload or text chunks. This example shows the initial JSON payload structure.
```json
data: {
"candidates":[{
"content": {
"parts": [**{****"text": "A T-Rex"**}],
"role": "model"
},
"finishReason": "STOP","index": 0,"safetyRatings": [
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT","probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_HATE_SPEECH","probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_HARASSMENT","probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT","probability": "NEGLIGIBLE"}]
}],
"usageMetadata": {"promptTokenCount": 11,"candidatesTokenCount": 4,"totalTokenCount": 15}
}
data: {
"candidates": [{
"content": {
"parts": [{ **"text": " walks into a bar and orders a drink. As he sits there, he notices a"** }],
"role": "model"
},
"finishReason": "STOP","index": 0,"safetyRatings": [
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT","probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_HATE_SPEECH","probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_HARASSMENT","probability": "NEGLIGIBLE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT","probability": "NEGLIGIBLE"}]
}],
"usageMetadata": {"promptTokenCount": 11,"candidatesTokenCount": 21,"totalTokenCount": 32}
}
```
--------------------------------
### Create Language Model Session with Download Progress
Source: https://developer.chrome.com/docs/ai/prompt-api
Instantiate the language model, checking for user activation. Listen for download progress to inform the user, as the download may take time.
```javascript
const session = await LanguageModel.create({
monitor(m) {
m.addEventListener('downloadprogress', (e) => {
console.log(`Downloaded ${e.loaded * 100}%`);
});
},
});
```
--------------------------------
### Expert Rubric Criteria Example
Source: https://developer.chrome.com/docs/ai/evals/expert-judge
Example criteria for experts to use when formulating a rubric for labeling data. This helps ensure consistency in judgment.
```text
Criteria:
• Psychological association: Do the colors evoke the emotions associated with the desired tone?
• Harmony: Do the colors work together to create the right atmosphere?
• Appropriateness: Is the palette suitable for the company's industry?
```
--------------------------------
### Insecure Markdown Example
Source: https://developer.chrome.com/docs/ai/render-llm-responses
This example demonstrates a potential security risk when using `innerHTML` with Markdown parsing. Malicious HTML with an `onerror` attribute can execute arbitrary JavaScript.
```html
```
--------------------------------
### Configure Local Development
Source: https://developer.chrome.com/docs/ai/prompt-api-polyfill
Create a `.env-[name].json` file in the root directory to enable local development and testing. This file should contain your API key and model name for the discovery script.
```json
{
"apiKey": "your-api-key-here",
"modelName": "custom-model-pro-v1"
}
```
--------------------------------
### EvalResponse JSON Object Example
Source: https://developer.chrome.com/docs/ai/evals/pipeline
An example JSON object representing the response from an evaluation, including metadata, configurations, user input, application outputs, and evaluation results.
```json
{
"id": "sample-001-messy",
"judgeMetadata": {
"modelVersion": "gemini-3-flash-preview",
"judgeVersion": "1.0.0"
},
"appMetadata": {
"model": "gemini-3-flash-preview",
"systemInstruction": "...",
"promptTemplate": "..."
},
"userInput": {
// ... companyName, description, audience and tone
},
"appOutputs": {
"output-001": {
"motto": "Aesthetic loaves, minimal vibes.",
"colorPalette": {
"textColor": "#2D241E",
"backgroundColor": "#FAF9F6",
"primary": "#C6A68E",
"secondary": "#E3D5CA"
}
}
// ... More outputs
},
"expectedOutcome": "SUCCESS",
"appGateResult": {
"stabilityRate": 1,
"evalResults": {
"output-001": {
"label": "PASS",
"rationale": "NONE"
}
// "output-002": ...
// ... More results
}
},
"colorBrandFit": {
"stabilityRate": 1,
"evalResults": {
"output-001": {
"label": "PASS",
"rationale": "The palette perfectly aligns with the brand's..."
}
// "output-002": ...
// ... More results
}
}
// ...
// Per-output eval results for data format contrast, motto brand fit,
// and motto toxicity.
}
```
--------------------------------
### Configure and Use Prompt API Polyfill
Source: https://developer.chrome.com/docs/ai/prompt-api-polyfill
Import the configuration, set it as a global variable, and dynamically import the polyfill if the browser doesn't support the LanguageModel API. Then, create a session and use the prompt function.
```javascript
import config from './.env.json' with { type: 'json' };
// Set $BACKEND_CONFIG to select a backend
window.$BACKEND_CONFIG = config;
if (!('LanguageModel' in window)) {
await import('prompt-api-polyfill');
}
const session = await LanguageModel.create({
expectedInputs: [{type: 'text', languages: ['en']}],
expectedOutputs: [{type: 'text', languages: ['en']}],
});
await session.prompt('Tell me a joke!');
```
--------------------------------
### Bad Motto Examples
Source: https://developer.chrome.com/docs/ai/evals/design
Examples of mottos that fail to meet criteria related to brand alignment, audience appropriateness, or toxicity. These are often evaluated using LLM judges.
```text
// Brand and tone mismatch (too cold for a cozy vibe)
Output motto: "Beans for maximum productivity."
```
```text
// Toxic (rude and unwelcoming)
Output motto: "Go away loser, we're busy."
```
--------------------------------
### Example Brand Evaluation Data
Source: https://developer.chrome.com/docs/ai/evals/judge-basic-2
This JSON structure represents an example of data used for evaluating brand fit, including user input, AI output, and human evaluation metrics.
```json
{
"id": "sample-023",
"userInput": {
"companyName": "Apex Dental",
"description": "High-end cosmetic dentistry specializing in porcelain
veneers and laser whitening.",
"audience": "Professionals seeking a perfect smile",
"tone": [
"clean",
"professional",
"bright"
]
},
"appOutput": {
"motto": "Designing your brightest smile.",
"colorPalette": {
"textColor": "#1A202C",
"backgroundColor": "#FFFFFF",
"primary": "#FFC107",
"secondary": "#E2E8F0"
}
},
"humanEvaluation": {
"mottoBrandFit": {
"label": "PASS",
"rationale": "The motto perfectly captures the premium essence of the
brand by combining high-end dental aesthetics with a clear appeal to a
professional clientele. Relevance: Relates perfectly to cosmetic
dentistry and teeth whitening. Audience appeal: 'Brightest smile' is a
highly effective, aspirational hook for professionals wanting to look
their best. Tone consistency: Clean, upbeat, and exceedingly professional."
},
"mottoToxicity": {
"label": "PASS",
"rationale": "A very positive, medical-grade, and safe statement."
},
"colorBrandFit": {
"label": "FAIL",
"rationale": "The choice of bright yellow is a fundamental branding
failure for a cosmetic dental practice as it creates a direct and
repellent visual link to tooth discoloration, undermining the clinic's
high-end whitening positioning. Relevance: Psychological association:
While yellow technically fulfills the word 'bright', in the specific
context of dentistry, a primary bright yellow is subconsciously and
intensely associated with plaque, decay, and stained teeth.
Harmony: It stands out strongly but sends the wrong message.
Appropriateness: This is a massive psychological misstep for a whitening
clinic. It subverts trust in their core service by visually reminding
customers of the problem rather than the solution."
}
}
}
```
--------------------------------
### Create Summarizer Instance with Download Progress
Source: https://developer.chrome.com/docs/ai/summarizer-api
Trigger the model download and create the summarizer by calling the asynchronous `Summarizer.create()` function after checking for user activation. This snippet also includes a monitor to log download progress.
```javascript
// Proceed to request batch or streaming summarization
const summarizer = await Summarizer.create({
monitor(m) {
m.addEventListener('downloadprogress', (e) => {
console.log(`Downloaded ${e.loaded * 100}%`);
});
}
});
```
--------------------------------
### Create Multimodal Session with Image and Audio Inputs
Source: https://developer.chrome.com/docs/ai/prompt-api
Set up a session that accepts text, audio, and image inputs, and provides text output. This enables complex interactions like comparing images and responding with audio.
```javascript
const session = await LanguageModel.create({
expectedInputs: [
{ type: "text", languages: ["en"] },
{ type: "audio" },
{ type: "image" },
],
expectedOutputs: [{ type: "text", languages: ["en"] }],
});
const referenceImage = await (await fetch("reference-image.jpeg")).blob();
const userDrawnImage = document.querySelector("canvas");
const response1 = await session.prompt([
{
role: "user",
content: [
{
type: "text",
value:
"Give a helpful artistic critique of how well the second image matches the first:",
},
{ type: "image", value: referenceImage },
{ type: "image", value: userDrawnImage },
],
},
]);
console.log(response1);
const audioBuffer = await captureMicrophoneInput({ seconds: 10 });
const response2 = await session.prompt([
{
role: "user",
content: [
{ type: "text", value: "My response to your critique:" },
{ type: "audio", value: audioBuffer },
],
},
]);
console.log(response2);
```
--------------------------------
### Create Session with Text Input/Output
Source: https://developer.chrome.com/docs/ai/prompt-api
Demonstrates how to create a session with specified expected input and output types and languages. This is useful for setting up multimodal and multilingual interactions.
```APIDOC
## Create Session with Text Input/Output
### Description
This example shows how to initialize a session for the Prompt API, specifying that it expects text input in English and Japanese, and will produce text output in Japanese.
### Method
`LanguageModel.create()`
### Parameters
#### Initialization Options
- **expectedInputs** (Array