Getting Started
SDK Reference
Official SDKs for TypeScript/JavaScript and Python. Full coverage of every API endpoint with typed methods.
Installation
The TypeScript SDK supports Node.js, Deno, Bun, and browser environments (ESM & CommonJS). The Python SDK supports Python 3.9+.
npm install @metriqual/sdkpip install metriqualInitialization
Constructor Options
apiKey / api_keystringrequiredYour Metriqual proxy key (mql_...)
baseUrl / base_urlstringAPI base URL
Default: https://api.metriqual.com
import Metriqual from '@metriqual/sdk';
const mql = new Metriqual({
apiKey: process.env.MQL_API_KEY!,
baseUrl: 'https://api.metriqual.com'
});from metriqual import MQL
client = MQL(api_key="mql_...")
# Or with context manager
with MQL(api_key="mql_...") as client:
...Available APIs
mql.chat
Methods
create()Promise<ChatResponse>Create a chat completion
stream()AsyncGenerator<ChatChunk>Stream a chat completion. Supports async iteration and onChunk/onComplete callbacks.
streamToCompletion()Promise<string>Stream and return full accumulated text when done
complete()Promise<string>Convenience method — returns only the text content
const res = await mql.chat.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello!' }]
});
// Streaming
for await (const chunk of mql.chat.stream({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello!' }]
})) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
}response = client.chat.create(
messages=[{"role": "user", "content": "Hello!"}],
model="gpt-4o",
)
# Streaming
for chunk in client.chat.stream(
messages=[{"role": "user", "content": "Hello!"}],
model="gpt-4o",
):
print(chunk["choices"][0]["delta"].get("content", ""), end="")
# Simple helper — returns just the text
text = client.chat.complete(
[{"role": "user", "content": "Hello!"}],
model="gpt-4o",
)mql.images
Methods
generate()Promise<ImageResponse>Generate images with OpenAI models (DALL·E, gpt-image-1)
generateMiniMax()Promise<MiniMaxImageResponse>Generate images with MiniMax image-01
// OpenAI
const img = await mql.images.generate({
model: 'gpt-image-1',
prompt: 'A sunset over mountains'
});
// MiniMax
const mmImg = await mql.images.generateMiniMax({
model: 'image-01',
prompt: 'A futuristic cityscape'
});# OpenAI
img = client.images.generate(prompt="A sunset over mountains", model="gpt-image-1")
# MiniMax
mm_img = client.images.generate_minimax(prompt="A futuristic cityscape")
# Get URLs directly
urls = client.images.generate_urls(prompt="A sunset over mountains")mql.audio
Methods
speech()Promise<ArrayBuffer>Generate speech from text (TTS)
speechAsync()Promise<AsyncSpeechResponse>Create async speech task for long text (up to 50k chars)
speechAsyncStatus()Promise<AsyncSpeechStatusResponse>Get status of an async speech task
speechAsyncDownload()Promise<ArrayBuffer>Download completed async speech audio
speechAsyncAndWait()Promise<ArrayBuffer>Create async speech and wait for completion
transcribe()Promise<TranscriptionResponse>Transcribe audio to text (STT)
translate()Promise<TranslationResponse>Translate audio to English text
cloneVoice()Promise<CloneVoiceResponse>Clone a voice from audio sample
uploadVoiceClone()Promise<VoiceCloneUploadResponse>Upload audio file for voice cloning
uploadAndCloneVoice()Promise<CloneVoiceResponse>Upload + clone in one step
uploadPromptAudio()Promise<PromptAudioUploadResponse>Upload prompt audio for TTS voice matching
designVoice()Promise<DesignVoiceResponse>Design a new voice with parameters
createVoice()Promise<CreateVoiceResponse>Create a named voice on OpenAI
getVoices()Promise<VoicesResponse>List available voices
deleteVoice()Promise<void>Delete a custom voice
createVoiceConsent()Promise<VoiceConsent>Create a voice consent record
getVoiceConsent()Promise<VoiceConsent>Get a voice consent by ID
updateVoiceConsent()Promise<VoiceConsent>Update a voice consent
deleteVoiceConsent()Promise<void>Delete a voice consent
listVoiceConsents()Promise<VoiceConsentListResponse>List all voice consents
generateLyrics()Promise<LyricsResponse>Generate song lyrics
// Text-to-speech
const audio = await mql.audio.speech({
model: 'speech-02-hd',
text: 'Hello, world!',
voice_setting: { voice_id: 'male-qn-qingse' }
});
// Transcription
const transcript = await mql.audio.transcribe({
file: audioBuffer,
model: 'whisper-1'
});# Text-to-speech (returns bytes)
audio_bytes = client.audio.speech(input="Hello, world!", voice="alloy")
# Async TTS with polling
audio_bytes = client.audio.speech_async_and_wait(
input="Long text...", voice="alloy", model="tts-1-hd"
)
with open("output.mp3", "wb") as f:
f.write(audio_bytes)
# Transcription
with open("audio.wav", "rb") as f:
transcript = client.audio.transcribe(file=f, model="whisper-1")mql.music
Methods
generate()Promise<MusicResponse>Generate music from a text prompt or lyrics
const music = await mql.music.generate({
model: 'music-01',
prompt: 'An upbeat electronic track',
audio_setting: {
sample_rate: 44100,
bitrate: 256000,
format: 'mp3'
}
});result = client.music.generate_from_prompt("An upbeat electronic track")
# With lyrics
result = client.music.generate_with_lyrics(
"A sad ballad",
"Verse 1: Under the fading sky..."
)mql.video
Methods
create()Promise<VideoResponse>Create a video generation job (Sora or MiniMax T2V)
getStatus()Promise<VideoResponse>Check Sora generation status
download()Promise<ArrayBuffer>Download generated Sora video content
createAndWait()Promise<VideoResponse>Create a Sora video and poll until complete
createAndDownload()Promise<ArrayBuffer>Create, wait, and download in one call
createFromImage()Promise<MinimaxI2VResponse>MiniMax image-to-video generation
queryVideoStatus()Promise<VideoTaskStatus>Check MiniMax generation status
downloadVideo()Promise<VideoDownloadResponse>Get MiniMax video download URL
queryAndWait()Promise<VideoTaskStatus>Poll MiniMax task until complete
queryAndDownload()Promise<VideoDownloadResponse>Poll + download MiniMax video in one call
// Sora
const video = await mql.video.create({
model: 'sora',
prompt: 'A timelapse of a flower blooming',
aspect_ratio: '16:9',
duration: 10
});
// MiniMax text-to-video
const mmVideo = await mql.video.create({
model: 'MiniMax-Hailuo-2.3',
prompt: 'Ocean waves at sunset',
duration: 6,
resolution: '1080P'
});# Submit and poll until complete
status = client.video.create_and_wait(
model="sora",
prompt="A timelapse of a flower blooming"
)
# Submit, poll, and download bytes
video_bytes = client.video.create_and_download(
model="MiniMax-Hailuo-2.3",
prompt="Ocean waves at sunset"
)
# MiniMax image-to-video
result = client.video.create_from_image(first_frame_image="https://...")mql.embeddings
Methods
create()Promise<EmbeddingResponse>Create vector embeddings from text
const embeddings = await mql.embeddings.create({
model: 'text-embedding-3-small',
input: 'The quick brown fox'
});
console.log(embeddings.data[0].embedding);response = client.embeddings.create(
input="The quick brown fox",
model="text-embedding-3-small"
)
print(response["data"][0]["embedding"])mql.analytics
Methods
getOverview()Promise<AnalyticsOverview>Get usage summary (requests, tokens, cost, errors)
getTimeseries()Promise<TimeseriesPoint[]>Get usage data over time for charting
getProviderStats()Promise<ProviderStats[]>Break down usage by provider
getUsageLogs()Promise<UsageLogsResponse>Get individual request logs for a proxy key
getUsageAnalytics()Promise<UsageAnalyticsResponse>Get aggregated usage analytics for a proxy key
const overview = await mql.analytics.getOverview({ range: '7d' });
console.log('Total requests:', overview.total_requests);
console.log('Total cost:', overview.total_cost);
const timeseries = await mql.analytics.getTimeseries({
range: '7d',
granularity: 'daily'
});overview = client.analytics.get_overview(start_date="2024-01-01")
timeseries = client.analytics.get_timeseries()
provider_stats = client.analytics.get_provider_stats()
# Org-scoped
org_overview = client.analytics.get_org_overview(org_id)mql.organizations
Methods
create()Promise<Organization>Create a new organization
get()Promise<Organization>Get organization details
update()Promise<Organization>Update organization settings
list()Promise<Organization[]>List your organizations
getMembers()Promise<Member[]>List organization members
inviteMember()Promise<Invite>Invite a user to the organization
const orgs = await mql.organizations.list();
const members = await mql.organizations.getMembers(orgs[0].id);orgs = client.organizations.list()
members = client.organizations.list_members(orgs["organizations"][0]["id"])
client.organizations.invite_member(org_id, email="dev@company.com")mql.proxyKeys
Methods
create()Promise<ProxyKey>Create a new proxy key
list()Promise<ProxyKey[]>List all proxy keys
get()Promise<ProxyKey>Get a proxy key by ID
update()Promise<ProxyKey>Update proxy key settings
delete()Promise<void>Delete a proxy key
rotate()Promise<ProxyKey>Rotate a proxy key
const key = await mql.proxyKeys.create({
name: 'Production Key',
org_id: 'org_abc123'
});
console.log('Key:', key.key);key = client.proxy_keys.create(
name="Production Key",
providers=[{"provider": "openai", "api_key": "sk-..."}]
)
print("Key:", key["key"])mql.filters
Methods
list()Promise<Filter[]>List all content filters
create()Promise<Filter>Create a content filter rule
update()Promise<Filter>Update a filter rule
delete()Promise<void>Delete a filter rule
const filters = await mql.filters.list(orgId);filters = client.filters.list()
client.filters.create(
name="Block PII",
filter_type="regex",
pattern=r"\b\d{3}-\d{2}-\d{4}\b",
action="block"
)mql.models
Methods
list()Promise<Model[]>List all available models
listByProvider()Promise<Model[]>List models for a specific provider
getPricing()Promise<Pricing[]>Get model pricing information
const models = await mql.models.list();
const openaiModels = await mql.models.listByProvider('openai');models = client.models.list()
openai_models = client.models.list_by_provider("openai")
specific = client.models.get("gpt-4o")mql.promptHub
Methods
create()Promise<Prompt>Create a new prompt
list()Promise<Prompt[]>List your prompts
get()Promise<Prompt>Get a prompt by ID
update()Promise<Prompt>Update a prompt
delete()Promise<void>Delete a prompt
publish() / unpublish()Promise<Prompt>Publish or unpublish a prompt
share()Promise<ShareLink>Generate a share link
star() / unstar()Promise<void>Star or unstar a prompt
fork()Promise<Prompt>Fork a prompt to your account
attachToKey()Promise<void>Attach prompt as system prompt to a proxy key
detachFromKey()Promise<void>Detach prompt from a proxy key
const prompt = await mql.promptHub.create({
name: 'Code Reviewer',
content: 'You are a senior code reviewer...',
model: 'gpt-4o',
is_public: false
});
// Attach to proxy key as system prompt
await mql.promptHub.attachToKey(prompt.id, 'mql_key_id');prompt = client.prompt_hub.create(
name="Code Reviewer",
content="You are a senior code reviewer...",
model="gpt-4o",
is_public=False,
)
# Attach to proxy key as system prompt
client.prompt_hub.attach_to_key(prompt["id"], "mql_key_id")mql.subscription
Methods
getStatus()Promise<SubscriptionStatus>Get current subscription status and plan details
getPlanTier()Promise<string>Get the current plan tier (free, pro, team, enterprise)
getLimits()Promise<Limits>Get current plan limits
getFeatures()Promise<Features>Get available features for current plan
hasFeature()Promise<boolean>Check if a specific feature is available
const status = await mql.subscription.getStatus();
console.log('Plan:', status.tier);
console.log('Limits:', status.limits);status = client.subscription.get_status()
tier = client.subscription.get_plan_tier()
has_prompts = client.subscription.has_feature("prompt_hub")
# Org-scoped
org_status = client.subscription.get_status(org_id="org_abc123")Error Handling
Both SDKs throw typed errors with status codes and error messages from the API.
try {
const res = await mql.chat.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hi' }]
});
} catch (error) {
if (error instanceof Error) {
console.error('API Error:', error.message);
}
}from metriqual import MQL, MQLAPIError, MQLTimeoutError
try:
response = client.chat.create(
messages=[{"role": "user", "content": "Hi"}],
model="gpt-4o",
)
except MQLTimeoutError:
print("Request timed out")
except MQLAPIError as e:
print(f"API error {e.status}: {e}")Language Support
@metriqual/sdk (npm) and the Python SDK uses metriqual (PyPI).