web-ai-prompt-api
Chrome's built-in Prompt API implementation guide. Use Gemini Nano locally in browser for AI features - session management, multimodal input, structured output, streaming, Chrome Extensions. Reference for all Prompt API development.
What this skill does
# Chrome Prompt API Reference
Complete implementation guide for Chrome's built-in Prompt API using Gemini Nano.
## Hardware & OS Requirements
**OS:** Windows 10/11, macOS 13+ (Ventura+), Linux, ChromeOS (Platform 16389.0.0+) on Chromebook Plus
**Storage:** 22 GB free (model downloaded separately)
**GPU:** >4 GB VRAM OR **CPU:** 16 GB RAM + 4 cores
**Network:** Unmetered connection for download
**Chrome:** 138+ (Extensions in stable, Web in origin trial)
**Not supported:** Mobile (Android, iOS), non-Chromebook Plus ChromeOS
Check model size: `chrome://on-device-internals`
Model removed if storage <10 GB after download.
## Language Support
From Chrome 140: English, Spanish, Japanese (input/output)
## Availability Check
```javascript
const availability = await LanguageModel.availability();
// Returns: "unavailable" | "downloadable" | "downloading" | "available"
```
**CRITICAL:** Always pass same options to `availability()` as you use in `create()`. Some models don't support certain modalities/languages.
## Model Parameters
```javascript
await LanguageModel.params();
// { defaultTopK: 3, maxTopK: 128, defaultTemperature: 1, maxTemperature: 2 }
```
## Session Creation
### Basic Session
```javascript
const session = await LanguageModel.create();
```
### With Custom Parameters
```javascript
const params = await LanguageModel.params();
const session = await LanguageModel.create({
temperature: Math.min(params.defaultTemperature * 1.2, 2.0),
topK: params.defaultTopK
});
```
### With Download Monitoring
```javascript
const session = await LanguageModel.create({
monitor(m) {
m.addEventListener('downloadprogress', (e) => {
console.log(`Downloaded ${e.loaded * 100}%`);
});
}
});
```
### With AbortSignal
```javascript
const controller = new AbortController();
stopButton.onclick = () => controller.abort();
const session = await LanguageModel.create({
signal: controller.signal
});
```
## Initial Prompts (Context Setting)
```javascript
const session = await LanguageModel.create({
initialPrompts: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'What is the capital of Italy?' },
{ role: 'assistant', content: 'The capital of Italy is Rome.' },
{ role: 'user', content: 'What language is spoken there?' },
{ role: 'assistant', content: 'The official language is Italian.' }
]
});
```
**Use cases:**
- Resume stored sessions after browser restart
- N-shot prompting
- Set assistant personality/tone
- Provide conversation history
## Multimodal Input (Origin Trial)
### expectedInputs & expectedOutputs
```javascript
const session = await LanguageModel.create({
expectedInputs: [
{
type: "text", // or "image", "audio"
languages: ["en" /* system */, "ja" /* user prompt */]
}
],
expectedOutputs: [
{ type: "text", languages: ["ja"] }
]
});
```
**Input types:** text, image, audio
**Output types:** text only
Throws `NotSupportedError` if unsupported modality.
### Using with Images/Audio
```javascript
const session = await LanguageModel.create({
initialPrompts: [{
role: 'system',
content: 'Analyze images for patterns.'
}],
expectedInputs: [{ type: 'image' }]
});
// Append image
await session.append([{
role: 'user',
content: [
{ type: 'text', value: 'Analyze this image' },
{ type: 'image', value: fileInput.files[0] }
]
}]);
```
## Prompting Methods
### Non-Streaming (Short Responses)
```javascript
const result = await session.prompt('Write me a haiku!');
console.log(result);
```
### Streaming (Long Responses)
```javascript
const stream = session.promptStreaming('Write me a long poem!');
for await (const chunk of stream) {
console.log(chunk); // Partial results as they arrive
}
```
### With AbortSignal
```javascript
const controller = new AbortController();
stopButton.onclick = () => controller.abort();
const result = await session.prompt('Write a poem', {
signal: controller.signal
});
```
## Response Constraints (Structured Output)
Pass JSON Schema to get predictable JSON responses:
```javascript
const schema = {
type: "object",
properties: {
hashtags: {
type: "array",
maxItems: 3,
items: {
type: "string",
pattern: "^#[^\\s#]+$"
}
}
},
required: ["hashtags"],
additionalProperties: false
};
const result = await session.prompt(
`Generate hashtags for: ${post}`,
{ responseConstraint: schema }
);
const data = JSON.parse(result); // Guaranteed valid JSON
```
**Simple boolean example:**
```javascript
const schema = { "type": "boolean" };
const result = await session.prompt(
`Is this about pottery?\n\n${text}`,
{ responseConstraint: schema }
);
console.log(JSON.parse(result)); // true or false
```
**Measure input quota usage:**
```javascript
const usage = session.measureInputUsage({ responseConstraint: schema });
```
**Omit schema from input quota:**
```javascript
const result = await session.prompt(
`Summarize as JSON { rating } with 0-5 number:`,
{
responseConstraint: schema,
omitResponseConstraintInput: true
}
);
```
## Response Prefixes
Guide model output format by prefilling assistant response:
```javascript
const result = await session.prompt([
{ role: 'user', content: 'Create a TOML character sheet' },
{ role: 'assistant', content: '```toml\n', prefix: true }
]);
// Model continues from "```toml\n"
```
## append() Method
Add messages to session without immediate response (useful for multimodal):
```javascript
await session.append([
{
role: 'user',
content: [
{ type: 'text', value: 'First context message' },
{ type: 'image', value: imageFile }
]
}
]);
// Later, prompt with accumulated context
const result = await session.prompt('Analyze the images');
```
Promise fulfills when validated and appended.
## Session Management
### Check Quota
```javascript
console.log(`${session.inputUsage}/${session.inputQuota}`);
const remaining = session.inputQuota - session.inputUsage;
```
When quota exceeded, oldest messages lost from context.
### Clone Session
Clones inherit parameters, initial prompts, and history:
```javascript
const mainSession = await LanguageModel.create({
initialPrompts: [{ role: 'system', content: 'Speak like a pirate' }]
});
const clone1 = await mainSession.clone();
const clone2 = await mainSession.clone({ signal: controller.signal });
// Independent conversations with same setup
await clone1.prompt('Tell me a joke about parrots');
await clone2.prompt('Tell me a joke about treasure');
```
**Use for:** Parallel conversations, "what if" scenarios, resource efficiency
### Restore Session from localStorage
```javascript
let sessionData = getFromLocalStorage(uuid) || {
initialPrompts: [],
topK: (await LanguageModel.params()).defaultTopK,
temperature: (await LanguageModel.params()).defaultTemperature
};
const session = await LanguageModel.create(sessionData);
// Track conversation
const stream = session.promptStreaming(prompt);
let result = '';
for await (const chunk of stream) {
result = chunk;
}
sessionData.initialPrompts.push(
{ role: 'user', content: prompt },
{ role: 'assistant', content: result }
);
localStorage.setItem(uuid, JSON.stringify(sessionData));
```
### Destroy Session
```javascript
session.destroy();
// Frees resources, aborts ongoing execution
// Session unusable after destroy
```
**Best practice:** Keep one empty session alive to keep model loaded. Destroy only when truly done.
## User Activation Requirement
Model download requires user interaction:
```javascript
if (navigator.userActivation.isActive) {
const session = await LanguageModel.create();
}
```
**Sticky activation events:** click, tap, keydown, mousedown
## Permission Policy & iframes
**Default:** Top-level windows + same-origin iframes only
**Grant cross-origin iframe access:**
```html
<iframe src="https://cross-origin.example.com/"
aRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.