AI-Generated Content
How to use the AI integration in Pixi’VN to generate dialogue, backgrounds and characters at runtime during a play session, and how to configure ink and ComfyUI.
The AI integration is currently in a testing phase and its API may change in future releases.
@drincs/pixi-vn-ai is a small, high-level AI abstraction for Pixi’VN. It is not a
low-level LLM client: it exposes three functions — ai.text.generateDialog,
ai.image.generateBackground and ai.image.generateElement — that hide all prompt engineering.
You pass a natural-language request plus a few structured options (scene, style, speaker,
alignment, ...), and the library assembles the actual prompt and sends it to whatever model you
configured.
It is designed to run entirely in the browser, and can generate dialogue, backgrounds and characters directly during a play session, without a custom backend.
Within your Pixi’VN project, you can use the AI integration to generate narrative dialogue and images (backgrounds, characters, ...) on the fly, using any AI SDK compatible model (OpenAI, Anthropic, Google, Ollama, ...), a self-hosted ComfyUI server, or a small local WebLLM model that requires no API key and no server at all.
安装
To install the AI package in an existing JavaScript project, use one of the following commands:
npm install @drincs/pixi-vn-aiCall ai.init(...) once, at startup. Wrap it in its own function, exported from a dedicated file,
so it can be awaited alongside your other startup tasks and later swapped for a different provider
without touching where it's called from:
import { ai } from "@drincs/pixi-vn-ai";
export async function initAi() {
await ai.init();
}If you're using the router-based template, run it from the root route's loader, alongside the
other startup tasks, instead of from main.ts:
import { initAi } from "@/lib/utils/ai-utility";
export const Route = createRootRouteWithContext<RouterContext>()({
// ...
loader: async ({ context, location }) => {
await Promise.all([
import("@/content"),
initAi(),
// ...
]);
await setupPixivnViteData();
// ...
},
// ...
});With no arguments, ai.init() downloads and runs a small local WebLLM model
(SmolLM2-360M-Instruct) directly in the browser. This covers ai.text.generateDialog out of the
box.
For images, ai.image.generateBackground/ai.image.generateElement always require an external
model — an AI SDK provider or ComfyUI. WebLLM cannot generate images.
To use a specific model instead, pass it through the AI SDK. From here on, only the body of
initAi changes — how and where you call it stays the same:
import { ai } from "@drincs/pixi-vn-ai";
import { openai } from "@ai-sdk/openai";
export async function initAi() {
await ai.init({
textProvider: openai("gpt-5"),
imageProvider: openai.image("gpt-image-1"),
});
}textProvideris aLanguageModelfrom any AI SDK provider. It drivesai.text.generateDialog, and is also used as a fallback for image generation on multimodal models (e.g. Gemini's image generation).imageProvideris anImageModelfrom any AI SDK provider. It drivesai.image.generateBackground/ai.image.generateElement.
You don't need both: set only textProvider for dialogue, only imageProvider for images, or
both.
You can enable AI hashtag commands in your ink scripts by using the
createAiHandler function.
import { addBaseHashtagCommands } from "@drincs/pixi-vn-ink";
import { createAiHandler } from "@drincs/pixi-vn-ai/ink";
addBaseHashtagCommands({ bundleIds, assetAliasIds });
createAiHandler(); This registers four commands: # ai background, # ai element, # ai dialog and
# ai dialog as \<character> — see the Usage section below for each of them.
Optionally, pass known character ids (e.g. the characterIds generated by vitePluginPixivn's
assetsManifest option) so # ai dialog as \<character> validates the character at runtime instead
of accepting any string:
createAiHandler({ characterIds }); If you want to generate images with a self-hosted ComfyUI server instead of an AI SDK image provider, also install:
npm install @stable-canvas/comfyui-clientThen pass a ComfyUIImageModel as
imageProvider:
import { ai } from "@drincs/pixi-vn-ai";
import { ComfyUIImageModel } from "@drincs/pixi-vn-ai/comfyui";
import myWorkflow from "./my-workflow-api.json"; // exported from ComfyUI's "Save (API Format)"
export async function initAi() {
await ai.init({
imageProvider: new ComfyUIImageModel({
apiHost: "127.0.0.1:8188",
workflow: myWorkflow,
// the node/input in `myWorkflow` that holds the positive prompt (usually a CLIPTextEncode node)
promptNodeId: "6",
promptInputName: "text", // optional, defaults to "text"
}),
});
}Since ComfyUI runs an arbitrary node graph rather than accepting a plain prompt,
ComfyUIImageModel only injects the developer request into the node/input you point it at —
everything else (checkpoint, sampler, seed, resolution, ...) is whatever your exported workflow
already specifies.
ComfyUIImageModel only talks HTTP to apiHost — it doesn't start the server for you. The
simplest setup is to let the player point apiHost at a ComfyUI instance they already run
themselves (locally or on a LAN/remote machine), with no bundling at all.
If instead you want your Tauri
build to ship and launch ComfyUI itself, since ComfyUI is a Python process, Rust doesn't run it
in-process — it spawns it as a child process. The standard way to do this in Tauri is a
sidecar binary via
tauri-plugin-shell, pointing at a portable ComfyUI build
(which bundles its own Python) added to externalBin:
[dependencies]
tauri-plugin-shell = "2"{
"bundle": {
"externalBin": ["binaries/comfyui-portable/run_nvidia_gpu"]
}
}use tauri_plugin_shell::ShellExt;
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.setup(|app| {
app.shell().sidecar("comfyui-portable/run_nvidia_gpu")?.spawn()?;
Ok(())
})
// ...Tauri sidecars must be named with the target's platform triple suffix (e.g.
run_nvidia_gpu-x86_64-pc-windows-msvc.exe) — see the sidecar
docs for the exact naming and signing requirements per
platform.
Since ComfyUI takes a few seconds to boot, poll its HTTP API before calling ai.init. Add the wait
inside the same initAi function from before — where and how it's called doesn't change:
import { ai } from "@drincs/pixi-vn-ai";
import { ComfyUIImageModel } from "@drincs/pixi-vn-ai/comfyui";
import myWorkflow from "./my-workflow-api.json"; // exported from ComfyUI's "Save (API Format)"
async function waitForComfyUI(apiHost: string, timeoutMs = 30000) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
try {
if ((await fetch(`http://${apiHost}/system_stats`)).ok) return;
} catch {
// not up yet
}
await new Promise((r) => setTimeout(r, 500));
}
throw new Error("ComfyUI did not start in time");
}
export async function initAi() {
await waitForComfyUI("127.0.0.1:8188");
await ai.init({
imageProvider: new ComfyUIImageModel({
apiHost: "127.0.0.1:8188",
workflow: myWorkflow,
promptNodeId: "6",
}),
});
}A bundled Python + PyTorch + model environment can add several GB to your installer and needs a compatible GPU on the player's machine. Most games only bundle ComfyUI for internal/offline asset generation, and ship the "point at an external server" option to end users.
使用方法
@drincs/pixi-vn-ai never asks you to write a prompt yourself. As a developer, you just describe
in plain language what you want to generate and, optionally, pass a few structured options
(scene, style, context, the narrative history, a speaker, an alignment, ...); the library
is the only one responsible for turning that into the actual message sent to the model, filling in
whatever extra information it needs (canvas size, reference images, narrative history, ...) along
the way.
showBackground generates a background image
and shows it on the canvas, filling it edge-to-edge. It's the combination of
ai.image.generateBackground and Pixi’VN's showImage, using
AIImageSprite so the generated image itself is
saved with the game and restored on load, without generating it again.
import { newLabel } from "@drincs/pixi-vn";
import { showBackground } from "@drincs/pixi-vn-ai";
export const startLabel = newLabel("start", [
async () => {
await showBackground(
"throneRoom",
"The throne room, lit by torches, a storm outside the windows.",
{
scene: "Night, medieval castle interior.",
style: "Oil painting, warm color palette.",
},
);
},
]);The ink command also accepts an optional entrance transition, just like # show for any other
canvas element:
# ai background throneRoom "The throne room, lit by torches." with dissolve duration 1showElement generates a single visual element
(typically a character), with a transparent background, and shows it on the canvas. It's
positioned with align — the only supported way to position it, since the image itself is already
composed for that position. It's the combination of ai.image.generateElement and Pixi’VN's
showImage, again using AIImageSprite.
import { newLabel } from "@drincs/pixi-vn";
import { showElement } from "@drincs/pixi-vn-ai";
export const startLabel = newLabel("start", [
async () => {
await showElement(
"advisor",
"The advisor, an elderly man with a long grey beard, wearing dark blue robes, worried expression.",
{
style: "Oil painting, warm color palette, matching the background.",
backgroundImage: true,
align: { x: 0.75, y: 1 },
},
);
},
]);backgroundImage (a Pixi’VN asset alias, or true to capture whatever is currently on the game
canvas) gives the model visual context on what it's being composited over, so it can match
lighting, perspective and scale. See canvas
position for more about align.
showDialog generates a line of dialogue from a
developer request and sets it as the current Pixi’VN narration dialogue. It's the combination of
ai.text.generateDialog and Pixi’VN's narration.dialogue. Passing a
character also sets it as the
dialogue's character, and — unless options.speaker is already set — as the
prompt's speaker, so the model knows who it's writing for.
import { newLabel } from "@drincs/pixi-vn";
import { showDialog } from "@drincs/pixi-vn-ai";
export const startLabel = newLabel("start", [
async () => {
await showDialog("Greet the king with the bad news.", "advisor", {
scene: "The throne room, late at night, lit only by torches.",
style: "Tense, formal, a little melancholic.",
});
},
]);Without a character, use # ai dialog \<request> [\<key> \<value> …] (or call showDialog(request, undefined, options)).
其他功能
ai.image.generateBackground
and
ai.image.generateElement
are the lower-level functions behind showBackground/showElement: they only generate the image
and return it as a data URI, without touching the canvas. Use them directly when you want to
post-process the generated image yourself, cache it, or show it with something other than
AIImageSprite.
import { canvas } from "@drincs/pixi-vn/canvas";
import { ai, AIImageSprite } from "@drincs/pixi-vn-ai";
const dataUri = await ai.image.generateBackground(
"The throne room, lit by torches, a storm outside the windows.",
);
const sprite = new AIImageSprite(undefined, dataUri);
await sprite.load();
canvas.add("throneRoom", sprite);generateBackground's image is meant to fill the whole game canvas — its size is read directly
from Pixi’VN and included in the prompt automatically. generateElement's image is meant to be
layered on top of other visuals, with a transparent background; both accept a referenceImage
(a Pixi’VN asset alias, or a URL/data URI) used as image-to-image guidance.
You can also override the default prompt "Instructions" per kind — ai.templates.image.background
/ ai.templates.image.element (and ai.templates.dialog for text, see below).
ai.text.generateDialog
is the lower-level function behind showDialog: it only generates the dialogue text and returns
it as a string, without setting it as the current narration dialogue. Use it directly when you want
to use the generated text for something other than narration.dialogue (e.g. a log, a tooltip, a
custom UI element).
import { ai } from "@drincs/pixi-vn-ai";
const line = await ai.text.generateDialog(
"The advisor reassures the king that the kingdom is safe.",
{ speaker: "advisor", listeners: ["king"] },
);history (on by default) pulls Pixi’VN's narrative history so the model has continuity;
speaker/listeners accept a character id (resolved against Pixi’VN's registered characters, or
used as-is otherwise) or a plain object, single or array.
AIImageSprite is the canvas component used
internally by showBackground/showElement and by the # ai background/# ai element ink
commands. It behaves exactly like Pixi’VN's own ImageSprite, but also keeps the generated image
(a data URI) in its memory, so that save games
store the generated image itself and restore the exact same image on load, instead of calling the
AI provider again — which would produce a different image.
That same memory is also kept in the go back
step history, as a plain string — a data URI can easily be several hundred KB, so generating many
AIImageSprites can make that history heavy. It's recommended to lower
stepHistory.stepLimitSaved
so only the last few steps keep their full canvas/storage data in the save file.
import { canvas } from "@drincs/pixi-vn/canvas";
import { ai, AIImageSprite } from "@drincs/pixi-vn-ai";
const dataUri = await ai.image.generateBackground(
"The throne room, lit by torches.",
);
const sprite = new AIImageSprite(undefined, dataUri);
await sprite.load();
canvas.add("background", sprite);You only need to construct it yourself if you're combining ai.image.* with the canvas manually,
as shown above; showBackground/showElement and the ink commands already do this for you.