Pixil XD 1.3 · Text Chat API
Build your next
conversation.
Everything from your first request to streaming responses, a branded website widget, human support and measured token billing.
Server API
Your interface, our text API
Website widget
AI and human support
Streaming
SSE replies and events
01 / GUIDE
Get started
Pixizen Chat API provides text-only language-model responses through your Pixizen backend. Create a Pixizen account, open API → Overview, and create a project. API-only projects do not need website verification; public widgets do.
Open Billing to add a separate Chat API balance. Open API Keys, select your project, and generate a key. Copy it once into a server environment variable. Never put this key in browser JavaScript, a public repository, or a mobile binary.
The base URL is your deployed Pixizen backend origin followed by /api/chat/v1. Examples use api.example.com as a placeholder. Replace it with your actual backend hostname. Paid requests require published pricing and configured upstream metering.
02 / GUIDE
Authentication and projects
Send Authorization: Bearer YOUR_API_KEY on every developer request. A key belongs to one customer and one project. It expires after 90 days, can be revoked immediately, and has a lifetime USD spending budget. To rotate, create a replacement key, update your backend, then revoke the old key.
Dashboard authentication uses the existing Pixizen account session. Widget visitors use separate short-lived conversation tokens. None of these credentials can be substituted for another. Keys authorize only chat endpoints; they cannot generate images, videos, audio, or access your dashboard.
export PIXIZEN_API_KEY="YOUR_SECRET_KEY"
export PIXIZEN_BASE_URL="https://api.example.com/api/chat/v1"03 / GUIDE
Your first request
POST /chat/completions accepts model, messages, max_tokens, and stream. Other top-level fields are rejected. The currently configured public model is returned by GET /models. The default model identifier is pixil-xd-1.3.
Provide 1–40 messages. Every message has role system, user, or assistant, and plain-text content of at most 32,000 characters. Image inputs and tool calls are not supported. Input is also bounded by the published conservative UTF-8 byte limit.
curl "$PIXIZEN_BASE_URL/chat/completions" \
-H "Authorization: Bearer $PIXIZEN_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-help-001" \
-d '{"model":"pixil-xd-1.3","messages":[{"role":"user","content":"Hello"}],"max_tokens":300,"stream":false}'04 / GUIDE
Response and token usage
The response contains id, model, choices[0].message.content, usage, and cost_usd. prompt_tokens includes cached tokens. completion_tokens is generated output. total_tokens is input plus output. prompt_tokens_details.cached_tokens is the reported cached portion, or null when unavailable; cache_metering_available indicates whether the provider reported it.
Only measured provider token counts settle a request. A provider that does not report cache hits receives no cached-token discount; this does not claim cache metering support. Missing or invalid input/output counts place the request in reconciliation.
{
"id": "request_hash",
"object": "chat.completion",
"model": "pixil-xd-1.3",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello!"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 1000,
"completion_tokens": 100,
"total_tokens": 1100,
"prompt_tokens_details": {
"cached_tokens": 0
}
},
"cost_usd": 0.0025
}05 / GUIDE
Streaming responses with SSE
Set stream:true. Read data events as they arrive and append choices[0].delta.content. A completed event contains final response, measured usage, and cost; data: [DONE] closes the successful stream. An error event is terminal and may arrive after partial output. Never treat partial text as proof of completed billing.
Keep the customer API key on your server. Your backend can relay text to the browser using its own authenticated SSE or streaming connection. Streaming here is HTTP text delivery, not a voice or audio API.
const response = await fetch(process.env.PIXIZEN_BASE_URL + '/chat/completions', {
method: 'POST',
headers: { Authorization: 'Bearer ' + process.env.PIXIZEN_API_KEY,
'Content-Type': 'application/json' },
body: JSON.stringify({model:'pixil-xd-1.3', stream:true,
messages:[{role:'user',content:'Explain this briefly'}], max_tokens:300})
});
if (!response.ok) throw new Error('Chat request failed');
// Parse SSE blocks separated by a blank line. Chunks are not whole events.
for await (const chunk of response.body) process.stdout.write(chunk);06 / GUIDE
Python example
This standard-library example runs on your server. Save credentials in environment variables. Set an application timeout and handle non-2xx responses.
import os, json, urllib.request
body = {"model":"pixil-xd-1.3", "messages":[{"role":"user", "content":"Hello"}], "max_tokens":300}
request = urllib.request.Request(
os.environ["PIXIZEN_BASE_URL"] + "/chat/completions",
data=json.dumps(body).encode(),
headers={"Authorization":"Bearer " + os.environ["PIXIZEN_API_KEY"],
"Content-Type":"application/json"}, method="POST")
with urllib.request.urlopen(request, timeout=100) as response:
result=json.load(response)
print(result["choices"][0]["message"]["content"])07 / GUIDE
Realtime notifications and reconnect
GET /events streams durable notifications authorized to the API key’s project. Event types include usage.completed and usage.reconciliation. Dashboard event streams additionally deliver message.created, conversation.created, conversation.updated, assistant.unavailable, and payment.updated.
Authenticate streams using a fetch client or server HTTP client with the Bearer header. Do not put keys in query strings. On reconnect send Last-Event-ID using the last processed SSE id. Records are retained for seven days. Fetch current resource state after connecting or if your cursor is older than retention. There are at most five open event streams per actor.
Heartbeats keep the connection alive. Authentication is checked again at least every 15 seconds. A revoked key or expired visitor session loses the stream. These are server-to-client SSE notifications; message writes use ordinary authenticated POST requests.
curl -N "$PIXIZEN_BASE_URL/events" \
-H "Authorization: Bearer $PIXIZEN_API_KEY" \
-H "Last-Event-ID: YOUR_LAST_EVENT_SEQUENCE"08 / GUIDE
Widget installation and domain verification
Create a project for an exact HTTPS hostname. In Chat Widget, copy the _pixizen-chat.<hostname> DNS TXT record and value into your DNS provider. Verify it in Pixizen. A different subdomain requires a separate verified project.
Copy the script from your project and place it once in your website’s shared layout or WordPress footer. The public widget ID is not an API key. The loader requires no jQuery, isolates its CSS using Shadow DOM, and avoids duplicate widgets. Native apps can use a WebView or integrate through their own backend.
The widget creates a visitor session scoped to one conversation and origin. Its token lasts 24 hours and is retained in that browser tab’s session storage. Domain changes, suspension, and expiry invalidate access. Anonymous visitor names are not verified identities. Public origin controls reduce unauthorized browser embedding but cannot guarantee that a determined non-browser attacker cannot imitate an origin. Rate limits and wallet reservations bound abuse.
<script src="https://api.example.com/api/chat-widget/v1.js"
data-widget-id="YOUR_PUBLIC_WIDGET_ID" async></script>
// Optional controls after loading:
window.PixizenChat.open();
window.PixizenChat.close();09 / GUIDE
Widget customization and human support
Chat Widget offers ten presets plus name, greeting, brand color, avatar HTTPS URL, and left/right placement. Upload a PNG, JPEG or WebP avatar up to 512 KB, or provide an HTTPS image URL; arbitrary HTML and JavaScript are not accepted. Settings apply when a new visitor session starts.
Visitors can request a person. In API → Inbox, take over the conversation before replying. Human takeover invalidates pending AI delivery; returning to AI is explicit. Resolved conversations stop accepting messages. Human replies do not create LLM token charges. A waiting conversation does not guarantee an operator is online.
Knowledge accepts UTF-8 TXT and Markdown up to 1 MB, with 30 documents per project. The customer panel also extracts text from PDF files locally before uploading; scanned pages need OCR first. Retrieval selects matching text chunks for the project. External URL crawling and semantic vector search are not enabled in this release. API-only chat currently uses supplied messages; automatic knowledge retrieval belongs to the hosted widget.
10 / GUIDE
Free test subscriptions
Superadmin can create and grant a free test package with an explicit credit allowance and validity period. The current PDF-based test package costs USD 0, includes USD 10 of test credit, and lasts 30 days. These allowances are test configuration, not monthly package prices supplied by the PDF.
Test mode uses a separate test balance and reservation ledger. It never debits paid funds, and real Stripe/bKash checkout is blocked. An expired or missing test subscription cannot generate replies. Repeating the same package grant does not add duplicate credit or extend its term.
The supplied PDF identifies USD 0.50 uncached input, USD 0.06 cached input and USD 5.00 output per million tokens as internal base cost. Its illustrative 60% margin selling rates are USD 1.25, USD 0.15 and USD 12.50. Those illustrative rates are used for this test package; live commercial rates still need explicit review.
Each subscription snapshots its package rates/version; editing a package does not silently reprice existing subscriptions or historical requests. Test usage is recorded separately from real revenue. Switch to live mode only after validating metering and merchant payments.
11 / GUIDE
Pricing, reservations and billing
Chat API balance is separate from Pixizen image/video credits. Rates are USD per one million uncached-input, cached-input and output tokens. Read the current published rates in Overview. Each request records its own rate version so future price changes do not alter past charges.
Charge = ((input − cached) × input_rate + cached × cached_rate + output × output_rate) / 1,000,000. System prompts, retrieved knowledge, and included conversation history are input. A message is not a token; Bengali and English have different tokenization patterns.
Before inference, reserve the configured maximum input allowance plus requested maximum output, using the highest applicable input category rate. This conservative reservation can require more available balance than the final actual charge. Completion settles measured cost and releases the remainder. Money uses integer nano-USD internally, with rounding only at that precision.
A failed or disconnected inference may still have generated upstream usage. Such requests retain a reservation for manual reconciliation; they are not silently charged using guessed tokens. Administrators can audit and release old unresolved reservations. Validation/authentication failures before reservation have no inference charge.
Top up USD 5–1,000 using Stripe or bKash when configured. bKash settles in BDT using the administrator-configured checkout conversion; the USD credit and BDT amount are stored on the payment. Browser redirects never prove payment. Credit is added only after server verification. Auto-recharge, credit expiry, refunds, and tax invoicing are not automated in this release.
12 / GUIDE
Errors, limits and safe retries
400: invalid request or unsupported fields. 401: invalid, expired, or revoked credential. 402: insufficient balance or key budget. 403: suspended account or unauthorized domain. 404: inaccessible resource. 409: request already running, reused idempotency key, or invalid conversation state. 429: rate/stream limit. 502: upstream response or usage problem. 503: product/provider configuration unavailable.
Use a unique Idempotency-Key for each logical request. A completed matching request replays without charging again. Reusing it with different messages or output limits returns 409. Concurrent or unresolved repeats also return 409. Replays return the completed response instead of re-running inference.
Do not automatically retry payment creation or a failed generation using a new idempotency key. A new inference may create another billable request. For 429, wait at least a minute and use exponential backoff with jitter. Default account limits are 30 requests per minute, 100,000 reserved tokens per minute, and 5 concurrent inferences; administrators may change them. Token limits conservatively count each request’s full input reservation plus requested output. The maximum output is configured in Overview.
Usage shows the latest 100 requests and offers CSV export. It is not an unlimited historical analytics API. Keep request IDs for support and accounting.
{
"error": {
"code": "insufficient_balance",
"message": "Insufficient Chat API balance."
}
}13 / GUIDE
Security, privacy and production setup
Keep HTTPS enabled. Proxies must not buffer SSE responses; configure proxy_buffering off, proxy_read_timeout above the heartbeat interval, and do not cache authenticated endpoints. MongoDB must support transactions through a replica set. All replicas must share the same MongoDB data.
API keys are hashed and shown once. Visitor text is rendered as text rather than HTML. Tenant ownership is checked on dashboard, key, document, conversation, message, and event access. Uploaded knowledge is untrusted reference material, not an authorization source.
Conversation content is stored for inbox history and sent to the configured LLM provider. This release does not promise zero retention or no-training terms on behalf of that provider. Configure and publish retention, deletion and provider policies before onboarding real customer data. Event records expire after seven days; raw conversation and ledger data do not currently have an automatic deletion policy.
Live payments and provider token accounting must pass sandbox/staging verification before pricing is published. There is no claimed uptime SLA or benchmark. Version one supports text chat; vision, tool/function execution, audio, image generation, signed logged-in visitor identity, outbound webhooks, and native mobile SDKs are not supported.