Introduction

GLM‑5.2 is a powerful large‑language model exposed via OpenAI‑compatible chat completion endpoints. It brings native deep‑reasoning control, structured JSON output, function‑calling capability and SSE streaming responses. Developers can build reasoning‑heavy services, structured data pipelines and agent‑based workflows by adjusting a small set of top‑level request parameters. This document walks through authentication, core feature configuration, full request‑response schemas, parameter definitions and common troubleshooting cases for production integration. While you can send raw requests directly to model endpoints, Treerouter can act as an API gateway to unify authentication, rate‑limiting and multi‑model routing for mixed‑model stacks.

1. Basic Chat Completion Request Structure

The chat completion endpoint follows standard OpenAI message format. Valid values for the role field inside messages array include system, user, assistant, and tool. The system role sets global persona and behavior rules for the model session.

Sample minimal request body:

{
  "model": "glm-5.2",
  "messages": [
    {
      "role": "system",
      "content": "You are a senior full‑stack backend engineer skilled in complex code implementation and problem troubleshooting."
    },
    {
      "role": "user",
      "content": "Implement fast‑sort algorithm in Go language, include detailed inline comments."
    }
  ],
  "stream": false
}

The stream boolean controls whether the server returns a full single‑shot reply or incremental SSE chunks. Set stream:false for standard synchronous invocation.

2. Authentication Requirement

Every HTTP request must carry a Bearer token inside the HTTP Authorization header.

Authorization: Bearer $TREEROUTER_API_KEY

Replace $TREEROUTER_API_KEY with your actual access credential. Missing or invalid tokens will trigger HTTP 401 rejection. All feature‑rich requests including reasoning mode, JSON output and tool calling require this header.

3. Deep‑Reasoning Mode Configuration

GLM‑5.2 ships built‑in deep‑reasoning capability. Developers can toggle reasoning activation and adjust reasoning intensity through the top‑level reasoning_effort parameter to fit simple Q&A or complex logical inference scenarios.

Request example with high reasoning effort

{
  "model": "glm-5.2",
  "messages": [
    {
      "role": "user",
      "content": "Which number is larger: 9.11 or 9.8?"
    }
  ],
  "reasoning_effort": "high"
}

Value specification for reasoning_effort

  • low: lightweight reasoning for straightforward tasks
  • medium: default value, balanced reasoning intensity
  • high: full‑depth reasoning for complicated logic, math and multi‑step deduction
  • none: disable reasoning module entirely, faster response for trivial questions

When reasoning mode is enabled, the returned message object contains an extra reasoning_content field storing the model’s internal thought trace. Final usable answer sits inside standard content. For business parsing logic, always consume content. The reasoning_content field is meant for debugging, log review and thought‑chain display only and should not be treated as business output.

4. JSON Structured Output Configuration

When applications need machine‑parseable structured data, enable JSON output mode by setting response_format. This parameter works together with explicit prompt instructions to stabilize JSON generation.

Complete JSON‑mode request sample

{
  "model": "glm-5.2",
  "messages": [
    {
      "role": "system",
      "content": "Reply strictly in JSON format."
    },
    {
      "role": "user",
      "content": "List three programming languages and their key features."
    }
  ],
  "response_format": {
    "type": "json_object"
  }
}

Two critical implementation notes:

  1. response_format must be passed as an object {"type":"json_object"}, raw string values are invalid.
  2. You must add explicit JSON‑format requirements within prompt content (system message or user message). Parameter configuration alone cannot guarantee valid JSON output without prompt guidance.

After receiving HTTP response, parse choices[0].message.content directly with JSON parser. This design fits downstream structured‑data processing pipelines such as data extraction, form filling and backend API payload generation.

5. Function Calling (Tool Calling)

Declare available callable functions through the top‑level tools array. The model will return tool_calls payload when it decides external tool invocation is necessary.

{
  "model": "glm-5.2",
  "messages": [
    {
      "role": "user",
      "content": "What is the current weather in Hangzhou?"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Fetch real‑time weather for given city",
        "parameters": {}
      }
    }
  ]
}

Workflow rules for tool‑call rounds:

  1. When finish_reason equals tool_calls, the model requests tool execution.
  2. Execute target functions locally on your service side.
  3. Append tool execution result back into messages array with role tool and matching tool_call_id.
  4. Resend the full message sequence to obtain final model completion.

The tool_choice parameter controls tool‑selection strategy: acceptable values are none, auto, required, or a custom tool definition object for forcing specific function invocation.

6. Streaming Response

Set stream:true to activate SSE streaming. The Content‑Type response header will switch to text/event‑stream. Server pushes partial content chunks incrementally. Stream terminates with a final data: [DONE] marker.

If token‑usage statistics are required at stream tail, attach stream_options: {"include_usage": true} within request body. Usage metrics will arrive in the final stream chunk.

7. Full Request Parameter Reference Table

FieldTypeRequiredDefaultDescription
modelstringFixed identifier: glm‑5.2
messagesarrayConversation history array; role enum: system, user, assistant, tool
reasoning_effortstringmediumReasoning intensity: low/medium/high/none
streambooleanfalseEnable SSE chunked streaming
stream_optionsobjectOnly valid when stream=true. Supports include_usage boolean
temperaturefloat1Sampling temperature, valid range 0‑2
top_pfloat1Nucleus sampling, valid range 0‑1
max_tokensinteger65536Upper limit for output token count
stopstring \arrayCustom stop sequence(s)
frequency_penaltyfloat0Frequency penalty, range‑2 ~ 2
presence_penaltyfloat0Presence penalty, range‑2 ~ 2
response_formatobjectPass {"type":"json_object"} to enable JSON output mode
toolsarrayDefinition array for available tool functions
tool_choicestring \objectautoTool invocation strategy: none / auto / required or target‑tool object

8. Response Body Structure and finish_reason Enumeration

Non‑streaming complete response sample (truncated):

{
  "id": "chatcmpl‑xxx",
  "object": "chat.completion",
  "created": 1714300000,
  "model": "glm‑5.2",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant"
      }
    }
  ]
}

Under reasoning‑enabled mode, message object additionally carries reasoning_content field storing internal reasoning trace.

finish_reason possible values

ValueMeaning
stopNormal completion triggered by natural model stopping point or stop‑sequence hit
lengthTerminated because max_tokens limit or context window upper bound is reached
tool_callsModel decides to invoke external tools
content_filterOutput intercepted by content safety moderation rules

9. Frequently Encountered Issues & Troubleshooting

Q1: How to disable reasoning mode for GLM‑5.2?

Pass "reasoning_effort":"none" inside request payload. This cuts reasoning overhead for simple questions. Use "high" for multi‑step complex reasoning assignments. Default setting is "medium".

Q2: Difference between reasoning_content and content in response payload

reasoning_content holds internal intermediate thinking steps generated by reasoning module. content contains final answer for end‑user consumption. Production business logic should parse only content. Reserve reasoning_content for logging, debugging and thought‑chain visualization.

Q3: Malformed JSON output even after enabling response_format

Double‑check two points:

  1. response_format is correctly assigned as object {"type":"json_object"} instead of string literal.
  2. Your prompt explicitly tells model to produce JSON output in either system message or user message.

Activating JSON‑mode parameter alone without corresponding prompt constraints frequently yields invalid JSON fragments.

Q4: Model‑ID related 404 not‑found error

Returned 404 not_found_error indicates invalid or offline model identifier. Request body must strictly use glm‑5.2 as model value. Typo or wrong version string will trigger this error.

Q5: 400 invalid_request_error diagnosis

Status code 400 signals parameter value out‑of‑bounds. Validate numeric parameter ranges:

  • temperature: 0 ~ 2
  • top_p: 0 ~ 1

Any value exceeding defined boundaries will raise invalid‑request error.

10. Integration Summary

GLM‑5.2 implements standard OpenAI‑compatible chat completion protocol. Three core configurable capabilities are:

  1. Deep‑reasoning controlled by reasoning_effort for adjustable inference depth.
  2. Structured JSON output combining response_format parameter and explicit prompt instructions.
  3. Standard‑spec function‑calling workflow through tools and tool_choice.

Developers can implement scenarios covering regular dialogue, complex reasoning tasks, structured‑data extraction and AI agent tool invocation following above schema definitions. When operating multiple LLM backends in production, an API gateway helps centralize credential management and request normalization. Treerouter provides unified entry points for multi‑model deployments and reduces repetitive integration work.

Learn more:https://treerouter.com