REST · SSE · OpenAI & Anthropic compatible

AI API Docs: OpenAI & Anthropic Compatible

One API key, dozens of models. Point your existing code at a new base URL. The OpenAI and Anthropic SDKs both work with nothing else changed.

Base URL

https://router.bangunweb.com/v1

API key

bwr_live_… Get an API key
OpenCodeHow to use → BangunWeb CodeHow to use → Browser agentHow to use → APIHow to use →
For AI agents: Plain-text (.md) Copy a ready prompt · BangunWeb Account API

Three steps to your first call

From nothing to a first answer, usually under two minutes.

  1. 1

    Get a key

    Open the AI Router dashboard, create a key, copy it. Keys look like bwr_live_… and their owner can read them again at any time.

  2. 2

    Change the base URL

    In your existing app, point the OpenAI/Anthropic base URL at the gateway. Nothing else changes.

  3. 3

    Call a model

    Use a model name from our catalogue. Tokens come off your balance on each successful request.

Popular models (click to copy)

Most used by customers in the last 7 days. Put it in the "model" field. All models →

curl https://router.bangunweb.com/v1/chat/completions \
  -H "Authorization: Bearer bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "bw-swift",
    "messages": [
      {"role": "system", "content": "Jawab ringkas dalam bahasa Indonesia."},
      {"role": "user", "content": "Sebutkan tiga ide nama toko kopi."}
    ]
  }'

Authentication

Every request except /health carries a key. Two header styles are accepted — use whichever your library sends:

OpenAI style

Authorization: Bearer bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Anthropic style

x-api-key: bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

They are equivalent: the same key works on both endpoints. No version header is required; anthropic-version may be sent and is safely ignored.

Never ship a key to the browser

The gateway allows CORS so developer tooling can reach it, but a key sent from a browser is readable by anyone who opens DevTools. Keep keys on your server or in environment variables. A leaked key can be revoked from the dashboard, and revocation takes effect immediately.

Base URL & compatibility

One address serves both API styles. What decides the response shape is the endpoint you call, not the key or a header.

For OpenAI-style SDKs and tools, use the address ending in /v1:

https://router.bangunweb.com/v1

For the Anthropic SDK, use the address without /v1 — the SDK appends it itself:

https://router.bangunweb.com

Models will not load on one network?

If you see "failed to load models" or dropped connections on one WiFi while a hotspot or another network works fine, that internet provider's route to our server is probably impaired. Switch your base URL to this backup address. Your API key, balance, and models stay the same.

For OpenAI-style tools:

https://router-cf.bangunweb.com/v1

For the Anthropic SDK and Claude Code:

https://router-cf.bangunweb.com

The main address is still recommended for normal use. The backup address may occasionally return a 520 error, and non-streaming requests longer than 100 seconds may be cut off, so enable streaming and automatic retries.

Verified working with

OpenAI SDKs (Python, Node, Go)

Set base_url and api_key, nothing else.

Anthropic SDKs (Python, Node)

Set base_url and api_key; max_tokens is still required.

LangChain / LlamaIndex

Use the OpenAI-compatible connector and set openai_api_base.

Editors & CLI agents

Anything that reads OPENAI_BASE_URL or ANTHROPIC_BASE_URL.

Modes (Swift, Focus, Pro, Apex, Unbound)

A mode is a model name that never changes. Behind it sits a chain of real models: if the first one is having trouble, your request is served by the next model in the chain automatically. Put the mode name in the model field, just like any model name, in SDKs, curl, Claude Code, OpenCode, Cline, Cursor or n8n.

ModeModel nameServed by (in order)Best for
Swift DEFAULT bw-swift DeepSeek V4.1 Flash → DeepSeek V4 Flash → GLM 5.3 Flash daily work, quick edits, chatbots
Focus bw-focus DeepSeek V4 Pro → Kimi K2.7 Code → DeepSeek V4.1 Flash new features, debugging, analysis
Pro bw-pro GPT 6 Sol → GPT 6.1 Sol → GPT 5.6 Luna complex logic, code review
Apex bw-apex Claude Opus 5.5 → Claude Sonnet 5.5 → Claude Opus 5 the hardest tasks only
Unbound bw-unbound DeepSeek V4.1 Creative → qwen-3.8-creative → GLM 5.3 Flash Creative security research, fiction, sensitive topics

Usage examples

curl https://router.bangunweb.com/v1/chat/completions \
  -H "Authorization: Bearer bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"model":"bw-swift","messages":[{"role":"user","content":"Halo"}]}'

Claude Code

export ANTHROPIC_BASE_URL=https://router.bangunweb.com
export ANTHROPIC_AUTH_TOKEN=bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
export ANTHROPIC_MODEL=bw-focus
export ANTHROPIC_SMALL_FAST_MODEL=bw-swift

Install a coding agent in one line

Paste this into your terminal. It installs OpenCode (a free coding agent) and connects it to BangunWeb in Swift mode. Log in by clicking "Allow" in your browser. No API key to copy.

Mac / Linux

curl -fsSL https://bangunweb.com/install | sh

Windows (PowerShell)

irm https://bangunweb.com/install.ps1 | iex

On Windows? Use the PowerShell line. curl … | sh is for Mac/Linux only; on Windows it fails with "sh is not recognized". From CMD: powershell -ExecutionPolicy Bypass -c "irm https://bangunweb.com/install.ps1 | iex"

No account yet? Sign up free with Google when asked. Your existing OpenCode config is backed up automatically. Switch modes in OpenCode with /models.

OpenCode (ready-made config, modes listed first)

curl https://router.bangunweb.com/v1/setup/opencode
  • Accepted names: bw-swift, swift, bw/swift or bangunweb/swift (same for every mode).
  • Billing uses the price of the first model in the chain. If a backup model answers, you are billed the cheaper of the two, never more.
  • The x-bwr-mode header holds the mode you used; x-bwr-model holds the model that actually answered.
  • GET /v1/models lists modes first (bangunweb.mode = true, with the model currently serving and its chain).
  • Apex runs on Claude models and is only available to accounts that have bought a package before. Unbound is subject to our Terms of Service: no fraud, no malware against others' systems, no child content.
  • We may update the chain at any time (e.g. when a newer or cheaper model ships). The mode name stays, so your app needs no changes.

Endpoints

All paths are relative to the base URL above.

POST /v1/chat/completions Key required

OpenAI-style chat. Supports stream, tools, tool_choice, response_format, temperature and the other usual parameters — all forwarded to the model untouched.

POST /v1/messages Key required

Anthropic-style messages. max_tokens is required. Non-Claude models work here too — the gateway translates the request and response shapes.

POST /v1/images/generations Key required

Create an image from text. The prompt field is required; aspect_ratio and n are passed through to the model.

POST /v1/images/edits Key required

Create an image from a reference image, for editing or for keeping the same person and place across images. A reference is required: an image file (multipart, the OpenAI SDK way) or an images array (JSON).

POST /v1/audio/speech Key required

Turns text into MP3 speech. model and input are required; voice and language are optional.

GET /v1/audio/voices Key required

Lists voices, models, and token rates per character.

POST /v1/music/generations Key required

Create a full song (vocals from lyrics, or instrumental). Synchronous, 1-3 minutes; JSON response with base64 audio.

POST /v1/videos/generations Key required

Start a video render (asynchronous). Returns a job id right away; tokens are charged on acceptance and refunded automatically if the job fails.

GET /v1/videos/{id} Key required

Video job status. When status is done, url holds the download link (same key required).

GET /v1/videos/{id}/content Key required

Download the finished video (status done) as an MP4 straight through the gateway. Requires the same key that created it; any other status returns 400.

GET /v1/videos/models No key

Music & video models with token rates, durations and resolutions. No key needed.

GET /v1/tools/models No key

Full catalog of music, video and tool models (web search, fetch, X, OCR, rerank) with token rates. No key needed. Same content as /v1/music/models and /v1/videos/models.

POST /v1/web/fetch Key required

Fetch a public web page as clean text plus its links.

POST /v1/ocr Key required

OCR: a PDF or image (base64 data URL) to text per page. Billed per page read.

POST /v1/rerank Key required

Order documents by relevance to a query (Cohere/Jina style). Model: bge-reranker-base.

POST /v1/responses Key required

OpenAI Responses API (used by Codex CLI, OpenCode and newer SDKs). Translated to chat/completions, so every model and mode works; streaming supported.

POST /v1/completions Key required

Legacy text API: prompt → text. Supports suffix (fill-in-the-middle / editor autocomplete such as Continue and Tabby) and streaming. Billed like chat.

Example request

curl https://router.bangunweb.com/v1/completions \
  -H "Authorization: Bearer bwr_live_..." \
  -H "Content-Type: application/json" \
  -d '{"model":"bw-swift","prompt":"def tambah(a, b):","suffix":"\n\nprint(tambah(1, 2))","max_tokens":200}'
POST /v1/messages/count_tokens Key required

Count Anthropic-format prompt tokens before sending (used by Claude Code). Free, does not touch your balance.

GET /v1/models No key

The models currently on sale, with their tier and billing multipliers. The shape follows OpenAI, plus a bangunweb object carrying pricing metadata. Readable without a key. Each model also carries context_length, architecture (input/output modalities), capabilities, and pricing in rupiah per 1M input/output tokens + per request (cheapest personal package rate; bulk packages are cheaper).

Example response

{
  "object": "list",
  "data": [
    {
      "id": "bw-swift",
      "object": "model",
      "owned_by": "bangunweb",
      "display_name": "BangunWeb Swift",
      "bangunweb": {
        "mode": true,
        "serves": "deepseek-v4.1-flash",
        "chain": ["deepseek-v4.1-flash","deepseek-v4-flash","glm-5.3-flash"],
        "family": "DeepSeek",
        "vision": true,
        "token_multiplier": { "input": 1.5, "output": 1.5, "base": 2650 },
        "request_base_tokens": 2650
      }
    }
  ]
}
GET /v1/models/{id} No key

One model in detail. Useful for SDKs that check a model exists before sending a prompt.

GET /v1/account Key required

Tokens left, key limit, and a 7-day usage summary. Useful for warning your own users before the balance runs out.

Example response

{
  "email": "[email protected]",
  "key_name": "server produksi",
  "tokens_remaining": 4830112,
  "key_limit": null,
  "key_tokens_used": 169888,
  "last_7_days": { "requests": 412, "billed_tokens": 169888 },
  "topup_url": "https://bangunweb.com/akun/ai"
}
GET /v1/key Key required

Info about the key in use: name, tokens used, key limit and remaining limit, account balance. Same shape as OpenRouter GET /key, so tools that already support OpenRouter can read the balance directly.

Example response

{
  "data": {
    "label": "server produksi",
    "unit": "tokens",
    "usage": 1250000,
    "limit": 5000000,
    "limit_remaining": 3750000,
    "tokens_remaining": 48200000,
    "is_free_tier": false
  }
}
GET /v1/credits Key required

Account token balance: total credited (purchases + bonuses), total used, and remaining.

GET /v1/generation?id={request_id} Key required

Stats for one request from the x-bwr-request-id header: answering model, input/output/billed tokens, status, latency. Only requests from your own account.

Example response

{
  "data": {
    "id": "bwr_8bdc939452ae",
    "model": "deepseek-v4.1-flash",
    "requested_model": "bw-swift",
    "status": "ok",
    "tokens_prompt": 530,
    "tokens_completion": 98,
    "tokens_billed": 3592,
    "latency_ms": 2223,
    "created_at": "2026-11-18T01:50:42Z"
  }
}
GET /v1/usage?days=7&group=day Key required

Usage rollup for reports and automation. days 1–90; group = day (WIB days), model, or key; scope=key for this key only (default: whole account).

Example response

{
  "object": "list",
  "days": 7,
  "group": "day",
  "timezone": "Asia/Jakarta",
  "total": { "requests": 812, "tokens_billed": 41250000 },
  "data": [
    { "day": "2026-11-17", "requests": 402, "success_rate": 99.5,
      "tokens_prompt": 3100000, "tokens_completion": 210000, "tokens_billed": 20400000 }
  ]
}
GET /v1/setup/opencode No key

Ready-to-use OpenCode config (modes & models with context limits). No key needed; easiest: curl -fsSL https://bangunweb.com/install | sh

GET /health No key

Liveness check. Touches no balance and needs no key.

POST /v1/embeddings Key required

Text vectors for semantic search/RAG, OpenAI format (text or array input ≤2,048 items; optional dimensions). Models: text-embedding-3-small (default, 1,536 dims, multiplier 2), text-embedding-3-large (3,072, ×12), bge-m3 & qwen3-embedding-0.6b (1,024, multilingual, ×1.6), mistral-embed (×9). Billed per input token, no base cost.

Example request

curl https://router.bangunweb.com/v1/embeddings \
  -H "Authorization: Bearer bwr_live_..." \
  -H "Content-Type: application/json" \
  -d '{"model":"text-embedding-3-small","input":["halo dunia","selamat pagi"]}'
GET /v1/embeddings/models No key

Embedding models with their dimensions and billing multipliers. Readable without a key.

POST /v1/audio/transcriptions Key required

Speech/video → text, OpenAI format (multipart: file up to 25 MB, model, language, prompt, response_format json|text|srt|vtt|verbose_json). Any common audio/video format is accepted (converted automatically). Billed per audio second: whisper-large-v3-turbo 1,200 tokens/s (default, cheap), whisper-1 & gpt-transcribe 13,000 tokens/s (cleanest). Duration is in the x-bwr-audio-seconds header.

Example request

curl https://router.bangunweb.com/v1/audio/transcriptions \
  -H "Authorization: Bearer bwr_live_..." \
  -F model=whisper-large-v3-turbo \
  -F language=id \
  -F [email protected]

Streaming

Send "stream": true. The response is Server-Sent Events in the original shape: chat/completions emits chat.completion.chunk pieces then data: [DONE], while messages emits message_start, content_block_delta and the rest.

stream = client.chat.completions.create(
    model="bw-swift",
    messages=[{"role": "user", "content": "Tulis satu paragraf tentang kopi."}],
    stream=True,
)

usage = None
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        usage = chunk.usage        # potongan penutup membawa angka tagihan kami

print("\ntoken ditagih:", usage.billed_tokens)

The gateway re-emits the closing chunk with our billing numbers, so the usage you receive at the end of a stream is exactly what came off your balance — not the upstream raw count.

Long streams are safe: default timeouts are disabled and proxies are told not to buffer. If you disconnect mid-stream, what was already generated is still billed — the model had already done the work.

Tool calling

Tool definitions are forwarded untouched, in both the OpenAI and Anthropic shapes. Streamed tool calls work too.

tools = [{
    "type": "function",
    "function": {
        "name": "cek_stok",
        "description": "Cek sisa stok satu produk di gudang.",
        "parameters": {
            "type": "object",
            "properties": {"sku": {"type": "string"}},
            "required": ["sku"],
        },
    },
}]

r = client.chat.completions.create(
    model="bw-swift",
    messages=[{"role": "user", "content": "Masih ada stok SKU-1187?"}],
    tools=tools,
)

call = r.choices[0].message.tool_calls[0]
print(call.function.name, call.function.arguments)   # arguments dijamin JSON sah

One thing the gateway quietly fixes: some upstreams emit tool arguments as concatenated, invalid JSON. We reassemble them before forwarding, so your client never has to parse broken JSON.

Not every model handles tools equally well. Models marked Premium in the catalogue are the most reliable for multi-tool flows.

Reading images (vision)

Many models can read images you send in a message: photos, screenshots, receipts, documents. Use the normal chat endpoint and set content to an array with a text block and an image_url block (a base64 data URL or a public URL).

import base64
from openai import OpenAI

client = OpenAI(base_url="https://router.bangunweb.com/v1", api_key="bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
foto = base64.b64encode(open("struk.jpg", "rb").read()).decode()

r = client.chat.completions.create(
    model="gpt-6.2-sol",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "Baca total belanja di struk ini."},
            {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + foto}},
            # atau URL publik: {"type": "image_url", "image_url": {"url": "https://..."}}
        ],
    }],
)
print(r.choices[0].message.content)

On /v1/messages use an Anthropic-style image block. Both shapes work on every vision model.

# Gaya Anthropic (/v1/messages): blok "image" dengan source base64
{"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": foto}}

Models that can read images (60)

claude-opus-5.5 claude-opus-5 claude-opus-4.8 claude-opus-4.7 claude-opus-4.6 claude-sonnet-5 claude-fable-5 claude-fable-5.1 claude-sonnet-4.6 claude-sonnet-5.5 gpt-6-astra gpt-6.1-sol claude-haiku-4.5 gpt-6-luna gpt-6-sol claude-haiku-5.5 claude-opus-4.5 gpt-6-luna-search claude-sonnet-4.5 gpt-5.6-luna gpt-5.6-terra gpt-6.1-terra gpt-5.6-sol gpt-5.5 gpt-5.4 gpt-5.6-luna-review gpt-5.4-mini gpt-5.6-terra-review gpt-4o gpt-5.6-sol-review gpt-oss-120b deepseek-v4-pro deepseek-v4-flash deepseek-v4.1-flash kimi-k3.1-pro kimi-k3 glm-5.3 kimi-k2.7-code glm-5.3-flash qwen-3.8-flash qwen-3.7-flash minimax-m3.1-flash mimo-v2.6-flash gemini-3.8-flash-high mimo-v2.6-pro gemini-3.8-flash hy4-preview gemma-4-creative qwen-3.6-plus-creative gpt-6.2-astra gpt-6.2-sol gemini-3.1-flash-lite gemini-3.1-pro gemini-3.6-flash grok-4.6 hy4 inkling-2-mini-creative muse-wonder-1.0 qwen-3.7-plus qwen-3.8-27b-creative

This capability is tested automatically twice a day for each supplier route and shown as "vision": true in GET /v1/models. Requests with images only go through routes proven to see images. If you send an image to a model that cannot read it, the gateway serves it with the closest vision model: its name is in the x-bwr-model header, the model you asked for is in x-bwr-model-requested, and you are never billed more than the model you asked for. Don't want a substitute? Send x-bwr-substitute: off and the request is rejected with a 400 that lists models that can.

Images are billed as ordinary input tokens (usually a few hundred up to about 1,500 tokens per image, depending on size and model). Around 1024 px is enough to read text and is faster; send JPEG rather than large PNG files.

Image models

Models marked Image in the catalogue are served by their own endpoints, not /v1/chat/completions. Send a prompt, get the image back as base64 in data[0].b64_json. The response is synchronous: the connection is held until the image is ready, usually 15-40 seconds, so set your client timeout to at least 120 seconds.

import base64, requests

r = requests.post(
    "https://router.bangunweb.com/v1/images/generations",
    headers={"Authorization": f"Bearer bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"},
    json={
        "model": "bwr-image",
        "prompt": "Spanduk toko online bergaya minimalis, latar oranye, tanpa teks.",
        "size": "1024x1024",
    },
    timeout=300,
)
r.raise_for_status()

hasil = r.json()
open("hasil.png", "wb").write(base64.b64decode(hasil["data"][0]["b64_json"]))
print(hasil["usage"])   # {'images': 1, 'billed_tokens': 1200000}

Editing an existing image

To edit an image, or to keep the same person and place across several images, use /v1/images/edits. It accepts two forms: a file upload (multipart/form-data, same as the OpenAI API, so the OpenAI SDK works as is) or JSON with an images array. Without a reference image the request is rejected and nothing is billed.

Easiest: the official OpenAI SDK (Python or Node), just change base_url.

import base64
from openai import OpenAI

client = OpenAI(base_url="https://router.bangunweb.com/v1", api_key="bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", timeout=300)

r = client.images.edit(
    model="bwr-image",
    image=open("acuan.png", "rb"),   # beberapa acuan: [open("a.png", "rb"), open("b.png", "rb")]
    prompt="Orang yang sama, ruangan yang sama. Ubah HANYA warna kaosnya jadi hitam.",
    size="1024x1024",
)

open("hasil.png", "wb").write(base64.b64decode(r.data[0].b64_json))

With curl: upload the file directly. Repeat image[] for several references.

curl https://router.bangunweb.com/v1/images/edits \
  -H "Authorization: Bearer bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -F model=bwr-image \
  -F "prompt=Ubah latarnya jadi putih polos, objeknya jangan diubah." \
  -F "image[][email protected]" \
  -F "image[][email protected]" \
  --max-time 300

Without an SDK: send JSON. Fill images with base64 data URLs or public image URLs.

import base64, requests

acuan = base64.b64encode(open("acuan.png", "rb").read()).decode()

r = requests.post(
    "https://router.bangunweb.com/v1/images/edits",
    headers={"Authorization": f"Bearer bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"},
    json={
        "model": "bwr-image",
        "prompt": "Orang yang sama, ruangan yang sama. Ubah HANYA warna kaosnya jadi hitam.",
        "images": ["data:image/png;base64," + acuan],   # atau URL publik: "https://contoh.com/foto.jpg"
        "size": "1024x1024",
    },
    timeout=300,
)

open("hasil.png", "wb").write(base64.b64decode(r.json()["data"][0]["b64_json"]))

Reference image rules

  • Up to 16 reference images per request, PNG, JPEG or WebP. The optional mask field marks the area that may change.
  • Reference URLs must be http:// or https:// to a public address on port 80/443, without a username/password. Local and private-network addresses (localhost, 127.0.0.1, 10.x, 192.168.x and the like) are rejected with a 400 error.
  • The URL must point to an image file of at most 20 MB. Redirects are followed at most 3 times.
  • The request body is limited to 12 MB. Base64 inflates files by about a third, so for large files a file upload or a URL is more efficient.

Change one thing per request. Asking for a new outfit, a new pose and a new angle at once makes the model redraw the face, and you get a different person.

Image models are billed per IMAGE at a flat rate, not per token. Each model rate is listed in the catalogue and in the tokens_per_image field of GET /v1/models. Failed requests bill nothing.

AI Voice

Send text to /v1/audio/speech and save the response as an MP3 file. Models: eleven-flash, eleven-v3, kokoro (English voices: heart, bella, alloy), and gemini-tts (cheapest, multilingual incl. Indonesian, 30 voices such as kore, puck, charon; max 2,500 characters). The limit is 5,000 characters per request.

import requests

r = requests.post(
    "https://router.bangunweb.com/v1/audio/speech",
    headers={"Authorization": f"Bearer bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"},
    json={
        "model": "eleven-flash",
        "input": "Halo, selamat datang di toko kami.",
        "voice": "sarah",
    },
    timeout=130,
)
r.raise_for_status()

open("suara.mp3", "wb").write(r.content)
print(r.headers["x-bwr-billed-tokens"])

Charges are based on the character count and the actual cost of that request, returned in the x-bwr-billed-tokens header. Failed requests are not charged.

Only for accounts that have purchased a token package. Trial or bonus tokens alone do not qualify.

Do not use these voices to impersonate others, deceive, or break the law. Tell listeners the voice is AI-generated where the law requires it.

AI Music & Video

Put the song style in prompt and the words in lyrics ([Verse]/[Chorus] markers help), or send instrumental: true without lyrics. Songs usually take 1-3 minutes; set a client timeout of at least 15 minutes. Errors after the connection opens arrive as HTTP 200 with an error object, so always check for an error key.

import base64, requests

r = requests.post(
    "https://router.bangunweb.com/v1/music/generations",
    headers={"Authorization": f"Bearer bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"},
    json={
        "model": "suno-v5",   # 2 versi lagu sekaligus; lyria-3-pro = 1 lagu
        "prompt": "pop Indonesia ceria, vokal perempuan, gitar akustik",
        "lyrics": "[Verse]
Pagi cerah di kota

[Chorus]
Ayo mulai hari ini",
    },
    timeout=900,   # lagu butuh 1-3 menit
)
hasil = r.json()   # spasi di awal balasan = penjaga koneksi, json() mengabaikannya
if "error" in hasil:
    raise SystemExit(hasil["error"]["message"])
for i, d in enumerate(hasil["data"], 1):   # suno-v5: 2 item (title, duration, lyrics ikut)
    open(f"lagu-{i}." + d["format"], "wb").write(base64.b64decode(d["b64_json"]))

Video is asynchronous: create a job, poll GET /v1/videos/{id} every few seconds until status is done, then download from url. Failed/expired jobs refund the tokens automatically.

import base64, time, requests

H = {"Authorization": f"Bearer bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}
foto = "data:image/jpeg;base64," + base64.b64encode(open("foto.jpg", "rb").read()).decode()

job = requests.post("https://router.bangunweb.com/v1/videos/generations", headers=H, json={
    "model": "veo-3.1-fast",   # 8 dtk 720p bersuara; image_url opsional (foto awal)
    "prompt": "kamera pelan mendekat, daun berguguran",
    "aspect_ratio": "9:16",    # Veo: 16:9 atau 9:16
    "image_url": foto,
}, timeout=240).json()

while job.get("status") == "rendering":
    time.sleep(10)
    job = requests.get("https://router.bangunweb.com/v1/videos/" + job["id"], headers=H, timeout=30).json()

if job["status"] == "done":
    open("video.mp4", "wb").write(requests.get(job["url"], headers=H, timeout=300).content)
else:
    print(job.get("failure_reason"), job.get("refunded"))   # gagal = token dikembalikan
  • suno-v5 — 14.000.000 tokens per song
  • lyria-3-pro — 7.800.000 tokens per song
  • lyria-3.5 — 11.600.000 tokens per song
  • video-10s-pro — 720p: 900.000 tokens/sec · 10 sec
  • veo-3.1-fast — 720p: 1.700.000 tokens/sec · 8 sec
  • veo-3.1 — 720p: 2.200.000 tokens/sec · 8 sec
  • vidu-q3-turbo — 720p: 5.200.000 tokens/sec · 5/8/10 sec
  • muse-video — 720p: 2.400.000 tokens/sec · 10 sec · from photo

AI music and video are available to accounts that have purchased a token package.

Web search, OCR & rerank

Ready-made tools without picking a model: for agents, chatbots that need fresh information, and reading documents. Failed calls are not charged.

import base64, requests

H = {"Authorization": f"Bearer bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}

# Pencarian web (hasil: judul, url, cuplikan)
cari = requests.post("https://router.bangunweb.com/v1/web/search", headers=H, json={"query": "harga emas hari ini", "max_results": 5}).json()
for x in cari["results"]:
    print(x["title"], x["url"])

# Ambil isi halaman jadi teks
hal = requests.post("https://router.bangunweb.com/v1/web/fetch", headers=H, json={"url": "https://bangunweb.com/ai"}).json()

# Pencarian X/Twitter: jawaban ringkas + sumber
x = requests.post("https://router.bangunweb.com/v1/x/search", headers=H, json={"query": "berita AI terbaru"}).json()

# OCR: PDF atau gambar jadi teks (ditagih per halaman)
data = "data:application/pdf;base64," + base64.b64encode(open("struk.pdf", "rb").read()).decode()
ocr = requests.post("https://router.bangunweb.com/v1/ocr", headers=H, json={"file": {"filename": "struk.pdf", "file_data": data}}).json()

# Rerank: urutkan dokumen menurut kecocokan
rr = requests.post("https://router.bangunweb.com/v1/rerank", headers=H, json={
    "query": "cara bayar QRIS", "documents": ["Bayar pakai QRIS", "Jam buka toko", "Cara isi saldo"], "top_n": 2,
}).json()
  • /v1/web/search — Pencarian web: 400.000 tokens per call
  • /v1/web/fetch — Ambil isi halaman web: 400.000 tokens per call
  • /v1/x/search — Pencarian X (Twitter): 800.000 tokens per call
  • /v1/ocr — OCR dokumen (per halaman): 200.000 tokens per page
  • /v1/rerank — Rerank dokumen: 0.464 tokens per input token (min 1,000)

How tokens are counted

One successful request bills:

billed tokens = base cost + (input tokens × input multiplier) + (output tokens × output multiplier)

The base cost and both multipliers differ per model and are listed in the catalog and in GET /v1/models. A failed request bills nothing. The row is still recorded at 0 so it stays visible in your history.

{
  "object": "list",
  "days": 7,
  "group": "day",
  "timezone": "Asia/Jakarta",
  "total": { "requests": 812, "tokens_billed": 41250000 },
  "data": [
    { "day": "2026-11-17", "requests": 402, "success_rate": 99.5,
      "tokens_prompt": 3100000, "tokens_completion": 210000, "tokens_billed": 20400000 }
  ]
}

The usage field on every response is the number that came off your balance, already stripped of the upstream provider’s hidden system prompt. The same number is sent as the x-bwr-tokens-billed header, so you can log cost without parsing the body.

Tokens never expire and no subscription is required. The balance only moves when you use it.

Limits

Limits apply per key, not per account. Give a busy app its own key.

Requests per minute

600

Concurrent requests

12

Request body size

12 MB

Single request duration

Unlimited

Streams running for minutes are never cut off by the gateway.

Going over answers 429 and bills nothing. Need higher limits for production traffic? Talk to us.

Rate-limit headers

Every response carries OpenAI-style headers so SDKs can pace themselves. When the limit is exceeded the gateway returns 429 with a retry-after header (seconds).

x-ratelimit-limit-requests: 600
x-ratelimit-remaining-requests: 599
x-ratelimit-reset-requests: 60s
retry-after: 12

Per-key security settings

Configure at /akun/ai → API keys → three-dot button → Advanced settings. Everything empty = no restrictions.

  • Key token allowance: a total limit from the time it is set (402 when used up).
  • Monthly token limit: resets on the 1st of each month WIB (402 insufficient_quota when reached).
  • Allowed models: the key can only call the checked models/modes (403 permission_error otherwise). Great for client keys or public apps.
  • Allowed IPs: IPv4/IPv6 or CIDR ranges, comma separated (401 from other IPs). The error names the detected IP so it is easy to add.
  • Expiry: the key stops automatically after the chosen date (end of day WIB).

English error messages

Error messages default to Indonesian. Send the header x-bwr-lang: en (or an Accept-Language other than id) to receive English messages; error type/code stay the same.

Error codes

The error envelope follows the style of the endpoint you called, so OpenAI and Anthropic clients both parse it without special handling.

OpenAI style (/v1/chat/completions)

{
  "error": {
    "message": "Saldo token tidak cukup (sisa 1.204, perlu sekitar 3.500).",
    "type": "insufficient_quota",
    "code": "insufficient_quota"
  }
}

Anthropic style (/v1/messages)

{
  "type": "error",
  "error": {
    "type": "insufficient_quota",
    "message": "Saldo token tidak cukup (sisa 1.204, perlu sekitar 3.500)."
  }
}
400 invalid_request_error

The body is not valid JSON, or max_tokens is missing on /v1/messages.

400 invalid_request_error

An image was sent to a model that cannot read it while x-bwr-substitute: off is set. Use a model with "vision": true in GET /v1/models.

401 authentication_error

Key missing, unknown, or revoked. Check it in the dashboard.

402 insufficient_quota

Not enough tokens for a request this size, or the key hit its own limit. Top up.

403 access_denied

Claude models (including the bw-apex mode) are only available to accounts that have bought a token package. Buy any package, then retry. Free trial tokens work on other models.

404 model_not_found

Wrong model name, or that model is not on sale right now. Fetch the current list from GET /v1/models.

429 rate_limit_error

Over the per-minute or concurrency limit. Retry after a short pause.

503 api_error

Every provider for this model is failing. Nothing is billed. Try another model, or send us the request id.

The gateway tries fallback providers automatically before giving up, so a 503 with code api_error means the whole chain failed — not just one provider.

Integration examples

Everything below can be copied as-is.

Python (OpenAI SDK)

from openai import OpenAI

client = OpenAI(
    base_url="https://router.bangunweb.com/v1",
    api_key="bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
)

r = client.chat.completions.create(
    model="bw-swift",
    messages=[{"role": "user", "content": "Sebutkan tiga ide nama toko kopi."}],
)

print(r.choices[0].message.content)
print("token ditagih:", r.usage.billed_tokens)

Node.js (OpenAI SDK)

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://router.bangunweb.com/v1",
  apiKey: "bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
});

const r = await client.chat.completions.create({
  model: "bw-swift",
  messages: [{ role: "user", content: "Sebutkan tiga ide nama toko kopi." }],
});

console.log(r.choices[0].message.content);

Python (Anthropic SDK)

import anthropic

client = anthropic.Anthropic(
    base_url="https://router.bangunweb.com",
    api_key="bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
)

r = client.messages.create(
    model="claude-opus-5.5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Sebutkan tiga ide nama toko kopi."}],
)

print(r.content[0].text)

curl

curl https://router.bangunweb.com/v1/chat/completions \
  -H "Authorization: Bearer bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "bw-swift",
    "messages": [
      {"role": "system", "content": "Jawab ringkas dalam bahasa Indonesia."},
      {"role": "user", "content": "Sebutkan tiga ide nama toko kopi."}
    ]
  }'

Environment variables

Many off-the-shelf tools (editors, CLI agents) need only these variables, with no code changes at all.

# Gaya OpenAI
export OPENAI_BASE_URL="https://router.bangunweb.com/v1"
export OPENAI_API_KEY="bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# Gaya Anthropic
export ANTHROPIC_BASE_URL="https://router.bangunweb.com"
export ANTHROPIC_API_KEY="bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Connect to IDE & tools

This API is OpenAI and Anthropic compatible. It works out of the box with any tool that supports a custom endpoint.

Per-tool guides: Cline, Roo Code, Cursor, Claude Code, n8n, Open WebUI and more →

Claude Code

# Paling mudah (pasang + login 1 klik + atur otomatis):
#   curl -fsSL https://bangunweb.com/install/claude | sh
#   Windows: irm https://bangunweb.com/install/claude.ps1 | iex
# Atau manual:
export ANTHROPIC_BASE_URL="https://router.bangunweb.com"
export ANTHROPIC_AUTH_TOKEN="bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
export ANTHROPIC_MODEL="bw-swift"
claude

VS Code (Continue / Cline)

// Continue: tambahkan di .continue/config.yaml
models:
  - model: bw-swift
    title: BangunWeb AI
    provider: openai
    apiBase: https://router.bangunweb.com/v1
    apiKey: bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

// Cline: Settings > Cline > API Provider > OpenAI Compatible
// Base URL: https://router.bangunweb.com/v1
// API Key: bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Model: bw-swift

OpenCode

export OPENAI_BASE_URL="https://router.bangunweb.com/v1"
export OPENAI_API_KEY="bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
opencode
# Pilih model: bw-swift

Cursor

Settings > Models > OpenAI API Key
API Key: bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Override OpenAI Base URL: https://router.bangunweb.com/v1
Model: bw-swift

n8n (workflow automation)

Credentials > OpenAI API:
  API Key: bwr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  Base URL: https://router.bangunweb.com/v1

Di node "AI Agent" atau "Chat Model":
  Model: bw-swift

We do not store your conversations

The gateway records numbers only: model, token counts, latency, success or failure. Prompts and answers are written to no database and used to train nothing.

Those numbers are what you see in the usage history on your dashboard, and what we look at when you question a charge.

Token management API

Besides the gateway for sending model requests, BangunWeb also provides a REST API for managing your token balance, usage history, and purchasing packages programmatically.

Management base URL

https://bangunweb.com/api/v1/ai

Authentication uses a BangunWeb API key (not a gateway bwr_live_ key). Create one in the API menu on your account dashboard, and send it as a bearer token.

GET /api/v1/ai/balance

Remaining token balance, total usage, and a 14-day summary (by day & model).

GET /api/v1/ai/usage

Per-request usage history + summary. Parameters: days (1-90, default 7), limit (1-100, default 25).

GET /api/v1/ai/transactions

Token mutation history (purchases, bonuses, adjustments, refunds). Parameter: limit (1-100, default 25).

GET /api/v1/ai/packages

Token packages currently on sale, plus custom purchase options.

GET /api/v1/ai/models

AI models available at the gateway (same as GET /v1/models but without a gateway key).

POST /api/v1/ai/topup

Buy a token package. Send package (slug) OR amount (custom rupiah). Balance is charged immediately.

Full documentation including example responses is on the BangunWeb API page.

Open API docs

Frequently asked

Can I send a photo or screenshot to a model? +

Yes, to models marked vision. See the list under "Reading images" or the vision field in GET /v1/models. If your chosen model cannot read images, the gateway automatically uses the closest vision model and tells you via the x-bwr-model-requested header.

How much of my code has to change? +

The base URL and the key. Parameter names, response shapes, streaming and tool calling all stay the same.

Why does the token count differ from my own estimate? +

Providers inject a hidden system prompt into every request. The gateway strips that out before billing, so the usage you receive is clean and matches what left your balance.

If a provider goes down, does my request fail? +

Each model has a fallback chain that is tried in order. A request only fails when the whole chain fails, and then nothing is billed.

Can my tokens expire? +

No. Tokens never expire, and no subscription is required.

Can I cap a single key? +

Yes. Per-key caps are useful when handing a key to another app or team. Contact us to set one.

Which model should I use? +

Start on the Budget tier for high-volume work like classification and summarizing. Move up to Premium for long reasoning and multi-tool flows.

Something not working?

Send us the request id (x-bwr-request-id) from the failing response — with that we can trace it all the way to the provider.

Contact us