xiaohongshu
xiaohongshu
dzmm-builder
Comprehensive skill for building, debugging, and optimizing DZMM.AI applications. Use this skill when users request creating interactive web apps on the DZMM platform, need guidance on DZMM API usage, or require help with existing DZMM applications. Covers AI-driven chatbots, visual novels, datin...
Full skill instructions
Build AI-driven interactive web applications on the DZMM.AI platform using specialized knowledge, complete examples, and reusable code patterns. This skill provides comprehensive support for creating single-file HTML applications that leverage streaming AI conversations, cloud key-value storage, and browser effect systems.
Invoke this skill when users:
Generate complete, single-file HTML applications for the DZMM platform based on user requirements.
Approach:
assets/examples/ as foundationArchitecture Patterns:
Stateless Generator - For one-shot content generation:
assets/examples/小红书文案.html for minimal implementationreferences/code-snippets.md section 2State Management Game - For interactive games with dynamic variables:
assets/examples/恋爱游戏.html for complete implementationStateful Dialogue System - For multi-turn conversations:
assets/examples/dungeon-adventure.html and assets/examples/horror-story.htmlLayered Cache Platform - For content communities:
assets/examples/贴吧.html for full implementationVisual Novel / Galgame System - For narrative-driven interactive fiction:
Provide detailed guidance on using DZMM's specialized APIs.
Core APIs:
window.dzmm.completions() - Streaming AI generation:
await window.dzmm.completions(
{
model: 'nalang-turbo-0826' | 'nalang-medium-0826' |
'nalang-max-0826' | 'nalang-xl-0826' |
'nalang-max-0826-16k' | 'nalang-xl-0826-16k',
messages: [{ role: 'user' | 'assistant', content: string }],
maxTokens: number // Optional, 200-3000, default 1000
},
(newContent, done) => {
// newContent is cumulative, not incremental
// done is true when generation completes
}
);
window.dzmm.chat - Tree-structured conversation storage (⭐ NEW):
// Insert messages into conversation tree (supports branching storylines)
const result = await window.dzmm.chat.insert(parentId, [
{ role: 'user', content: 'Player choice' },
{ role: 'assistant', content: 'Story response' }
]);
const newMessageIds = result.ids; // Array of new message IDs
// Get message details (with parent/children relationships)
const messages = await window.dzmm.chat.list(['msg-123', 'msg-124']);
// Returns: [{ id, role, content, timestamp, parent, children }, ...]
// Get complete conversation timeline
const timeline = await window.dzmm.chat.timeline(messageId);
const fullHistory = await window.dzmm.chat.list(timeline);
Use cases: Galgame save/load systems, branching narratives, multi-route stories, interactive fiction with choice history.
window.dzmm.kv - Cloud key-value storage:
// Save (auto-serializes objects)
await window.dzmm.kv.put(key, value);
// Load
const result = await window.dzmm.kv.get(key);
if (result.value) {
const data = result.value;
}
// Delete
await window.dzmm.kv.delete(key);
Limits: Keys ≤256 chars, values ≤1MB recommended. Development mode: data lost on refresh. Production: persistent.
Critical Requirements:
dzmm:ready event before any API callsuser and assistant roles supported (no system)app_state_v1)Reference: Consult references/developer-guide.md sections 2-3 for complete API documentation and references/code-snippets.md sections 1-3 for ready-to-use code patterns.
Implement "fourth wall breaking" effects where AI can control the user's browser environment.
Effect Categories:
Visual Effects:
Audio Effects:
Dynamic Elements:
Implementation Pattern:
// 1. AI outputs special instructions
const aiPrompt = `When the user says "turn off lights", output:
###EFFECT
{"action":"lights","params":{"state":"off"}}
###END`;
// 2. Parse and execute
const effectMatch = content.match(/###EFFECT\s*({[\s\S]*?})\s*###END/);
if (effectMatch) {
const effect = JSON.parse(effectMatch[1]);
executeEffect(effect);
// Remove instruction from display
content = content.replace(/###EFFECT[\s\S]*?###END/, '').trim();
}
// 3. Effect executor
function executeEffect(effect) {
switch(effect.action) {
case 'lights':
document.body.classList.add(`lights-${effect.params.state}`);
break;
// ... more effects
}
}
Reference: See assets/examples/horror-story.html for complete effect system with CSS animations, Web Audio, and Canvas particles.
Diagnose and fix common DZMM application issues.
Common Issues:
HTTP 400 Errors:
role: 'system' in messages (not supported)user message or maintain in frontend variablesNo Response from AI:
dzmm:ready event is awaited before any API callsContext Overflow:
State Not Persisting:
Form Submission Blocked (Public Release Only):
allow-forms permissionBlocked form submission to '' because the form's frame is sandboxed<form> with <div>, use @click instead of @submit.prevent<!-- ❌ WRONG: Will fail in public release -->
<form @submit.prevent="handleSubmit()">
<button type="submit">Submit</button>
</form>
<!-- ✅ CORRECT: Works in all environments -->
<div>
<button type="button" @click="handleSubmit()">Submit</button>
</div>
Performance Optimization:
Reference: Consult references/developer-guide.md section "常见问题" for comprehensive troubleshooting guide.
Provide reusable, production-ready code patterns for common DZMM tasks.
Available Patterns:
Usage: Reference references/code-snippets.md for copy-paste ready code snippets organized by category. All snippets are tested and can be used directly or with minimal modifications.
New Visual Novel Patterns (from yoshiwara-chronicles):
Clarify Requirements
Select Template
assets/examples/ for similar applications:
小红书文案.html - Simple content generator, Markdown rendering恋爱游戏.html - Dating sim, multi-variable state managementhorror-story.html - Effect system, immersive experiencedungeon-adventure.html - Turn-based game, state managementneon-gomoku.html - AI opponent, game logic贴吧.html - Content platform, two-tier cachingBuild Application
dzmm:ready)Test and Refine
Identify the Issue
Diagnose Root Cause
references/developer-guide.mduser/assistant)Apply Fix
references/code-snippets.mdOptimize
Two Approaches Available:
Use modern build tools to maintain component-based development, then bundle to single HTML.
Tech Stack: React + TypeScript + Vite + vite-plugin-singlefile
Workflow:
npm create vite@latest my-app -- --template react-tsnpm install -D vite-plugin-singlefilenpm run build:single → generates standalone HTMLKey Considerations:
Critical Fixes:
<form> with <div> + button onClickSee: Q11 in references/developer-guide.md for complete implementation guide
Convert component hierarchy to single HTML with Alpine.js reactive sections.
Assessment
Resource Strategy (Critical)
Structure Migration
useState → Alpine reactive data propertiesuseEffect → Alpine x-init or watchersprops → Alpine function parameters or computed propertiesonClick={fn} → @click="fn"API Migration
fetch('/api/chat') with dzmm.completions()dzmm.kv operations (or safe storage wrapper)dzmm:ready event waitingFeature Additions (from yoshiwara-chronicles patterns)
Testing and Refinement
Comparison:
| Factor | React + Vite | Alpine.js |
|---|---|---|
| Type Safety | ✅ TypeScript | ❌ Plain JS |
| Dev Experience | ✅ Hot reload | ⚠️ Manual refresh |
| Ecosystem | ✅ Rich (shadcn/ui, etc.) | ⚠️ Limited |
| File Size | ⚠️ Larger (900KB+) | ✅ Smaller (<100KB) |
| Maintenance | ✅ Component-based | ⚠️ Single file can get messy |
| Learning Curve | ⚠️ Steeper for beginners | ✅ Easier to learn |
Choose the appropriate DZMM AI model based on task complexity:
Standard Models (32K context):
16K Models (faster, shorter context):
Legacy Model Names (may still work in some examples):
nalang-xl → likely maps to nalang-xl-0826nalang-xl-10 → likely maps to nalang-xl-0826Selection Tips:
nalang-turbo-0826 for speednalang-max-0826 or nalang-xl-0826 for qualityComplete DZMM platform developer guide covering:
Load this reference when users need in-depth understanding of DZMM concepts, detailed API specifications, or comprehensive architecture guidance.
Organized library of reusable code patterns:
Load this reference when implementing specific features or need quick access to proven code patterns.
Seven complete, working DZMM applications:
小红书文案.html (~15KB) - Stateless Generator
恋爱游戏.html (~35KB) - State Management Game
horror-story.html (29KB) - Effect System
dungeon-adventure.html (41KB) - Turn-based Game
neon-gomoku.html (24KB) - Board Game
贴吧.html (26KB) - Content Platform
yoshiwara-chronicles-dzmm.html (84KB) - Complete Visual Novel System (Alpine.js) ⭐
<last_input> emphasis, token optimization, format rules at bottom)yoshiwara-chronicles-react (893KB, gzip: 473KB) - React Multi-Component Version 🚀
assets/react-examples/yoshiwara-chronicles-react.mdUse these as starting templates or reference implementations for specific features.
dzmm:ready event before any API callwindow.dzmm directly + event listener + timeout recheckif (window.dzmm) {
this.dzmmReady = true;
} else {
window.addEventListener('dzmm:ready', () => { this.dzmmReady = true; });
setTimeout(() => {
if (!this.dzmmReady && window.dzmm) this.dzmmReady = true;
}, 2000);
}
1.5. ⚠️ Resource Reuse Strategy (Critical for Migrations)
<!-- ✅ CORRECT: Direct URL reference -->
<div style="background-image: url('https://raw.githubusercontent.com/user/repo/main/public/image.jpg')">
<!-- ❌ WRONG: CSS simulation of textures -->
<div style="background: linear-gradient(...); box-shadow: inset ...">
const ASSET_BASE = 'https://raw.githubusercontent.com/user/repo/main/public';
const assets = {
backgrounds: { welcome: `${ASSET_BASE}/bg1.jpg` },
music: [{ src: `${ASSET_BASE}/music/track1.mp3` }]
};
Manage Conversation History
role: 'system'Handle Errors Gracefully
Optimize Performance
Design Clear Prompts with Format Control
【正确示例】
用户:早上好
回复:
###STATE
{"affection":52,"mood":"高兴"}
###END
早上好呀!
【错误示例 - 绝对不要这样】
❌ 把对话写在STATE前面
❌ 不写STATE
Smart State Persistence
const excludeKeys = ['disabled', 'loading', 'input'];
const saveData = {};
Object.keys(this).forEach(key => {
if (!excludeKeys.includes(key) && typeof this[key] !== 'function') {
saveData[key] = this[key];
}
});
Responsive Design for Mobile
Configuration UI Pattern
Markdown Integration (for content generators)
marked.setOptions({ breaks: true, gfm: true })x-html="renderMarkdown(content)".post-body h1, .post-body p, etc.)Version Your Data
app_state_v1)Use Chat API for Branching Narratives
parentId to create branching storylines at decision pointstimeline() for save/load functionality// Save choice and branch
const result = await dzmm.chat.insert(currentNodeId, [
{ role: 'user', content: playerChoice },
{ role: 'assistant', content: storyResponse }
]);
currentNodeId = result.ids[result.ids.length - 1];
localStorage.setItem('savePoint', currentNodeId);
// Load save
const timeline = await dzmm.chat.timeline(savedNodeId);
const history = await dzmm.chat.list(timeline);
Respect API Limits
Rich Text Rendering with Placeholder Technique
<options> inside AI responses) conflict with regex replacementsrenderRichText(text) {
// 1. Extract options blocks with placeholders
const optionsMap = [];
let result = text.replace(/<options>([\s\S]*?)<\/options>/g, (match, content) => {
const placeholder = '___OPTIONS_' + optionsMap.length + '___';
optionsMap.push(content);
return placeholder;
});
// 2. Process regular text (italics, quotes, line breaks)
result = result
.replace(/\*([^*]+)\*/g, '<em>$1</em>')
.replace(/「([^」]+)」/g, '<span class="dialogue">「$1」</span>')
.replace(/\n/g, '<br>');
// 3. Restore options as HTML buttons
optionsMap.forEach((content, i) => {
const buttons = /* generate buttons from content */;
result = result.replace('___OPTIONS_' + i + '___', buttons);
});
return result;
}
<button data-option="${escaped}">event.target.closest('[data-option]')Message Management Features
// Reroll: preserve context
const contextMessages = this.messages.slice(0, messageIndex);
// Edit: delete subsequent + auto-respond
this.messages = this.messages.slice(0, index + 1);
await this.getAIResponse(editedContent, false);
// Delete: with confirmation
if (confirm('Delete this and all following messages?')) {
this.messages = this.messages.slice(0, index);
}
editingIndex and rerollingIndex for UI state tracking<options> tags from history to prevent AI format inertiaMulti-Opening Scene System
[{ id: 'night', label: '夜之章' }]{ night: 'content...', day: 'content...' }selectedOpening and previousOpening for cancel supportchangeOpening() {
if (this.messages.length > 1) {
if (!confirm('Switch will clear conversation. Continue?')) {
this.selectedOpening = this.previousOpening; // Revert
return;
}
}
this.previousOpening = this.selectedOpening;
this.messages = [];
this.messages.push({ role: 'assistant', content: this.getOpeningGreeting() });
}
Responsive Mobile Design
flex-col md:flex-row for vertical (mobile) → horizontal (desktop)flex-wrap and gap-1.5 to allow wrappingtext-xs md:text-sm for responsive font sizeshidden md:blockpy-4 → py-1.5)h-screen + flex-1 + flex-shrink-0 for header/content/footerwhitespace-nowrap to prevent button text wrappingAdvanced Prompt Engineering
<时代背景>, <创作美学>, <回复规范> for clear hierarchyconst messages = [
{ role: 'user', content: systemPrompt }, // Top: World/character setting
...cleanedHistory, // Middle: Conversation
{ role: 'user', content: getEmphasis() } // Bottom: Format rules (strongest)
];
for (let i = cleanedMessages.length - 1; i >= 0; i--) {
if (cleanedMessages[i].role === 'user') {
cleanedMessages[i].content = `<last_input>\n${cleanedMessages[i].content}\n</last_input>`;
break;
}
}
<option> → <op> saves ~12 chars × 3)<options> blocks from history to prevent AI format inertiaKV Storage Advanced Patterns
// Save: Full game state
await dzmm.kv.put(`game_slot_${slotNumber}`, JSON.stringify({
character, messages, timestamp, ...gameState
}));
// Preview: Extract metadata only (don't load full messages)
const data = JSON.parse(result.value);
return {
characterName: data.character.name,
messageCount: data.messages.length,
lastMessage: data.messages[messages.length-1].content.slice(0, 50),
timestamp: new Date(data.timestamp).toLocaleString()
};
Promise.all() for parallel KV operations${appName}_v2_${dataKey} for schema upgrades{ value, expiresAt } and check timestamp on loadStreaming AI Response Optimization
done === false$nextTick() to ensure DOM updated before scrollingthis.messages.push({ role: 'assistant', content: '' });
const idx = this.messages.length - 1;
await dzmm.completions({ /* ... */ }, (content, done) => {
this.messages[idx].content = content;
if (done) {
this.$nextTick(() => scrollToBottom());
}
});
Follow DZMM conventions:
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience