skills/ajv009/web-ai-prompt-api/SKILL.md
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.
npx skillsauth add aiskillstore/marketplace web-ai-prompt-apiInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Complete implementation guide for Chrome's built-in Prompt API using Gemini Nano.
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.
From Chrome 140: English, Spanish, Japanese (input/output)
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.
await LanguageModel.params();
// { defaultTopK: 3, maxTopK: 128, defaultTemperature: 1, maxTemperature: 2 }
const session = await LanguageModel.create();
const params = await LanguageModel.params();
const session = await LanguageModel.create({
temperature: Math.min(params.defaultTemperature * 1.2, 2.0),
topK: params.defaultTopK
});
const session = await LanguageModel.create({
monitor(m) {
m.addEventListener('downloadprogress', (e) => {
console.log(`Downloaded ${e.loaded * 100}%`);
});
}
});
const controller = new AbortController();
stopButton.onclick = () => controller.abort();
const session = await LanguageModel.create({
signal: controller.signal
});
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:
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.
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] }
]
}]);
const result = await session.prompt('Write me a haiku!');
console.log(result);
const stream = session.promptStreaming('Write me a long poem!');
for await (const chunk of stream) {
console.log(chunk); // Partial results as they arrive
}
const controller = new AbortController();
stopButton.onclick = () => controller.abort();
const result = await session.prompt('Write a poem', {
signal: controller.signal
});
Pass JSON Schema to get predictable JSON responses:
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:
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:
const usage = session.measureInputUsage({ responseConstraint: schema });
Omit schema from input quota:
const result = await session.prompt(
`Summarize as JSON { rating } with 0-5 number:`,
{
responseConstraint: schema,
omitResponseConstraintInput: true
}
);
Guide model output format by prefilling assistant response:
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"
Add messages to session without immediate response (useful for multimodal):
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.
console.log(`${session.inputUsage}/${session.inputQuota}`);
const remaining = session.inputQuota - session.inputUsage;
When quota exceeded, oldest messages lost from context.
Clones inherit parameters, initial prompts, and history:
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
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));
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.
Model download requires user interaction:
if (navigator.userActivation.isActive) {
const session = await LanguageModel.create();
}
Sticky activation events: click, tap, keydown, mousedown
Default: Top-level windows + same-origin iframes only
Grant cross-origin iframe access:
<iframe src="https://cross-origin.example.com/"
allow="language-model">
</iframe>
Not available in Web Workers (permission policy complexity)
chrome://flags/#prompt-api-for-gemini-nano-multimodal-inputawait LanguageModel.availability();"available"Troubleshoot:
chrome://on-device-internals → Model Status tabAvailable in Chrome 138+ stable for extensions.
Remove expired origin trial permissions:
{
"permissions": ["aiLanguageModelOriginTrial"] // REMOVE THIS
}
Register for current origin trial if needed.
Session management:
Performance:
Structured output:
Context preservation:
try {
const session = await LanguageModel.create();
const result = await session.prompt('Hello');
} catch (err) {
if (err.name === 'AbortError') {
// User stopped generation
} else if (err.name === 'NotSupportedError') {
// Unsupported modality/language
} else {
console.error(err.name, err.message);
}
}
development
Apple Human Interface Guidelines for content display components. Use this skill when the user asks about charts component, collection view, image view, web view, color well, image well, activity view, lockup, data visualization, content display, displaying images, rendering web content, color pickers, or presenting collections of items in Apple apps. Also use when the user says how should I display charts, what's the best way to show images, should I use a web view, how do I build a grid of items, what component shows media, or how do I present a share sheet. Cross-references: hig-foundations for color/typography/accessibility, hig-patterns for data visualization patterns, hig-components-layout for structural containers, hig-platforms for platform-specific component behavior.
tools
Automate HelpDesk tasks via Rube MCP (Composio): list tickets, manage views, use canned responses, and configure custom fields. Always search tools first for current schemas.
testing
Expert Haskell engineer specializing in advanced type systems, pure functional design, and high-reliability software. Use PROACTIVELY for type-level programming, concurrency, and architecture guidance.
tools
GraphQL gives clients exactly the data they need - no more, no less. One endpoint, typed schema, introspection. But the flexibility that makes it powerful also makes it dangerous. Without proper controls, clients can craft queries that bring down your server. This skill covers schema design, resolvers, DataLoader for N+1 prevention, federation for microservices, and client integration with Apollo/urql. Key insight: GraphQL is a contract. The schema is the API documentation. Design it carefully.