GLM 5.2 API Key Setup: OpenAI-Compatible Endpoint, Model ID, and Python Example

Set up a GLM 5.2 API key with OurToken's OpenAI-compatible endpoint. Copy the exact model ID, test cURL, and call GLM 5.2 from Python.

O
OurToken Team//13 min
GLM 5.2 API Key Setup: OpenAI-Compatible Endpoint, Model ID, and Python Example

A GLM 5.2 API key is only useful when the credential, base URL, endpoint, model ID, and request body agree. A valid key can still produce a 400, 401, or 404 response if an application sends it to the wrong gateway, uses glm/glm-5.2 instead of glm-5.2, or gives an OpenAI-compatible SDK the full endpoint URL instead of the SDK base URL.

This guide shows the shortest reliable path to a first GLM 5.2 request through OurToken. You will create or locate an API key, configure the GLM 5.2 API endpoint, run a cURL smoke test, call the same route from Python, inspect usage fields, calculate a realistic cost, and add production safeguards. The current OurToken route is:

Base URL:     https://api.ourtoken.ai/v1
Full URL:     https://api.ourtoken.ai/v1/chat/completions
Model ID:     glm-5.2

The examples use the current GLM 5.2 API page and the related OurToken API documentation as the configuration source. The page is the compatibility boundary for the OurToken route: use its model ID, request fields, and current prices rather than assuming that every GLM provider parameter is accepted unchanged.

Verification status: The examples are documentation-verified against the public OurToken GLM 5.2 page, but they were not executed with a live API key in this draft. Run the minimal request with your own credential, inspect its response, and verify optional features before sending production traffic.

GLM 5.2 API Key Setup and First Request

The key, base URL, operation path, and model value are separate settings. Keep them separate in environment variables or server-side configuration so a model switch does not require editing every request call.

Exact values to copy

SettingCurrent OurToken valueWhat it controls
API keyOURTOKEN_API_KEYAuthenticates the request
SDK base URLhttps://api.ourtoken.ai/v1The URL passed to an OpenAI-compatible SDK
Full API endpointhttps://api.ourtoken.ai/v1/chat/completionsThe URL used by cURL or raw HTTP
Model IDglm-5.2Selects the GLM 5.2 route
Required body fieldsmodel, messagesIdentifies the route and conversation
Output limitmax_tokensCaps generated output for a predictable test

The difference between a base URL and a full endpoint is the most common setup mistake. The Python SDK appends /chat/completions when you call client.chat.completions.create, so its base_url must stop at /v1. cURL does not construct that path; it must use the complete /v1/chat/completions URL.

What the OpenAI-compatible route means

An OpenAI-compatible API is a request and response contract, not a promise that every provider exposes identical models or parameters. With the OurToken route, the reusable parts are the Bearer authorization header, the Chat Completions path, the messages array, and the OpenAI SDK method. The model-specific value is glm-5.2.

Do not use any of these as the API model value:

  • glm/glm-5.2, which resembles the website catalog path;
  • GLM 5.2, which is a display name rather than the current model ID;
  • a provider-specific model alias copied from another gateway;
  • glm-5-2, which changes the punctuation in the model ID.

The current OurToken page lists temperature, top_p, stream, stream_options, tools, tool_choice, and response_format as optional Chat Completions fields. Start without them. Add one at a time after the plain request works, because a compatibility route can expose a generic field while still applying model-specific limits or behavior.

Get and Test a GLM 5.2 API Key

An API key authenticates an application request. It is not a GLM website login, a model ID, or a browser session. For the OurToken route, use the OurToken API Keys page to create or manage the credential. The protected page may redirect to login before key management is available.

Store the key in a server-side secret or a local environment variable during development. Never put it in frontend JavaScript, a mobile bundle, a public repository, a notebook shared with other people, or a screenshot.

On macOS or Linux:

export OURTOKEN_API_KEY="paste-your-key-locally"

On Windows PowerShell:

$env:OURTOKEN_API_KEY = "paste-your-key-locally"

The variable name is an application convention. The HTTP header remains:

Authorization: Bearer YOUR_API_KEY

Configuration checklist.

  1. The key was created for the OurToken gateway.
  2. The full cURL URL ends in /v1/chat/completions.
  3. The Python SDK base URL ends in /v1, not /chat/completions.
  4. The JSON model value is exactly glm-5.2.
  5. The messages value is an array of role/content objects.
  6. The first request uses a short prompt and a small max_tokens value.
  7. The key is available only to the server process that needs it.

cURL smoke test

This is a minimal non-streaming GLM 5.2 cURL example. It uses a short prompt and a small output limit so configuration failures return quickly:

curl -sS https://api.ourtoken.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${OURTOKEN_API_KEY}" \
  -d '{
    "model": "glm-5.2",
    "messages": [
      {
        "role": "user",
        "content": "Give me a three-step checklist for reviewing a database migration."
      }
    ],
    "max_tokens": 256
  }'

PowerShell version.

PowerShell can build the JSON body as an object. This avoids nested quote escaping and is easier to edit for a real prompt:

$payload = @{
  model = "glm-5.2"
  messages = @(
    @{
      role = "user"
      content = "Give me a three-step checklist for reviewing a database migration."
    }
  )
  max_tokens = 256
} | ConvertTo-Json -Depth 5

curl.exe "https://api.ourtoken.ai/v1/chat/completions" `
  -H "Content-Type: application/json" `
  -H "Authorization: Bearer $env:OURTOKEN_API_KEY" `
  --data-raw $payload

What a successful response should contain.

Do not depend on the exact generated wording. Inspect the response structure and confirm the returned model before adding application logic:

{
  "id": "chatcmpl-redacted",
  "object": "chat.completion",
  "model": "glm-5.2",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "1. Review the schema changes.\n2. Test rollback.\n3. Validate production impact."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 30,
    "completion_tokens": 24,
    "total_tokens": 54
  }
}

This is an illustrative response shape, not a live response captured from an OurToken account. The current model page documents prompt_tokens, completion_tokens, and total_tokens. When cache details are present, prompt_tokens_details.cached_tokens is a breakdown of the prompt total, not a second full input quantity.

Common cURL mistakes.

SymptomLikely causeFix
401 UnauthorizedMissing, expired, or wrong-provider keyCheck the environment variable and use an OurToken key with the OurToken URL
404 Not FoundWrong path or model valueUse /v1/chat/completions and glm-5.2
400 for a missing fieldMalformed JSON or missing messagesValidate the JSON and send an array of messages
400 after adding an optionThe route rejects an optional fieldRemove it and compare with the current model page
429 Too Many RequestsRate limit or account capacityUse bounded backoff and avoid unlimited retries
Empty or partial outputOutput cap or context limit was reachedInspect finish_reason and adjust the prompt or max_tokens

Do not retry a 400, 401, or 404 request unchanged. Those responses indicate a configuration or request problem, not a transient service failure.

GLM 5.2 Python API Usage

The official OpenAI Python library can send requests through the OurToken-compatible base URL. Install it in the same environment that will run the integration:

python -m pip install --upgrade openai

Then configure the client with the base URL, not the full endpoint:

import os

from openai import OpenAI


client = OpenAI(
    api_key=os.environ["OURTOKEN_API_KEY"],
    base_url="https://api.ourtoken.ai/v1",
)

response = client.chat.completions.create(
    model="glm-5.2",
    messages=[
        {
            "role": "system",
            "content": "You are a concise software engineering assistant.",
        },
        {
            "role": "user",
            "content": "List the checks for a safe database migration.",
        },
    ],
    max_tokens=256,
)

message = response.choices[0].message
print(message.content or "")

if response.usage:
    usage = response.usage
    cached_details = getattr(usage, "prompt_tokens_details", None)
    print(
        {
            "prompt_tokens": usage.prompt_tokens,
            "completion_tokens": usage.completion_tokens,
            "total_tokens": usage.total_tokens,
            "cached_tokens": getattr(cached_details, "cached_tokens", 0),
        }
    )

The response usage names matter. Do not silently rename prompt_tokens/completion_tokens to input_tokens/output_tokens unless your own application adds an explicit conversion layer. Different SDKs and providers use different aliases; the current OurToken compatibility response documents the prompt/completion names above.

Keep the first Python request deterministic.

The first successful call should prove four things: the key is accepted, the route is reachable, the model ID is correct, and the response contains an assistant message. These checks catch proxy or configuration mistakes earlier than a long application workflow:

assert response.model == "glm-5.2"
assert response.choices
assert response.choices[0].message.role == "assistant"
assert response.choices[0].message.content is not None

In production, replace assertions with structured error handling and telemetry. An application should fail clearly if a gateway returns a different model or an empty response.

Multi-turn, streaming, and optional fields

Chat Completions is stateless from the application's perspective. Send the conversation history again when asking a follow-up question:

messages = [
    {"role": "system", "content": "You are a concise software engineering assistant."},
    {"role": "user", "content": "What should I verify before a migration?"},
]

first = client.chat.completions.create(
    model="glm-5.2",
    messages=messages,
    max_tokens=256,
)

messages.append(first.choices[0].message)
messages.append(
    {
        "role": "user",
        "content": "Now turn that into a release checklist.",
    }
)

second = client.chat.completions.create(
    model="glm-5.2",
    messages=messages,
    max_tokens=256,
)

print(second.choices[0].message.content or "")

If you add tools, preserve the complete assistant message, including tool-call metadata, instead of storing only content. Tool results must keep their matching tool-call IDs. The OpenAI-compatible tool-calling guide shows the general message pattern and validation concerns.

For streaming output, set stream=True and print non-empty content deltas:

stream = client.chat.completions.create(
    model="glm-5.2",
    messages=[{"role": "user", "content": "Summarize the deployment checklist."}],
    max_tokens=256,
    stream=True,
)

for chunk in stream:
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)

print()

Streaming changes where you receive the final usage object. If your application needs token accounting for streamed responses, check the current model page's stream_options behavior and handle the final usage-bearing event rather than assuming every chunk contains complete usage data.

Do not add tools, structured output, or provider-specific reasoning controls to the first request. Verify each optional field on the current OurToken route, then add one feature and one test case at a time.

Move from Testing to Production

A successful smoke test proves only that one request passed. A usable GLM 5.2 integration also needs secret isolation, usage accounting, budget controls, timeouts, retries, and a plan for model selection.

Request architecture.

User or internal service
          |
          | application request
          v
Your backend or job worker
          |
          | Authorization: Bearer OURTOKEN_API_KEY
          v
https://api.ourtoken.ai/v1/chat/completions
          |
          | model = glm-5.2
          v
GLM 5.2 route
          |
          v
Assistant response + usage data
          |
          v
Redacted logs, budget checks, and application output

Never expose the API key to a browser. The backend should also own the model allowlist instead of accepting an arbitrary model string from an untrusted client:

SUPPORTED_MODELS = {
    "glm": "glm-5.2",
}


def resolve_model(name: str) -> str:
    try:
        return SUPPORTED_MODELS[name]
    except KeyError as exc:
        raise ValueError("Unsupported model selection") from exc

A practical coding workflow.

The current GLM 5.2 model page positions the route for coding workflows, long-context evaluation, and production assistant tasks. A code-review service can start with a stable system instruction, the relevant diff, and test output, then ask for findings in a predictable format. A safe workflow is:

  1. Keep repository instructions and the review policy on the server.
  2. Send only the relevant diff and test output for each review.
  3. Bound max_tokens so a malformed prompt cannot create an unbounded bill.
  4. Validate paths, commands, and structured fields before using model output.
  5. Require human approval before a tool can modify a repository.
  6. Record model, status, latency, token usage, and cost without logging the key.

For a service with several supported models, the model routing guide describes how to send simpler work to a lower-cost route and reserve stronger routes for tasks that need them.

Cost, usage, and reliability

The following prices are the current OurToken GLM 5.2 listing checked on July 21, 2026. Prices can change, so confirm the live GLM 5.2 pricing and model configuration before setting a budget.

Token categoryOurToken price
Input$0.8400 / 1M tokens
Output$2.6400 / 1M tokens
Cached input$0.1560 / 1M tokens
Cache writes$0 / 1M tokens

For 100,000 uncached input tokens and 10,000 output tokens:

Input:  100,000 / 1,000,000 * $0.8400 = $0.08400
Output:  10,000 / 1,000,000 * $2.6400 = $0.02640
Total:                               = $0.11040

For a repeated-context request with 50,000 cached input tokens, 50,000 uncached input tokens, and 10,000 output tokens:

Uncached input: 50,000 / 1,000,000 * $0.8400 = $0.04200
Cached input:   50,000 / 1,000,000 * $0.1560 = $0.00780
Output:         10,000 / 1,000,000 * $2.6400 = $0.02640
Total:                                         = $0.07620

The second calculation assumes the route reports 50,000 cached tokens. Caching does not reduce the number of tokens your application sends; it changes how a portion of input is billed. If prompt_tokens_details.cached_tokens is returned, calculate uncached input once:

uncached_input_tokens = prompt_tokens - cached_tokens

estimated_cost =
  uncached_input_tokens * input_rate
  + cached_tokens * cache_read_rate
  + completion_tokens * output_rate

Do not charge the full prompt_tokens value at the normal input rate and then charge cached_tokens again. The prompt caching guide explains how stable prefixes, cache hits, and usage measurement affect a compatible API workflow. Measure actual usage instead of assuming that every repeated prompt receives a cache hit.

Retry and timeout policy.

StatusRetry by default?Action
400NoFix the body or remove an unsupported field
401NoReplace or reconfigure the credential
404NoCheck the base URL, path, and model ID
429Yes, boundedBack off and respect account limits
500-599Yes, boundedRetry with a maximum attempt count
Network timeoutConditionalRetry only when duplicate execution is safe

Retries can duplicate a model request after a client-side timeout. For chat-only work, that may be acceptable; for tool calls or external side effects, use an idempotency strategy and require confirmation before executing the action.

Release checklist.

  1. The key is available only to a server process or protected worker.
  2. The cURL smoke test succeeds with model: "glm-5.2".
  3. The Python client uses base_url="https://api.ourtoken.ai/v1".
  4. The response model, message role, finish reason, and usage are validated.
  5. Cached tokens are not counted twice in cost calculations.
  6. 400, 401, 404, 429, timeout, and 5xx behavior is tested.
  7. Prompts, responses, and authorization headers are redacted in logs.
  8. Streaming, tools, and structured output are enabled one at a time.

Conclusion and Frequently Asked Questions

The reliable GLM 5.2 API setup is small: create an OurToken key, set https://api.ourtoken.ai/v1 as the SDK base URL, call /chat/completions, and send the exact glm-5.2 model ID. Start with the short cURL request, repeat it in Python, inspect usage, and only then add streaming, tools, structured output, or larger prompts.

When you are ready to test with a real credential, review the GLM 5.2 API configuration and create a key through the OurToken API Keys page. Keep the key server-side and compare actual usage with the dated pricing examples before moving to production traffic.

FAQ

What is the GLM 5.2 API endpoint on OurToken?

The current full endpoint is https://api.ourtoken.ai/v1/chat/completions. When using the OpenAI Python SDK, set base_url to https://api.ourtoken.ai/v1 and call client.chat.completions.create.

What is the GLM 5.2 model ID?

Use glm-5.2 as the API model value. Do not use the catalog path glm/glm-5.2, the display name GLM 5.2, or the hyphenated variant glm-5-2.

Can I use a GLM provider key with OurToken?

Use an OurToken API key with api.ourtoken.ai. API keys belong to the gateway that issued them; a key from another provider is not automatically valid on the OurToken route.

Can I use the OpenAI Python SDK for GLM 5.2?

Yes. Install the openai package, set the OurToken base URL, load the key from OURTOKEN_API_KEY, and call Chat Completions with model="glm-5.2".

Which usage fields should I read in Python?

Use prompt_tokens, completion_tokens, and total_tokens as documented by the current OurToken model page. If available, read prompt_tokens_details.cached_tokens as a breakdown of the input total.

Should I add tools or structured output to the first request?

No. Start with a plain text request, verify the route and response, then add one optional field at a time. Validate tool arguments and structured output in your application before using them in an external action.