API REFERENCE v1.0

CodexbaseAIHub Docs

CodexbaseAIHub is a unified AI API platform. One API key, one base URL, access to 15 AI engines, chat, code, NLP, vision, and more. All engines share the same authentication pattern, response envelope, and error format.

Quick start: Get an API key from your dashboard, then pass it as X-API-Key: cxb_your_key in any request.

Authentication

All API requests require an API key passed in the X-API-Key header. API keys are prefixed with cxb_ and are generated from your dashboard.

HTTP Header
X-API-Key: cxb_your_api_key_here

Keys can be scoped to specific engines. An unscoped key (default) has access to all engines your plan supports.

Response Envelope

Every engine response wraps results in a standard envelope:

JSON
{
  "status": "success",       // "success" | "error"
  "engine": "engine-slug",   // which engine processed the request
  "provider": "Codexbase",   // always Codexbase; the backing model is not
                             // part of the contract and may change
  "latency_ms": 312.5,       // server-side latency in milliseconds
  // ...engine-specific fields
}

Base URL

All endpoints are relative to:

BASE URL
https://aihub.codexbase.net/api/v1

You can also explore all endpoints interactively via the Swagger UI →

Error Handling

All errors return a JSON body with error and code fields:

JSON
// 400: Bad request / validation error
{ "error": "prompt is required", "code": 400 }

// 401, Missing or invalid API key
{ "error": "Authentication required", "code": 401 }

// 403, Plan does not include this engine
{ "error": "Forbidden", "code": 403 }

// 429, Rate limit exceeded
{ "error": "Rate limit exceeded", "code": 429 }

// 500, Engine or provider error
{ "error": "Engine error. Please try again.", "code": 500 }

Rate Limits

Rate limits are enforced per API key per engine. Limits vary by engine complexity and your plan.

Engine TypeDefault LimitPlan Override
Chat / Text30 req / minUp to 200/min on Enterprise
Code / Analysis20 req / minUp to 100/min on Pro+
Image Generation10 req / minUp to 50/min on Pro+
Medical Analyzer10 req / minRequires Pro or higher

When a rate limit is exceeded, you'll receive a 429 response. Wait and retry using exponential backoff.

Image Generation Vision

Generate stunning images from text prompts.

POST /api/v1/image/generate
Requires Basic plan or higher.

Provide a text prompt and receive a generated image URL. Supports size and quality options.

Request Parameters

FieldTypeRequiredDescriptionDefault
prompt string Required Image description prompt -
size string
256x256 | 512x512 | 1024x1024 | 1792x1024 | 1024x1792
Optional 1024x1024
quality string
standard | hd
Optional standard
style string
vivid | natural
Optional vivid

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/image/generate \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "example text"}'

Response

JSON Response
{
  "status": "success",
  "engine": "image-generation",
  "provider": "Codexbase",
  "url": "...",  // Generated image URL
  "revised_prompt": "...",  // 
  "latency_ms": 245.3
}

Sentiment Analysis NLP

Analyze emotional tone. Basic = instant, rule-based. Detailed = AI-scored, with emotion bars.

POST /api/v1/sentiment/analyze

Provide text and receive POSITIVE/NEGATIVE/NEUTRAL with confidence score.

Request Parameters

FieldTypeRequiredDescriptionDefault
text string Required Text to analyze -
mode string
basic | detailed
Optional basic=rule-based, detailed=AI basic

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/sentiment/analyze \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"text": "example text"}'

Response

JSON Response
{
  "status": "success",
  "engine": "sentiment-analysis",
  "provider": "Codexbase",
  "result": "...",  // 
  "latency_ms": 245.3
}

Text Generation NLP

Generate text from a prompt, with automatic failover across several backends so a single outage does not stop a reply.

POST /api/v1/text/generate

Send a prompt and receive AI-generated text.

Request Parameters

FieldTypeRequiredDescriptionDefault
prompt string Required Text prompt -
max_tokens integer Optional 500
temperature number Optional 0.7
system string Optional System instruction -

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/text/generate \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "example text"}'

Response

JSON Response
{
  "status": "success",
  "engine": "text-generation",
  "provider": "Codexbase",
  "result": "...",  // 
  "tokens_used": 0,  // 
  "latency_ms": 245.3
}

Nexus AI Assistants

Composite AI engine: conversational reasoning with persistent memory, any-file understanding, web-grounded answers, data analysis and file generation: behind one API. Behaviour is configured per API key, so the same engine can serve a chatbot, a document extractor and a business analyst without code changes.

POST /api/v1/nexus/chat
30 per minute
Requires Basic plan or higher.

Nexus is a composite engine: one endpoint that reasons, remembers and (progressively) reads and writes files.

Conversation memory#

Pass a session_id to continue a thread. Omit it and one is created and returned; reuse that value on the next call and Nexus remembers the exchange. Memory is isolated per API key, not merely per account: a chatbot key and an analyst key issued to the same user never see each other's threads.

Long conversations stay inside the model's context window automatically: once the transcript exceeds a token budget the oldest turns are condensed into a running brief. You do not need to trim history yourself, and GET /session/<id> still returns the full transcript.

Modes#
ModeForTone and defaults
chatbotend-user assistantswarm, brief, temperature 0.8
analystbusiness analysisfinding-first, quantified, temperature 0.3
extractordocument → JSONliteral, nulls not guesses, temperature 0.0
generalanythingbalanced default

The mode is set on your API key, not in the request body, so a key issued for a public chatbot cannot ask for analyst behaviour or raised limits. Request mode when you ask for the key.

Endpoints#
EndpointMethodPurpose
/chatPOSTsend a message, get a reply
/extractPOSTdocument to structured JSON, returned in data
/session/<id>GETfull transcript and metadata
/session/<id>DELETEerase a thread's history
/sessionsGETlist your threads
/infoGETcapabilities, live features, quota headroom
/artifact/<key>GETdownload a generated file
Bots#

White-label assistants with their own identity and keys.

EndpointMethodPurpose
/botsPOST, GETcreate a bot, list your bots
/bots/<id>GET, PATCH, DELETEread, update or remove one
/bots/<id>/chatPOSTtalk to it, authenticated by its publishable key
/bots/<id>/keysPOST, GETissue and list pk_nx_ publishable keys
/bots/<id>/keys/<prefix>DELETErevoke one key
/bots/<id>/connectorsPOST, GETattach live data sources
/bots/<id>/connectors/<name>PATCH, DELETEupdate or detach one

The full machine-readable contract, including every request and response field, is at GET /api/v1/openapi.json.

A two-turn conversation#

This is the flow most integrations get wrong. Send the first message with no session_id, keep the one that comes back, and send it with the next message. That is all memory requires.

# turn 1: no session_id, so a thread is created
curl -sX POST https://aihub.codexbase.net/api/v1/nexus/chat \
  -H 'X-API-Key: cxb_your_key' -H 'Content-Type: application/json' \
  -d '{"message": "my budget is 4000 euros"}'

# -> {"reply": "...", "session_id": "nxs_8Kd2mQ7xR4vN1pLz", ...}

# turn 2: pass it back and Nexus remembers the budget
curl -sX POST https://aihub.codexbase.net/api/v1/nexus/chat \
  -H 'X-API-Key: cxb_your_key' -H 'Content-Type: application/json' \
  -d '{"message": "what can i afford?",
       "session_id": "nxs_8Kd2mQ7xR4vN1pLz"}'

If session_id comes back null, memory is switched off for that key. Only extractor mode is stateless by design; chatbot, analyst and general all issue threads. memory.enabled reports the same thing and notes explains it in the reply, so check those before assuming the thread was lost.

Errors#

Errors use the same envelope as a success, so one parser handles both. error carries the message and code repeats the status.

StatusMeansWhat to do
401key missing, revoked, or not valid for this enginecheck the X-API-Key header
403key is valid but not entitled to this engine or botrequest access for that engine
429per-minute rate limit or daily quotaback off and retry; the limit is per key
422the model returned nothing usable, e.g. invalid JSON for /extractsimplify the schema or the input
503every provider lane is down or spentretry shortly; this one is worth retrying
{
  "status": "error",
  "type": "error",
  "error": "Invalid or missing API key.",
  "code": 401,
  "text": "Invalid or missing API key.",
  "data": null,
  "files": []
}
Structured output#

Send "output_format": "json" and the parsed object comes back in data, with type set to data. Read data; do not parse reply, which is markdown and may carry code fences. data is null only when the model returned nothing parseable.

Check degraded, not just the status code. A 200 answered by the text-only fallback when you sent an image is a silent failure, the reply will read plausibly but nothing looked at your file. When that happens degraded is true and notes says why. (provider is always Codexbase and will not tell you: the backing model is not part of the contract.)

Rendering the reply. text is markdown. Rather than parsing it, ask for structure with "render": ["html"] (escaped and safe to inject) or ["blocks"] (typed JSON for a native UI); true gives both. Code blocks carry class="language-x", so any client-side highlighter can colour them. Set render on your key or bot to have it apply to every turn.

Capacity. Multimodal work and web search run on a metered backend with a small per-minute allowance. A rate-limited key is parked for the delay the upstream asks for and the next one takes over, so bursts degrade in latency rather than failing. /info reports throughput and which lanes are ready. Text-only turns route elsewhere, so ordinary chat does not consume the multimodal allowance.

Running code from replies#

Code in a reply comes back as fenced Markdown blocks with a language tag (``python, `cpp ...). Nothing in the chat request or response changes for this. To run one, send its contents to the platform's code sandbox with the same key: POST /api/v1/sandbox/run with {"language": "cpp", "code": "...", "stdin": ""} returns stdout, stderr, a status (ok, compile_error, timeout, runtime_error), CPU time and memory. Python, JavaScript, C, C++, Java, Go, Rust, Ruby, PHP, Lua and Bash are supported; GET /api/v1/sandbox/languages` lists them. Code runs isolated, with no network and hard limits, never on the API server. The console's Nexus page does exactly this behind its Run button.

Request Parameters

FieldTypeRequiredDescriptionDefault
message string Required The user's message. -
session_id string Optional Thread to continue. Omit to start a new one: the id is returned in the response and should be reused for the next turn. -
mode string
chatbot | analyst | extractor | general
Optional Behaviour profile. Honoured only for keys with no configured profile: a key provisioned as a chatbot stays a chatbot and ignores this. -
intent string
conversation | analysis | extraction | interpretation | generation
Optional Override intent detection. Normally unnecessary: Nexus infers this from your wording. -
file file Optional Attach a file to the turn as multipart/form-data. Any field name works. Up to 5 files per request, 25 MB each. Accepts pdf; images (png, jpg, webp, gif, bmp, tiff, heic); audio (mp3, wav, m4a, ogg, flac, aac); video (mp4, mov, avi, webm, mkv); spreadsheets (csv, xlsx, xls, tsv); text (txt, md, json, yaml, xml, html, log); and code (py, js, ts, java, go, rb, php, c, cpp, rs, sql, sh). Scanned PDFs are read with OCR, capped at 8 pages; 25 pages are read in total and anything skipped is reported in `attachments` rather than ignored. -
file_base64 string Optional The same thing as a JSON body instead of multipart, for callers that cannot send form data. Pass `filename` alongside it so the type can be detected; content is sniffed by magic bytes where the extension disagrees. -
output_format string
auto | text | markdown | json | csv | xlsx | pdf | png | code
Optional How to deliver the answer. Omit and the engine picks: prose for short answers, a table for comparisons, a file for datasets and reports. Saying 'give me an excel file' in the message works too. auto
search string
on | off | auto
Optional Web grounding for this turn: 'on', 'off' or 'auto'. Auto searches only when the question depends on current facts. auto
temperature number Optional 0.0-2.0. Defaults to the mode's setting. -
max_tokens integer Optional Reply length cap. Bounded by the key's limit. -
render array Optional Return the reply as structure as well as text, so you do not have to parse markdown yourself. 'blocks' gives typed JSON (paragraph, table, code, list, heading, quote, rule) for a native or mobile UI; 'html' gives escaped, ready-to-inject markup for a web one. Send `true` for both. Omit and the response is unchanged. Can also be set once on your key or bot so you never repeat it. -

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/nexus/chat \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"message": "What were the main risks in the report I sent?"}'

Response

JSON Response
{
  "status": "success",
  "engine": "nexus",
  "provider": "Codexbase",
  "reply": "...",  // The assistant's response, as markdown. Identical to `text`.
  "text": "...",  // Same value as `reply`. Both are returned so older clients keep working.
  "type": "...",  // Shape of this response: 'text', 'data' (structured), 'files', 'mixed' or 'error'.
  "data": ...,  // Parsed structured output. Populated when output_format is 'json' and the model returned valid JSON, and by /extract. Null otherwise, so check it rather than parsing `reply`.
  "model": "...",  // The engine that produced the reply.
  "intent": "...",  // Detected intent for this turn.
  "mode": "...",  // Behaviour profile this key resolved to: chatbot, analyst, extractor or general.
  "sources": ...,  // Web sources behind the answer: [{title, url}]. Empty when nothing was looked up.
  "tools_used": ...,  // Tools the model invoked, and whether each succeeded: [{tool, arguments, ok}].
  "session_id": "...",  // Thread id, reuse for the next turn. NULL when the key's mode has memory disabled (extractor is stateless by design); `memory.enabled` reports the same thing and `notes` says so.
  "memory": ...,  // {enabled, session_id, turns, condensed}. Check `enabled` before relying on threads.
  "files": ...,  // Generated artifacts: [{artifact_key, filename, content_type, size_bytes, download_url, expires_at}].
  "has_files": ...,  // Convenience flag, true when `files` is non-empty.
  "file_count": 0,  // Length of `files`.
  "attachments": ...,  // What the engine read on the way in, including whether a document was truncated, so a full read can be told from a partial one.
  "degraded": ...,  // True if answered by a weaker path than requested, e.g. vision unavailable so text-only answered. Check this, not just the status code.
  "notes": ...,  // Why the answer looks the way it does: media unreadable, reply truncated, memory disabled, research dropped.
  "latency_ms": 0,  // Server-side time for the whole request. Compare with your own wall clock: a large gap is transport, not inference.
  "tokens": 0,  // Tokens consumed, prompt plus completion.
  "meta": ...,  // Diagnostics: {elapsed_s, format, format_source, truncated, tokens, pipeline, provider, model, intent, mode, notes, tools_used}.
  "latency_ms": 245.3
}

Fast Chat Chat

Fast conversational AI, with automatic failover across several backends so a single outage does not stop a reply.

POST /api/v1/grok/chat
Requires Basic plan or higher.

Fast conversational chat with automatic backend failover. Supports multi-turn conversations.

Request Parameters

FieldTypeRequiredDescriptionDefault
message string Required User message -
messages array Optional Conversation history -
system string Optional You are a helpful AI assistant.
max_tokens integer Optional 1000
temperature number Optional 0.7

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/grok/chat \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"message": "example text"}'

Response

JSON Response
{
  "status": "success",
  "engine": "grok-chat",
  "provider": "Codexbase",
  "reply": "...",  // 
  "model_used": "...",  // 
  "tokens_used": 0,  // 
  "latency_ms": 245.3
}

Text Classification Custom ML

Custom ML engine: classify text into your own categories. Train on your CSV, Excel, or database data, then classify instantly. No external AI provider required.

POST /api/v1/text-classification/classify

Text Classification: Custom Engine#

This is a custom engine: runs entirely on your own training data using scikit-learn. No external AI API key is required.

How to use#
  1. Train a model by uploading a CSV/Excel file or connecting a database. This is done in the dashboard, not with an API key.
  2. Classify by sending text with the model_key training returned. This is the API-key endpoint.
Which endpoints take an API key#
EndpointAuthNotes
POST /classifyAPI keythe endpoint you integrate against
GET /infoAPI keycapabilities
POST /train, /train-db, /train-supabasesigned-in sessionfile upload and database training, dashboard only
GET /modelssigned-in sessionlists your trained models

Sending an API key to a session-only route returns 401, and the key is not the problem. Train in the dashboard, then classify over the API with the model_key it gives you. File uploads belong to training, which is why /classify takes text and no file.

Training data format#

CSV/Excel: product_name, product_description, category_name columns.
Common aliases (name, title, description, category, label) accepted.

System model#

Admin trains a system-wide model. Use model_key: 'system' to reference it.

Request Parameters

FieldTypeRequiredDescriptionDefault
text string Required Text to classify -
model_key string Required Cloudinary public_id of your trained model (returned by /train). Use 'system' for the admin-trained system model. -
top_n integer Optional Number of top predictions to return (1–10) 3

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/text-classification/classify \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"model_key": "codexbase/tc_user_myshop", "text": "wireless noise-cancelling headphones 30hr battery"}'

Response

JSON Response
{
  "status": "success",
  "engine": "text-classification",
  "provider": "Custom (scikit-learn ensemble, no API key needed)",
  "results": ...,  // 
  "model_info": ...,  // 
  "model_key": "...",  // 
  "latency_ms": 245.3
}

Pro Assistant Chat

Advanced conversational assistant with automatic backend failover. Supports multi-turn chat, custom system prompts, and structured outputs.

POST /api/v1/gpt/chat
Requires Pro plan or higher.

Full-featured conversational assistant with automatic backend failover, so a single upstream outage does not stop a reply. Pass a message for single-turn, or messages array for multi-turn.

Request Parameters

FieldTypeRequiredDescriptionDefault
message string Required User message -
messages array Optional Full conversation history for multi-turn chat -
system string Optional System persona You are a helpful assistant.
max_tokens integer Optional 1000
temperature number Optional 0.7
response_format string
text | json_object
Optional text

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/gpt/chat \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"message": "example text"}'

Response

JSON Response
{
  "status": "success",
  "engine": "gpt-assistant",
  "provider": "Codexbase",
  "reply": "...",  // 
  "model_used": "...",  // 
  "tokens_used": 0,  // 
  "latency_ms": 245.3
}

LabWise Lab Interpreter Medical

AI-powered medical lab result interpretation. Submit text, PDF, or image lab results, get plain-language explanations, abnormal flags, agentic self-correction (up to 3 loops), and personalized wellness recommendations. PII stripped before every AI call (NDPR/POPIA). Supports 80+ lab tests.

POST /api/v1/labwise/interpret
10 per minute
Requires Pro plan or higher.

Submit lab result text, a PDF, or a photo of a report and receive a full agentic interpretation. Supports CBC, metabolic panel, lipids, thyroid, hormones, kidney, liver, infectious disease and 80+ other tests. 3-gate validation ensures quality. PII is anonymized before AI processing.

Endpoints

EndpointMethodBodyPurpose
/interpretPOSTJSONinterpret pasted result text
/interpret/filePOSTmultipartinterpret a PDF or an image
/simplifyPOSTJSONrewrite an interpretation in plain language
/recommendPOSTJSONwellness recommendations from an interpretation
/infoGETcapabilities and supported tests

Uploading a file. Text goes to /interpret as JSON, but a file goes to a different endpoint with a different content type. This is the part the parameter table below cannot show, because those fields describe the JSON body only.

curl -X POST https://aihub.codexbase.net/api/v1/labwise/interpret/file \
  -H 'X-API-Key: cxb_your_key' \
  -F 'file=@bloodwork.pdf' \
  -F 'patient_id=ANON'
field namefile (required), patient_id (optional)
acceptedapplication/pdf, or any image: JPEG, PNG, TIFF, WEBP
maximum size10 MB
rate limit10 requests per minute

A scanned report is read with OCR, so a sharp, straight photo gives a better interpretation than a skewed or low-light one. Anything that could not be read is reported rather than guessed at.

Requires an AI provider key configured in Admin, Agent API Keys.

Request Parameters

FieldTypeRequiredDescriptionDefault
text string Optional Lab result text, for the JSON endpoints. Required for /interpret, /simplify and /recommend. Not used when uploading a file. -
file file Optional PDF or image of a lab report. Send as multipart/form-data to POST /interpret/file, not as JSON. Accepts application/pdf or any image (JPEG, PNG, TIFF, WEBP), up to 10 MB. Scanned reports are read with OCR. -
patient_id string Optional Anonymized patient ID: never use real names or IDs ANON
mode string
interpret | simplify | recommend
Optional interpret=full analysis | simplify=plain language | recommend=wellness tips interpret
simplify_level string
basic | child | bullet
Optional For mode=simplify: basic=plain English, child=12yr level, bullet=emoji list basic
format string
full | brief
Optional For mode=recommend: full=narrative+ranked list, brief=5 tips full

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/labwise/interpret \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{}'

Response

JSON Response
{
  "status": "success",
  "engine": "labwise",
  "provider": "Codexbase",
  "interpretation": "...",  // AI-generated interpretation text
  "confidence": 0,  // AI quality confidence 0.0–1.0
  "metrics_found": 0,  // Number of lab tests parsed
  "refinement_loops": 0,  // Agentic self-correction loops used
  "was_refined": ...,  // 
  "warnings": ...,  // 
  "processing_time_ms": 0,  // 
  "feedback_id": "...",  // 
  "latency_ms": 245.3
}

Medical Result Analyzer Medical

AI-powered analysis of medical lab results, blood work, and clinical notes. Explains findings in plain language, flags abnormal values, and suggests follow-up questions. For informational purposes only: not medical advice.

POST /api/v1/medical/analyze
10 per minute
Requires Pro plan or higher.

Submit raw lab results text or clinical notes. Select audience: 'patient' (simple language) or 'clinician' (technical). Engine flags abnormal values, explains significance, and suggests questions.

Request Parameters

FieldTypeRequiredDescriptionDefault
text string Required Raw lab results, blood work, or clinical notes text -
audience string
patient | clinician
Optional Target audience: 'patient' for plain language, 'clinician' for technical patient
include_questions boolean Optional Whether to include suggested follow-up questions for the doctor True
max_tokens integer Optional Maximum tokens in the response (100–2000) 800

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/medical/analyze \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"text": "HbA1c: 8.2% (High). Fasting glucose: 185 mg/dL. LDL: 142 mg/dL."}'

Response

JSON Response
{
  "status": "success",
  "engine": "medical-analyzer",
  "provider": "Codexbase",
  "summary": "...",  // Plain-language summary of findings
  "abnormal": ...,  // List of flagged abnormal values
  "severity": "...",  // Overall severity: normal/mild/moderate/high
  "questions": ...,  // Suggested questions for the doctor
  "disclaimer": "...",  // Medical disclaimer
  "tokens_used": 0,  // 
  "latency_ms": 245.3
}

IGVoice Social Media

Build an Instagram voice from any public profile and generate on-brand posts using AI.

POST /api/v1/igvoice/generate

IGVoice learns how an Instagram account writes, then produces new posts in that voice.

Typical flow

  1. POST /api/v1/igvoice/profile with username, look up a public profile.
  2. POST /api/v1/igvoice/train with username: fetch its posts and build a voice profile. Returns a job_id; poll GET /api/v1/igvoice/job/{job_id} until it completes, then keep the voice_id.
  3. POST /api/v1/igvoice/generate with voice_id (or an inline voice_profile) plus a topic: returns posts and their post_ids.
  4. POST /api/v1/igvoice/feedback with a post_id and rating, updates the voice's quality score and improves later generations.

Note: generate requires either voice_id or voice_profile; calling it with neither returns 400.

Voices can also be listed (/voice/list), fetched (/voice/{id}) and refined directly (/voice/{id}/refine).

Request Parameters

FieldTypeRequiredDescriptionDefault
action string
search_profile | train_voice | save_voice | list_voices | generate_post | feedback
Optional Operation to run. Each route sets this automatically; only needed when posting to the engine directly. -
username string Optional Public Instagram handle, without the @. Required by search_profile and train_voice. -
voice_id integer Optional Id of a previously trained voice profile. generate_post needs either this or voice_profile. -
voice_profile object Optional Inline voice profile, as an alternative to voice_id, for generating without saving a voice first. -
topic string Optional What the generated post should be about. -
count integer Optional How many post variations to generate. 1
post_id integer Optional Generated post to rate. Required by feedback. -
rating string
good | bad
Optional Feedback verdict for a generated post. -
note string Optional Optional explanation of what was wrong, used to refine the voice. -

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/igvoice/generate \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{}'

Response

JSON Response
{
  "status": "success",
  "engine": "igvoice",
  "provider": "Codexbase",
  "posts": ...,  // Generated posts (generate_post)
  "post_ids": ...,  // Ids of generated posts, for feedback
  "voice_id": 0,  // Saved voice profile id (train_voice, save_voice)
  "profile": ...,  // Instagram profile data (search_profile)
  "job_id": 0,  // Training job id, poll GET /job/{id}
  "latency_ms": 0,  // Server-side processing time
  "latency_ms": 245.3
}

Product Tools Utilities

All-in-one product utility suite: AI marketing descriptions from image/video/pdf/audio/code with optional content validation checks, image/video/PDF watermarking, PDF compression, content-aware smart crop, background removal, and video compression.

POST /api/v1/product-tools/describe
20 per minute
Requires Basic plan or higher.

Ten operations over images, video and PDFs. Every endpoint is a POST and returns the result inline as base64: nothing is stored.

Two ways to send a file to any endpoint

  1. JSON with a base64 field: image_base64, video_base64, pdf_base64, watermark_base64.
  2. multipart/form-data with a real file upload, field names image, video, pdf, watermark.

You can also pass image_url / video_url instead and the file will be fetched. Max 10 MB decoded.

Operations

EndpointInputNotes
/describeimage, video, pdf, audio, codeAI marketing copy, optional validation
/watermark/imageimage + watermark
/watermark/videovideo + watermarkffmpeg
/watermark/pdfpdf + watermark
/compress/pdfpdf
/compress/videovideoffmpeg
/crop/smartimagecontent-aware, auto/face/saliency/entropy
/background/removeimageCloudinary AI cutout; png or webp
/info:capabilities and supported input types

Output formats: background removal and smart crop accept output_format: png | webp. webp is roughly seven times smaller than png for the same cutout, at the same visual quality.

A 200 is not always a full success: check the provider field in the response to confirm which backend actually handled the request.

Request Parameters

FieldTypeRequiredDescriptionDefault
image_url string Optional -
image_base64 string Optional -
video_url string Optional -
video_base64 string Optional -
pdf_url string Optional -
pdf_base64 string Optional -
audio_url string Optional -
audio_b64 string Optional -
code_url string Optional -
code_base64 string Optional -
code string Optional -
instructions string Optional -
category_list array Optional -
tone string Optional content creator
validation_checks array Optional e.g. ['is this a selfie?','contains adult content'] -
watermark_url string Optional -
watermark_base64 string Optional -
position string Optional bottom right
opacity integer Optional 80
quality string Optional standard
target_width integer Optional 800
target_height integer Optional 800
mode string Optional auto
output_format string Optional png

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/product-tools/describe \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{}'

Response

JSON Response
{
  "status": "success",
  "engine": "product-tools",
  "provider": "Codexbase",
  "action": "...",  // 
  "input_type": "...",  // 
  "descriptions": ...,  // 
  "names": ...,  // 
  "hashtags": ...,  // 
  "spotlight": "...",  // 
  "category": "...",  // 
  "validation_checks": ...,  // [{check, result(bool), confidence, explanation}]
  "result_base64": "...",  // 
  "result_format": "...",  // 
  "original_size_kb": 0,  // 
  "compressed_size_kb": 0,  // 
  "reduction_pct": 0,  // 
  "latency_ms": 245.3
}

Code Assistant Code

AI-powered code generation, review, debugging, and optimization.

POST /api/v1/code/assist

A code engine held to a principal-engineer standard: optimal complexity, no
security holes, fast and robust execution. One endpoint reviews, grades,
optimizes, designs and edits code across up to five files, and a sandbox runs it.

Quick start#

curl -X POST https://aihub.codexbase.net/api/v1/code/assist \
  -H "Authorization: Bearer cxb_your_key" -H "Content-Type: application/json" \
  -d '{"action": "diagnose", "language": "python",
       "code": "import subprocess\ndef run(cmd):\n    subprocess.call(cmd, shell=True)\n"}'

Every request is {"action": ..., "language": ..., ...}. language defaults to
python. The AI actions work for any language; Python also gets exact linting
(including security and performance rules) and exact formatting.

Authentication and limits#

AuthAuthorization: Bearer cxb_your_key or X-API-Key: cxb_your_key. Never put a key in a browser; for browsers use an embed session (below)
Rate limit30 requests a minute per key (code), 20 a minute (sandbox)
QuotaEach request counts once against your plan's daily quota
Sizecode up to 60,000 characters; files up to 5 files and 150,000 characters together
Key scopeA key limited to code-assistant can also use code-sandbox

Errors are JSON, {"error": "...", "code": <http status>}:

StatusMeaning
400Invalid input: unknown action, missing field, too large
401Missing, invalid, expired or revoked key or token
403The key or session may not use this engine or action
429Rate limit or daily quota reached
500Upstream failure; retry

Input#

FieldTypeUsed byDescription
actionstringallSee Actions
languagestringalle.g. python, javascript, typescript, cpp, java, go, rust
codestringsingle-file requestsSource code
filesarraymulti-file requestsUp to 5 {name, content, language}
namestringdiagnoseName of code within files, so imports from sibling files are checked
promptstringask, edit, design, generate; optional elsewhereQuestion or instruction
selectionobjectprose and rewrite actions{file, start_line, end_line}: focus on these lines
focusstringprose and rewrite actionsalgorithm, api, auth, data or concurrency: the field whose standard applies
prefix, suffixstringcompleteCode before and after the cursor

Actions#

ActionReturnsUse it to
diagnosediagnostics[], counts, categoriesFind security, performance and correctness issues with exact positions and fixes
evaluateevaluationGrade every function in every file against its optimal complexity
benchmarkharnessMeasure how each function really scales (Python)
completecompletionGet an inline suggestion at the cursor
formatformatted, changedReformat code
askresultAsk a question about the code
explain, reviewresultExplain, or review for security, performance and correctness
optimize, debug, document, generate, edit, designresult and code or files[]Get rewritten code to diff and apply
diagnose#
{"diagnostics": [{
   "start": {"line": 3, "column": 5}, "end": {"line": 3, "column": 36},
   "severity": "error", "category": "security", "rule": "S602", "source": "lint",
   "message": "`subprocess` call with `shell=True` identified, security issue",
   "fix": null
 }],
 "counts": {"error": 1, "warning": 0, "info": 0},
 "categories": {"syntax": 0, "security": 1, "performance": 0, "bug": 0, "style": 0}}

Positions are 1-based. category is syntax, security, performance, bug or
style. source is lint (exact), ai (semantic review) or project (an import
from a sibling file that no longer resolves). When fix is not null, apply its
edits ({start, end, text}) in order.

evaluate#

Send files or code. The code is analysed, not run.

{"evaluation": {
   "summary": "...", "level": "beginner | intermediate | advanced | expert",
   "time_complexity": "O(n^2)", "optimal_time_complexity": "O(n log n)",
   "space_complexity": "O(n)", "optimal_space_complexity": "O(n)", "is_optimal": false,
   "scores": {"efficiency": 52, "security": 100, "quality": 78, "overall": 70},
   "units": [{"file": "sorting.py", "name": "bubble_sort", "line": 1,
              "time_complexity": "O(n^2)", "optimal_time_complexity": "O(n log n)",
              "is_optimal": false, "efficiency": 40, "shortfall": "...", "fix": "..."}],
   "strengths": ["..."], "improvements": ["..."], "optimal_approach": "..."}}

overall weights efficiency twice. units has one row per function across all files.

benchmark#

Python only. Returns harness: a script that imports your modules, times each
function at growing input sizes and prints one JSON line per measurement,
{"function": "sorting.bubble_sort", "n": 1600, "seconds": 0.48}. Run it as
benchmark.py next to your files (in the browser sandbox, or anywhere you trust)
and fit log(seconds) against log(n): the slope k means O(n^k).

complete#

Send prefix and suffix. Returns completion, the text to insert; an empty
string means there is nothing useful to suggest. Call it after a pause in typing,
not on every keystroke.

Rewrites#

With code, the response has code: the complete revised program. With files,
it has files[]: {name, content, status: "modified" | "added"} for changed files
only. Public names and signatures are kept unless the instruction asks for a
rename. If a rewrite would break an import between files it is repaired
automatically once, and anything left is reported in warnings[].

design compares two or three candidate designs (complexity, security,
trade-offs), recommends one and implements it as linked files. With focus: "auth"
it may invent new flows, but only on proven primitives, never new cryptography.

Running code#

POST /api/v1/sandbox/run with {"language", "code", "stdin"} runs a program in
an isolated sandbox: no network, CPU, memory and process limits, nothing kept
between runs. GET /api/v1/sandbox/languages lists what is available.

Runs on the serverPython, JavaScript, C, C++, Java, Go, Rust, Ruby, PHP, Lua, Bash
Also in the browser, freePython, JavaScript
Not yetTypeScript, C#
{"ok": true, "status": "ok", "stdout": "42\n", "stderr": "", "error": null,
 "time_ms": 10.0, "memory_kb": 17048, "compile_ms": 2267.2}

status is ok, compile_error, compile_timeout, timeout or
runtime_error. A program that fails is still HTTP 200: branch on status.
Limits: 10 s of CPU (40 s to compile), 1 GB of memory for native code, 64 KB of
output per stream.

Examples#

# Optimize a two-file project for algorithmic efficiency
curl -X POST https://aihub.codexbase.net/api/v1/code/assist \
  -H "Authorization: Bearer cxb_your_key" -H "Content-Type: application/json" \
  -d '{"action": "optimize", "language": "python", "focus": "algorithm",
       "files": [{"name": "main.py", "content": "from algo import dupes\nprint(dupes([1,1,2]))\n"},
                 {"name": "algo.py", "content": "def dupes(xs):\n    return [x for i, x in enumerate(xs) if x in xs[:i]]\n"}]}'

# Grade every function
curl -X POST https://aihub.codexbase.net/api/v1/code/assist \
  -H "Authorization: Bearer cxb_your_key" -H "Content-Type: application/json" \
  -d '{"action": "evaluate", "language": "python", "code": "def two_sum(n, t):\n    for i in range(len(n)):\n        for j in range(i+1, len(n)):\n            if n[i]+n[j]==t: return [i, j]\n"}'

# Run C++ with input
curl -X POST https://aihub.codexbase.net/api/v1/sandbox/run \
  -H "Authorization: Bearer cxb_your_key" -H "Content-Type: application/json" \
  -d '{"language": "cpp", "code": "#include <iostream>\nint main(){int a,b;std::cin>>a>>b;std::cout<<a+b;}", "stdin": "2 40"}'

Embedding the workspace in your app#

Put the full workspace (editor, files, automatic checks, evaluation, assistant and
sandbox) in a web page or a mobile WebView, without your key reaching the browser.

1. Create a session on your server with your key:

curl -X POST https://aihub.codexbase.net/api/v1/embed/sessions \
  -H "Authorization: Bearer cxb_your_key" -H "Content-Type: application/json" \
  -d '{"subject": "student-1042", "title": "Exercise 3: Two Sum",
       "instructions": "Return the **indices** of two numbers adding to `target`. Aim for O(n).",
       "files": [{"name": "solution.py", "content": "def two_sum(nums, target):\n    pass\n"}],
       "allowed_origins": ["https://app.example.com"],
       "features": {"assistant": true}, "ttl_seconds": 3600, "max_calls": 300}'

All fields are optional. features has assistant, autocomplete, analysis,
format and run, all on by default; set "assistant": false for an exam and the
server refuses AI help, not only the page. ttl_seconds is 60 to 86400,
max_calls 1 to 5000. allowed_origins is required for an iframe.

The response includes embed_url, token, session_id and expires_at.

2. Show embed_url in an iframe served from an allowed origin, or in a WebView.
Add &theme=light or &theme=dark to match your app. The token travels in the
URL fragment, which is never sent to a server, and the page removes it on load.

3. Listen for the student's code (optional). The page posts
{source: "codexbase-workspace", type: "ready" | "files", files: [{name, content, language}]}
to its parent with postMessage, and to a WebView JavaScriptChannel named
CodexbaseWorkspace. A parent on an allowed origin can send
{type: "codexbase:setFiles", files} or {type: "codexbase:getFiles"}.

4. Manage it with your key: GET /api/v1/embed/sessions/<id> for usage,
DELETE /api/v1/embed/sessions/<id> to revoke it at once. A session also stops at
expiry, at max_calls, or when the key that created it is revoked. It can only
use the code engine and the sandbox, and usage counts against your quota.

Building your own interface#

The workspace is made of two ES modules you can use directly:

<script type="module">
  import { createCodeEditor } from 'https://aihub.codexbase.net/static/vendor/code-editor/editor.js';
  import { createSandbox } from 'https://aihub.codexbase.net/static/vendor/code-editor/sandbox.js';

  const ed = createCodeEditor(document.getElementById('editor'), { placeholder: 'Write code' });
  await ed.openFile('main.py', 'print("hello")', 'python');

  const sandbox = createSandbox({
    workerUrl: 'https://aihub.codexbase.net/static/vendor/code-editor/sandbox-worker.js',
    // For languages the browser cannot run: call YOUR server, which calls
    // /api/v1/sandbox/run with your key.
    remote: (req) => fetch('/your-backend/run', { method: 'POST', body: JSON.stringify(req) }).then(r => r.json()),
  });
  const result = await sandbox.run({ language: 'python', code: ed.getValue(), files: ed.allFiles() });
</script>

Editor methods: openFile, switchFile, closeFile, renameFile, allFiles,
getValue, replaceAll, insertAtCursor, selection, cursor, setLanguage,
setDiagnostics (takes diagnose output), applyFix, showDiff, acceptDiff,
rejectDiff, formatLocal, setCompletionProvider (wire it to complete),
setWrap, onChange.

Request Parameters

FieldTypeRequiredDescriptionDefault
action string
explain | review | generate | debug | optimize | document | ask | edit | design | diagnose | complete | format | evaluate | benchmark
Required What to do with the code. diagnose, complete, format and evaluate return structured data for editors. -
code string Optional The code snippet. Required for diagnose and format. -
files array Optional Up to 5 files [{name, content, language}] instead of code. Rewrite actions then return the changed files. -
name string Optional diagnose: file name of `code` within `files`, so imports from sibling files are checked -
focus string
algorithm | api | auth | data | concurrency
Optional Field whose standard the answer must meet -
selection object Optional {file, start_line, end_line}: focus the request on these lines -
prefix string Optional complete only: the code before the cursor -
suffix string Optional complete only: the code after the cursor -
prompt string Optional Additional instruction -
language string Optional Programming language python

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/code/assist \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"action": "example text"}'

Response

JSON Response
{
  "status": "success",
  "engine": "code-assistant",
  "provider": "Codexbase",
  "result": "...",  // AI response (prose actions)
  "diagnostics": ...,  // diagnose: [{start, end, severity, category, message, rule, source, fix}], category is syntax, security, performance, bug or style, positions are 1-based {line, column}; fix is {title, edits: [{start, end, text}]} or null
  "code": "...",  // optimize, debug, document, generate, edit: the complete revised code, ready to diff against the input
  "files": ...,  // rewrite actions with files: [{name, content, status: modified|added}], only changed files
  "warnings": ...,  // rewrite actions with files: problems left after the automatic repair pass, e.g. an import that no longer resolves
  "completion": "...",  // complete: text to insert at the cursor, possibly empty
  "evaluation": ...,  // evaluate: units (one per function across all files: complexity as written and optimal, efficiency, shortfall, fix), time/space complexity as written and optimal, is_optimal, scores {efficiency, security, quality, overall} 0-100, level, strengths, improvements, optimal_approach
  "harness": "...",  // benchmark: Python timing harness printing BENCH {function, n, seconds} lines; run it in a sandbox next to the project files
  "formatted": "...",  // format: the reformatted code
  "action": "...",  // 
  "language": "...",  // 
  "latency_ms": 245.3
}

Face Capture Vision

Guided selfie capture and photo preparation for official documents: checks face, pose, light and sharpness, replaces the background, and returns the photo cropped and sized to the chosen country format.

POST /api/v1/face-capture/prepare
30 per minute

Send a photo (multipart field image, image_base64, or image_url) with a format such as passport, FR/passport or US/dv_lottery, and an optional background (original, white, light_grey, blue, red, green). The photo is checked and, if it passes, returned finished at the format's exact size. For live guided capture, create a session with POST /sessions and follow the returned URLs. Photos are never stored.

Request Parameters

FieldTypeRequiredDescriptionDefault
image file Optional The photo (multipart) -
image_base64 string Optional The photo, base64 -
image_url string Optional A public URL of the photo -
format string Optional Format id from GET /api/v1/face-capture/formats passport
background string Optional original, white, off_white, light_grey, light_blue, blue, red or green -
language string Optional Prompt language: en, fr, ar, es, de, hi, pt, zh, ru, sw, tr en
file_type string
jpeg | png | webp
Optional Output file type; each format lists the ones it accepts -
max_kb integer Optional Largest allowed file size in KB (JPEG and WebP are compressed to fit) -
print_sheet boolean Optional Also return a 6x4 in print sheet -

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/face-capture/prepare \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{}'

Response

JSON Response
{
  "status": "success",
  "engine": "face-capture",
  "provider": "Codexbase",
  "accepted": ...,  // The photo passed every required check
  "score": 0,  // 0 to 100
  "checks": ...,  // pass, warn or fail per check
  "reasons": ...,  // Stable codes for what failed
  "prompt": ...,  // What to tell the person, code and text
  "photo": ...,  // The finished photo: base64, mime, size, dpi
  "latency_ms": 245.3
}

Code Sandbox Code

Run code in an isolated sandbox: Python, JavaScript, C, C++, Java, Go, Rust and more, with CPU time and memory.

POST /api/v1/sandbox/run
20 per minute

Send source code, a language and optional stdin; receive stdout, stderr, status, CPU time and peak memory. Untrusted code is isolated with CPU, memory, file and process limits, no network and a hard timeout.

Request Parameters

FieldTypeRequiredDescriptionDefault
language string Required One of the languages listed by GET /api/v1/sandbox/languages -
code string Required Complete program source -
stdin string Optional Standard input for the program -

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/sandbox/run \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"code": "example text", "language": "example text"}'

Response

JSON Response
{
  "status": "success",
  "engine": "code-sandbox",
  "provider": "Codexbase",
  "ok": ...,  // True when the program compiled and exited with status 0
  "stdout": "...",  // 
  "stderr": "...",  // Runtime errors, or the compiler's messages on compile_error
  "error": "...",  // Short human-readable failure, null on success
  "time_ms": 0,  // CPU time of the program itself (not compilation)
  "memory_kb": 0,  // Peak resident memory
  "compile_ms": 0,  // Compilation wall time, for compiled languages
  "latency_ms": 245.3
}

Voice Bridge Voice

Add a real-time, interruptible voice to any chat model: your own OpenAI-style endpoint, your backend through a webhook, or a Codexbase engine. Speech in, speech out, with barge-in.

POST /api/v1/voice/calls
30 per minute

Create an agent that points at your model (POST /agents), then start a call (POST /calls) and connect your app to the returned stream_url. Send 16 kHz PCM audio, receive 24 kHz PCM audio and JSON captions. Talking over the agent interrupts it. Also: POST /transcribe (speech to text) and POST /speak (text to speech).

Request Parameters

FieldTypeRequiredDescriptionDefault
agent_id string Required From POST /api/v1/voice/agents -

Code Examples

cURL
curl -X POST https://aihub.codexbase.net/api/v1/voice/calls \
  -H "X-API-Key: cxb_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{"agent_id": "example text"}'

Response

JSON Response
{
  "status": "success",
  "engine": "voice-bridge",
  "provider": "Codexbase",
  "call_id": "...",  // 
  "stream_url": "...",  // WebSocket URL, single use, valid 60 seconds
  "audio": ...,  // Input and output audio formats
  "latency_ms": 245.3
}

Product Tools 8 APIs · Vision · Media

8 AI-powered media APIs. Every endpoint accepts inputs as a public URL, base64-encoded bytes, or a multipart file upload.

Base URL: /api/v1/product-tools  ·  Auth: X-API-Key: cxb_your_key

1 · Product Describer

POST /api/v1/product-tools/describe
POST /api/v1/product-tools/describe/file  (multipart)

Analyse any image, video, PDF, audio clip, or code file with AI vision. Returns 5 descriptions, 5 name/title suggestions, 15 hashtags, a spotlight headline, optional matched category, detected content type, and per-check true/false validation results.

All Request Parameters

FieldTypeRequiredDescriptionDefault
INPUT: provide exactly one of the following groups
image_urlstringOne of*Public URL of an image (JPEG/PNG/WebP/GIF). Max ~10 MB.-
image_base64stringOne of*Base64-encoded image bytes. No data-URI prefix needed.-
video_urlstringOne of*Public URL of an MP4/MOV/AVI. A representative frame is extracted for vision analysis.-
video_base64stringOne of*Base64-encoded video bytes. Max ~100 MB.-
pdf_urlstringOne of*Public URL of a PDF. First page rendered as image; full text extracted.-
pdf_base64stringOne of*Base64-encoded PDF bytes. Max ~80 MB.-
audio_urlstringOne of*Public URL of an MP3/WAV/OGG/M4A file. Transcribed, then described.-
audio_b64stringOne of*Base64-encoded audio bytes. Max ~50 MB.-
code_urlstringOne of*Public URL of a code file (.html .py .js .css .json .yaml .sql …).-
code_base64stringOne of*Base64-encoded code file bytes.-
codestringOne of*Raw code string pasted directly into the JSON body.-
OPTIONS
tonestringOptionalWriting persona: content creator · business professional · luxury brand · lifestyle blogger · tech reviewer · real estate agent · fashion influencer · sports brand · food bloggercontent creator
instructionsstringOptionalCustom guidance for the AI, e.g. "focus on eco-friendly materials and sustainability".-
category_listarray of stringsOptionalList of category labels to match against. The AI picks the closest match and returns it in the category response field. E.g. ["Fashion", "Tech", "Home"].-
validation_checksarray of stringsOptionalFree-text checks to run on the content. Each check returns result: true|false, confidence: high|medium|low, and an explanation. E.g. ["is this a selfie?", "contains adult content", "shows a product for sale?"].-

* For /describe/file (multipart), send the file as the file field; all other parameters go as additional form fields. category_list = JSON array string. validation_checks = pipe-separated string, e.g. "is this a selfie?|contains adult content".

Complete Request Body: All Parameters

JSON body: image URL (all parameters shown)
POST /api/v1/product-tools/describe
Content-Type: application/json
X-API-Key: cxb_your_key_here

{
  "image_url": "https://example.com/product.jpg",

  "tone": "content creator",
  "instructions": "Focus on the eco-friendly materials and premium feel",

  "category_list": ["Fashion", "Tech", "Home & Living", "Sports", "Beauty"],

  "validation_checks": [
    "is this a selfie or close-up portrait?",
    "contains adult or 18+ content?",
    "shows a physical product for sale?",
    "is this an invoice or receipt?"
  ]
}

Complete Response

JSON Response: all fields
{
  "status": "success",
  "engine": "product-tools",
  "provider": "Codexbase",
  "latency_ms": 3241,
  "data": {
    "action": "describe",
    "input_type": "image",
    "content_type": "professional headshot of a man in a polka-dot shirt",

    "validation_checks": [
      { "check": "is this a selfie or close-up portrait?",
        "result": true, "confidence": "high",
        "explanation": "Close-up solo portrait against plain white background, typical of a professional headshot." },
      { "check": "contains adult or 18+ content?",
        "result": false, "confidence": "high",
        "explanation": "Fully clothed professional portrait with no explicit elements." },
      { "check": "shows a physical product for sale?",
        "result": false, "confidence": "high",
        "explanation": "This is a person portrait, not a product photo." },
      { "check": "is this an invoice or receipt?",
        "result": false, "confidence": "high",
        "explanation": "No document or text visible, this is a photographic portrait." }
    ],

    "spotlight": "Crisp headshot for a confident professional presence.",

    "descriptions": [
      "A clear and professional headshot of a man with short dark hair, looking directly at the camera with a neutral expression. Set against a plain white background. 📸",
      "This portrait captures a focused and composed individual, ideal for LinkedIn profiles, resumes, or official identification. Simple, clean, impactful.",
      "Project confidence and approachability with a professional image that speaks volumes. This headshot is perfect for making a strong first impression. ✨",
      "Elevate your professional presence instantly! A high-quality headshot like this can significantly boost your personal brand and online credibility. 🚀",
      "Sharp, professional, and ready for your next big step. Your image, your impact."
    ],

    "names": [
      "The Professional Gaze",
      "Modern Professional Portrait",
      "Executive Profile",
      "The Polka Dot Professional",
      "Focused Vision"
    ],

    "hashtags": [
      "#ProfessionalHeadshot", "#BusinessPortrait", "#CorporatePhotography",
      "#PersonalBranding", "#LinkedInProfile", "#ExecutiveLook",
      "#ProfessionalImage", "#HeadshotGoals", "#CareerReady",
      "#PolkaDotStyle", "#FormalWear", "#WhiteBackground",
      "#Confidence", "#FirstImpression", "#ModernProfessional"
    ],

    "category": "Photography",
    "tokens_used": 892
  }
}

Code Examples

Python
import requests, base64

API_KEY = "cxb_your_key_here"
BASE    = "https://aihub.codexbase.net"

# ── URL input ──────────────────────────────────────────────────────
r = requests.post(f"{BASE}/api/v1/product-tools/describe",
    headers={"X-API-Key": API_KEY},
    json={
        "image_url": "https://example.com/product.jpg",
        "tone": "content creator",
        "instructions": "Focus on eco-friendly materials",
        "category_list": ["Fashion", "Tech", "Home & Living"],
        "validation_checks": [
            "is this a selfie?",
            "contains adult content?",
            "shows a product for sale?"
        ]
    })
data = r.json()["data"]
print(data["content_type"])             # "professional headshot of a man..."
print(data["spotlight"])                # "Crisp headshot for a confident..."
print(data["descriptions"][0])          # first description string
print(data["descriptions"])             # list of 5 description strings
print(data["names"])                    # list of 5 name/title strings
print(data["hashtags"])                 # list of 15 hashtag strings
print(data["category"])                 # "Photography" (matched from category_list)
for chk in data["validation_checks"]:  # iterate validation results
    print(chk["check"], "→", chk["result"], f"({chk['confidence']})")
    print("  ", chk["explanation"])

# ── Base64 input (no public URL available) ─────────────────────────
with open("product.jpg", "rb") as f:
    b64 = base64.b64encode(f.read()).decode()
r2 = requests.post(f"{BASE}/api/v1/product-tools/describe",
    headers={"X-API-Key": API_KEY},
    json={"image_base64": b64, "tone": "luxury brand"})

# ── File upload ────────────────────────────────────────────────────
with open("product.jpg", "rb") as f:
    r3 = requests.post(f"{BASE}/api/v1/product-tools/describe/file",
        headers={"X-API-Key": API_KEY},
        files={"file": ("product.jpg", f, "image/jpeg")},
        data={
            "tone": "content creator",
            "category_list": '["Fashion","Tech"]',
            "validation_checks": "is this a selfie?|contains adult content?"
        })

2 · Watermark

Overlay a watermark image on a photo, video, or every page of a PDF. All endpoints accept URL or base64 for both inputs.

POST /api/v1/product-tools/watermark/image  , RapidAPI (4×100 req/mo) + Pillow fallback
POST /api/v1/product-tools/watermark/video  , FFmpeg overlay (allow 2–5 min)
POST /api/v1/product-tools/watermark/pdf  , PyMuPDF stamps every page
FieldForRequiredDescriptionDefault
image_url / image_base64Image WMRequiredSource image: URL or base64.-
video_url / video_base64Video WMRequiredSource video: URL or base64.-
pdf_url / pdf_base64PDF WMRequiredSource PDF: URL or base64.-
watermark_url / watermark_base64AllRequiredWatermark image: URL or base64. PNG with transparency recommended.-
positionAllOptionalbottom right · bottom left · top right · top left · centerbottom right
opacityAllOptional0 (fully transparent) – 100 (fully opaque)80 (image/video) · 30 (pdf)
JSON body + responses
# Watermark image
{ "image_url": "https://example.com/photo.jpg",
  "watermark_url": "https://example.com/logo.png",
  "position": "bottom right", "opacity": 80 }
# Response: { result_url (RapidAPI) OR result_base64 + result_format, method, position, opacity }

# Watermark video (longer processing, allow 2–5 min per minute of video)
{ "video_url": "https://example.com/clip.mp4",
  "watermark_url": "https://example.com/logo.png",
  "position": "bottom right", "opacity": 80 }
# Response: { result_base64, result_format:"mp4", method:"ffmpeg", position, opacity }

# Watermark PDF
{ "pdf_url": "https://example.com/doc.pdf",
  "watermark_url": "https://example.com/logo.png",
  "position": "bottom right", "opacity": 30 }
# Response: { result_base64, result_format:"pdf", pages_stamped, method:"pymupdf" }

3 · Compress

POST /api/v1/product-tools/compress/pdf  , PyMuPDF 3-pass · up to 70 MB → ≤100 KB
POST /api/v1/product-tools/compress/video  , FFmpeg H.264/AAC re-encode
FieldForRequiredDescriptionDefault
pdf_url / pdf_base64PDFRequiredSource PDF. Max ~70 MB input.-
qualityPDFOptionalstandard, cleanup + image downsample. aggressive, 96 DPI JPEG re-render (lossy, smallest).standard
video_url / video_base64VideoRequiredSource video.-
qualityVideoOptionalhigh (CRF 23) · standard (CRF 28) · aggressive (CRF 35)standard
max_widthVideoOptionalMax output width px (64–7680). Height scaled proportionally.1280
audio_bitrateVideoOptionalAAC audio bitrate, e.g. 96k, 128k, 192k.96k
JSON body + responses
# Compress PDF
{ "pdf_url": "https://example.com/large.pdf", "quality": "aggressive" }
# Response: { result_base64, original_size_kb, compressed_size_kb, reduction_pct, pages, quality_mode }

# Compress video
{ "video_url": "https://example.com/clip.mp4",
  "quality": "standard", "max_width": 1280, "audio_bitrate": "96k" }
# Response: { result_base64, original_size_kb, compressed_size_kb, reduction_pct, crf, quality_mode }

4 · Smart Crop & Background Remover

POST /api/v1/product-tools/crop/smart  : face → saliency → entropy cascade
POST /api/v1/product-tools/background/remove  , rembg U2Net · local · no quota
FieldForRequiredDescriptionDefault
image_url / image_base64BothRequiredSource image: URL or base64.-
target_widthSmart CropOptionalOutput width px (16–8000).800
target_heightSmart CropOptionalOutput height px (16–8000).800
modeSmart CropOptionalauto (face→saliency→entropy) · face · saliency · entropyauto
output_formatBG RemoveOptionalpng or webp, both preserve transparency.png
JSON body + responses
# Smart crop
{ "image_url": "https://example.com/photo.jpg",
  "target_width": 800, "target_height": 800, "mode": "auto" }
# Response: { result_base64, result_format:"webp", crop_region:{x,y,w,h}, output_size:{width,height}, method_used }

# Remove background
{ "image_url": "https://example.com/product.jpg", "output_format": "png" }
# Response: { result_base64, result_format:"png", has_alpha:true, method:"rembg" }

IGVoice: All Endpoints 11 endpoints

Train a custom AI writing voice from an Instagram profile, then generate on-brand posts for any topic. The training pipeline fetches posts → analyses tone/style/vocabulary with AI vision → stores a voice profile in the database for reuse.

Base URL: /api/v1/igvoice  ·  Auth: X-API-Key: cxb_your_key

POST /api/v1/igvoice/profile

Look up a public Instagram profile by username. Returns follower count, bio, post count, category, and whether it's a business account. Results cached 1 hour.

FieldTypeRequiredDescription
usernamestringRequiredInstagram username (with or without @). E.g. "natgeo" or "@natgeo".
Example
POST /api/v1/igvoice/profile
{ "username": "natgeo" }
# Response: { status, username, full_name, followers, following, posts,
#             bio, is_verified, is_business, category, profile_pic_url }

POST /api/v1/igvoice/train

Start a background voice-training job. Returns immediately with a job_id, the job runs asynchronously. Poll GET /api/v1/igvoice/job/{job_id} for status. The trained voice is saved automatically to the database when done.

FieldTypeRequiredDescriptionDefault
usernamestringRequiredInstagram username to train from (public account).-
voice_namestringOptionalFriendly label for this voice, e.g. "My Brand Voice".@username voice
max_postsintegerOptionalNumber of recent posts to analyse (1–30). More posts = richer voice.20
Example
POST /api/v1/igvoice/train
{ "username": "natgeo", "voice_name": "NatGeo Style", "max_posts": 20 }
# Response: { status:"queued", job_id:42, message:"Training started..." }
# → Poll: GET /api/v1/igvoice/job/42

GET /api/v1/igvoice/job/{job_id}

Poll the status of a background training job. Only the job owner can poll (API key auth required).

Example
GET /api/v1/igvoice/job/42
X-API-Key: cxb_your_key_here

# Response:
{ "status": "done",          # "queued" | "running" | "done" | "failed"
  "progress": 100,
  "voice_id": 7,             # set when done, use for generate
  "voice_name": "NatGeo Style",
  "message": "Voice trained successfully from 20 posts." }

POST /api/v1/igvoice/generate

Generate Instagram posts in a trained voice. Pass voice_id (from training) or an inline voice_profile dict. Returns post text, hashtags, emojis, and a call-to-action, plus a post_id for submitting feedback.

FieldTypeRequiredDescriptionDefault
topicstringRequiredWhat to write about, e.g. "new product launch", "summer collection".-
voice_idintegerOne of*ID of a saved trained voice (from /train → poll → voice_id).-
voice_profileobjectOne of*Inline voice profile dict (if you don't have a saved voice_id).-
post_typestringOptionalimage_text · carousel · reel · storyimage_text
num_postsintegerOptionalNumber of variations to generate (1–5).1
extra_contextstringOptionalExtra context for the AI, e.g. "product is eco-certified, mention sustainability".-
Example
POST /api/v1/igvoice/generate
{
  "voice_id": 7,
  "topic": "summer collection launch",
  "post_type": "image_text",
  "num_posts": 3,
  "extra_context": "The collection uses recycled ocean plastic, mention sustainability"
}
# Response: { posts: [ { post_id, caption, hashtags, emoji_set, call_to_action }, ... ] }

POST /api/v1/igvoice/feedback

Rate a generated post good or bad. Feedback accumulates and can be used to auto-refine the voice via /voice/{id}/refine.

FieldTypeRequiredDescription
post_idintegerRequiredID returned in the generate response.
ratingstringRequired"good" or "bad".
notestringOptionalFree-text explanation, e.g. "Too formal, brand is casual". Used during voice refinement.
Example
POST /api/v1/igvoice/feedback
{ "post_id": 123, "rating": "bad", "note": "Too formal, our brand is casual and playful" }
# Response: { status:"success", voice_quality_score: 0.72 }

POST /api/v1/igvoice/voice/{id}/refine

Pull all bad-rated feedback notes for this voice and sends them back through the model to produce an improved voice profile. The result is saved as a new version of the voice (version bumped).

FieldTypeRequiredDescription
voice_idintegerRequiredIn the URL path: POST /api/v1/igvoice/voice/7/refine
refinement_promptstringOptionalExtra instruction, e.g. "Make the tone more playful and use more emojis".
Example
POST /api/v1/igvoice/voice/7/refine
{ "refinement_prompt": "More playful, use emojis, shorter captions" }
# Response: { status:"success", voice_id:7, voice_version:2, improved_profile:{...} }

Voice Management

EndpointMethodKey ParametersDescription
/api/v1/igvoice/voice/savePOSTvoice_profile (required), name, source_handleSave a voice profile dict directly: no IG fetch needed. Returns voice_id.
/api/v1/igvoice/voice/listPOSTNo body requiredList all saved voices belonging to the authenticated user.
/api/v1/igvoice/voice/{id}GETvoice_id in URLGet details of a single saved voice including full profile and quality score.
/api/v1/igvoice/popularGETNo auth requiredList pre-seeded popular voice handles for inspiration.

Labwise: All Endpoints 4 endpoints

AI-powered medical lab report interpreter. Uses a 3-gate agentic pipeline (parse → interpret → self-refine) with AI vision. Accepts plain text, lab report images, or PDFs.

Medical disclaimer: Labwise provides general informational interpretations only. It is not a substitute for professional medical advice, diagnosis, or treatment. Always consult a qualified healthcare provider.
Base URL: /api/v1/labwise  ·  Auth: X-API-Key: cxb_your_key  ·  Rate: 10 req/min

POST /api/v1/labwise/interpret

Full 3-gate agentic interpretation of lab results from plain text. The pipeline: (1) extracts and parses all lab metrics, (2) interprets them against reference ranges, (3) self-corrects if confidence is low.

FieldTypeRequiredDescriptionDefault
textstringRequiredRaw lab result text. Include test names, values, units, and reference ranges for best results.-
patient_idstringOptionalAnonymized patient identifier. Never use real patient names or IDs.ANON
Request + Response
POST /api/v1/labwise/interpret
Content-Type: application/json
X-API-Key: cxb_your_key_here

{
  "text": "Hemoglobin: 8.5 g/dL (Ref: 13.5-17.5) LOW\nGlucose: 126 mg/dL (Ref: 70-100) HIGH\nCreatinine: 1.1 mg/dL (Ref: 0.6-1.2) NORMAL",
  "patient_id": "PT-001"
}

# Response:
{
  "status": "success",
  "interpretation": "The results show low hemoglobin (8.5 g/dL), consistent with anemia...",
  "confidence": 0.91,
  "metrics_found": 3,
  "refinement_loops": 1,
  "was_refined": true,
  "warnings": ["Low hemoglobin, potential anemia"],
  "processing_time_ms": 4210,
  "feedback_id": "a1b2c3d4"
}

POST /api/v1/labwise/interpret/file

Interpret a lab report from a PDF or image file upload. AI vision reads the document directly: no OCR pre-processing needed. Supports JPEG, PNG, TIFF, WebP, and PDF.

FieldTypeRequiredDescription
filefile (multipart)RequiredLab report image (JPEG/PNG/TIFF/WebP) or PDF. Max file size configured server-side.
patient_idstring (form field)OptionalAnonymized patient ID. Never use real names.
cURL + Python
# cURL
curl -X POST https://aihub.codexbase.net/api/v1/labwise/interpret/file \
  -H "X-API-Key: cxb_your_key_here" \
  -F "file=@lab_report.pdf" \
  -F "patient_id=PT-001"

# Python
import requests
with open("lab_report.jpg", "rb") as f:
    r = requests.post(
        "https://aihub.codexbase.net/api/v1/labwise/interpret/file",
        headers={"X-API-Key": "cxb_your_key_here"},
        files={"file": ("lab_report.jpg", f, "image/jpeg")},
        data={"patient_id": "PT-001"}
    )
print(r.json()["interpretation"])

POST /api/v1/labwise/simplify

Rewrite an existing lab interpretation in plain language. Choose the simplification level to match your audience.

FieldTypeRequiredDescriptionDefault
textstringRequiredThe interpretation text to simplify (e.g. output from /interpret).-
simplify_levelstringOptionalbasic, plain English for adults. child, 12-year-old reading level. bullet, emoji-enhanced bullet list.basic
Example
POST /api/v1/labwise/simplify
{
  "text": "Hemoglobin 8.5 g/dL indicates microcytic hypochromic anemia...",
  "simplify_level": "child"
}
# Response: { status:"success", simplified_text:"Your blood doesn't have enough iron carriers..." }

POST /api/v1/labwise/recommend

Generate general wellness recommendations based on interpreted lab results. Not medical advice, always recommend the user consult a doctor.

FieldTypeRequiredDescriptionDefault
textstringRequiredInterpretation text to generate recommendations from.-
formatstringOptionalfull, narrative explanation + ranked recommendation list. brief, 5 concise tips.full
Example
POST /api/v1/labwise/recommend
{
  "text": "Hemoglobin 8.5 g/dL (LOW), consistent with iron-deficiency anemia...",
  "format": "full"
}
# Response: { status:"success", recommendations:"1. Increase dietary iron intake (red meat, spinach, lentils)...",
#             disclaimer:"This is general information only. Please consult a qualified healthcare provider." }

Face Capture: All Endpoints 9 endpoints

Official photos from a selfie or an uploaded picture: passport, ID card, visa, student card, birth certificate and more, for 98 countries. Each photo is checked (face, pose, light, sharpness, expression, cover), the background is replaced if you ask, the photo is cleaned up (white balance, exposure, noise) and returned at the format's exact size. Photos are never stored: the finished photo comes back in the response and is discarded.

Base URL: /api/v1/face-capture  ·  Auth: X-API-Key: cxb_your_key
Your app must obtain consent from the person photographed (from a parent or guardian for a minor) under the data protection rules of each country you serve.

POST /api/v1/face-capture/prepare

Check one photo and, if it passes, return it finished. Send the photo as multipart image, JSON image_base64, or JSON image_url (max 8 MB).

FieldTypeRequiredDescription
image / image_base64 / image_urlfile / stringOne ofThe photo. JPEG, PNG or WebP.
formatstringOptionalFormat id from GET /formats: passport (default), id_card, student, dv_lottery, CM/passport, NG/id_card, AE/emirates_id, ... or custom.
backgroundstringOptionaloriginal, white, off_white, light_grey, light_blue, blue, red, green. Each format lists the ones it accepts; US passport and DV lottery keep the original background (edited photos are refused there) and check it is plain.
file_typestringOptionaljpeg, png or webp, as the format allows (DV lottery: JPEG only).
max_kbintegerOptionalLargest file size. JPEG and WebP are compressed to fit; a PNG over the limit is refused.
languagestringOptionalLanguage of the prompt text: en, fr, ar, es, de, hi, pt, zh, ru, sw, tr.
print_sheetbooleanOptionalAlso return a 6x4 in (10x15 cm) sheet of copies for printing.
customobjectOptionalWith format: "custom": {"width_mm": 25, "height_mm": 30, "dpi": 300} or {"width_px", "height_px"}.
cURL
curl -X POST https://aihub.codexbase.net/api/v1/face-capture/prepare \
  -H "X-API-Key: cxb_your_key" \
  -F image=@selfie.jpg -F format=CM/passport -F background=white -F language=fr
Response (accepted)
{
  "status": "ok", "accepted": true, "score": 94,
  "checks": {"face_present": "pass", "pose": "pass", "brightness": "pass", "sharpness": "pass",
             "eyes_open": "pass", "expression": "warn", "occlusion": "pass", "resolution": "pass"},
  "reasons": [], "prompt": {"code": "perfect", "text": "Perfect, hold it"},
  "photo": {"base64": "...", "mime": "image/jpeg", "width_px": 413, "height_px": 531,
            "dpi": 300, "bytes": 77412, "file_type": "jpeg", "background": "white", "enhanced": true},
  "format": {"id": "CM/passport", "width_mm": 35, "height_mm": 45, "status": "unverified"}
}

When accepted is false there is no photo: reasons lists stable codes (wrong_pose, bad_light, too_blurry, eyes_closed, face_covered, background_not_plain, ...) and prompt says what to tell the person.

POST /api/v1/face-capture/analyze

Same input as /prepare; returns the checks and score only, no image.

POST /api/v1/face-capture/sessions

Guided live capture. Call it from your server; the response carries everything the device needs, and your API key never reaches it.

FieldTypeRequiredDescription
format, background, file_type, languagestringOptionalAs for /prepare.
posesarrayOptionalAny of front (default), left, right, chin_up; up to 4.
external_refstringOptionalYour own id for the person, stored as is.
Response 201
{
  "session_id": "fc_9f3a...", "state": "created", "current_pose": "front",
  "session_token": "eyJ...",              // Authorization: Bearer for upload_url and frames_url
  "upload_url": "https://.../face/shots", // POST the full-resolution photo (multipart image + pose)
  "stream_url": "wss://.../face/stream?token=...", // optional live guidance, single use, 60 s
  "frames_url": "https://.../face/frames",          // the same guidance over HTTP
  "rules": {...}, "prompts": {...}, "poses": {...}, "expires_in": 600
}

Flow: coach on the device with the returned rules (or stream 320x240 JPEG frames to stream_url; each message has checks, ready, hold_ms, capture and a prompt). When capture is true, POST one full-resolution photo to upload_url. Accepted shots return the finished photo with next_pose and progress. Sessions expire after 10 minutes without activity; five rejected shots of one pose set the state to needs_help.

GET / DELETE /api/v1/face-capture/sessions/{id}  ·  POST /sessions/{id}/tokens

GET returns state, results and scores (never images). DELETE cancels the session. POST /tokens with body {} returns fresh tokens, for example to reconnect a dropped stream.

GET /formats  ·  /formats/{id}  ·  /rules  ·  /languages  ·  /health

Public, no key. /formats?country=FR lists a country's documents with size, pixels, dpi, head height, allowed backgrounds and file types, and status: verified or unverified against the official source. /rules?format=...&language=... returns the thresholds and prompt texts the server applies, for on-device coaching.

Voice Bridge: All Endpoints 11 endpoints

A spoken, interruptible front end for the chat model you already have. People talk, your model answers, they hear the answer and can cut in at any time, like a phone call. Your model stays yours: use Codexbase Nexus (no key needed), any OpenAI-compatible endpoint, or your own backend through a webhook. Languages include English, French, Arabic, Spanish, German, Hindi, Portuguese, Chinese, Russian, Swahili, Turkish and Pidgin, with a standard or genz speaking style.

Base URL: /api/v1/voice  ·  Auth: X-API-Key: cxb_your_key

POST /api/v1/voice/agents

An agent says how to reach your model and how it should sound. Keys you give are stored encrypted and never returned (responses show only that a key is set and its last four characters); they never reach a browser.

FieldTypeRequiredDescription
namestringRequiredYour label for the agent.
modestringRequirednexus, openai_compatible or webhook.
llmobjectDependsnexus: nothing (default Nexus, uses your account and its limits) or {"api_key", "bot_id"}. openai_compatible: {"base_url", "model", "api_key"}. webhook: {"url", "secret"} (https only).
system_promptstringOptionalInstructions for OpenAI-compatible models.
greetingstringOptionalSaid when the call connects.
languagestringOptionalen, fr, ar, es, de, hi, pt, zh, ru, sw, tr, pcm (Pidgin) or auto. A fixed language understands noisy rooms best.
stylestringOptionalstandard or genz (casual, current slang).
voicestringOptionalFrom GET /options.
max_secondsintegerOptionalCall length limit, 30 to 900 (default 300).
speechobjectOptionalYour own speech keys for production volume: {"stt_key", "tts_gemini_key", "tts_groq_key"}.

Also GET /agents, GET /agents/{id}, PATCH /agents/{id} (partial update; omitted keys are kept) and DELETE /agents/{id} (its keys are erased at once).

Webhook mode: we POST {"call_id", "transcript", "history", "instructions"} to your URL; answer with plain text, JSON {"reply": "..."}, or a text/event-stream of chunks (spoken sentence by sentence).

POST /api/v1/voice/calls

Start a call from your server with {"agent_id"}. Hand the returned stream_url (a WebSocket URL with a single-use token, valid 60 seconds) to your app.

Response 201
{
  "call_id": "vc_1f2e...", "state": "created", "expires_in": 60, "max_seconds": 300,
  "stream_url": "wss://.../voice/call?token=...",
  "audio": {"input":  {"encoding": "pcm_s16le", "sample_rate": 16000, "channels": 1},
            "output": {"encoding": "pcm_s16le", "sample_rate": 24000, "channels": 1}}
}

The call (WebSocket)

DirectionMessageMeaning
App to serverbinary16 kHz mono PCM16 microphone audio, 20 to 100 ms chunks. Turn on echo cancellation (getUserMedia({audio: {echoCancellation: true}})).
App to server{"type":"text","text":"..."}A typed turn instead of speech.
Server to appbinary24 kHz mono PCM16 agent audio; play in order.
Server to appready, transcript, agent_text, agent_speaking, agent_done, links, errorJSON events for captions and state. transcript has final: true|false.
Server to app{"type":"interrupted"}The person spoke over the agent: drop any agent audio still buffered.
cURL
curl -X POST https://aihub.codexbase.net/api/v1/voice/agents -H "X-API-Key: cxb_your_key" \
  -H "Content-Type: application/json" \
  -d '{"name": "Help line", "mode": "nexus", "language": "pcm", "style": "genz", "greeting": "How you dey?"}'

curl -X POST https://aihub.codexbase.net/api/v1/voice/calls -H "X-API-Key: cxb_your_key" \
  -H "Content-Type: application/json" -d '{"agent_id": "va_..."}'

A call ends when the app disconnects or at max_seconds. GET /calls/{id} returns duration and turns. Audio and transcripts are not stored.

POST /api/v1/voice/transcribe  ·  POST /api/v1/voice/speak

/transcribe: multipart audio (WAV, MP3, M4A, OGG, WebM; 10 MB) and optional language; returns text and the detected language. /speak: JSON {"text", "voice"}; returns WAV as base64, or raw audio with Accept: audio/wav. GET /options (public) lists modes, languages, styles and voices.

SDKs & Libraries

No SDK required: CodexbaseAIHub is a standard REST API. Use any HTTP client in any language. The examples above show cURL, Python requests, JavaScript fetch, and Go's net/http.

For interactive exploration, use the Swagger UI which lets you try every endpoint with your API key in the browser.

Plans & Limits

PlanDaily RequestsEnginesAPI Keys
Free100Free-tier engines3
Basic1,000Free + Basic engines10
Pro10,000All engines10
EnterpriseUnlimitedAll engines + priorityUnlimited

View full pricing →