EN ▾
Get API key

GLM API Integration Guide for Bots and Backends

A GLM API integration comes down to where the key lives, how many requests you let run at once and what happens when the API says wait. This guide covers those decisions for backends, bots and workflow tools, with code you can adapt.

Updated

Gateway cube receiving items from app, chat and automation blocks, representing API integration

Key points

  • Keep the key on a server you control and let apps call your backend, never the API directly from a browser.
  • Cap in-flight requests at the key's limit: 8 for a full key, 2 for a trial key.
  • Plan the budget from tokens: at $0.15 and $0.50 per 1M, a typical bot message costs a fraction of a cent.
  • Any tool with an OpenAI-compatible option and a custom base URL field can use https://api.glmapikey.com/v1.

Pick the integration pattern first

Most glm api integration work falls into one of four shapes, and the choice affects everything else: where secrets live, how you handle bursts and what a failure looks like to the user.

PatternGood forMain risk
Backend proxyWeb apps and mobile apps with their own usersOpen endpoint that anyone can drain
Queue workerBots, batch jobs, bulk text processingBacklog when requests outpace the limits
Chat botDiscord, Telegram or Matrix characters and companionsLong histories inflating cost
Automation toolWorkflows in tools that offer an HTTP or OpenAI nodeSilent failures when a step errors

All four use the same call underneath: POST /v1/chat/completions on https://api.glmapikey.com/v1 with a bearer key and the model uncensored. The API is OpenAI-compatible, so you can use any OpenAI SDK, or raw HTTP if your stack has no SDK. It is one open-weight model run by an independent provider, not the official API of any vendor and not a router, so build for one model's behaviour. Text only: if your product also needs images or embeddings, plan a second provider for those parts.

The docs page lists endpoints and headers, and the GLM key article explains how to obtain a key.

Backend proxy: keep the key off the client

Anything that runs in a browser or an app bundle can be inspected. If the key ships there, anyone can copy it and spend your credit. The fix is a thin server route that holds the key, applies your own rules and forwards the request.

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
from pydantic import BaseModel

app = FastAPI()
client = AsyncOpenAI(
    base_url="https://api.glmapikey.com/v1",
    api_key="YOUR_KEY",
)

class Ask(BaseModel):
    prompt: str

@app.post("/ask")
async def ask(body: Ask):
    async def gen():
        stream = await client.chat.completions.create(
            model="uncensored",
            messages=[{"role": "user", "content": body.prompt[:4000]}],
            max_tokens=600,
            stream=True,
        )
        async for chunk in stream:
            if chunk.choices and chunk.choices[0].delta.content:
                yield chunk.choices[0].delta.content
    return StreamingResponse(gen(), media_type="text/plain")

The route truncates the prompt and caps the reply, which is the minimum. Add real controls before launch: user authentication, a per-user daily token budget, and a limit on request rate per IP or account. The API returns usage on every call, so you can count tokens per user in your database and refuse requests that exceed their share.

Streaming through a proxy needs one check: confirm your reverse proxy does not buffer responses, or the text will arrive in one block at the end instead of word by word.

Queue worker: respect the concurrency limit

The limits are per key. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. For a steady stream of jobs, concurrency is usually the one that binds first, because each request occupies a slot until it completes, and a streamed one until the stream ends.

A worker pool sized to the limit is the clean answer. Jobs wait in your queue instead of failing with 429:

import asyncio
from openai import AsyncOpenAI, RateLimitError

client = AsyncOpenAI(
    base_url="https://api.glmapikey.com/v1",
    api_key="YOUR_KEY",
    max_retries=0,
)
WORKERS = 8  # use 2 on a trial key

async def run_job(prompt: str) -> str:
    for attempt in range(5):
        try:
            r = await client.chat.completions.create(
                model="uncensored",
                messages=[{"role": "user", "content": prompt}],
                max_tokens=500,
            )
            return r.choices[0].message.content
        except RateLimitError as e:
            delay = float(e.response.headers.get("retry-after", 2 * (attempt + 1)))
            await asyncio.sleep(delay)
    raise RuntimeError("gave up after repeated 429 responses")

async def worker(queue: asyncio.Queue, results: list):
    while True:
        prompt = await queue.get()
        try:
            results.append(await run_job(prompt))
        finally:
            queue.task_done()

async def main(prompts):
    queue, results = asyncio.Queue(), []
    for p in prompts:
        queue.put_nowait(p)
    tasks = [asyncio.create_task(worker(queue, results)) for _ in range(WORKERS)]
    await queue.join()
    for t in tasks:
        t.cancel()
    return results

The error code in the 429 body tells you why you were stopped: rate_limited for requests per minute, concurrency for too many at once, and a plain 429 with Retry-After: 5 for a short overload. Honouring the header is simpler than guessing a delay. Failed and refused requests are not charged, so the retries cost nothing.

Bots and characters

A chat bot is the usual place where cost surprises appear, because a bot that keeps history resends it on every message. Decide early how many messages of history to keep, and store the history yourself, since the API holds no state between calls.

A budget example makes the point. Suppose a bot has 500 active users who each send 20 messages a day. Every message carries 1,500 input tokens (persona, a short history and the new line) and returns 250 tokens:

  • Per message: 1,500 / 1,000,000 x $0.15 = $0.000225 in, plus 250 / 1,000,000 x $0.50 = $0.000125 out, so $0.00035
  • Per day: 500 x 20 = 10,000 messages, so $3.50
  • Per 30 days: $105

If you let history grow until it fills a 12,000-token context instead, input per message rises eightfold to 12,000 tokens, or $0.0018 for the input alone, and the monthly figure climbs accordingly. A rolling window plus a short summary of older events keeps the persona consistent at a lower price.

For companion and roleplay bots, keep the product rules in your own layer. The model is tuned to answer without content refusals for lawful adult use, and the one hard limit is sexual content involving minors, which the service refuses. If your bot lives in a public server, add age gating and channel rules that match the platform you run it on.

Automation tools and no-code workflows

Workflow tools that offer an OpenAI-style node with a configurable base URL can use this API by changing three fields: the URL to https://api.glmapikey.com/v1, the key and the model name to uncensored. Tools that only have a generic HTTP request node can send the raw request instead:

curl https://api.glmapikey.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "uncensored", "messages": [{"role": "user", "content": "Classify this ticket: printer offline"}], "response_format": {"type": "json_object"}}'

For workflow steps that feed another step, JSON mode is worth using, so the next node receives parseable text. Add an error branch for any step that calls the API, because 429 and 5xx responses will happen occasionally and a silent failure in the middle of a workflow is hard to find later. Set a retry with a short wait on that node, and make sure parallel branches do not exceed the number of concurrent requests your key allows.

What your users see when something fails

Every integration needs a plan for the unhappy path, and the user-facing part is as important as the retry code. Three situations come up in practice.

The first is a short overload: a 429 with Retry-After: 5. Retry quietly, and show a typing indicator in the meantime, so the user sees a slightly slower reply instead of an error. The second is hitting your own pool limit. If all eight slots are busy, queue the message and tell the user it is waiting, which is better than a blank screen. The third is running out of credit, which no retry fixes. Watch the balance header, alert yourself at a threshold, and keep a fallback message ready for the day it runs out unnoticed.

Do not show raw API errors to end users. Log them with the request ID, and show a plain sentence that says what happened and what to do next. Never include the key, the base URL or stack traces in anything a user can read.

Money, monitoring and launch checks

Billing is prepaid. You top up any whole amount from $20 to $500, with +5% from $50, +10% from $100 and +15% from $200. Credit does not expire, and there is no subscription. Pay by crypto (USDT on TRC20, USDC on Base). New users can claim $0.50 of trial credit with one click on the API key page, valid for 7 days, so you can test an integration before you fund it. See the pricing page for the rates.

What to monitor in production:

  • Balance. Read X-Balance-USD from responses and alert when it drops under a threshold you choose.
  • Request IDs. Store X-Request-Id next to each job so one failure can be traced.
  • Token usage. Sum usage per user and per feature to see where money goes.
  • 429 rate. A rising count means your pool is larger than the key's limits.

A short launch list: run one real request from the production host, test a forced 429 in staging, confirm that a user cannot reach the API without your auth, and write down what your service shows when the API is unreachable. Prompts are not used for training, which you can pass on to your own users, but say in your own privacy policy that their text is sent to a third-party provider to generate replies.

Questions and answers

Should I call the API from the browser?

No. Keep the key on your server and have the browser call your backend, because a key in client code can be copied and its credit spent by anyone.

How many requests can run at once?

A full key allows 8 concurrent requests and 300 per minute. A trial key allows 2 concurrent and 60 per minute.

What should my code do on a 429?

Read the error code, then wait. Use the Retry-After value when it is present, which is 5 seconds on a temporary overload, and retry. Failed requests are not charged.

Is state kept between calls?

No. You send the whole conversation each time, up to 100,000 tokens for prompt and reply together, and you pay for the input tokens on every call.

Can I use it from no-code tools?

Yes, if the tool lets you set a base URL on its OpenAI node or send a custom HTTP request to https://api.glmapikey.com/v1/chat/completions with a bearer key.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API key