Glim DocsAPI v1

Build on one key, call any model

The Glimpoint is an OpenAI-compatible API at https://glim.run/v1. Point the SDK you already use at it, and 60 chat, image, video and music models answer without ever seeing who you are.

Introduction

Glim is private AI inference below list price. One wallet, one balance and one Glim API key reach every chat, image, video and music model on the network.

What Glim does

Every request you send reaches the model under one pooled key. Before it leaves our servers we remove your wallet, IP address, user agent and client details, so the host sees the question and never you. We keep no copy of prompts or outputs.

  • One endpoint. The Glimpoint speaks the OpenAI wire format, so the chat SDKs you use today keep working once you change the base URL.
  • Below list price. Most models sit up to 50% below the list price each maker publishes, and most Claude models 55% below. Every response carries what it cost beside what it would have cost at list.
  • Held, then settled. Each call holds its worst case and charges only what it used. A call that fails before any output releases its hold in full.
  • No account. You sign one message with a wallet. No email, no password, no form.

Base URL

https://glim.run/v1

Where to go next

New here? Start with the Quickstart. Moving an existing app? Read SDKs. Building with an AI coding tool? Add the MCP server.

Quickstart

From a wallet to your first streamed reply in about two minutes.

  1. Connect a wallet. Open Glim Console and sign one message. It costs nothing and sends no transaction. Your wallet is stored only as a hash.
  2. Top up. Send USDC on Elysium to the deposit address shown under Billing. There is no minimum. Paying in $GLIM is credited at face value.
  3. Create a key. Under API keys, press Create key. The secret starts with glim_ and is shown once. Store it as an environment variable.
  4. Send your first request.
export GLIM_API_KEY="glim_..."
curl https://glim.run/v1/chat/completions \
  -H "Authorization: Bearer $GLIM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-5.5",
    "messages": [{"role": "user", "content": "Explain attested hardware in two sentences."}]
  }'
# pip install openai
import os
from openai import OpenAI

client = OpenAI(base_url="https://glim.run/v1", api_key=os.environ["GLIM_API_KEY"])

reply = client.chat.completions.create(
    model="claude-sonnet-5.5",
    messages=[{"role": "user", "content": "Explain attested hardware in two sentences."}],
)
print(reply.choices[0].message.content)
// npm install openai
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://glim.run/v1", apiKey: process.env.GLIM_API_KEY });

const reply = await client.chat.completions.create({
  model: "claude-sonnet-5.5",
  messages: [{ role: "user", content: "Explain attested hardware in two sentences." }],
});
console.log(reply.choices[0].message.content);

The response is a standard chat completion. Glim adds a glim object with the price of the call:

"glim": { "held": 0.072018, "charged": 0.000318, "list": 0.000707, "currency": "USD", "privacy": "anonymized" }
No wallet yet? Glim Chat lets you try every model from the browser with a demo wallet before you write any code. Open Glim Chat.

Authentication

Every request carries a Glim API key as a bearer token.

Authorization: Bearer glim_7f3a9c41e2b8d0...

Keys

  • A key reaches every model on the network and draws on your one balance.
  • Secrets are shown once. Glim stores only a SHA-256 hash, so a lost key cannot be recovered; revoke it and create another.
  • Create a separate key per app or environment. Console shows spend and last use per key, so a leak is easy to spot and to revoke.
  • Never ship a key in client-side code. Call Glim from your server, as in the tutorial.

Wallet sign-in

Console and Chat sign you in with one personal_sign message. The message has a nonce and an issue time, and sends no transaction. We keep the wallet as a hash; the address itself never leaves Glim's servers and is never forwarded to a model host.

Models

Every model on the Glimpoint, live from the catalog, with its id, kind, price and list price.

Use the id as the model field. Prices are in USD: per 1M tokens (input / output) for chat, per image, per second of video and per song.

ModelidKindMakerPriceListBelow list

The same list is served by GET /v1/models. Models marked Sealed run in attested hardware; see Sealed models.

Pricing & holds

Each call holds its worst case, charges only what it used, and releases the rest at once.

How a call is billed

  1. Hold. Before the request leaves, Glim reserves the most the call could cost: the input tokens plus max_tokens of output (default 16,000), or the full length of a media job.
  2. Run. The model answers. If your balance cannot cover the hold, the call fails with 402 insufficient_balance and nothing is sent.
  3. Settle. When the response ends, Glim charges the tokens or units actually used at the Glim price.
  4. Release. The rest of the hold returns to your balance. A call that fails before any output releases its hold in full.

Worked example

A request to claude-sonnet-5.5 ($0.90 / $4.50 per 1M tokens) with 1,200 input tokens and the default 16,000 max_tokens:

StepCalculationAmount
Hold1,200 × $0.90 / 1M + 16,000 × $4.50 / 1M$0.073080
Used1,200 in, 380 out
Charge1,200 × $0.90 / 1M + 380 × $4.50 / 1M$0.002790
Release$0.073080 − $0.002790$0.070290
At list price1,200 × $2.00 / 1M + 380 × $10.00 / 1M$0.006200

Lower max_tokens when you run many calls at once, so less of your balance is held at any moment.

Price headers

HeaderMeaning
x-glim-heldThe worst case held for this call, in USD
x-glim-chargedWhat the call cost (sent as a trailer on streams)
x-glim-listWhat it would have cost at the maker's list price
x-glim-privacyanonymized or sealed

Every price and its source is on the pricing page; each maker's list price is checked on its own page and dated.

Privacy

Every model is labelled Anonymized or Sealed.

Anonymized

The request reaches the model host under one pooled Glim key. Before it leaves our servers we remove your wallet, IP address, user agent and client details. We keep no copy of prompts or outputs. The host can still read the content under its own policy, but it cannot tell whose it is.

Sealed

The model runs inside attested hardware whose memory neither the host nor Glim can read. You get an attestation record with each reply. See Sealed models & attestation.

What is kept, and for how long

DataKept
Your promptNot kept
The reply, image, clip or songNot kept (media is streamed to you, then deleted)
WalletStored as a hash; never forwarded to a host
IP address, user agent, deviceRemoved before forwarding; not logged
Billing rows (model, token count, cost, key)90 days, then only daily totals
Error logs7 days, content-free

Chat history in Glim Chat lives in your browser, where you can export or wipe it. The reasoning behind this design is in the thesis.

Chat completions

POST/v1/chat/completions

Create a reply from any chat model. The request and response follow the OpenAI chat completions format.

Request body

FieldTypeNotes
modelstring, requiredA chat model id from Models
messagesarray, required{role, content} with role system, user or assistant
max_tokensintegerOutput cap and the size of the hold. Default 16,000
streambooleanStream server-sent events. Default false
stream_options.include_usagebooleanSend a final chunk with token usage and price
tools, tool_choicearray, stringFunction calling, passed through on models that support it
response_formatobject{"type": "json_object"} on models that support it
userstringIgnored. Glim never forwards an end-user id
curl https://glim.run/v1/chat/completions \
  -H "Authorization: Bearer $GLIM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-opus-5.5",
    "max_tokens": 1024,
    "messages": [
      {"role": "system", "content": "You answer in plain English."},
      {"role": "user", "content": "What is a pooled API key?"}
    ]
  }'
reply = client.chat.completions.create(
    model="claude-opus-5.5",
    max_tokens=1024,
    messages=[
        {"role": "system", "content": "You answer in plain English."},
        {"role": "user", "content": "What is a pooled API key?"},
    ],
)
print(reply.choices[0].message.content)
const reply = await client.chat.completions.create({
  model: "claude-opus-5.5",
  max_tokens: 1024,
  messages: [
    { role: "system", content: "You answer in plain English." },
    { role: "user", content: "What is a pooled API key?" },
  ],
});
console.log(reply.choices[0].message.content);

Response

{
  "id": "chatcmpl_01J9X2K8Q4",
  "object": "chat.completion",
  "created": 1796032800,
  "model": "claude-opus-5.5",
  "choices": [
    {
      "index": 0,
      "message": { "role": "assistant", "content": "A pooled key is one provider key shared by many users..." },
      "finish_reason": "stop"
    }
  ],
  "usage": { "prompt_tokens": 31, "completion_tokens": 142, "total_tokens": 173 },
  "glim": { "held": 0.020536, "charged": 0.001334, "list": 0.002964, "currency": "USD", "privacy": "anonymized" }
}

Streaming

With "stream": true the reply arrives as server-sent events. Each event is a chat.completion.chunk; the stream ends with data: [DONE]. Ask for stream_options.include_usage to get a last chunk with usage and price.

data: {"id":"chatcmpl_01J9","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"A pooled"}}]}

data: {"id":"chatcmpl_01J9","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" key is"}}]}

data: {"id":"chatcmpl_01J9","object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":31,"completion_tokens":142},"glim":{"charged":0.001334,"list":0.002964}}

data: [DONE]
stream = client.chat.completions.create(
    model="claude-sonnet-5.5",
    messages=[{"role": "user", "content": "Write a haiku about fireflies."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
const stream = await client.chat.completions.create({
  model: "claude-sonnet-5.5",
  messages: [{ role: "user", content: "Write a haiku about fireflies." }],
  stream: true,
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
curl -N https://glim.run/v1/chat/completions \
  -H "Authorization: Bearer $GLIM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "claude-sonnet-5.5", "stream": true,
       "messages": [{"role": "user", "content": "Write a haiku about fireflies."}]}'

If the client disconnects mid-stream, Glim charges only the tokens already produced and releases the rest of the hold.

Images

POST/v1/images/generations

Create an image from a prompt. Priced per image, held before it renders.

FieldTypeNotes
modelstring, requiredAn image model id, e.g. nano-banana-2
promptstring, requiredWhat to draw
ninteger1 to 4 images. Each is priced and held
sizestring1024x1024, 1536x1024 or 1024x1536
response_formatstringb64_json (default) or url; URLs expire after 10 minutes
curl https://glim.run/v1/images/generations \
  -H "Authorization: Bearer $GLIM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "nano-banana-2", "prompt": "A lighthouse on a basalt cliff at dusk, long exposure", "size": "1024x1024"}'
import base64
img = client.images.generate(
    model="nano-banana-2",
    prompt="A lighthouse on a basalt cliff at dusk, long exposure",
    size="1024x1024",
)
open("lighthouse.png", "wb").write(base64.b64decode(img.data[0].b64_json))
import { writeFileSync } from "node:fs";
const img = await client.images.generate({
  model: "nano-banana-2",
  prompt: "A lighthouse on a basalt cliff at dusk, long exposure",
  size: "1024x1024",
});
writeFileSync("lighthouse.png", Buffer.from(img.data[0].b64_json, "base64"));
{ "created": 1796032800, "data": [{ "b64_json": "iVBORw0KGgo..." }], "glim": { "held": 0.0471, "charged": 0.0471, "list": 0.067 } }

Video

Video renders as an async job: create it, poll it, then download the clip. The full clip length is held when the job starts; you pay only for a clip that arrives.

POST/v1/videos
FieldTypeNotes
modelstring, requiredA video model id, e.g. veo-3.1-fast
promptstring, requiredWhat happens in the clip
secondsinteger4, 6 or 8. Default 8
aspect_ratiostring16:9 (default), 9:16 or 1:1
curl https://glim.run/v1/videos \
  -H "Authorization: Bearer $GLIM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "veo-3.1-fast", "seconds": 8, "aspect_ratio": "16:9",
       "prompt": "A slow dolly shot along a row of server racks, status lights blinking in the dark"}'
{ "id": "vid_01J9X3M2", "object": "video.job", "status": "queued", "model": "veo-3.1-fast", "seconds": 8, "glim": { "held": 0.48 } }
GET/v1/videos/{id}

Poll every few seconds. status moves through queued, running (with progress from 0 to 1), then succeeded or failed. A failed job releases its hold in full.

GET/v1/videos/{id}/content

Returns the MP4 once the job has succeeded. The file is kept for one hour, then deleted.

import time, httpx, os
H = {"Authorization": f"Bearer {os.environ['GLIM_API_KEY']}"}
API = "https://glim.run/v1"

job = httpx.post(f"{API}/videos", headers=H, json={
    "model": "veo-3.1-fast", "seconds": 8,
    "prompt": "A slow dolly shot along a row of server racks",
}).json()

while job["status"] in ("queued", "running"):
    time.sleep(4)
    job = httpx.get(f"{API}/videos/{job['id']}", headers=H).json()

if job["status"] == "succeeded":
    open("clip.mp4", "wb").write(httpx.get(f"{API}/videos/{job['id']}/content", headers=H).content)
const API = "https://glim.run/v1";
const H = { Authorization: `Bearer ${process.env.GLIM_API_KEY}`, "Content-Type": "application/json" };

let job = await (await fetch(`${API}/videos`, { method: "POST", headers: H,
  body: JSON.stringify({ model: "veo-3.1-fast", seconds: 8, prompt: "A slow dolly shot along a row of server racks" }) })).json();

while (job.status === "queued" || job.status === "running") {
  await new Promise(r => setTimeout(r, 4000));
  job = await (await fetch(`${API}/videos/${job.id}`, { headers: H })).json();
}
if (job.status === "succeeded") {
  const clip = await fetch(`${API}/videos/${job.id}/content`, { headers: H });
  (await import("node:fs")).writeFileSync("clip.mp4", Buffer.from(await clip.arrayBuffer()));
}
curl https://glim.run/v1/videos/vid_01J9X3M2 -H "Authorization: Bearer $GLIM_API_KEY"
curl -o clip.mp4 https://glim.run/v1/videos/vid_01J9X3M2/content -H "Authorization: Bearer $GLIM_API_KEY"

Music

POST/v1/music

Songs render as jobs, the same way as video. One song is held when the job starts.

FieldTypeNotes
modelstring, requiredsuno, suno-v6-mini or suno-v6-wild
promptstring, requiredStyle, mood, tempo and instruments
lyricsstringOptional lyrics; leave out for an instrumental
curl https://glim.run/v1/music \
  -H "Authorization: Bearer $GLIM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "suno", "prompt": "A calm piano piece with a soft synth pad, slow tempo, late at night"}'

Poll GET /v1/music/{id}, then download the MP3 from GET /v1/music/{id}/content.

Models endpoint

GET/v1/models

List every model with its kind, price and list price. No key is needed.

{
  "object": "list",
  "data": [
    {
      "id": "claude-opus-5.5",
      "object": "model",
      "owned_by": "anthropic",
      "kind": "chat",
      "context_window": 1000000,
      "privacy": "anonymized",
      "price": { "input": 1.80, "output": 9.00, "unit": "per_1m_tokens" },
      "list_price": { "input": 4.00, "output": 20.00, "checked": "2026-11-26", "source": "platform.claude.com" }
    }
  ]
}
GET/v1/models/{id}

Returns one model in the same shape.

Balance endpoint

GET/v1/balance

The balance behind the key, what is held right now, and Holder Credit.

{ "balance": 17.99, "held": 0.072018, "holder_credit": 2.68, "spendable": 20.597982, "currency": "USD" }

spendable is balance plus Holder Credit minus open holds. Holder Credit is spent first.

Errors & limits

Errors use the OpenAI error shape, with a stable code you can branch on.

{ "error": { "type": "billing_error", "code": "insufficient_balance", "message": "This call holds up to $0.073080 and your spendable balance is $0.012000.", "param": null } }

Status codes

StatuscodeMeaningRetry?
400invalid_requestMalformed body or an unknown field valueNo, fix the request
401invalid_api_keyMissing, wrong or revoked keyNo
402insufficient_balanceSpendable balance cannot cover the holdAfter a top-up, or with a lower max_tokens
403model_not_allowedThe key is restricted and this model is not on its listNo
404model_not_foundNo model with this idNo
408timeoutThe host did not answer in time; the hold is releasedYes, with backoff
413context_too_longInput exceeds the model's context windowNo, shorten the input
429rate_limitedToo many requests or tokens per minute for this keyYes, after retry-after
500internal_errorSomething failed at Glim; the hold is releasedYes, with backoff
502 / 503upstream_unavailableThe model host is down or overloaded; see StatusYes, with backoff

Rate limits

Limits apply per key. Every response carries the current state:

HeaderMeaning
x-ratelimit-limit-requestsRequests allowed per minute (default 600)
x-ratelimit-remaining-requestsRequests left in this window
x-ratelimit-limit-tokensTokens allowed per minute (default 2,000,000)
x-ratelimit-remaining-tokensTokens left in this window
x-ratelimit-reset-requestsTime until the request window resets, e.g. 12s
retry-afterOn 429, seconds to wait before retrying

Retry guidance

  • Retry 408, 429, 500, 502 and 503 with exponential backoff and jitter, starting at 1 second and capping at 30. Honour retry-after when it is set.
  • Do not retry 400, 401, 403, 404 or 413: the same request will fail again.
  • Retries are safe for billing: a failed call releases its hold, so you are never charged twice for one answer.
  • The OpenAI SDKs retry twice by default; set max_retries to change it.
client = OpenAI(base_url="https://glim.run/v1", api_key=os.environ["GLIM_API_KEY"], max_retries=4, timeout=120)

MCP server

Add Glim's models to any app that speaks the Model Context Protocol: Claude Code, Claude Desktop, Cursor and others.

The Glim MCP server lives at https://mcp.glim.example/mcp (streamable HTTP) and authenticates with your Glim API key. It gives the host app these tools:

ToolWhat it does
list_modelsLists models, with kind, price and privacy label
ask_modelSends a prompt to any chat model and returns the reply and its price
generate_imageCreates an image and returns it
generate_video, generate_musicStarts a media job and returns its id
get_jobReports a media job's status and, when done, its download link
get_balanceReturns balance, open holds and Holder Credit

Claude Code

claude mcp add --transport http glim https://mcp.glim.example/mcp \
  --header "Authorization: Bearer $GLIM_API_KEY"

Run /mcp inside Claude Code to check that glim is connected, then ask, for example, “use glim to get a second opinion from gpt-6.1-sol on this function”.

Other MCP clients

Most clients read a JSON config. Add a glim server:

{
  "mcpServers": {
    "glim": {
      "type": "http",
      "url": "https://mcp.glim.example/mcp",
      "headers": { "Authorization": "Bearer glim_..." }
    }
  }
}

For clients that only support stdio, run the bridge package:

{
  "mcpServers": {
    "glim": {
      "command": "npx",
      "args": ["-y", "@glim/mcp"],
      "env": { "GLIM_API_KEY": "glim_..." }
    }
  }
}
Spend control. Create a dedicated key for MCP use so its spend shows separately in Console, and revoke it from there if a tool misbehaves.

SDKs

Glim has no SDK of its own. Change the base URL and use the key in the SDK you already have.

OpenAI Python and TypeScript

from openai import OpenAI
client = OpenAI(base_url="https://glim.run/v1", api_key=os.environ["GLIM_API_KEY"])
import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://glim.run/v1", apiKey: process.env.GLIM_API_KEY });
# Many tools read these two variables
export OPENAI_BASE_URL="https://glim.run/v1"
export OPENAI_API_KEY="$GLIM_API_KEY"

LangChain

from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="claude-sonnet-5.5", base_url="https://glim.run/v1", api_key=os.environ["GLIM_API_KEY"])
print(llm.invoke("Name three uses for a pooled key.").content)

Vercel AI SDK

import { createOpenAI } from "@ai-sdk/openai";
import { streamText } from "ai";

const glim = createOpenAI({ baseURL: "https://glim.run/v1", apiKey: process.env.GLIM_API_KEY });
const result = streamText({ model: glim("gemini-4-hydrogen"), prompt: "Summarise the thesis of private inference." });
for await (const part of result.textStream) process.stdout.write(part);

Other tools

Anything with an “OpenAI-compatible” or “custom base URL” setting works: LlamaIndex, LiteLLM, Continue, Open WebUI and most editors. Use the model ids from Models.

Sealed models & attestation

Four open-weight chat models run inside attested hardware, where neither the host nor Glim can read the content.

Sealed models today: . They are available in Glim Chat, Glim Console and the API.

How it works

  1. The model runs in a confidential-computing enclave on GPUs that encrypt memory. The host operator cannot read it.
  2. The enclave produces a signed measurement of the exact code and weights it loaded.
  3. Glim checks that measurement against the published one before sending your request, and encrypts the request to the enclave's key. Glim's own servers only see ciphertext.
  4. Each reply carries an attestation record you can verify yourself.
"glim": {
  "privacy": "sealed",
  "attestation": {
    "enclave": "verified",
    "measurement": "9f2c4e…a71e",
    "issued": "2026-11-29T14:02:11Z",
    "report_url": "https://glim.run/v1/attestations/att_01J9X5"
  }
}

Fetch report_url to get the raw signed report and verify it against the hardware vendor's root certificate.

Holder Credit

Hold $GLIM, and a share of the swap tax is paid to you every hour as platform credit.

Every $GLIM swap pays a fixed 3% tax: 0.25% is burned, 0.75% goes to Holder Credit, and 2% funds development. At the top of every hour the Holder Credit pool is valued in USDC and split across wallets holding about $20 or more of $GLIM, in step with each wallet's average balance over the hour.

  • Credit is added to your balance by itself and spent before your USDC balance.
  • It works for every model, in Glim Chat and through the API.
  • GET /v1/balance returns it as holder_credit.

Live numbers and the next sweep are on the token page.

Tutorial: your first app

Build a small streaming chat web app in about 60 lines. The key stays on your server; the browser streams the reply token by token.

1. Set up

mkdir glim-chat && cd glim-chat
npm init -y && npm pkg set type=module
npm install openai express
export GLIM_API_KEY="glim_..."

2. The server

Create server.js. It serves the page and streams each reply as plain text.

import express from "express";
import OpenAI from "openai";

const glim = new OpenAI({ baseURL: "https://glim.run/v1", apiKey: process.env.GLIM_API_KEY });
const app = express();
app.use(express.json());
app.use(express.static("public"));

app.post("/api/chat", async (req, res) => {
  const { messages, model = "claude-sonnet-5.5" } = req.body;
  res.setHeader("Content-Type", "text/plain; charset=utf-8");
  try {
    const stream = await glim.chat.completions.create({ model, messages, stream: true, max_tokens: 2048 });
    for await (const chunk of stream) res.write(chunk.choices[0]?.delta?.content ?? "");
  } catch (err) {
    res.write(`\n[error ${err.status ?? ""}: ${err.message}]`);
  }
  res.end();
});

app.listen(3000, () => console.log("Open http://localhost:3000"));

3. The page

Create public/index.html.

<!doctype html>
<meta charset="utf-8">
<title>My Glim chat</title>
<style>
  body { font: 16px system-ui; max-width: 680px; margin: 40px auto; background: #000; color: #eee; }
  .msg { white-space: pre-wrap; padding: 10px 0; border-bottom: 1px solid #222; }
  .user { color: #ccff00; }
  form { display: flex; gap: 8px; margin-top: 16px; }
  input { flex: 1; padding: 10px; background: #111; color: #eee; border: 1px solid #333; }
</style>
<div id="log"></div>
<form id="f"><input id="q" placeholder="Ask anything" autofocus><button>Send</button></form>
<script>
  const messages = [];
  const log = document.getElementById("log");
  const add = (cls, text) => { const d = document.createElement("div"); d.className = "msg " + cls; d.textContent = text; log.append(d); return d; };

  document.getElementById("f").onsubmit = async (e) => {
    e.preventDefault();
    const q = document.getElementById("q");
    messages.push({ role: "user", content: q.value });
    add("user", q.value); q.value = "";
    const out = add("bot", "");
    const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messages }) });
    const reader = res.body.getReader(), dec = new TextDecoder();
    for (;;) { const { value, done } = await reader.read(); if (done) break; out.textContent += dec.decode(value, { stream: true }); }
    messages.push({ role: "assistant", content: out.textContent });
  };
</script>

4. Run it

node server.js

Open http://localhost:3000 and ask a question. The reply streams in as it is written. Check Usage in Console to see the call, its price and its list price.

5. Take it further

  • Add a model picker: send model from the page, e.g. gpt-6.1-sol or gemini-4-hydrogen.
  • Use a sealed model such as glm-5.3 when the content should be unreadable even to the host.
  • Set max_tokens per request to keep holds small when many users chat at once.