GLM 5.2 System Prompt Guide: Templates for Coding, Analysis, and Writing
Jul 20, 2026

GLM 5.2 System Prompt Guide: Templates for Coding, Analysis, and Writing

The system prompt sets the frame for everything GLM 5.2 outputs. Here are proven templates for code generation, document analysis, and structured extraction, with token-efficiency tips.

Every output GLM 5.2 produces is shaped by what comes before the user turn. A vague system prompt produces vague output. A precisely framed one locks in role, format, and tone — and because GLM 5.2 caches prompt prefixes at $0.26 per million tokens, a long, stable system prompt becomes almost free after the first call. This guide gives you copy-paste templates for the three workloads where system prompt design has the most leverage: code generation, document analysis, and structured writing.

Why System Prompts Matter More for GLM 5.2

GLM 5.2 is a 753B-parameter Mixture-of-Experts model with a 1M-token (1,048,576) context window. That context size changes the calculus for system prompts in a practical way: you can load an entire styleguide, codebase section, API reference, or knowledge base directly into the system prompt and have it available for every turn.

The economic case for front-loading content into the system prompt is the cache hit price. Standard input pricing is $1.40 per million tokens. Cached prefix hits drop to $0.26 per million — an 81% discount. The rule: anything stable belongs in the system prompt; anything dynamic belongs in the user message.

Token typePrice per million
Input (uncached)$1.40
Cache hit$0.26
Output$4.40

At 158 tokens per second — third fastest among frontier models according to Artificial Analysis — GLM 5.2 also returns completions quickly, so even long system prompts don't introduce painful latency. TTFT is 1.54 seconds.

Architecture Note: What GLM 5.2 Processes

GLM 5.2 is text-only. It does not accept image, audio, or video input. If your workflow involves multimodal inputs, route those to a model that handles them; use GLM 5.2 for the text reasoning and generation steps.

The model uses a Transformer decoder with 78 layers, 256 experts per layer, and 8 experts activated per forward pass (Mixture of Experts, DSA attention). This architecture means very high capacity relative to compute cost — which is why the model scores 89% on GPQA Diamond, 62.1% on SWE-bench Pro, and 90%+ on HumanEval, while keeping output pricing competitive at $4.40 per million tokens.

Understanding the architecture matters for system prompt design: the model has strong instruction-following at scale, so explicit format constraints in the system prompt are respected reliably rather than being suggestions.

The Core Principle: Role + Format + Constraints

Every effective GLM 5.2 system prompt contains three elements:

  1. Role: Who the model is acting as, with enough specificity to narrow behavior.
  2. Format: Exactly what the output should look like — code fences, JSON schema, word count, heading structure.
  3. Constraints: What the model should not do — no preamble, no apologies, no unsolicited explanations.

Omitting any of these creates ambiguity that costs tokens and can produce inconsistent outputs at scale.

Template 1: Code Generation

Use this for generating functions, modules, tests, or refactors. The key constraint is "output only code" — without it, GLM 5.2 will often include explanation prose, which costs output tokens and requires post-processing to strip.

You are a senior software engineer specializing in [language/framework].

Rules:
- Output ONLY code in markdown fences with the correct language tag.
- Do not include explanations, comments, or preamble unless the user explicitly asks.
- If the request is ambiguous, ask one clarifying question before writing code.
- Match the style of any code the user provides (indentation, naming conventions, idioms).
- When writing tests, use [pytest/jest/go test] and cover edge cases.

If the user says "explain", add a brief comment block above each logical section.

For agentic coding workflows where GLM 5.2 is calling tools, extend this template with explicit tool listings. From the GLM 5.2 overview:

You are a senior software engineer. You have access to these tools:
- bash(command: str) — runs a shell command, returns stdout/stderr
- read_file(path: str) — returns file contents
- write_file(path: str, content: str) — writes content to disk

Always read a file before editing it. Never assume file contents.
Output tool calls as JSON: {"tool": "bash", "args": {"command": "..."}}

SWE-bench Pro score of 62.1% reflects real-world software engineering capability — explicit tool declarations in the system prompt are part of what enables that performance.

Template 2: Document Analysis and Structured Extraction

For extraction tasks — parsing contracts, summarizing reports, pulling structured data from unstructured text — the most important system prompt element is the output schema. When GLM 5.2 knows exactly what shape the output must take, it does not invent fields or omit required ones.

You are a data analyst specializing in document extraction.

Rules:
- Think step by step before outputting your final answer.
- Output ONLY valid JSON matching this exact schema:
  {
    "summary": string,          // 2-3 sentence summary
    "key_entities": string[],   // named people, orgs, places
    "dates": string[],          // all dates in ISO 8601 format
    "action_items": string[],   // any explicit tasks or commitments
    "risk_flags": string[]      // any ambiguous, contradictory, or missing information
  }
- If a field has no data, output an empty array or empty string — never omit the key.
- Do not include any text outside the JSON object.

For analysis tasks where you want reasoning visible before the final answer, add a scratchpad instruction:

You are a senior analyst. Before answering, think through the problem inside <thinking>...</thinking> tags. After closing the thinking tags, output your final answer in the requested format. The user will only see what comes after </thinking>.

This pattern is useful when debugging why a model produced a particular answer, since the reasoning is preserved in the response but can be stripped before display.

Template 3: Technical Writing

For generating documentation, API references, blog posts, or structured reports. The key variables are audience, tone, and length cap. Without a length cap, the model will often over-generate.

You are a technical writer. Your audience is professional software developers.

Rules:
- Tone: direct, concrete, and precise. No filler phrases ("In conclusion", "It is worth noting").
- Length: stay under [word count] words unless the user specifies otherwise.
- Structure: use markdown headings (##, ###), bullet lists for items, and code blocks for all code.
- Do not use passive voice when active voice is clearer.
- If the user provides existing text to edit, preserve their terminology unless it is factually wrong.
- Never add a "Summary" section unless the user asks for one.

For localized writing or brand voice, use the 1M context window to embed the full styleguide:

You are a technical writer following the style guide below.

[STYLE GUIDE — paste entire document here, up to several hundred pages]

Rules:
- Follow the style guide exactly.
- If the user's request conflicts with the style guide, follow the guide and note the conflict.
- Output in markdown.

Because the style guide is a stable prefix, subsequent calls in the same session hit cache at $0.26/M rather than $1.40/M.

Template 4: Function Calling and Tool Use

GLM 5.2 supports function calling. For reliable tool dispatch, list available functions explicitly in the system prompt with their signatures and purpose. Ambiguity about when to call a tool versus when to respond directly is one of the most common sources of failure in agentic systems.

You are an assistant with access to the following tools. Use them when the user's request requires real-time data, file access, or computation.

Tools:
- search(query: str) -> list[dict]: Search the web. Returns a list of {title, url, snippet} objects. Use when the user asks about recent events or facts you may not have.
- calculator(expression: str) -> float: Evaluate a mathematical expression. Use for any numeric computation.
- get_user_data(user_id: str) -> dict: Retrieve user account data. Use only when the user explicitly asks about their account.

Rules:
- Call tools only when necessary. Do not call search for questions you can answer directly.
- Always explain your reasoning before calling a tool.
- After receiving tool output, summarize the key information before responding.
- If a tool returns an error, tell the user and ask how to proceed.

Caching Strategy: What to Put Where

The 1M context window makes it tempting to put everything in the system prompt. The correct split is based on stability, not size.

Content typePut inReason
Role definitionSystem promptNever changes per session
Output format / schemaSystem promptStable across all calls
Style guide or reference docsSystem promptStatic content, cache hit after first call
Current user queryUser messageChanges every turn
Dynamic data (today's date, user ID)User messageVariable, can't cache
Conversation historyMessage arrayManaged by the API
One-off instructionsUser messageNot worth caching

At $0.26/M for cache hits versus $1.40/M for uncached input, a 10,000-token system prompt loaded 1,000 times costs $2.60 in cache hits versus $14.00 uncached — a saving of $11.40 on that one prompt alone. At scale, this compounds significantly.

Common Issues

IssueLikely causeFix
Model ignores format instructionsFormat rule buried in long proseMove format rule to the top; use numbered list
JSON output has extra textNo "output ONLY JSON" constraintAdd "Do not include any text outside the JSON"
Code output includes unwanted proseMissing "output only code" ruleAdd explicit constraint; add "no explanations unless asked"
Tool called unnecessarilyAmbiguous tool trigger conditionAdd explicit "Use only when..." for each tool
Output too longNo length constraintAdd word count or "be concise" with specific target
Style drift across turnsStyle rules too vagueAdd negative examples ("Do not use passive voice")

Frequently Asked Questions

Does GLM 5.2 follow system prompt instructions reliably?

Yes, with explicit instructions. GLM 5.2 is a 753B-parameter model trained to follow detailed directives. Vague instructions produce variable results; specific, imperative instructions — "Output ONLY valid JSON", "Do not include preamble" — are followed consistently.

How long can a system prompt be?

The total context window is 1,048,576 tokens. The system prompt can theoretically consume a large portion of that, but practically, keep the core instruction section tight (under 500 tokens) and use the bulk of the window for reference material like codebases, documents, or styleguides. The model attends to the instruction section most reliably when it's concise and near the top.

Does the cache apply to partial system prompt matches?

Cache hits apply to exact prefix matches from the beginning of the prompt. If you change anything before the cached portion, the cache miss is charged. This is why dynamic content — timestamps, user IDs, per-call variables — should always go in the user message, not the system prompt.

Can I use GLM 5.2 system prompts through OpenRouter?

Yes. GLM 5.2 is available on OpenRouter as z-ai/glm-5.2. The system prompt field behaves identically. For direct API access, use base_url=https://api.z.ai/v1 with model glm-5.2 via the Z.ai endpoint.

What is the best system prompt for coding tasks specifically?

Start with the template in this article: role as senior engineer, output-only-code rule, and one clarifying-question policy. For agentic coding that matches the 62.1% SWE-bench Pro benchmark, add explicit tool listings and a "read before writing" instruction for file operations.

Should I include examples in the system prompt?

Few-shot examples in the system prompt are cached and reused, making them cost-effective at scale. One or two well-chosen examples often outperform several paragraphs of instruction for format-sensitive tasks like extraction or structured output. For simple tasks, keep the system prompt instruction-only.

How do I debug a system prompt that isn't working?

Add a scratchpad instruction (<thinking>...</thinking> tags) temporarily to see the model's reasoning. This reveals whether the model is misunderstanding the task, ignoring a specific rule, or producing correct reasoning but wrong formatting. Once identified, refine the specific failing rule rather than rewriting the whole prompt.

Next Steps

The templates above are starting points. Adapt them to your stack by substituting the specific language, schema, or style constraints your workflow requires. For production use:

  1. Pin your system prompt as a stable string in version control.
  2. Measure cache hit rate via the API usage response fields to verify the caching is working.
  3. Benchmark output quality with a small eval set before deploying changes — system prompt edits can have nonobvious downstream effects on edge cases.
  4. For function-calling workflows, see how GLM 5.2's 1M context enables loading full API schemas — covered in GLM 5.2 API guide.

Try GLM 5.2 — no API key needed: glm5.app/chat.

Sources

Begynd at bruge GLM 5 i dag

Prøv GLM 5 gratis — ræsonnering, kodning, agenter og billedgenerering på en platform.