@aituber-onair/core
v0.26.34
Published
Core library for AITuber OnAir providing voice synthesis and chat processing
Maintainers
Readme
AITuber OnAir Core
Chat 0.73.0 and Voice 0.31.0
Core 0.26.34 uses published Chat 0.73.0 and Voice 0.31.0.
Gemini 4 Neon is an explicit, paid, image-capable option with streaming and
tools on two routes. Native Gemini (gemini-4-neon, MODEL_GEMINI_4_NEON)
exposes low (package default), medium, and high; OpenRouter
(google/gemini-4-neon, MODEL_GOOGLE_GEMINI_4_NEON) also exposes xhigh.
Native Gemini 4 routes omit xhigh when its REST enum is undocumented:
currently Hydrogen and Neon. Neon returns signed model
history. Core forwards it unchanged within one tool-call loop, but its chat log
keeps only the visible reply text, so later turns and saved logs carry no
signatures. To keep signed history across turns, call Chat directly and append
the returned assistant_message.
OpenRouter also adds five explicit image-capable routes with tools and
streaming: tencent/hy4-flash (no reasoning control), qwen/qwen4-max
(default none), openai/gpt-6.2-sol and openai/gpt-6.2-astra (default
low), and thinkingmachines/inkling-2-mini (default none). Provider
default models are unchanged.
OpenRouter TTS adds Qwen3 TTS 1.7B (qwen/qwen3-tts-1.7b) as an explicit
model: one-shot MP3 with its published preset voices only, such as ono_anna
for Japanese. Speed, instructions, and reference audio are not exposed.
Native OpenAI GPT-6.2 Sol (gpt-6.2-sol) and GPT-6.2 Astra (gpt-6.2-astra)
are explicit image-capable options. Reasoning starts at low; only low and
medium are exposed, and other saved levels are normalized to that range.
Responses is the default endpoint and is required for tools and MCP. Tool-free
Chat Completions remains available; custom endpoints with tools fail before
sending. Mistral-hosted DeepSeek V4.1 Flash 1017 (deepseek-v4-1-flash-1017)
is an explicit public-preview option with image input, streaming, and tools;
no reasoning control is sent because none is documented. Mistral tool calls
now continue correctly in follow-up requests. Provider defaults are unchanged.
Gemini 4 models (currently Argon, Carbon, Hydrogen, and Neon) are explicit,
image-capable choices with mandatory thinking. Select low (package default),
medium, or high; provider default models are unchanged.
Hydrogen (gemini-4-hydrogen, OpenRouter google/gemini-4-hydrogen) is
available on the rate-limited direct Gemini API free tier; its OpenRouter route
is paid. Google defaults Hydrogen to high. Its additional xhigh level is
not exposed because the GenerateContent REST enum spelling is undocumented.
Argon and Carbon require the paid tier and default to medium upstream.
Carbon uses more thinking tokens than Argon, with higher latency and token use.
Thinking counts toward output limits. All Gemini 4 models keep an implicit 32,768-token floor, including on OpenRouter. For direct Gemini calls, explicit limits are capped per model: Argon/Carbon at 32,768 non-streaming / 65,536 streaming; Hydrogen and Neon at 65,536 in both modes. Smaller explicit limits are preserved. Request short replies in the prompt. Long decode and automatic continuation are not implemented.
New OpenRouter text/image routes support tools and streaming without changing the provider default:
| Model ID | Reasoning efforts (package default) |
| --- | --- |
| meta/muse-ember | max, xhigh, high, medium, low, minimal (minimal) |
| thinkingmachines/inkling-2-small | max, high, medium, low, minimal (minimal) |
| nex-agi/nex-n2.6 | high, medium (medium); thinking cannot be disabled |
| inclusionai/ling-3.2-flash:free | No effort selector; provider default |
These routes expose no reasoning token-budget control. Ling uses its exact
:free ID and retains includeReasoning display control. Audio, video, and
file inputs are not added. See the Chat documentation.
Claude Fable 5.2
(claude-fable-5-2, OpenRouter anthropic/claude-fable-5.2), Gemini 4 Argon
(gemini-4-argon, OpenRouter google/gemini-4-argon), and Mistral-hosted
GLM-5.3 Flash (zai-glm-5-3-flash) are explicit image-capable options.
Fable and Argon support low/medium/high effort; Fable also supports xhigh/max.
Mistral GLM Flash supports low/high/max. All three start at low for responsive
chat. Fable keeps automatic tool selection and requires preserving signed
thinking with its preceding history unchanged. Gemini 4 output budgets follow the per-model limits above.
OpenRouter also adds the paid image-capable options ~openai/gpt-luna-latest,
~openai/gpt-terra-latest, ~deepseek/deepseek-flash-latest,
~z-ai/glm-flash-latest, xiaomi/mimo-v2.6-pro, tencent/hy4,
cohere/command-a-plus, bytedance-seed/seed-2-1-turbo,
nvidia/nemotron-3.5-super-vl, and sakana/sakana-namazu. The Nemotron free
route remains separate. Namazu omits output-token limits; responseLength is
not a hard cap for that route. Unsupported reasoning levels are not exposed.
New configurations use the current supported lists; DeepSeek now starts at
deepseek-flash for text and vision. Newly retired OpenAI GPT-4o/GPT-4.1,
Gemini 2.5 Pro/Flash, DeepSeek V4 Flash/Vision Exp, Mistral Medium 3.5, and
OpenRouter Mercury 2.5/3, Kimi K2.5, and GPT Latest are excluded from new
selection. Their exported constants and saved IDs remain compatible. The
OpenRouter picker hides deprecated catalog rows while retaining a saved
selection. Other provider defaults are unchanged.

AITuber OnAir Core is a TypeScript library developed to provide functionality for the AITuber OnAir web service, designed for AI-based virtual streaming (AITuber).
While it is primarily intended to provide functionality for AITuber OnAir, this project is published as open-source software and is available as an npm package under the MIT License.
It specializes in generating response text and audio from text or image inputs, and is designed to easily integrate with other parts of an application (storage, YouTube integration, avatar control, etc.).
Chat and Voice model updates
Core exposes the models and capability helpers from Chat 0.65.0 and the speech engines, option types, and endpoint helpers from Voice 0.28.0. Existing provider defaults are unchanged.
Chat 0.65.0 identifies DeepSeek-V4.1-Flash-1017 through the existing rolling
deepseek-flashID (MODEL_DEEPSEEK_FLASH). It supports text/image input and streaming; the ID follows provider updates rather than pinning this revision. Thinking stays disabled by default and is required to be disabled for tool calling. See the DeepSeek API guide.Voice 0.27.0 / 0.28.0 add explicit Fish Audio
drama-3-preview/drama-3choices to all ten React TTS settings examples. These use the existing one-shot, single-speaker HTTP path;s2-proremains the default and the preview model's availability may change.Voice 0.27.0 also fixes empty-audio completion and Piper Plus multilingual model inputs. Piper Plus still defaults to Japanese;
setLanguage()is an engine-level method, not a CorevoiceOptionsor example setting.Chat 0.64.0 adds Mistral Large 4 (
mistralai/mistral-large-4-0) as an explicit OpenRouter public preview after Pareto, with text and image input. Its reasoning defaults tonone; explicithighis preserved. The model selected when switching to OpenRouter is unchanged.Chat 0.63.0 adds Claude Haiku 5.5 (
claude-haiku-5-5) as an explicit option appended to the Claude model list. Avatar examples that list Claude models newest first (Inochi2D, Live2D, Purupuru, and VRM) now select Haiku 5.5 when switching to Claude; the other examples keep their first model. Claude models with adjustable effort now default tolowand send it when no effort is set; previously requests ran at the API'shighdefault. Setreasoning_effortexplicitly to use another level.Chat 0.62.0 adds explicit OpenRouter options: Ling 3.1 Flash (
inclusionai/ling-3.1-flash), Solar Pro 4 (upstage/solar-pro4), Solar Mini4 (upstage/solar-mini4), MiMo V2.6 Flash (xiaomi/mimo-v2.6-flash), Apodex 1.1 Mini Free (apodex/apodex-1.1-mini:free), and Pareto 26.10 Preview (unbiased/pareto-26.10-preview). MiMo and Pareto accept images; the others are text-only.The OpenRouter default model is unchanged, but
AITuberOnAirCore.getSupportedModels('openrouter')now lists Ling 3.1 Flash first. Avatar examples select the first listed model when switching to OpenRouter, so they now pick Ling 3.1 Flash.Voice 0.26.0 adds an
openRouterTTS engine for the public-previewmicrosoft/mai-voice-2.1andmicrosoft/mai-voice-2.1-flashmodels. See OpenRouter TTS setup.Native models: GPT-6 Astra, Sol, and Luna; Claude Fable 5.1/5.2, Opus 5.5, and Sonnet 5.5; DeepSeek V4.1 Flash 1017; and Grok 4.7.
OpenAI-compatible endpoint helpers:
resolveOpenAICompatibleEndpoint,listOpenAICompatibleModels,testOpenAICompatibleConnection, andOPENAI_COMPATIBLE_LOCAL_PRESETS(Ollama, LM Studio, llama.cpp, vLLM). See the local LLM guide.OpenAI-compatible speech helpers:
resolveOpenAICompatibleSpeechEndpoint,listOpenAICompatibleSpeechModels,listOpenAICompatibleSpeechVoices,getOpenAICompatibleSpeechServerInfo, andtestOpenAICompatibleSpeechfor local TTS servers. See the local TTS guide.OpenRouter: GPT-6 Astra / Astra Pro, Claude Fable 5.1/5.2, DeepSeek V4.1 Flash, Gemini 3.8 Flash, Ling 3.0 Flash VL (free), Nex N2.5 Mini / Pro (free), Qwen3.8 Max 0902, and Muse Spark 1.3.
Models with required reasoning use their supported effort values. Native Astra uses the Responses API and starts at
low; useisOpenAIReasoningModelandgetDefaultReasoningEffortForOpenAIModelfor the expanded OpenAI family. Existing GPT-5 helpers remain available.Native DeepSeek tool calling requires non-thinking mode (
reasoning_effort: 'none'). OpenRouter reasoning and vision support follow the selected model's Chat capability metadata.Gemini TTS adds
gemini-3.8-flash-lite-ttsandgemini-3.8-flash-ttsto every React example. Existing TTS defaults remain unchanged. On 3.8 models, the style prompt is sent as speech metadata and language code is unavailable.Inworld supports
inworld-tts-2-flashin addition to the defaultinworld-tts-2. Models without delivery-mode support, currently Flash, omit that option and disable its control in all React examples. Voice-list selection, persisted settings, and other audio options remain available.
The React basic example lists the new models explicitly. Avatar examples load the supported model list from Core and apply the Casual preset to supported OpenAI reasoning models. Node examples pass the model and provider options through to Core.
- New explicit Chat options include native GPT-6.1 Sol and Z.ai GLM-5.3
FlashX, Mistral-hosted
zai-glm-5-3, and OpenRouter GPT-6.1 Sol / GPT-6 Sol / Luna, Claude Sonnet / Opus 5.5, Grok 4.7, GLM-5.3 FlashX,nvidia/nemotron-3.5-lightning,qwen/qwen3.8-27b, andqwen/qwen3.8-omni-flash. - Models without documented reasoning effort or token-budget controls omit
those fields.
OPENROUTER_MODELS_WITHOUT_REASONING_BUDGETidentifies the three new Nemotron/Qwen options; the two Qwen models support images, while Nemotron and Mistral GLM-5.3 are text-only. Mistral GLM-5.3 requires an eligible subscription tier and has no adjustable reasoning effort. - GPT-6.1 Sol uses
lowreasoning for the casual preset. Responses is the default and is required for tools; tool-free Chat Completions supportslow,medium,high,xhigh, andmax. Z.ai GLM-5.3 FlashX always reasons, supports images, and requires a Model API key. Native Z.ai browser calls may fail because of provider CORS restrictions. - Voice options include ElevenLabs
eleven_v4(Stability and Similarity; no Style, Speed, or Speaker Boost), Cartesiasonic-3.6andsonic-3.6-2026-08-27(default remainssonic-3.5), Deepgram Flux, and the opt-in Gradiumgradium-tts-betamodel throughgradiumModel.
For endpoint details and limitations, see the Chat README and Voice README.
Deepgram Flux setup
Use engineType: 'deepgram', an API key, and an English or Japanese Flux voice ID
such as flux-haley-en. Core re-exports DeepgramEngine, its option types,
and the speech/catalog URL constants. getVoiceEngineVoiceList('deepgram')
lists English and Japanese voices from the public v2 catalog without an API key.
deepgramSpeed accepts 0.5–1.5 in 0.05 steps. This integration returns a
complete MP3 from POST /v2/speak; it does not use Aura or WebSocket speech.
See the Deepgram batch guide.
All ten React TTS examples use /api/deepgram/v2/speak and
/api/deepgram/v2/models via Vite dev/preview proxies. Production apps need
equivalent authenticated backend routes with API keys kept server-side.
Avatar settings allow custom TTS/catalog URLs. Voice-list refreshes preserve
the selected voice and the previous list on empty or failed responses;
Haley remains selectable. Gradium settings default to production and reset
to production when switching back to Gradium.
OpenRouter TTS setup
Use engineType: 'openRouter', an OpenRouter API key, an explicit
openRouterModel (microsoft/mai-voice-2.1 or
microsoft/mai-voice-2.1-flash), and a full voice ID from that model's
catalog, such as en-US-Harper:MAI-Voice-2.1. Core re-exports
OpenRouterEngine, OpenRouterTtsModel, the option types, and
OPENROUTER_TTS_API_URL / OPENROUTER_MODELS_API_URL.
getVoiceEngineVoiceList('openRouter', { openRouterModel }) returns only
the selected model's voices. Both models are public previews without an SLA
and are not recommended for production. Catalogs checked on October 1, 2026
had no Japanese voices.
All ten React TTS examples add an OpenRouter engine. No preview model is selected automatically. After a model is chosen, its voices load and an English voice is selected; users can pick another. The TTS API key field shares the OpenRouter key from the LLM settings, so users enter it only once. The examples call OpenRouter directly from the browser, so the API key is visible to the page; deploy shared apps behind your own backend. Direct access depends on the provider's CORS policy.
Table of Contents
- Overview
- Installation
- Main Features
- Basic Usage
- Tool System
- Function Calling Differences
- Using MCP
- Using OpenAI Remote MCP
- Using Claude MCP Connector
- Response Length Control
- Architecture
- Main Components
- Event System
- Supported Speech Engines
- AI Provider System
- Agent SDK providers (Codex / Claude Agent SDK / Copilot)
- Memory & Persistence
- Examples
- Integration with Existing Applications
- Testing & Development
- Migration Guide for Memory Events
Overview
AITuberOnAirCore is the central module that provides core features for AI tubers. It forms the core of the AITuber OnAir application. It encapsulates complex AI response generation, conversation context management, speech synthesis, and more, making these features available through a simple API.
Installation
You can install AITuber OnAir Core using npm:
npm install @aituber-onair/coreOr using yarn:
yarn add @aituber-onair/coreOr using pnpm:
pnpm install @aituber-onair/coreMain Features
- AI Response Generation from Text Input
Generates natural responses to user text input using OpenAI GPT models. - AI Response Generation from Images (Vision)
Generates AI responses based on recognized content from images (e.g., live broadcast screens). - Conversation Context Management & Memory
Maintains long-running conversation context via short-, mid-, and long-term memory systems. - Text-to-Speech Conversion
Compatible with multiple speech engines (VOICEVOX, VoicePeak, AivisSpeech, Aivis Cloud, OpenAI TTS, Gemini TTS, xAI, Unreal Speech, ElevenLabs, Inworld, Gradium, Piper Plus, Web Speech API). - Emotion Extraction & Processing
Extracts emotion from AI responses and utilizes it for speech synthesis or avatar expressions. - Event-Driven Architecture
Emits events at each stage of processing to simplify external integrations. - Customizable Prompts
Allows customization of prompts for vision processing and conversation summarization. - Pluggable Persistence
Memory features can be persisted via LocalStorage, IndexedDB, or other customizable methods. - Function Calling with Tools Support
Enables AI to use tools for performing actions beyond text generation, such as calculations, API calls, or data retrieval.
Basic Usage
Below is a simplified example of how to use AITuber OnAir Core:
import {
AITuberOnAirCore,
AITuberOnAirCoreEvent,
AITuberOnAirCoreOptions
} from '@aituber-onair/core';
// 1. Define options
const options: AITuberOnAirCoreOptions = {
chatProvider: 'openai', // Optional. If omitted, the default OpenAI will be used.
apiKey: 'YOUR_API_KEY',
chatOptions: {
systemPrompt: 'You are an AI streamer. Act as a cheerful and friendly live broadcaster.',
visionSystemPrompt: 'Please comment like a streamer on what is shown on screen.',
visionPrompt: 'Look at the broadcast screen and provide commentary suited to the situation.',
memoryNote: 'This is a summary of past conversations. Please refer to it appropriately to continue the conversation.',
// Response length control
maxTokens: 150, // Direct token limit for text chat
responseLength: 'medium', // Or use preset: 'veryShort', 'short', 'medium', 'long'
visionMaxTokens: 200, // Direct token limit for vision processing
visionResponseLength: 'long', // Or use preset for vision responses
},
// OpenAI Default model is gpt-4o-mini
// You can specify different models for text chat and vision processing
// model: 'o3-mini', // Lightweight model for text chat (no vision support)
// visionModel: 'gpt-4o', // Model capable of image processing
memoryOptions: {
enableSummarization: true,
shortTermDuration: 60 * 1000, // 1 minute
midTermDuration: 4 * 60 * 1000, // 4 minutes
longTermDuration: 9 * 60 * 1000, // 9 minutes
maxMessagesBeforeSummarization: 20,
maxSummaryLength: 256,
// You can specify a custom summarization prompt
summaryPromptTemplate: 'Please summarize the following conversation in under {maxLength} characters. Include important points.'
},
voiceOptions: {
engineType: 'voicevox', // Speech engine type
speaker: '1', // Speaker ID
apiKey: 'ENGINE_SPECIFIC_API_KEY', // If required (e.g., OpenAI, MiniMax)
groupId: 'YOUR_GROUP_ID', // If using MiniMax
endpoint: 'global', // If using MiniMax: 'global' or 'china'
onComplete: () => console.log('Voice playback completed'),
// Custom API endpoint URLs (optional)
voicevoxApiUrl: 'http://custom-voicevox-server:50021',
voicepeakApiUrl: 'http://custom-voicepeak-server:20202',
aivisSpeechApiUrl: 'http://custom-aivis-server:10101',
},
debug: true, // Enable debug output
};
// 2. Create an instance
const aituber = new AITuberOnAirCore(options);
// 3. Set up event listeners
aituber.on(AITuberOnAirCoreEvent.PROCESSING_START, () => {
console.log('Processing started');
});
aituber.on(AITuberOnAirCoreEvent.ASSISTANT_PARTIAL, (text) => {
// Receive streaming responses and display in UI
console.log(`Partial response: ${text}`);
});
aituber.on(AITuberOnAirCoreEvent.ASSISTANT_RESPONSE, (data) => {
const { message, screenplay, rawText } = data;
console.log(`Complete response: ${message.content}`);
console.log(`Original text with emotion tags: ${rawText}`);
if (screenplay.emotion) {
console.log(`Emotion: ${screenplay.emotion}`);
}
});
aituber.on(AITuberOnAirCoreEvent.SPEECH_START, (data) => {
// The SPEECH_START event includes the screenplay object and rawText
if (data && data.screenplay) {
console.log(`Speech playback started: emotion = ${data.screenplay.emotion || 'neutral'}`);
console.log(`Original text with emotion tags: ${data.rawText}`);
} else {
console.log('Speech playback started');
}
});
aituber.on(AITuberOnAirCoreEvent.SPEECH_END, () => {
console.log('Speech playback finished');
});
aituber.on(AITuberOnAirCoreEvent.TOOL_USE, (toolBlock) =>
console.log(`Tool use -> ${toolBlock.name}`, toolBlock.input));
aituber.on(AITuberOnAirCoreEvent.TOOL_RESULT, (resultBlock) =>
console.log(`Tool result ->`, resultBlock.content));
aituber.on(AITuberOnAirCoreEvent.ERROR, (error) => {
console.error('Error occurred:', error);
});
// Memory and chat history related events
aituber.on(AITuberOnAirCoreEvent.CHAT_HISTORY_SET, (messages) =>
console.log('Chat history set:', messages.length));
aituber.on(AITuberOnAirCoreEvent.CHAT_HISTORY_CLEARED, () =>
console.log('Chat history cleared'));
aituber.on(AITuberOnAirCoreEvent.MEMORY_CREATED, (memory) =>
console.log(`New memory created: ${memory.type}`));
aituber.on(AITuberOnAirCoreEvent.MEMORY_REMOVED, (memoryIds) =>
console.log('Memory removed:', memoryIds));
aituber.on(AITuberOnAirCoreEvent.MEMORY_LOADED, (memories) =>
console.log('Memory loaded:', memories.length));
aituber.on(AITuberOnAirCoreEvent.MEMORY_SAVED, (memories) =>
console.log('Memory saved:', memories.length));
// 4. Process text input
await aituber.processChat('Hello, how is the weather today?');
// 5. Clear event listeners if needed
aituber.offAll();Tool System
AITuber OnAir Core includes a powerful tool system that allows AI to perform actions beyond text generation, such as retrieving data or making calculations. This is particularly useful for creating interactive AITuber experiences.
Tool Definition Structure
Tools are defined using the ToolDefinition interface, which conforms to the function calling specification used by LLM providers:
type ToolDefinition = {
name: string; // The name of the tool
description?: string; // Optional description of what the tool does
parameters: {
type: 'object'; // Must be 'object' (strictly typed)
properties?: Record<string, {
type?: string; // Parameter type (e.g. 'string', 'integer')
description?: string; // Parameter description
enum?: any[]; // For enumerated values
items?: any; // For array types
required?: string[]; // Required nested properties
[key: string]: any; // Other JSON Schema properties
}>;
required?: string[]; // Names of required parameters
[key: string]: any; // Other JSON Schema properties
};
config?: { timeoutMs?: number }; // Optional configuration
};Note that the parameters.type property is strictly typed as 'object' to conform to function calling standards used by LLM providers.
Registering and Using Tools
Tools are registered when initializing AITuberOnAirCore:
// Define a tool
const randomIntTool: ToolDefinition = {
name: 'randomInt',
description: 'Return a random integer from 0 to (max - 1)',
parameters: {
type: 'object', // This must be 'object'
properties: {
max: {
type: 'integer',
description: 'Upper bound (exclusive). Defaults to 100.',
minimum: 1,
},
},
},
};
// Create a handler for the tool
async function randomIntHandler({ max = 100 }: { max?: number }) {
return Math.floor(Math.random() * max).toString();
}
// Register the tool with AITuberOnAirCore
const aituber = new AITuberOnAirCore({
// ... other options ...
tools: [{ definition: randomIntTool, handler: randomIntHandler }],
});
// Set up event listeners for tool use
aituber.on(AITuberOnAirCoreEvent.TOOL_USE, (toolBlock) =>
console.log(`Tool use -> ${toolBlock.name}`, toolBlock.input));
aituber.on(AITuberOnAirCoreEvent.TOOL_RESULT, (resultBlock) =>
console.log(`Tool result ->`, resultBlock.content));Tool Iteration Control
You can limit the number of tool call iterations using the maxHops option:
const aituber = new AITuberOnAirCore({
// ... other options ...
chatOptions: {
systemPrompt: 'Your system prompt',
// ... other chat options ...
maxHops: 10, // Maximum number of tool call iterations (default: 6)
},
tools: [/* your tools */],
});Function Calling Differences
AITuber OnAir Core supports major AI providers including OpenAI, Claude, Gemini, and Z.ai. Each provider has a different implementation of function calling (tool invocation). These differences are abstracted by AITuber OnAir Core, allowing developers to use a unified interface, but understanding the background is important.
Note: This explanation covers the API versions as of May 2025. APIs are frequently updated, so please refer to the official documentation for the latest information.
OpenAI Function Calling Implementation
OpenAI's function calling has the following characteristics:
- Tool Definition Format: Uses an array of
functions(deprecated) ortools(recommended from 2023-12-01) based on JSON Schema - Response Format: Returns a response object containing a
tool_callsarray when using tools - Tool Result Submission: Tool results are sent as messages with
role: 'tool' - Multiple Tool Support: Can call multiple tools simultaneously (Parallel function calling)
// OpenAI tool definition example (minimal form)
const tools = [
{
type: "function",
function: {
name: "randomInt",
description: "Return a random integer from 0 to (max - 1)",
parameters: {
type: "object",
properties: {
max: {
type: "integer",
description: "Upper bound (exclusive). Defaults to 100."
}
},
required: [] // Explicitly specifying even when empty improves schema validity
}
}
}
];
// OpenAI tool call response example
{
role: "assistant",
content: null,
tool_calls: [
{
id: "call_abc123",
type: "function",
function: {
name: "randomInt",
arguments: "{\"max\":10}" // Note that this is returned as a stringified JSON
}
}
]
}
// Multiple tool calls example (Parallel function calling)
{
role: "assistant",
content: null,
tool_calls: [
{
id: "call_abc123",
type: "function",
function: {
name: "randomInt",
arguments: "{\"max\":10}"
}
},
{
id: "call_def456",
type: "function",
function: {
name: "getCurrentTime",
arguments: "{\"timezone\":\"JST\"}"
}
}
]
}
// OpenAI tool result submission example
{
role: "tool",
tool_call_id: "call_abc123",
content: "7"
}When handling OpenAI's function calling, AITuber OnAir Core converts tool definitions to OpenAI's format and processes tool calls and results. The transformToolToFunction method in the class performs this conversion.
Claude's Tool Calling Implementation
Claude's tool calling has the following characteristics:
- Tool Definition Format: Specifies
name,description, andinput_schemafor each tool in thetoolsarray - Response Format: Returned as a special block with
type: 'tool_use'and stops withstop_reason: 'tool_use' - Tool Result Submission: Included in user role messages as
type: 'tool_result' - Special Streaming Handling: Requires special logic to handle tool calls in streaming responses
// Claude tool definition example
const tools = [
{
name: "randomInt",
description: "Return a random integer from 0 to (max - 1)",
input_schema: {
type: "object",
properties: {
max: {
type: "integer",
description: "Upper bound (exclusive). Defaults to 100."
}
}
}
}
];
// Claude tool call response example
{
id: "msg_abc123",
model: "claude-haiku-4-5-20251001",
role: "assistant",
content: [
{ type: "text", text: "I'll generate a random number for you." },
{
type: "tool_use",
id: "tu_abc123",
name: "randomInt",
input: { max: 10 }
}
],
stop_reason: "tool_use"
}
// Example with only tool use, no text content
{
id: "msg_xyz789",
model: "claude-haiku-4-5-20251001",
role: "assistant",
content: [
{
type: "tool_use",
id: "tu_xyz789",
name: "randomInt",
input: { max: 100 }
}
],
stop_reason: "tool_use"
}
// Claude tool result submission example
{
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "tu_abc123",
content: "7"
}
]
}When handling Claude's tool calls, AITuber OnAir Core processes Claude's unique format and abstracts the complex processing, especially during streaming responses. Special handling is included in the runToolLoop method.
Gemini's Tool Calling Implementation
Gemini's tool calling has the following characteristics:
- Tool Definition Format: Describes definitions in
functionDeclarationswithin thetoolsarray - Response Format: Returned as content objects containing
functionCallparts - Tool Result Submission: Sent as
functionResponseobjects included in content parts - Compositional Calling: Supports Compositional Function Calling
// Gemini tool definition example
const tools = [
{
functionDeclarations: [
{
name: "randomInt",
description: "Return a random integer from 0 to (max - 1)",
parameters: {
type: "object",
properties: {
max: {
type: "integer",
description: "Upper bound (exclusive). Defaults to 100."
}
}
}
}
]
}
];
// Gemini tool call response example (note the deep structure)
{
candidates: [
{
content: {
parts: [
{
functionCall: {
name: "randomInt",
args: {
max: 10
}
}
}
]
}
}
]
}
// Compositional function calling example
{
candidates: [
{
content: {
parts: [
{
functionCall: {
name: "randomInt",
args: {
max: 10
}
}
},
{
functionCall: {
name: "formatResult",
args: {
prefix: "Random number:",
value: "<function_response:randomInt>"
}
}
}
]
}
}
]
}
// Gemini tool result submission example
// Include functionResponse directly in content parts (SDK automatically sets the role)
{
parts: [
{
functionResponse: {
name: "randomInt",
response: {
value: "7"
}
}
}
]
}
// When directly calling REST API, you might include role like this
{
role: "function",
parts: [
{
functionResponse: {
name: "randomInt",
response: {
value: "7"
}
}
}
]
}When handling Gemini's tool calls, AITuber OnAir Core processes Gemini's complex response structure and tool result format. Special logic is needed to convert tool responses to the appropriate JSON format.
Streaming Implementation Differences
Each provider also has differences in how tool calls are processed during streaming responses:
OpenAI:
- During streaming, delta updates are sent as
delta.tool_calls - Requires accumulation to reconstruct complete tool call data
- During streaming, delta updates are sent as
Claude:
- SSE streaming uses special event types
content_block_deltaandcontent_block_stop - Sends
stop_reason: "tool_use"when a tool call is completed - Requires a special parser to detect tool calls
- SSE streaming uses special event types
Gemini:
- During streaming,
functionCallmay be split across chunks - Requires buffering to reconstruct complete JSON structures
- During streaming,
AITuber OnAir Core abstracts these streaming processing differences, allowing you to process tool calls and results with the same interface regardless of which provider you use.
Key Differences and Abstraction Between Providers
AITuber OnAir Core abstracts the differences between these three providers and provides a unified interface:
Input Format Differences:
- Each provider uses its own tool definition format
- AITuber OnAir Core performs appropriate conversions internally and provides a common
ToolDefinitioninterface
Response Processing Differences:
- OpenAI uses
tool_callsobjects - Claude uses
tool_useblocks - Gemini uses
functionCallobjects - AITuber OnAir Core processes each format and converts to unified
TOOL_USEevents
- OpenAI uses
Tool Result Submission Format Differences:
- Each provider accepts tool results in different formats
- AITuber OnAir Core converts and sends in the appropriate format
Streaming Processing Differences:
- Claude in particular requires special handling for tool calls during streaming
- AITuber OnAir Core abstracts this and provides a consistent streaming experience across all providers
Tool Call Iteration:
- The
runToolLoopmethod is implemented according to each provider's characteristics, providing consistent tool iteration
- The
Through these abstractions, developers can use tool functionality through AITuber OnAir Core's unified interface without worrying about the details of provider implementations. Even when switching providers, there's no need to change tool definition and processing code.
Using MCP
AITuber OnAir Core allows you to integrate MCP using tool calls.
Here's an example of integration.
The following is a simple sample that integrates an MCP that returns a random number.
// mcpClient.ts
import { Client as MCPClient } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
let clientPromise: Promise<MCPClient> | null = null;
async function getMcpClient(): Promise<MCPClient> {
if (clientPromise) return clientPromise;
const client = new MCPClient({
name: "random-int-server",
version: "0.0.1",
});
const endpoint = import.meta.env.VITE_MCP_ENDPOINT as string;
if (!endpoint) throw new Error("VITE_MCP_ENDPOINT is not defined");
const transport = new StreamableHTTPClientTransport(new URL(endpoint));
clientPromise = client.connect(transport).then(() => client);
return clientPromise;
}
export function createMcpToolHandler<T extends { [key: string]: unknown } = any>(toolName: string) {
return async (args: T): Promise<string> => {
const client = await getMcpClient();
const out = await client.callTool({ name: toolName, arguments: args });
return (out.content as { text: string }[] | undefined)?.[0]?.text ?? "";
};
}import { createMcpToolHandler } from './mcpClient';
// tool definition
const randomIntTool: ToolDefinition<{ max: number }> = {
name: 'randomInt',
description:
"Return a random integer from 0 (inclusive) up to, but not including, `max`. If `max` is omitted the default upper‑bound is 100.",
parameters: {
type: 'object',
properties: {
max: { type: 'integer', description: 'Exclusive upper bound for the random integer', minimum: 1 },
},
required: ['max'],
},
};
// mcp tool handler
const randomIntHandler = createMcpToolHandler<{ max: number }>('randomInt');
// create options
const aituberOptions: AITuberOnAirCoreOptions = {
chatProvider,
apiKey: apiKey.trim(),
model,
chatOptions: {
systemPrompt: systemPrompt.trim() || DEFAULT_SYSTEM_PROMPT,
visionPrompt: visionPrompt.trim() || DEFAULT_VISION_PROMPT,
},
tools: [{ definition: randomIntTool, handler: randomIntHandler }],
debug: true,
};
// create new instance
const newAITuber = new AITuberOnAirCore(aituberOptions);Using OpenAI Remote MCP
OpenAI's Responses API allows connecting to remote MCP servers. When you specify
MCP server configurations via the mcpServers option, AITuberOnAirCore
automatically switches to the Responses API endpoint for OpenAI.
import {
AITuberOnAirCore,
AITuberOnAirCoreOptions,
MCPServerConfig,
} from '@aituber-onair/core';
const mcpServers: MCPServerConfig[] = [
{
type: 'url',
url: 'https://mcp-server.example.com/',
name: 'example-mcp',
require_approval: 'never', // Optional: 'always' | 'never'
tool_configuration: { allowed_tools: ['example_tool'] },
authorization_token: 'YOUR_TOKEN',
},
];
const options: AITuberOnAirCoreOptions = {
chatProvider: 'openai',
apiKey: 'your-openai-api-key',
model: 'gpt-4.1',
mcpServers, // Automatically switches to Responses API when MCP servers are configured
};
const aituber = new AITuberOnAirCore(options);Note: The endpoint configuration is OpenAI-specific and is automatically managed
based on MCP server configuration. Other providers (Claude, Gemini) use their own
fixed endpoints.
Using Claude MCP Connector
AITuber OnAir Core supports Claude's Model Context Protocol (MCP) connector feature, allowing you to connect to remote MCP servers directly from the Messages API without a separate MCP client.
Basic Usage
When using the Claude provider, you can specify MCP servers in the mcpServers option:
import { AITuberOnAirCore, AITuberOnAirCoreOptions } from '@aituber-onair/core';
import { MCPServerConfig } from '@aituber-onair/core';
// Define MCP server configuration
const mcpServers: MCPServerConfig[] = [
{
type: 'url',
url: 'https://mcp-server.example.com/sse',
name: 'example-mcp',
tool_configuration: {
enabled: true,
allowed_tools: ['example_tool_1', 'example_tool_2']
},
authorization_token: 'YOUR_TOKEN' // Optional, for OAuth-enabled servers
}
];
// Create AITuberOnAirCore instance with MCP servers
const options: AITuberOnAirCoreOptions = {
chatProvider: 'claude', // MCP is only supported with Claude
apiKey: 'your-claude-api-key',
model: 'claude-haiku-4-5-20251001',
chatOptions: {
systemPrompt: 'You are an AI streamer with access to remote tools via MCP.',
},
// Traditional tools (optional, can be used alongside MCP)
tools: [
{
definition: {
name: 'local_tool',
description: 'A local tool',
parameters: {
type: 'object',
properties: {
input: { type: 'string', description: 'Input text' }
}
}
},
handler: async (input) => {
return `Local result: ${input.input}`;
}
}
],
// MCP servers configuration
mcpServers: mcpServers,
debug: true,
};
const aituber = new AITuberOnAirCore(options);Multiple MCP Servers
You can connect to multiple MCP servers by including multiple configurations:
const mcpServers: MCPServerConfig[] = [
{
type: 'url',
url: 'https://mcp-server-1.example.com/sse',
name: 'server-1',
authorization_token: 'TOKEN_1'
},
{
type: 'url',
url: 'https://mcp-server-2.example.com/sse',
name: 'server-2',
tool_configuration: {
enabled: true,
allowed_tools: ['specific_tool_1', 'specific_tool_2']
}
}
];OAuth Authentication
For MCP servers that require OAuth authentication, you can obtain an access token using the MCP inspector:
npx @modelcontextprotocol/inspectorFollow the OAuth flow in the inspector and copy the access_token value to use as the authorization_token in your configuration.
Event Handling
MCP tool usage is handled through the same event system as traditional tools:
// Listen for tool usage (includes both traditional tools and MCP tools)
aituber.on(AITuberOnAirCoreEvent.TOOL_USE, (toolBlocks) => {
console.log('Tools used:', toolBlocks);
});
aituber.on(AITuberOnAirCoreEvent.TOOL_RESULT, (resultBlocks) => {
console.log('Tool results:', resultBlocks);
});Limitations
- MCP connector is only available with the Claude provider
- Only HTTP-based MCP servers are supported (STDIO servers are not supported)
- Currently only tool calls are supported from the MCP specification
- Not available on Amazon Bedrock and Google Vertex
Coexistence with Traditional Tools
MCP servers and traditional tool definitions can be used simultaneously. The AI can access both local tools and remote MCP tools seamlessly.
Response Length Control
AITuber OnAir Core provides comprehensive response length control functionality, allowing you to fine-tune AI response lengths for both text chat and vision processing.
Overview
Response length control helps you:
- Optimize costs by limiting token usage
- Control response verbosity for different scenarios
- Maintain consistent response patterns across your application
- Separate control for text chat and vision processing
Configuration Options
You can control response length using two approaches:
1. Direct Token Specification
Specify exact token limits directly:
const options: AITuberOnAirCoreOptions = {
chatOptions: {
maxTokens: 150, // Direct token limit for text chat
visionMaxTokens: 200, // Direct token limit for vision processing
},
// ... other options
};2. Preset Response Lengths
Use predefined presets for convenience:
const options: AITuberOnAirCoreOptions = {
chatOptions: {
responseLength: 'medium', // Preset for text chat
visionResponseLength: 'long', // Preset for vision processing
},
// ... other options
};Base token budgets for the presets (providers may apply model-specific minimums or use prompt instructions instead of hard limits):
'veryShort': 40 tokens - Brief, essential responses only'short': 100 tokens - Concise but complete responses'medium': 200 tokens - Balanced length for most scenarios'long': 300 tokens - Detailed responses with context
Priority System
For text chat, the following priority order applies:
chatOptions.maxTokensproviderOptions.responseLengthchatOptions.responseLength- Provider defaults
For local and self-hosted endpoints, token limits remain opt-in to avoid
truncating reasoning output. The openai-compatible provider does not inherit
chatOptions.responseLength; set providerOptions.responseLength or an explicit
chatOptions.maxTokens to request a limit.
Vision-Specific Settings
Vision processing often requires different response lengths than text chat. You can configure them separately:
const options: AITuberOnAirCoreOptions = {
chatOptions: {
// Text chat settings
responseLength: 'short', // Concise text responses
// Vision processing settings
visionResponseLength: 'long', // Detailed image descriptions
},
};Vision requests use visionMaxTokens, then visionResponseLength, then
maxTokens, and finally the provider's response-length setting or default.
Dynamic Updates
Response length settings can be updated at runtime:
aituber.updateChatOptions({
responseLength: 'short',
visionMaxTokens: 250,
});Changing responseLength updates the provider while preserving chat history,
memory, tools, and event listeners. Provider overrides and the
openai-compatible exception still apply. Active chat, vision, and one-shot
requests finish before the replacement takes effect. Provider-owned sessions
(such as Gemini Nano persistent sessions) are recreated using Core's history.
Usage Examples
Different Lengths for Different Scenarios
// Short responses for quick interactions
const quickChat = new AITuberOnAirCore({
chatOptions: {
responseLength: 'veryShort',
},
});
// Detailed responses for educational content
const educationalChat = new AITuberOnAirCore({
chatOptions: {
responseLength: 'long',
visionResponseLength: 'long',
},
});Mixing Direct Values and Presets
const options: AITuberOnAirCoreOptions = {
chatOptions: {
maxTokens: 120, // Direct value for text chat
visionResponseLength: 'medium', // Preset for vision
},
};Provider Compatibility
Response length control is supported across all AI providers:
- OpenAI: Uses
max_tokensparameter - Claude: Uses
max_tokensparameter - Gemini: Uses
maxOutputTokensparameter
The implementation handles provider-specific differences automatically.
Architecture
AITuberOnAirCore is designed with the following layered structure:
AITuberOnAirCore (Integration Layer)
├── ChatProcessor (Conversation handling)
│ └── ChatService (AI Chat)
├── MemoryManager (Memory handling)
│ └── Summarizer (Summarization)
└── VoiceService (Speech processing)
└── VoiceEngineAdapter (Speech Engine Interface)
└── Various Speech Engines (VOICEVOX, OpenAI, etc.)Directory Structure
The source code is organized around the following directory structure:
src/
├── constants/ # Constants and configuration
│ ├── index.ts # Exported constants
│ └── prompts.ts # Default prompts and templates
├── core/ # Core components
│ ├── AITuberOnAirCore.ts
│ ├── ChatProcessor.ts
│ └── MemoryManager.ts
├── services/ # Service implementations
│ ├── chat/ # Chat services
│ │ ├── ChatService.ts # Base interface
│ │ ├── ChatServiceFactory.ts # Factory for providers
│ │ └── providers/ # AI provider implementations
│ │ ├── ChatServiceProvider.ts # Provider interface
│ │ ├── claude/ # Claude-specific
│ │ │ ├── ClaudeChatService.ts
│ │ │ ├── ClaudeChatServiceProvider.ts
│ │ │ └── ClaudeSummarizer.ts
│ │ ├── gemini/ # Gemini-specific
│ │ │ ├── GeminiChatService.ts
│ │ │ ├── GeminiChatServiceProvider.ts
│ │ │ └── GeminiSummarizer.ts
│ │ └── openai/ # OpenAI-specific
│ │ ├── OpenAIChatService.ts
│ │ ├── OpenAIChatServiceProvider.ts
│ │ └── OpenAISummarizer.ts
│ ├── voice/ # Voice services
│ │ ├── VoiceService.ts
│ │ ├── VoiceEngineAdapter.ts
│ │ └── engines/ # Voice engine implementations
│ └── youtube/ # YouTube API integration
│ └── YouTubeDataApiService.ts # YouTube Data API client
├── types/ # TypeScript type definitions
└── utils/ # Utilities and helpers
├── screenplay.ts # Text and emotion processing
└── storage.ts # Storage utilitiesMain Components
AITuberOnAirCore
This is the overall integration class, responsible for initializing and coordinating other components. It extends EventEmitter and emits events at various processing stages. In most cases, you will interact primarily with this class to use its features.
Main methods include:
processChat(text)– Process text inputprocessVisionChat(imageDataUrl, visionPrompt?)– Process image input (optionally pass a custom prompt)stopSpeech()– Stop speech playbackgetChatHistory()– Retrieve chat historysetChatHistory(messages)– Set chat history from external source (e.g., for replay or migration)clearChatHistory()– Clear chat historyupdateVoiceService(options)– Update speech settingsisMemoryEnabled()– Check if memory functionality is enabledgenerateOneShotContentFromHistory(prompt, messageHistory)– Generate new content from a system prompt and provided message history (one-shot, no impact on internal chat history)offAll()– Remove all event listenersdispose()– Stop speech, release chat service resources (such as persistent Gemini Nano sessions), and remove all event listeners. Call it before discarding an instance, for example when recreating Core after a settings change
ChatProcessor
The component that sends text input to an AI model (e.g., OpenAI GPT) and receives responses. It manages the conversation flow and supports streaming responses. It also handles emotion extraction from responses.
updateOptions(newOptions)– Allows you to update settings at runtime
MemoryManager
MemoryManager is designed to prevent issues such as API token limits, increased costs, and slow responses that can occur when the chat log grows too large. When a certain time or message threshold is exceeded, older chat history is summarized and stored as short-, mid-, and long-term memory. This allows recent conversation to be sent as-is, while past context is provided as a summary, maintaining context for the AI while keeping API requests efficient.
Handles conversational context. In long conversations, older messages are summarized and maintained as short-term (1 min), mid-term (4 min), and long-term (9 min) memory. This helps maintain consistency in AI responses.
- Custom Settings:
summaryPromptTemplatecan be customized for summarization (it uses a{maxLength}placeholder).
VoiceService
Converts text to speech. It integrates with multiple external speech synthesis engines through the VoiceEngineAdapter.
speakTextWithOptions Method
The AITuberOnAirCore class provides a flexible speakTextWithOptions method for speech playback:
// Example of speaking text with temporary settings
await aituberOnairCore.speakTextWithOptions('[happy] Hello, everyone watching!', {
// Enable or disable avatar animation
enableAnimation: true,
// Temporarily override current speech settings
temporaryVoiceOptions: {
engineType: 'voicevox',
speaker: '8',
apiKey: 'YOUR_API_KEY' // If required
},
// Specify the ID of the HTML audio element for playback
audioElementId: 'custom-audio-player'
});Key Features:
- Temporary Voice Settings: Override current speech settings without permanently changing them.
- Animation Control: Control avatar animation with the
enableAnimationoption. - Flexible Audio Playback: Play audio in a specified HTML audio element.
- Automatic Emotion Extraction: Extract emotion tags (e.g.,
[happy]) from text and provide them in theSPEECH_STARTevent.
Event System
AITuberOnAirCore emits the following events:
PROCESSING_START: When processing beginsPROCESSING_END: When processing finishesASSISTANT_PARTIAL: Upon receiving partial responses from the assistant (streaming)ASSISTANT_RESPONSE: Upon receiving a complete response (includes a screenplay object and rawText with emotion tags)SPEECH_START: When speech playback starts (includes a screenplay object with emotion and rawText with emotion tags)SPEECH_END: When speech playback endsTOOL_USE: When the AI calls a tool (includes the name of the tool and its input parameters)TOOL_RESULT: When a tool execution completes and returns a resultERROR: When an error occursCHAT_HISTORY_SET: When chat history is setCHAT_HISTORY_CLEARED: When chat history is clearedMEMORY_CREATED: When a new memory is createdMEMORY_REMOVED: When memory is removedMEMORY_LOADED: When memory is loaded from storageMEMORY_SAVED: When memory is saved to storageSTORAGE_CLEARED: When storage is cleared
Safely Handling Event Data
In particular, when implementing a listener for the SPEECH_START event, it is recommended to check if data is present:
// Safe handling of SPEECH events
aituber.on(AITuberOnAirCoreEvent.SPEECH_START, (data) => {
if (!data) {
console.log('No data available');
return;
}
const screenplay = data.screenplay;
if (!screenplay) {
console.log('No screenplay object');
return;
}
const emotion = screenplay.emotion || 'neutral';
console.log(`Speech started: Emotion = ${emotion}`);
// Get original text with emotion tags
console.log(`Original text: ${data.rawText}`);
// Update UI or avatar animation
updateUIWithEmotion(emotion);
});Emotion Handling
In a React application, you might use useRef to store the latest emotion data for immediate access:
// Example in a React component
const [currentEmotion, setCurrentEmotion] = useState('neutral');
const emotionRef = useRef({ emotion: 'neutral', text: '' });
useEffect(() => {
if (aituberOnairCore) {
aituberOnairCore.on(AITuberOnAirCoreEvent.SPEECH_START, (data) => {
if (data?.screenplay?.emotion) {
setCurrentEmotion(data.screenplay.emotion);
emotionRef.current = data.screenplay;
}
});
}
}, [aituberOnairCore]);
// Use the ref for animation callbacks
const handleAnimation = () => {
const emotion = emotionRef.current.emotion || 'neutral';
// Perform animation based on emotion
};ChatProcessor Events
The internal ChatProcessor emits additional events:
chatLogUpdated: Fired when the chat log is updated (e.g., when new messages are added or history is cleared).
You can access this event by referencing the ChatProcessor instance directly:
// Example: using the chatLogUpdated event in ChatProcessor
const aituber = new AITuberOnAirCore(options);
const chatProcessor = aituber['chatProcessor']; // Accessing internal component
chatProcessor.on('chatLogUpdated', (chatLog) => {
console.log('Chat log updated:', chatLog);
// Example: Update UI
updateChatDisplay(chatLog);
// Example: Sync with an external system
syncChatToExternalSystem(chatLog);
});Possible use cases for chatLogUpdated include:
- Real-Time Chat UI Updates
Reflect new messages or cleared logs in the UI immediately. - External System Integration
Save chat logs to a database or send them to an analytics service. - Debugging & Monitoring
Monitor changes in the chat log during development.
Supported Speech Engines
AITuberOnAirCore supports the following speech engines:
- VOICEVOX: High-quality Japanese speech synthesis engine.
- VoicePeak: Speech synthesis engine with rich emotional expression, supporting single-tag or weighted emotion overrides.
- AivisSpeech: Speech synthesis using AI technology.
- Aivis Cloud: High-quality Japanese text-to-speech service with SSML support, emotional intensity control, and multiple output formats (WAV, FLAC, MP3, AAC, Opus).
- OpenAI TTS: Text-to-speech API from OpenAI.
- Gemini TTS: Gemini API-based text-to-speech with selectable preview TTS models including
gemini-3.1-flash-tts-preview, plus style/audio-tag prompt support. - xAI TTS: xAI text-to-speech with selectable codec, sample rate, and bit rate options.
- Unreal Speech: Unreal Speech v8
/streamendpoint with bitrate, speed, pitch, codec, and temperature options. - ElevenLabs: ElevenLabs Text to Speech API with model, output format, language code, voice settings, and text normalization options.
- Fish Audio: Fish Audio one-shot, single-speaker TTS with explicit
drama-3anddrama-3-previewmodel choices, S2 Pro by default, configurable output/latency options, and reference-voice list discovery. - Cartesia: Cartesia synchronous TTS with Sonic 3.5 / 3.6, language/output controls, and voice-list discovery.
- Deepgram Flux: English/Japanese one-shot MP3 speech with a public voice catalog and optional speed control.
- Inworld: Inworld TTS REST API with selectable model, audio encoding, sample rate, bitrate, language, delivery mode, and temperature options.
- Gradium: Gradium REST TTS API with selectable preset voices, output format, temperature, similarity, padding, and rewrite-rule options.
- OpenAI-Compatible TTS: Self-hosted or third-party
/v1/audio/speechcompatible endpoints. - MiniMax: Multi-language TTS using the current T2A v2 models and documented system voice presets. An API key is required; GroupId is a legacy optional query parameter.
- Piper Plus: Browser WASM TTS using ONNX Runtime Web and OpenJTalk assets for on-device synthesis.
- Web Speech API: Browser-native speech synthesis with runtime voice-list discovery and configurable rate, pitch, volume, and language. It plays audio directly through the browser and does not expose audio bytes, so the Core React examples do not support audio-buffer-based lip sync with this engine.
- None: No voice mode (no audio output).
You can dynamically switch the speech engine via updateVoiceService:
// Example of switching speech engines
aituber.updateVoiceService({
engineType: 'openai',
speaker: 'alloy',
apiKey: 'YOUR_OPENAI_API_KEY'
});Speech Chunking (Optional)
Speech synthesis can optionally split assistant responses into smaller chunks so that playback starts sooner for long messages. Chunking is disabled by default to preserve the previous behaviour (one TTS request per response).
You can enable and configure it when creating AITuberOnAirCore:
const aituber = new AITuberOnAirCore({
// ... existing options ...
speechChunking: {
enabled: true,
// Minimum "word" count before a new chunk is started. Japanese text falls
// back to character counts when spaces are not present.
minWords: 40,
// Pick a preset for punctuation detection (ja | en | ko | zh | all)
locale: 'ja',
// Or override with your own separator characters
// separators: ['.', '!', '?'],
},
});- When enabled, the core splits text at punctuation (
。!?!?and commas) and merges adjacent segments until theminWordsthreshold is reached. This keeps the number of TTS requests manageable while still reducing perceived latency. - Setting
minWordsto0(or omitting it) keeps the raw punctuation-based segments and simply streams them in order. - You can toggle the behaviour at runtime, for example when the viewer switches between local and cloud TTS engines:
aituber.updateSpeechChunking({ enabled: false });
aituber.updateSpeechChunking({
enabled: true,
minWords: 25,
locale: 'en',
separators: ['.', '!', '?'],
});Custom API Endpoints
For locally hosted or overridable voice engines (VOICEVOX, VoicePeak, AivisSpeech, OpenAI-Compatible TTS, Unreal Speech, ElevenLabs, Inworld, Gradium), you can specify custom API endpoint URLs:
// Example of setting custom API endpoints
aituber.updateVoiceService({
engineType: 'voicevox',
speaker: '1',
// Custom endpoint for a self-hosted or alternative VOICEVOX server
voicevoxApiUrl: 'http://custom-voicevox-server:50021'
});
// Example for VoicePeak
aituber.updateVoiceService({
engineType: 'voicepeak',
speaker: '2',
voicepeakApiUrl: 'http://custom-voicepeak-server:20202',
voicepeakEmotion: { happy: 40, fun: 60 },
voicepeakSpeed: 140,
voicepeakPitch: 20,
});
// Example for AivisSpeech
aituber.updateVoiceService({
engineType: 'aivisSpeech',
speaker: '3',
aivisSpeechApiUrl: 'http://custom-aivis-server:10101'
});
// Example for OpenAI-compatible TTS
aituber.updateVoiceService({
engineType: 'openaiCompatible',
openAiCompatibleApiUrl: 'http://localhost:8880/v1/audio/speech',
openAiCompatibleModel: 'your-model-id',
openAiCompatibleSpeed: 1.1
});
// Example for Aivis Cloud (high-quality Japanese TTS with SSML support)
aituber.updateVoiceService({
engineType: 'aivisCloud',
speaker: 'YOUR_SPEAKER_UUID', // Speaker UUID from Aivis Cloud
apiKey: 'YOUR_AIVIS_CLOUD_API_KEY',
// Optional parameters for advanced control
emotionalIntensity: 1.0, // 0.0-2.0 range for emotional expression
speakingRate: 1.0, // 0.5-2.0 range for speaking speed
outputFormat: 'wav' // wav, flac, mp3, aac, opus
});
// Example for MiniMax (simplified configuration)
aituber.updateVoiceService({
engineType: 'minimax',
speaker: 'Japanese_IntellectualSenior', // or another system voice preset
apiKey: 'YOUR_MINIMAX_API_KEY',
groupId: 'YOUR_GROUP_ID', // Legacy optional query parameter
endpoint: 'global' // Optional: 'global' (default) or 'china'
});
// Example for Unreal Speech
aituber.updateVoiceService({
engineType: 'unrealSpeech',
speaker: 'af_bella',
apiKey: 'YOUR_UNREAL_SPEECH_API_KEY',
unrealSpeechBitrate: '192k',
unrealSpeechCodec: 'libmp3lame',
unrealSpeechSpeed: 0.3,
});
// Example for ElevenLabs
aituber.updateVoiceService({
engineType: 'elevenLabs',
speaker: 'YOUR_ELEVENLABS_VOICE_ID',
apiKey: 'YOUR_ELEVENLABS_API_KEY',
elevenLabsModel: 'eleven_flash_v2_5',
elevenLabsOutputFormat: 'mp3_44100_128',
elevenLabsLanguageCode: 'ja',
});
// MiniMax GroupId is a legacy optional query parameter.
// MiniMax also supports region-specific endpoints:
// - 'global': For international users (default)
// - 'china': For users in mainland ChinaThis is useful when running voice engines on different ports or remote servers.
AI Provider System
AITuber OnAir Core adopts an extensible provider system, enabling integration with various AI APIs. Currently, OpenAI API, OpenAI-compatible APIs, Gemini API, Gemini Nano (Chrome Built-in AI), Claude API, xAI API, Z.ai API, Kimi API, and OpenRouter API, DeepSeek API, Mistral API, Sakana AI, Sarashina, and PLaMo are available. If you would like to use any other API, please submit a PR or send us a message.
Available Providers
Currently, the following AI provider is built-in:
- OpenAI: Supports models like GPT-6.2 Sol/Astra, GPT-6.1 Sol/Terra, GPT-6 Astra/Sol/Luna, GPT-5 family (Nano/Mini/Standard/5.1/5.4/5.5/5.6 Sol/Terra/Luna/5.4 Mini/5.4 Nano/5.4 Pro), GPT-4.1 (including Mini/Nano), GPT-4o, GPT-4o-mini, O3-mini, o1, o1-mini. GPT-5.6 models also support
maxreasoning effort. GPT-6.2 exposes onlylow(default) andmedium. - Gemini: Supports models like Gemini 3.8 Flash, Gemini 3.7 Flash, Gemini 3.6 Flash, Gemini 3.5 Flash / Flash-Lite, Gemini 3.1 Flash-Lite, Gemini 3.1 Pro Preview, Gemini 3 Flash Preview, Gemini 2.5 Pro, Gemini 2.5 Flash, Gemini 2.5 Flash Lite, Gemma 4 31B IT, and Gemma 4 26B A4B IT. Gemini 3 Flash-family models support configurable
reasoning_effort; Gemini 3.8 Flash and Gemini 3.7 Flash start atlow, while earlier Flash models start atminimaland Pro models atlow. Gemini 3.8 Flash also supports Vision and tool calling through the native Gemini provider. Gemini 2.5 continues to usethinkingBudgetinstead. - Gemini Nano: Supports the built-in Chrome
gemini-nanomodel without an API key (Chrome 138+ with Prompt API flags enabled) - Claude: Supports current Claude API model IDs including Claude Haiku 5.5, Claude Fable 5, Claude Opus 5, Claude Sonnet 5, Claude Opus 4.8, Claude Opus 4.7, Claude Opus 4.6, Claude Opus 4.5, Claude Sonnet 4.6, Claude Sonnet 4.5, and Claude Haiku 4.5. Retired IDs remain exported for source compatibility but are not advertised in selectors. Supported models accept
reasoning_effort, which maps to Anthropic'soutput_config.effort; the package defaults these models tolow(the API default ishigh). - xAI: Supports Grok 4.6, Grok 4.5, Grok 4.3, and Grok 4.20 model families. Grok 4.6 supports
low,medium,high, andxhighreasoning effort and defaults tolow; Grok 4.5 also defaults tolow, while Grok 4.3 defaults tononefor lower latency. Retired Grok 4.1 Fast IDs remain compatibility exports only. - DeepSeek: Supports DeepSeek V4 Flash, DeepSeek V4 Pro, and the vision-capable DeepSeek V4 Flash Vision Exp through the first-class
deepseekprovider. These models expose model-awarereasoning_effort; Core keeps Chat's low-latencynonedefault, while higher supported efforts remain selectable. Thinking and tool
