Polyweave

@polyweave/minimax (1.0.9)

Published 2026-07-11 15:27:24 +00:00 by Dvorak

Installation

@polyweave:registry=https://hub.kl1.tenere.ai/api/packages/Polyweave/npm/
npm install @polyweave/minimax@1.0.9
"@polyweave/minimax": "1.0.9"

About this package

@polyweave/minimax

MiniMax adapter for Polyweave — multi-modal AI adapter supporting text (Anthropic-compatible), audio/TTS (HTTP, WebSocket streaming, bidirectional streaming), image generation, video generation (async task-based with polling), music generation, voice cloning, voice design, voice management, and cost estimation with budget enforcement.

Synopsis

import { createMinimaxAdapter } from '@polyweave/minimax';

const adapter = createMinimaxAdapter({ apiKey: process.env.MINIMAX_API_KEY });

adapter.source.pipe(mySink);

adapter.sink.write({ type: 'PARAM', content: { key: 'model', value: 'MiniMax-M2.1-lightning' } });
adapter.sink.write({ type: 'PARAM', content: { key: 'task', value: 'tts' } });
adapter.sink.write({ type: 'PARAM', content: { key: 'use_websocket', value: true } });
adapter.sink.write({ type: 'TEXT', content: { text: 'Hello world' } });

Install

npm install @polyweave/minimax

Why

MiniMax provides 8 modalities (text, TTS, image, video, music, voice clone, voice design, voice management) under a single API with two regional endpoints. Rather than maintaining 8 separate adapters, this package unifies them into one Polyweave duplex. Task routing is driven by a task PARAM, frame type detection, or stream mode flags. Cost estimation (COST_CHECK) and budget enforcement prevent runaway spending with provider-specific pricing.

API

createMinimaxAdapter(config)

Creates a MiniMax multi-modal adapter as an IFrameDuplex.

Signature: createMinimaxAdapter(config?: Object): IFrameDuplex

Name Type Required Default Description
config Object No {} Adapter configuration
config.apiKey string No process.env.MINIMAX_API_KEY MiniMax API key. Can also be set later via duplex.setReady(key) or PARAM { key: 'apiKey' }.
config.baseURL string No Auto (region-based) Override API base URL.
config.region string No 'international' One of 'international' or 'china'. Determines baseURL if not explicitly set.
config.timeout number No 60000 Request timeout in milliseconds.
config.maxRetries number No 2 Maximum retry count for failed requests.
config.name string No null Name set on the returned duplex.

Returns: IFrameDuplex — The multi-modal adapter duplex.


Frame Protocol

Input frames accepted:

Frame Type Description
TEXT Text content. Accumulated in conversation. Routed to handler based on task PARAM. Default: text generation (Anthropic-compatible endpoint).
AUDIO Audio content. Routed to audio/TTS handler, or voice cloning if task is voice_clone.
IMAGE Image content. Routed to image generation handler.
VIDEO Video content. Routed to video generation handler.
TOOL_RESULT Tool results. Accumulated in conversation as { role: 'user', content: [{ type: 'tool_result', ... }] }.
PARAM Sets internal parameter. See parameter table below.
COST_CHECK Enables cost estimation dry-run mode. Subsequent frames are buffered and a COST frame with estimate is emitted.
ESTIMATED_OUTPUT Metadata frame specifying expected output dimensions (buffered, doesn't trigger estimate alone).
START Pass-through (no action).
END For streaming TTS sessions, forwarded to close the WebSocket. Otherwise no action.
TOPOLOGY_SCAN Emits TOPOLOGY_REPORT with adapter metadata, then forwards.
TOPOLOGY_REPORT, TOPOLOGY_COMPLETE Forwarded downstream.
TEST_INJECT Injects an array of frames from content.frames.
TEST_SNAPSHOT Emits snapshot with adapter ID and paused state.

Output frames emitted:

Frame Type Description
TEXT Chat completions (streaming), tool calls.
AUDIO TTS audio data.
IMAGE Generated image URLs/data.
VIDEO Generated video task IDs / download URLs.
TOOL_CALL Tool use requests from text generation.
RECEIPT Token usage / cost receipt.
COST Cost estimate from COST_CHECK mode.
ERROR Mapped error with code, message, and provider metadata.
END End of response stream.

PARAM Parameters

All settable via PARAM { key, value } frames:

Text Parameters

Key Type Default Description
model string 'MiniMax-M2.1-lightning' Text model name.
max_tokens number 1024 Maximum output tokens.
temperature number undefined Sampling temperature.
stream boolean false Enable streaming for text.
messages Array undefined Pre-set message array.
system string undefined System prompt.
tools Array undefined Tool definitions.
tool_choice * undefined Tool choice mode.
thinking * undefined Thinking/reasoning config.
logprobs * undefined Logprobs config.
top_logprobs * undefined Top logprobs count.

Audio (TTS) Parameters

Key Type Default Description
text string undefined Text to synthesize (for non-streaming).
voice_id string 'English_expressive_narrator' Voice ID for TTS.
speed number 1 Speech speed multiplier.
vol number 1 Volume.
pitch number 0 Pitch adjustment.
output_format string 'hex' 'hex' or 'url'.
audio_format string 'mp3' Output audio format.
sample_rate number 32000 Audio sample rate.
bitrate number 128000 Audio bitrate.
use_websocket boolean false Use WebSocket for TTS (single text input, streaming audio output).
streaming_tts boolean false True bidirectional streaming TTS (text chunks in → audio chunks out).
language_boost string undefined Language hint for TTS.

Voice Clone Parameters

Key Type Default Description
file_id string undefined Uploaded audio file ID for cloning.
auto_clone boolean false Auto-clone after upload.
need_noise_reduction boolean false Apply noise reduction.
need_volumn_normalization boolean false Apply volume normalization.
clone_prompt Object undefined { prompt_audio, prompt_text } for guided cloning.
prompt_text string undefined Text for cloning preview.

Voice Design Parameters

Key Type Default Description
prompt string undefined Natural language description of desired voice.
preview_text string undefined Text used for preview audio.

Voice Management Parameters

Key Type Default Description
voice_operation string undefined 'list' or 'delete'.
voice_type string 'all' Filter: 'system', 'voice_cloning', 'voice_generation', or 'all'.

Video Parameters

Key Type Default Description
duration number 6 Video duration in seconds.
resolution string '1080P' '1080P', '768P', or '720P'.
prompt_optimizer boolean true Enable prompt optimizer.
first_frame_image * undefined First frame image reference.
last_frame_image * undefined Last frame image reference.
subject_reference * undefined Subject reference image.

Image Parameters

Key Type Default Description
aspect_ratio string '1:1' e.g. '1:1', '16:9', '9:16'.

Music Parameters

Key Type Default Description
lyrics string undefined Song lyrics.
style string undefined Alias for prompt (music style).

Routing Parameter

Key Type Default Description
task string undefined Routes to a specific handler. See below.

Cost/Receipt Parameters

Key Type Default Description
receipt_mode string 'final' 'none', 'final', or 'progressive'.
receipt_interval number 50 Tokens between progressive receipts.

Task Routing

The task PARAM (or frame.metadata.task) determines which handler processes incoming TEXT/AUDIO frames:

task value Handler Description
(none / default) handleText Text generation via Anthropic-compatible endpoint. Supports tool use.
tts, t2a handleAudio / handleAudioWebSocket / handleAudioWebSocketStreaming Text-to-Audio. Handler chosen by streaming_tts and use_websocket flags.
image, image_generation handleImage Text-to-Image generation.
video, video_generation handleVideo Text-to-Video with async task polling.
music, music_generation handleMusic Text-to-Music generation.
voice_clone, clone handleVoiceClone Clone voice from audio sample.
voice_design, design_voice handleVoiceDesign Design voice from text description.
voice_management, voices, list_voices handleVoiceManagement List or delete voices.
delete_voice handleVoiceManagement Delete specified voice (sets voice_operation='delete').

Unsupported frame type error: If a frame arrives with an unrecognized type and no matching task, the adapter throws Error('Unsupported frame type: <type>. Supported types: TEXT, AUDIO, IMAGE, VIDEO'), which is caught and emits an ERROR frame with END.


Cost Estimation

COST_CHECK mode: When a COST_CHECK frame is received:

  1. Subsequent frames (TEXT, AUDIO, IMAGE, VIDEO, ESTIMATED_OUTPUT) are buffered.
  2. ESTIMATED_OUTPUT is a metadata-only frame that doesn't trigger estimation alone.
  3. On the next non-ESTIMATED_OUTPUT frame, cost is estimated:
    • Chat (text): Uses costEstimator.estimate() from @polyweave/costs.
    • Image: Uses estimateImageCost('minimax', { model: 'image-01', num_images }).
    • Video: Uses estimateVideoCost('minimax', { model: 'video-01', duration }).
    • Audio: Uses estimateAudioCost('minimax', { model: 'speech-01', duration }). Duration is estimated from text length (5 chars/word, 150 words/min) or from frame.content.duration.
  4. If maxBudget set in COST_CHECK content: budget check, emits BUDGET_EXCEEDED ERROR + END if exceeded.
  5. Otherwise: emits COST frame with { bounds, estimateSource, accuracy, forwardEstimate, inputBounds, maxOutputTokens, requestType }, then END.

Cost frame fields: { type: 'COST', content: { ...estimate, provider: 'minimax', model, currency, confidence: 'estimated' } }.


Additional Duplex Methods

Method Description
duplex.setReady(apiKey) Sets the API key and flushes the frame buffer.
duplex.resetConversation() Clears the internal conversation array.
duplex._conversation() Returns a copy of the current conversation.
duplex.name Name from config.name or null.

Handler Submodules

These are internal functions, not exported from the package root. Documented here for understanding frame routing:

Handler Signature Purpose
handleText (frame, duplex, params, sharedState) Anthropic-compatible text generation. Supports streaming and tool use.
handleAudio (frame, duplex, params, sharedState) HTTP-based T2A synthesis.
handleAudioWebSocket (frame, duplex, params, sharedState) WebSocket TTS — single text input, streaming audio output.
handleAudioWebSocketStreaming (frame, duplex, params, sharedState) Bidirectional WebSocket streaming TTS — text chunks in, audio chunks out. Also exports createStreamingTTSSession.
handleImage (frame, duplex, params, sharedState) Text-to-Image generation.
handleVideo (frame, duplex, params, sharedState) Text-to-Video with async task submission and polling.
handleMusic (frame, duplex, params, sharedState) Text-to-Music generation.
handleVoiceClone (frame, duplex, params, sharedState) Voice cloning from audio sample.
handleVoiceDesign (frame, duplex, params, sharedState) Voice design from text description.
handleVoiceManagement (frame, duplex, params, sharedState) List or delete voices.

Error Handling

Error mapper (utils/errorMapper.js):

Function Purpose
mapMinimaxErrorCode(statusCode, errorType?) Maps HTTP status codes and MiniMax error type strings to Polyweave ErrorCode values (AUTHENTICATION_ERROR, AUTHORIZATION_ERROR, RATE_LIMIT_EXCEEDED, INVALID_INPUT, SERVICE_UNAVAILABLE, JOB_NOT_FOUND, QUEUE_TIMEOUT, PROVIDER_ERROR, ADAPTER_ERROR).
mapMinimaxError(error, originalFrame?) Creates a full ERROR frame with mapped code, message, statusCode, errorType, provider, and original frame metadata.

Error delivery: All handler errors are caught in duplex.sink.write() and mapped to ERROR frames followed by END frames. If duplex.source.sink is available and not paused, both frames are emitted.

Cleanup: On duplex.sink.end(), all active HTTP requests are destroyed and all active video task polling timers are cleared.


Adapter States

State Condition
Not ready No apiKey configured. Frames are buffered until setReady() or PARAM { key: 'apiKey' } is received.
Ready apiKey is set. Frames are immediately processed.
COST_CHECK Evaluating cost estimate. Frames buffered, estimate emitted on first content frame.
Error Any handler error emits ERROR + END. Adapter remains ready.

Tests

npm test

Covers: adapter creation with/without apiKey, PARAM accumulation, task routing (text → handleText, tts → handleAudio, image → handleImage, video → handleVideo, music → handleMusic, voice_clone → handleVoiceClone, voice_design → voiceDesign, voice_management → voiceManagement), COST_CHECK mode with budget enforcement, error mapping (all MiniMax error types to Polyweave ErrorCodes), topology scan reporting, and frame buffer flushing on setReady.

Requirements

  • Node.js 22+
  • ESM only
  • Peer: @polyweave/core, @polyweave/errors, @polyweave/costs
  • Dependency: @polyweave/push-websocket (for WebSocket streaming TTS)

Dependencies

Dependencies

ID Version
@polyweave/push-websocket *

Development Dependencies

ID Version
@rigor/core *

Peer Dependencies

ID Version
@polyweave/core *
@polyweave/costs *
@polyweave/errors *

Keywords

polyweave minimax tts ai adapter
Details
npm
2026-07-11 15:27:24 +00:00
4
John Dvorak
SEE LICENSE IN LICENSE
27 KiB
Assets (1)
Versions (6) View all
1.0.2 2026-07-17
1.0.9 2026-07-11
1.0.6 2026-07-10
1.0.5 2026-07-10
1.0.4 2026-07-10