### Install the SDK Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/getting-started.md Use your preferred package manager to add the SDK to your project. ```bash npm install novelai-sdk-unofficial ``` ```bash pnpm add novelai-sdk-unofficial ``` ```bash yarn add novelai-sdk-unofficial ``` -------------------------------- ### Install NovelAI SDK Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/README.en.md Use the package manager to add the SDK to your project. ```bash pnpm add novelai-sdk-unofficial ``` -------------------------------- ### Quick Start with NovelAI SDK Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/README.en.md Initialize the client and perform basic image generation, text generation, and OpenAI-compatible chat requests. ```typescript import { NovelAI } from "novelai-sdk-unofficial"; import { writeFileSync } from "fs"; const client = new NovelAI({ apiKey: "your-api-key" }); // 🖼️ Image generation const images = await client.image.generate({ prompt: "1girl, cat ears, masterpiece, best quality", model: "nai-diffusion-4-5-full", size: "portrait", }); writeFileSync("output.png", images[0]); // 📝 Text generation const text = await client.text.generate({ input: "Once upon a time", model: "llama-3-erato-v1", maxLength: 80, }); console.log(text); // 🔄 OpenAI Compatible API (uses GLM models) const models = await client.openai.listModels(); const chat = await client.openai.chatCompletion({ messages: [{ role: "user", content: "Hello!" }], model: models[0].id, // glm-4-6 maxTokens: 100, }); console.log(chat.choices[0].message.content); ``` -------------------------------- ### GET /oa/v1/models Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/openai-compatible.md Lists all available models compatible with the OpenAI format. ```APIDOC ## GET /oa/v1/models ### Description List available models. ### Method GET ### Endpoint https://text.novelai.net/oa/v1/models ``` -------------------------------- ### Pose Transfer Example Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/controlnet.md Demonstrates using a reference image to transfer a specific pose to the generated output. ```typescript const images = await client.image.generate({ prompt: '1girl, dancing', controlnet: { images: [ { image: poseImage, infoExtracted: 0.8, strength: 0.7, }, ], }, }); ``` -------------------------------- ### V4+ Model Prompt Structure Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/index.md Example of how the SDK internally transforms user input into the required V4 prompt structure. ```typescript // User input { prompt: '1girl, cat ears', quality: true, } // SDK converts to { input: '1girl, cat ears', v4_prompt: { caption: { base_caption: '1girl, cat ears, very aesthetic, masterpiece, no text', char_captions: [] }, use_coords: false, use_order: true } } ``` -------------------------------- ### Background Change Example Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/image-to-image.md Uses a mask to replace the background of an image. ```typescript // With mask covering the background const images = await client.image.generate({ prompt: 'beach sunset background', i2i: { image: inputImage, strength: 0.8, mask: backgroundMask, }, }); ``` -------------------------------- ### Execute Complete Text Generation Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/parameters.md A full example demonstrating the use of length, sampling, repetition, sequence, and bias parameters. ```typescript const text = await client.text.generate({ input: 'The wizard raised his staff and', model: 'llama-3-erato-v1', // Length maxLength: 100, minLength: 20, // Sampling temperature: 1.1, topK: 50, topP: 0.95, typicalP: 1.0, tailFreeSampling: 0.95, minP: 0.05, // Repetition repetitionPenalty: 1.15, repetitionPenaltyRange: 512, repetitionPenaltyFrequency: 0.02, repetitionPenaltyPresence: 0.0, // Sequences stopSequences: ['\n\n', '***'], banSequences: [], // Bias logitBias: [ { token: 'magic', bias: 0.5 }, ], }); ``` -------------------------------- ### Color Correction Example Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/image-to-image.md Adjusts the color profile of an image using a prompt. ```typescript const images = await client.image.generate({ prompt: 'vibrant colors, high contrast', i2i: { image: inputImage, strength: 0.3, }, }); ``` -------------------------------- ### Define Token Count Parameters in TypeScript Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/variables/OAITokenCountParamsSchema.md Example of initializing the parameters object for a token count request. ```typescript const params: OAITokenCountParamsInput = { prompt: 'Hello, world!', model: 'llama-3-erato-v1', }; ``` -------------------------------- ### Capture Stack Trace Example Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/classes/RateLimitError.md Demonstrates how to use Error.captureStackTrace to generate a stack trace for an object or to hide specific implementation frames. ```js const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` ```js function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` -------------------------------- ### Custom Size Constraints Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/models-and-sizes.md Examples of valid and invalid custom size configurations based on the 64-pixel multiple and 1600-pixel limit rules. ```typescript // Valid custom sizes size: [768, 1024] // ✅ size: [1280, 768] // ✅ // Invalid sizes size: [700, 1000] // ❌ Not multiples of 64 size: [2048, 2048] // ❌ Exceeds 1600 ``` -------------------------------- ### Define completion parameters Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/variables/OAICompletionParamsSchema.md Example of creating an input object that conforms to the OAICompletionParamsSchema structure. ```typescript const params: OAICompletionParamsInput = { prompt: 'Once upon a time', maxTokens: 100, temperature: 0.7, }; ``` -------------------------------- ### Style Transfer Example Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/image-to-image.md Applies an artistic style to an existing photo. ```typescript const images = await client.image.generate({ prompt: 'oil painting style, impressionist', i2i: { image: photoImage, strength: 0.6, }, }); ``` -------------------------------- ### Configure character reference types Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/character-reference.md Examples of setting the reference type to either character-only or character-and-style. ```typescript characterReferences: [ { image: referenceImage, type: 'character', fidelity: 0.75, }, ] ``` ```typescript characterReferences: [ { image: referenceImage, type: 'character&style', fidelity: 0.75, }, ] ``` -------------------------------- ### Define generation parameters using GenerateTextParams Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/variables/GenerateTextParamsSchema.md Example showing how to initialize a parameter object conforming to the generation schema. ```typescript const params: GenerateTextParams = { input: 'Once upon a time', model: 'llama-3-erato-v1', temperature: 1.0, maxLength: 40, }; ``` -------------------------------- ### Style/Composition Transfer Example Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/controlnet.md Uses a reference image to influence the overall style or composition of the generated landscape. ```typescript const images = await client.image.generate({ prompt: 'landscape, mountains', controlnet: { images: [ { image: compositionReference, infoExtracted: 0.5, strength: 0.5, }, ], }, }); ``` -------------------------------- ### Strength Parameter Variations Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/image-to-image.md Examples of how the strength parameter affects the transformation intensity. ```typescript // Subtle enhancement i2i: { image: input, strength: 0.2 } // Moderate transformation i2i: { image: input, strength: 0.5 } // Major transformation i2i: { image: input, strength: 0.8 } ``` -------------------------------- ### Generate dialogue response Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/index.md Example of using stop sequences to manage turn-based dialogue generation. ```typescript const dialogue = `Alice: What do you think about the weather? Bob:`; const response = await client.text.generate({ input: dialogue, stopSequences: ['\nAlice:', '\n\n'], maxLength: 50, }); console.log(dialogue + response); ``` -------------------------------- ### Generate story continuation Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/index.md Example of appending generated text to an existing story prompt. ```typescript const story = `The old lighthouse keeper climbed the spiral stairs, his lantern casting dancing shadows on the stone walls.`; const continuation = await client.text.generate({ input: story, model: 'llama-3-erato-v1', temperature: 1.0, maxLength: 100, }); console.log(story + continuation); ``` -------------------------------- ### Three Characters Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/multi-character.md Example configuration for placing three characters in a group photo layout. ```typescript const images = await client.image.generate({ prompt: 'group photo', model: 'nai-diffusion-4-5-full', characters: [ { prompt: '1girl, red dress', position: [0.2, 0.5], }, { prompt: '1boy, blue suit', position: [0.5, 0.5], }, { prompt: '1girl, green dress', position: [0.8, 0.5], }, ], }); ``` -------------------------------- ### Define Chat Completion Parameters Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/variables/OAIChatCompletionParamsSchema.md Example of defining an input object that conforms to the chat completion parameters structure. ```typescript const params: OAIChatCompletionParamsInput = { messages: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'Hello!' }, ], maxTokens: 100, }; ``` -------------------------------- ### Adjust fidelity settings Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/character-reference.md Examples of using different fidelity values to control the influence of the reference image. ```typescript // Lower fidelity - more creative freedom characterReferences: [{ image: ref, fidelity: 0.3 }] // Higher fidelity - closer to reference characterReferences: [{ image: ref, fidelity: 0.9 }] ``` -------------------------------- ### Initialize and use the NovelAI client Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/classes/NovelAI.md Demonstrates how to instantiate the client using an explicit API key or an environment variable, followed by a basic image generation request. ```typescript // Initialize with API key const client = new NovelAI({ apiKey: 'your-api-key' }); // Or use environment variable NOVELAI_API_KEY const client = new NovelAI(); // Generate images const images = await client.image.generate({ prompt: 'a beautiful landscape', model: 'nai-diffusion-4-5-full', size: 'landscape', }); ``` -------------------------------- ### Initialize Client Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/authentication.md Initialize the client using different configuration strategies. ```typescript import { NovelAI } from 'novelai-sdk-unofficial'; const client = new NovelAI(); ``` ```typescript import { NovelAI } from 'novelai-sdk-unofficial'; const client = new NovelAI({ apiKey: 'your-api-key' }); ``` ```typescript import 'dotenv/config'; import { NovelAI } from 'novelai-sdk-unofficial'; const client = new NovelAI(); ``` -------------------------------- ### Configure Authentication via Environment Variable Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/llms-full.txt Set the API key as an environment variable and initialize the client without arguments. ```bash export NOVELAI_API_KEY=your_api_key_here ``` ```typescript import { NovelAI } from "novelai-sdk-unofficial"; const client = new NovelAI(); // Auto-reads from env ``` -------------------------------- ### NovelAI Client Initialization Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/llms-full.txt How to initialize the NovelAI client using either environment variables or direct configuration. ```APIDOC ## NovelAI Client Initialization ### Description Initializes the NovelAI SDK client to interact with the API. The client can automatically read the API key from the `NOVELAI_API_KEY` environment variable or be configured manually. ### Initialization ```typescript import { NovelAI } from "novelai-sdk-unofficial"; // Using environment variable const client = new NovelAI(); // Direct initialization const client = new NovelAI({ apiKey: "your-api-key" }); ``` ### Configuration Options - **apiKey** (string) - Optional - API Key for authentication. - **imageBase** (string) - Optional - Custom base URL for image generation API. - **textBase** (string) - Optional - Custom base URL for text generation API. - **timeout** (number) - Optional - Request timeout in milliseconds (default: 30000). ``` -------------------------------- ### Configure Full Generation Parameters Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/llms-full.txt Demonstrates the full range of configuration options including model selection, sampler settings, and prompt processing. ```typescript const images = await client.image.generate({ // Required prompt: "1girl, cat ears, masterpiece, best quality", // Model & Size model: "nai-diffusion-4-5-full", // ImageModel size: "portrait", // ImageSizePreset or [width, height] // Prompt Processing negativePrompt: "bad anatomy, blurry", quality: true, // Auto-append quality tags (default: true) ucPreset: "light", // UC preset: none|light|strong|furry_focus|human_focus // Generation Parameters steps: 23, // 1-50 (default: 23) scale: 5.0, // CFG scale 0-10 (default: 5.0) sampler: "k_euler_ancestral", // Sampler noiseSchedule: "karras", // NoiseSchedule seed: 12345, // 0-999999999 (random if not set) nSamples: 1, // 1-8 (default: 1) cfgRescale: 0, // 0-1 (default: 0) varietyBoost: false, // Enable variety boost // Advanced Features characterReferences: [...], // Character reference (V4.5 only) controlnet: {...}, // ControlNet i2i: {...}, // Image-to-Image characters: [...], // Multi-character positioning }); ``` -------------------------------- ### Initialize NovelAI Client Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/llms.txt Configure the client with an API key and optional base URLs or timeouts. ```typescript const client = new NovelAI({ apiKey: "your-api-key", // Required (or set NOVELAI_API_KEY env) imageBase: "https://...", // Optional: custom image API base URL textBase: "https://...", // Optional: custom text API base URL timeout: 30000, // Optional: request timeout in ms }); ``` -------------------------------- ### Initialize and Use OpenAI-Compatible Generation Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/classes/OpenAIGeneration.md Demonstrates basic usage of the OpenAI-compatible interface, including text completion, chat completion, and streaming responses. ```typescript const client = new NovelAI({ apiKey: 'your-api-key' }); // Text completion const response = await client.openai.completion({ prompt: 'Once upon a time', maxTokens: 100, }); // Chat completion const chat = await client.openai.chatCompletion({ messages: [{ role: 'user', content: 'Hello!' }], maxTokens: 100, }); // Streaming for await (const chunk of client.openai.chatCompletionStream({ messages: [{ role: 'user', content: 'Tell me a story' }], })) { const content = chunk.choices[0]?.delta?.content; if (content) process.stdout.write(content); } ``` -------------------------------- ### Character Outfit Change Example Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/image-to-image.md Uses a mask to modify the clothing of a character in an image. ```typescript // With mask covering the outfit const images = await client.image.generate({ prompt: 'wearing a red dress', i2i: { image: inputImage, strength: 0.7, mask: outfitMask, }, }); ``` -------------------------------- ### Initialize Client Directly Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/llms-full.txt Pass the API key directly to the constructor for manual initialization. ```typescript const client = new NovelAI({ apiKey: "your-api-key" }); ``` -------------------------------- ### Two Characters Side by Side Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/multi-character.md Example configuration for placing two characters side by side. ```typescript const images = await client.image.generate({ prompt: 'two friends talking', model: 'nai-diffusion-4-5-full', characters: [ { prompt: '1girl, blonde hair, smiling', position: [0.3, 0.5], }, { prompt: '1girl, brown hair, laughing', position: [0.7, 0.5], }, ], }); ``` -------------------------------- ### Basic Image-to-Image Generation Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/image-to-image.md Initializes the client and performs a basic image transformation using a prompt and strength setting. ```typescript import { NovelAI } from 'novelai-sdk-unofficial'; import { readFileSync, writeFileSync } from 'fs'; const client = new NovelAI({ apiKey: 'your-api-key' }); const inputImage = readFileSync('input.png'); const images = await client.image.generate({ prompt: 'cyberpunk style, neon lights', model: 'nai-diffusion-4-5-full', i2i: { image: inputImage, strength: 0.5, }, }); writeFileSync('output.png', images[0]); ``` -------------------------------- ### Basic Streaming Usage Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/streaming.md Demonstrates how to initialize the client and iterate through generation chunks to save intermediate and final images. ```typescript import { NovelAI } from 'novelai-sdk-unofficial'; import { writeFileSync } from 'fs'; const client = new NovelAI({ apiKey: 'your-api-key' }); const stream = client.image.generateStream({ prompt: '1girl, detailed background', model: 'nai-diffusion-4-5-full', steps: 28, }); for await (const chunk of stream) { if (chunk.event_type === 'intermediate') { console.log(`Step ${chunk.step_ix}/${chunk.steps}: sigma=${chunk.sigma}`); // Optionally save intermediate image const preview = Buffer.from(chunk.image, 'base64'); writeFileSync(`preview_${chunk.step_ix}.png`, preview); } else if (chunk.event_type === 'final') { console.log('Generation complete!'); const finalImage = Buffer.from(chunk.image, 'base64'); writeFileSync('final.png', finalImage); } } ``` -------------------------------- ### Import SDK Constants Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/llms-full.txt Access predefined models, samplers, and presets for consistent configuration. ```typescript import { // Image Models V4_5_FULL, V4_5_CURATED, V4_FULL, V4_CURATED, V3, V3_FURRY, ImageModelValues, // Text Models ERATO, KAYRA, CLIO, TextModelValues, // Samplers K_EULER, K_EULER_ANCESTRAL, K_DPMPP_2S_ANCESTRAL, K_DPMPP_2M, K_DPMPP_SDE, DDIM, SamplerValues, // Size Presets PRESET_MAP, ImageSizePresetValues, // Quality Tags QUALITY_TAGS, // UC Presets UNDESIRED_CONTENT_PRESETS, UCPresetValues, } from "novelai-sdk-unofficial"; ``` -------------------------------- ### new NovelAI(options) Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/classes/NovelAI.md Creates a new instance of the NovelAI client. Requires an API key either passed in the options or set via the NOVELAI_API_KEY environment variable. ```APIDOC ## Constructor ### Description Initializes a new NovelAI client instance. ### Signature `new NovelAI(options: NovelAIOptions)` ### Parameters - **options** (NovelAIOptions) - Optional - Client configuration options. ### Throws - **MissingAPIKeyError** - Thrown if the API key is not provided in options and not found in the environment variables. ``` -------------------------------- ### Perform text completion with OpenAI-compatible parameters Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/classes/OpenAIGeneration.md Demonstrates a basic call to the completion method with a prompt and sampling parameters. ```typescript const response = await client.openai.completion({ prompt: 'The quick brown fox', maxTokens: 50, temperature: 0.7, }); console.log(response.choices[0].text); ``` -------------------------------- ### Generate images with character reference Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/character-reference.md Demonstrates the full workflow of initializing the client, loading a reference image, and generating an image with character reference parameters. ```typescript import { NovelAI } from 'novelai-sdk-unofficial'; import { readFileSync, writeFileSync } from 'fs'; const client = new NovelAI({ apiKey: 'your-api-key' }); // Load reference image const referenceImage = readFileSync('reference.png'); const images = await client.image.generate({ prompt: '1girl, standing in a garden', model: 'nai-diffusion-4-5-full', characterReferences: [ { image: referenceImage, type: 'character', fidelity: 0.75, }, ], }); writeFileSync('output.png', images[0]); ``` -------------------------------- ### Define Coordinate Positions Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/multi-character.md Examples of coordinate pairs for placing characters at specific locations within the image frame. ```typescript // Left side position: [0.2, 0.5] // Center position: [0.5, 0.5] // Right side position: [0.8, 0.5] // Top-left corner position: [0.2, 0.2] ``` -------------------------------- ### Basic Text Streaming Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/streaming.md Initialize the client and iterate over the async generator to output text chunks as they arrive. ```typescript import { NovelAI } from 'novelai-sdk-unofficial'; const client = new NovelAI({ apiKey: 'your-api-key' }); const stream = client.text.generateStream({ input: 'Once upon a time', maxLength: 100, }); for await (const chunk of stream) { process.stdout.write(chunk); } console.log(); // New line at end ``` -------------------------------- ### Erase Metadata Usage Examples Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/functions/eraseMetadata.md Demonstrates how to remove all metadata or specifically the alpha channel metadata from an image file. ```typescript import { eraseMetadata } from 'novelai-ts-sdk'; // Remove all metadata const cleanImage = await eraseMetadata('./image.png', 'both'); // Remove only alpha channel metadata (convert to RGB) const rgbImage = await eraseMetadata('./image.png', 'alpha'); ``` -------------------------------- ### Apply ControlNet Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/llms-full.txt Uses a control image to guide the generation process with specific models like HED or Midas. ```typescript const images = await client.image.generate({ prompt: "1girl", controlnet: { image: readFileSync("control.png"), model: "hed", // hed, midas, fake_scribble, etc. strength: 1.0, }, }); ``` -------------------------------- ### client.openai.completion() Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/openai-compatible.md Generates text completions based on a provided prompt. ```APIDOC ## client.openai.completion() ### Description Generates a text completion based on the input prompt and specified model parameters. ### Parameters - **prompt** (string) - The text prompt to complete. - **model** (string) - The ID of the model to use. - **maxTokens** (number) - Optional. The maximum number of tokens to generate. - **temperature** (number) - Optional. The sampling temperature. ``` -------------------------------- ### Generate an image Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/getting-started.md Initialize the client and generate an image using the specified model and prompt. ```typescript import { NovelAI } from 'novelai-sdk-unofficial'; import { writeFileSync } from 'fs'; // Initialize client const client = new NovelAI({ apiKey: 'your-api-key' }); // Generate an image const images = await client.image.generate({ prompt: '1girl, cat ears, masterpiece, best quality', model: 'nai-diffusion-4-5-full', size: 'portrait', }); // Save the result writeFileSync('output.png', images[0]); ``` -------------------------------- ### Basic ControlNet Usage Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/controlnet.md Initializes the NovelAI client and performs a basic image generation using a pose reference image. ```typescript import { NovelAI } from 'novelai-sdk-unofficial'; import { readFileSync, writeFileSync } from 'fs'; const client = new NovelAI({ apiKey: 'your-api-key' }); const poseReference = readFileSync('pose.png'); const images = await client.image.generate({ prompt: '1girl, standing', model: 'nai-diffusion-4-5-full', controlnet: { images: [ { image: poseReference, infoExtracted: 0.7, strength: 0.6, }, ], strength: 1.0, }, }); writeFileSync('output.png', images[0]); ``` -------------------------------- ### Generate images with NovelAI SDK Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/classes/ImageGeneration.md Demonstrates basic and advanced image generation using the NovelAI client. Ensure the API key is provided during client initialization. ```typescript const client = new NovelAI({ apiKey: 'your-api-key' }); // Simple generation const images = await client.image.generate({ prompt: 'a beautiful landscape', }); // With options const images = await client.image.generate({ prompt: 'a beautiful landscape', model: 'nai-diffusion-4-5-full', size: 'landscape', steps: 28, scale: 5.0, }); ``` -------------------------------- ### Configure Client Options Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/authentication.md Customize client behavior including base URLs and request timeouts. ```typescript const client = new NovelAI({ apiKey: 'your-api-key', // API key imageBase: 'https://...', // Custom image API base URL textBase: 'https://...', // Custom text API base URL timeout: 30000, // Request timeout in ms (default: 30000) }); ``` -------------------------------- ### Implement Live Preview with TypeScript Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/streaming.md Displays intermediate images as they are generated by passing a callback function to the stream handler. ```typescript async function generateWithPreview(prompt: string, onPreview: (img: Buffer) => void) { const stream = client.image.generateStream({ prompt }); for await (const chunk of stream) { if (chunk.event_type === 'intermediate') { const preview = Buffer.from(chunk.image, 'base64'); onPreview(preview); } else if (chunk.event_type === 'final') { return Buffer.from(chunk.image, 'base64'); } } } // Usage await generateWithPreview('1girl', (preview) => { // Update UI with preview image displayImage(preview); }); ``` -------------------------------- ### Streaming with Full Parameters Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/streaming.md Demonstrates passing standard and advanced generation parameters to the stream. ```typescript const stream = client.image.generateStream({ prompt: '1girl, cat ears', model: 'nai-diffusion-4-5-full', size: 'portrait', steps: 28, scale: 5.0, sampler: 'k_euler_ancestral', seed: 12345, // Advanced features also work characterReferences: [...], controlnet: {...}, i2i: {...}, }); ``` -------------------------------- ### NovelAIOptions Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/interfaces/NovelAIOptions.md Configuration object used for initializing the NovelAI client instance. ```APIDOC ## NovelAIOptions ### Description Configuration interface for the NovelAI client initialization. ### Properties - **apiKey** (string) - Optional - API key for authentication. If not provided, the client will attempt to use the NOVELAI_API_KEY environment variable. - **imageBase** (string) - Optional - Base URL for the image generation API. - **textBase** (string) - Optional - Base URL for the text generation API. - **apiBase** (string) - Optional - Base URL for the general API (reserved for future use). - **timeout** (number) - Optional - Request timeout duration in milliseconds. ``` -------------------------------- ### Configure CFG Parameters Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/parameters.md Sets the CFG scale and negative prompt to improve prompt adherence. ```typescript { cfgScale: 1.5, cfgUc: 'boring, repetitive', } ``` -------------------------------- ### Image Generation with Options Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/index.md Configuring specific generation parameters like model, size, steps, and sampler. ```typescript const images = await client.image.generate({ prompt: '1girl, cat ears, masterpiece, best quality', model: 'nai-diffusion-4-5-full', size: 'portrait', steps: 23, scale: 5.0, sampler: 'k_euler_ancestral', seed: 12345, }); ``` -------------------------------- ### client.text.generate(options) Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/index.md Generates a text continuation based on the provided input and configuration parameters. ```APIDOC ## client.text.generate(options) ### Description Generates text continuations using NovelAI's language models based on the provided input string and configuration settings. ### Parameters - **input** (string) - Required - Input text to continue from. - **model** (TextModel) - Optional - Model to use (default: 'llama-3-erato-v1'). - **maxLength** (number) - Optional - Maximum tokens to generate (1-2048, default: 40). - **minLength** (number) - Optional - Minimum tokens to generate (1-2048, default: 1). - **temperature** (number) - Optional - Randomness control (0.1-100, default: 1.0). - **stopSequences** (string[]) - Optional - Sequences that stop generation when encountered. - **banSequences** (string[]) - Optional - Specific text to prevent from appearing in the output. ### Request Example ```typescript const text = await client.text.generate({ input: 'Once upon a time, in a kingdom far away,', model: 'llama-3-erato-v1', maxLength: 80, temperature: 1.0 }); ``` ``` -------------------------------- ### Supported image input formats Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/character-reference.md Demonstrates the different formats accepted for the reference image parameter. ```typescript // Buffer (from file) const image = readFileSync('reference.png'); // Base64 string const image = 'iVBORw0KGgoAAAANSUhEUgAA...'; // ArrayBuffer const response = await fetch('https://example.com/image.png'); const image = await response.arrayBuffer(); ``` -------------------------------- ### client.openai.listModels() Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/openai-compatible.md Retrieves a list of available models for text generation. ```APIDOC ## client.openai.listModels() ### Description Retrieves a list of available models that can be used for text or chat completion tasks. ### Returns - **models** (Array) - A list of model objects containing model IDs. ``` -------------------------------- ### client.image.generate(options) Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/index.md Generates images based on the provided prompt and configuration options. ```APIDOC ## client.image.generate(options) ### Description Generates one or more images using the specified model and generation parameters. The SDK automatically handles quality tag injection and preset mapping. ### Parameters - **prompt** (string) - Required - Text description of the image - **model** (ImageModel) - Optional - Model to use (default: 'nai-diffusion-4-5-full') - **size** (ImageSize) - Optional - Size preset or [width, height] (default: 'portrait') - **negativePrompt** (string) - Optional - What to avoid in the image - **quality** (boolean) - Optional - Auto-append quality tags (default: true) - **ucPreset** (UCPreset) - Optional - Undesired content preset (default: 'light') - **steps** (number) - Optional - Generation steps (1-50) (default: 23) - **scale** (number) - Optional - CFG scale (0-10) (default: 5.0) - **sampler** (Sampler) - Optional - Sampling method (default: 'k_euler_ancestral') - **noiseSchedule** (NoiseSchedule) - Optional - Noise schedule (default: 'karras') - **seed** (number) - Optional - Random seed (0-999999999) - **nSamples** (number) - Optional - Number of images (1-8) (default: 1) - **cfgRescale** (number) - Optional - CFG rescale (0-1) (default: 0) - **varietyBoost** (boolean) - Optional - Enable variety boost (default: false) ### Request Example ```typescript const images = await client.image.generate({ prompt: '1girl, cat ears', model: 'nai-diffusion-4-5-full', size: 'portrait', steps: 23, scale: 5.0, sampler: 'k_euler_ancestral', seed: 12345 }); ``` ### Response - **images** (Buffer[]) - An array of image buffers. ``` -------------------------------- ### Configure Top-A Sampling Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/parameters.md Uses probability ratios for filtering tokens. ```typescript topA: 0 // Disabled (default) topA: 0.1 // Light filtering ``` -------------------------------- ### Set Environment Variable Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/authentication.md Configure the API key using the NOVELAI_API_KEY environment variable. ```bash export NOVELAI_API_KEY=your_api_key_here ``` -------------------------------- ### Mirostat Parameters Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/parameters.md Configuration for the Mirostat adaptive sampling algorithm. ```APIDOC ## Mirostat Parameters ### Description Mirostat is an adaptive sampling algorithm that maintains stable perplexity in output. ### Parameters - **mirostatTau** (number) - Target perplexity. 0 = disabled. - **mirostatLr** (number) - Learning rate (0.0-1.0). ``` -------------------------------- ### Use Position Presets Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/multi-character.md Utilize grid-based presets for easier character placement and coordinate conversion. ```typescript import { positionPresetToCoords } from 'novelai-sdk-unofficial'; // Using preset characters: [ { prompt: '1girl', position: 'B2', }, ] // Convert preset to coordinates const coords = positionPresetToCoords('B2'); // [0.3, 0.3] ``` -------------------------------- ### client.openai.completionStream() Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/openai-compatible.md Streams text completion results as they are generated. ```APIDOC ## client.openai.completionStream() ### Description Returns an async iterable stream of text completion chunks. ### Parameters - **prompt** (string) - The text prompt. - **model** (string) - The model ID. - **maxTokens** (number) - Optional. Max tokens to generate. ``` -------------------------------- ### Configure Mirostat Parameters Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/parameters.md Sets the target perplexity and learning rate for the Mirostat adaptive sampling algorithm. ```typescript { mirostatTau: 5.0, // Target perplexity mirostatLr: 0.1, // Learning rate } ``` -------------------------------- ### Streaming Format Selection Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/streaming.md Configures the streaming format to either SSE or msgpack via the generateStream options. ```typescript const stream = client.image.generateStream({ prompt: '1girl', stream: 'sse', // Default, can be omitted }); ``` ```typescript const stream = client.image.generateStream({ prompt: '1girl', stream: 'msgpack', // Use msgpack format }); for await (const chunk of stream) { // Usage is identical to SSE if (chunk.event_type === 'final') { const image = Buffer.from(chunk.image, 'base64'); } } ``` -------------------------------- ### Augment images using augmentImage Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/classes/ImageGeneration.md Demonstrates how to perform background removal and colorization using the augmentImage method. ```typescript const client = new NovelAI({ apiKey: 'your-api-key' }); // Background removal const images = await client.image.augmentImage({ image: imageBuffer, type: 'bg-removal', width: 1024, height: 1024, }); // Colorization with prompt const colorized = await client.image.augmentImage({ image: sketchBuffer, type: 'colorize', width: 1024, height: 1024, prompt: 'vibrant colors, detailed shading', }); ``` -------------------------------- ### completion(params) Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/classes/OpenAIGeneration.md Generates text completions based on the provided prompt and configuration parameters. ```APIDOC ## completion(params) ### Description Performs text completion using the specified model and parameters. This method is OpenAI-compatible and supports various sampling configurations. ### Parameters - **params** (object) - Required - User-friendly completion parameters: - **prompt** (string | number[] | number[][] | string[]) - Required - The input prompt. - **model** ("llama-3-erato-v1" | "kayra-v1" | "clio-v1") - Optional - The model to use. - **maxTokens** (number) - Optional - Maximum tokens to generate (1-2048). - **temperature** (number) - Optional - Sampling temperature (0-2). - **topP** (number) - Optional - Nucleus sampling threshold (0-1). - **topK** (number) - Optional - Top-K sampling. - **minP** (number) - Optional - Min-P sampling threshold (0-1). - **frequencyPenalty** (number) - Optional - Frequency penalty (-2.0 to 2.0). - **presencePenalty** (number) - Optional - Presence penalty (-2.0 to 2.0). - **seed** (number) - Optional - Random seed for reproducibility. - **stop** (string | string[]) - Optional - Stop sequences. - **stream** (boolean) - Optional - Enable streaming response. - **n** (number) - Optional - Number of completions to generate. - **bestOf** (number) - Optional - Number of completions to generate server-side and return the best. - **echo** (boolean) - Optional - Echo back the prompt. - **logprobs** (number) - Optional - Number of log probabilities to return. - **logitBias** (Record) - Optional - Logit bias for specific tokens. - **suffix** (string) - Optional - Suffix to append. - **user** (string) - Optional - User identifier. - **unifiedCubic** (number) - Optional - Unified cubic sampling parameter. - **unifiedIncreaseLinearWithEntropy** (number) - Optional - Unified increase linear with entropy parameter. - **unifiedLinear** (number) - Optional - Unified linear sampling parameter. - **unifiedQuadratic** (number) - Optional - Unified quadratic sampling parameter. ### Returns - **Promise** - A promise that resolves to the completion response. ### Throws - **ZodError** - Thrown if parameters fail validation. ### Example ```typescript const response = await client.openai.completion({ prompt: 'The quick brown fox', maxTokens: 50, temperature: 0.7, }); console.log(response.choices[0].text); ``` ``` -------------------------------- ### Perform Text Completion Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/text-generation/openai-compatible.md Initializes the client and retrieves a model ID before requesting a text completion. ```typescript import { NovelAI } from 'novelai-sdk-unofficial'; const client = new NovelAI({ apiKey: 'your-api-key' }); // First get available models const models = await client.openai.listModels(); const model = models[0].id; // e.g. 'glm-4-6' const response = await client.openai.completion({ prompt: 'Once upon a time, in a kingdom far away,', model, maxTokens: 100, temperature: 0.7, }); console.log(response.choices[0].text); ``` -------------------------------- ### Stream text generation with cancellation Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/classes/TextGeneration.md Demonstrates how to initiate a streaming text generation request and handle cancellation using an AbortController. ```typescript const client = new NovelAI({ apiKey: 'your-api-key' }); const controller = new AbortController(); const stream = client.text.generateStream({ input: 'Once upon a time', temperature: 1.0, maxLength: 100, }, controller.signal); // Cancel after 5 seconds setTimeout(() => controller.abort(), 5000); try { for await (const chunk of stream) { process.stdout.write(chunk); } } catch (error) { if (error.name === 'AbortError') { console.log('Generation cancelled'); } } ``` -------------------------------- ### List available models with TypeScript Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/api/classes/OpenAIGeneration.md Retrieves and iterates through the list of models supported by the client. ```typescript const models = await client.openai.listModels(); for (const model of models) { console.log(`${model.id} (owned by ${model.owned_by})`); } ``` -------------------------------- ### Applying UC Presets Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/index.md Use predefined negative prompt presets to filter undesired content. ```typescript const images = await client.image.generate({ prompt: '1girl', ucPreset: 'strong', }); ``` -------------------------------- ### Augment Image with TypeScript Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/director-tools.md Demonstrates basic image augmentation using the high-level client. Ensure width and height match the input image dimensions to avoid 500 errors. ```typescript import { NovelAI } from 'novelai-sdk-unofficial'; import { readFileSync, writeFileSync } from 'fs'; const client = new NovelAI({ apiKey: 'your-api-key' }); // Background removal const images = await client.image.augmentImage({ image: readFileSync('input.png'), type: 'bg-removal', width: 1024, height: 1024, }); writeFileSync('output.png', images[0]); ``` ```typescript const colorized = await client.image.augmentImage({ image: readFileSync('sketch.png'), type: 'colorize', width: 1024, height: 1024, prompt: 'vibrant colors, detailed shading', }); ``` -------------------------------- ### Handle SDK Errors in TypeScript Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/error-handling.md Demonstrates catching and categorizing specific SDK error classes to provide meaningful feedback. ```typescript import { NovelAI, NovelAIError, MissingAPIKeyError, AuthenticationError, InvalidRequestError, RateLimitError, ServerError, NetworkError, } from 'novelai-sdk-unofficial'; async function generateImage(prompt: string) { try { const client = new NovelAI(); const images = await client.image.generate({ prompt }); return images[0]; } catch (error) { if (error instanceof MissingAPIKeyError) { throw new Error('Configuration error: API key not set'); } if (error instanceof AuthenticationError) { throw new Error('Authentication failed: Check API key'); } if (error instanceof InvalidRequestError) { throw new Error(`Invalid request: ${error.message}`); } if (error instanceof RateLimitError) { // Could implement retry with backoff throw new Error('Rate limited: Try again later'); } if (error instanceof ServerError) { throw new Error('Server error: Service temporarily unavailable'); } if (error instanceof NetworkError) { throw new Error('Network error: Check connection'); } if (error instanceof NovelAIError) { throw new Error(`SDK error: ${error.message}`); } throw error; // Re-throw unknown errors } } ``` -------------------------------- ### Generate text with full parameter configuration Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/llms-full.txt Configures advanced sampling, repetition penalties, and sequence constraints for fine-tuned text generation. ```typescript const text = await client.text.generate({ // Required input: "Once upon a time", // Model model: "llama-3-erato-v1", // ERATO (default), KAYRA, CLIO // Length Control maxLength: 40, // 1-2048 (default: 40) minLength: 1, // 1-2048 (default: 1) // Sampling Parameters temperature: 1.0, // 0.1-100 (default: 1.0) topP: 0.95, // Top-P sampling topK: 50, // Top-K sampling topA: 0, // Top-A sampling typicalP: 1, // Typical P sampling tailFreeSampling: 1, // TFS // Repetition Control repetitionPenalty: 1.1, repetitionPenaltyRange: 2048, repetitionPenaltySlope: 0, repetitionPenaltyFrequency: 0, repetitionPenaltyPresence: 0, // Sequence Control stopSequences: ["\n\n", "THE END"], banSequences: ["violence", "explicit"], // Advanced orderTokens: [...], // Token order for sampling logitBias: {...}, // Logit bias }); ``` -------------------------------- ### Perform Text Completion Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/llms-full.txt Generates text based on a provided prompt string. ```typescript const response = await client.openai.completion({ prompt: "The quick brown fox", model: "glm-4-6", maxTokens: 100, temperature: 0.7, }); console.log(response.choices[0].text); ``` -------------------------------- ### Access Low-Level API Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/llms.txt Use the APIClient for direct REST API interactions. Requires an API key for initialization. ```typescript import { APIClient } from "novelai-sdk-unofficial/api"; const api = new APIClient({ apiKey: "your-api-key" }); // Direct API calls const response = await api.image.generate({ input: "1girl", model: "nai-diffusion-4-5-full", parameters: { /* raw API parameters */ }, }); ``` -------------------------------- ### suggestTags(options) Source: https://github.com/yuanhuakk/novelai-sdk-unofficial/blob/master/docs/en/image-generation/director-tools.md Retrieves tag suggestions based on an incomplete tag query prompt. ```APIDOC ## suggestTags(options) ### Description Fetches tag suggestions for a given prompt, optionally specifying the model and language. ### Parameters - **prompt** (string) - Required - Incomplete tag query - **model** (ImageModel) - Optional - Image model (default: 'nai-diffusion-4-5-full') - **lang** ('en' | 'jp') - Optional - Language (default: 'en') ### Return Value - **tags** (Array) - Array of tag suggestion objects containing tag, confidence, and count. ```