How to find out what’s eating up the context in ZCode with GLM-5.4?

How to find out what’s eating up the context in ZCode with GLM-5.4?

Author’s note: This article explains how, when using GLM-5.4 in ZCode, you can use a same-task, single-variable controlled comparison to find which type of source is consuming the context.

Conclusion first: To find out what’s consuming GLM-5.4’s context in ZCode, first confirm what the three readings actually represent, then run controlled tests. The session context level above the input box shows when this conversation grows and when it gets compressed. App Usage and the plan page show aggregate consumption; they’re only good for spotting which time window looks abnormal. Once you’ve confirmed the version, model configuration, and max output, start new sessions with the same repo commit, same channel, and same reasoning tier, changing only one variable at a time: default injection, attachments, tool responses, or history. Compare the level difference before and after the same point in time, and you can attribute the growth to a specific source.

This conclusion has three prerequisites. The scope is GLM-5.4 selected in the built-in ZCode Agent on ZCode desktop. For the diagnostic baseline, prefer the official Zhipu Coding Plan channel. Calibrate the context window and max output first, or the comparison results won’t be comparable. The comparison log below is a reproducible diagnostic design; its numbers only demonstrate how to read the results, and are not measurements we have actually run.

glm-5-4-zcode-context-usage-diagnosis-en-image-0


Knowledge Map for Troubleshooting GLM-5.4 Context in ZCode

glm-5-4-zcode-context-usage-diagnosis-en-image-1

Figure notes: Finish the calibration in section 1 first, then follow the branch in section 2 that matches when your level grows. The four branches are parallel — look up the one that fits your symptom, there’s no need to work through them in order. All branches get recorded and verified in section 3 using the same format. If frequent compaction on light tasks only happens on the third-party channel, run one extra comparison on the first-party route.

Index:

  • 1 Pin down what each reading actually measures: this is the starting point. It decides whether the later numbers can be compared at all.
  • 2 Trace the source by growth timing: 2.1 through 2.4 are parallel — pick the one matching your symptom. Each is a single-variable comparison on the same task.
  • 3 Record and verify: write up the observations from section 2 in one format, so you have evidence you can hand to the model provider or ZCode support.

To Know

Term Plain explanation
Session level The current session’s context occupancy shown above the ZCode input box; use it to watch when the level grows and when compaction fires
App usage Settings → Usage statistics → App usage; estimates cumulative usage, peak, daily trend, and model usage from local session records
Plan quota The Z.ai or BigModel statistics shown on your personal or team plan page; shows balance and consumption over time
Compaction point The threshold at which the client triggers automatic compaction; determined by the window, max output, and fixed reserve together
Single-variable comparison Keep the project, commit, prompt, and channel fixed, change only one setting each time, then compare the readings
Tool receipt The result text a tool call returns to the agent — logs, file contents, search results, and so on

1 How to Read GLM-5.4 Context Numbers in ZCode

1.1 Confirm Your ZCode Version and GLM-5.4 Model Configuration

Open Help → About ZCode in the top-right corner and note the client version. ZCode v4.0.0 was released on 2026-11-23; the release notes state that GLM-5.4 is preconfigured and that a sporadic context-loss issue after switching models or providers has been fixed. If your version is older, upgrade first before troubleshooting, so you don’t mistake an already-fixed issue for context being used up.

Next, check the model shown in the bottom-right corner of the current session’s input box, and note the model name, provider, connection method, and reasoning effort. Then go to Settings → Model Settings → Edit Model Configuration and note the context window and max output tokens shown there. Keep in mind that older sessions split off from the same project may still be using the model selected when they were created; interpret the readings according to that session’s own configuration.

According to Zhipu’s official model card, GLM-5.4 has a 1M context window and a 128K max output, supports text, image, video, and file inputs, and the official Coding Plan already offers this model. When the client is authorized through a coding plan, ZCode selects the channel automatically. In API key mode, there are separate Coding-specific endpoints, such as the domestic https://open.bigmodel.cn/api/coding/paas/v4, and the officially preconfigured Anthropic-compatible endpoint https://open.bigmodel.cn/api/anthropic. The official model page ties the public Model API’s launch to security evaluation, so log fields and quotas should be based on the provider and protocol you actually use.

1.2 Distinguishing ZCode session level, app usage, and plan quota

These three readings come from different sources and serve different purposes. Mixing them together is the most common cause of misattribution:

Reading Location Data source Questions it’s good for
Session level Above the input box Current session Which turn this stretch of conversation grew at, and when it compacted
App usage Settings → Usage statistics → App usage Estimated from local session records Totals, peaks, daily trends, distribution by model
Plan quota Personal/team plan page Z.ai or BigModel stats Balance, consumption per time window by model or by tools like web search

The right order is to go from the summary down to the detail. When plan consumption speeds up, look at usage by model and tool first, find the anomalous time window, then take that moment back to the corresponding session and look at the level curve. To determine how much a particular attachment or a particular receipt accounts for, you have to record the difference before and after the operation using the same measurement basis. A daily summary can only tell you which day was abnormal; it can’t tell you which message caused it.

1.3 A theoretical worked example for the GLM-5.4 default compaction point

ZCode’s automatic compaction point is calculated as window − min(max output, 21,000) − about 13,000. Below is a theoretical worked example, assuming the window is the default 1,000,000 and max output is 128K. Because 128K is larger than 21,000, the reserve is taken as 21,000, so the compaction point is roughly 1,000,000 − 21,000 − 13,000 = 966,000.

Two details can make the readings look inconsistent. First, the trigger includes a live estimate of this turn’s tool results, so compaction may happen before the level in the input box reaches the threshold, and after compaction the level may suddenly drop back. Second, when max output is below 21,000, the reserve changes accordingly. You must fix max output before doing a comparison, otherwise the two groups start out with different compaction points.

If the default capacity is clearly too small, handle it in the order given by the official FAQ: update the client first, refresh the recommended value in model settings, then check whether there’s a manually entered override. Manually entered values have the highest priority, and you can restore the correct GLM-5.4 entry to 1,000,000. Also, don’t mistake the 1M shown by default for other routes as this model’s actual measured capacity. Automatic compaction is carried out by the client according to the rules; for manual compaction you can use /compact.

glm-5-4-zcode-context-usage-diagnosis-en-image-2

2 Tracing GLM-5.4 Context Sources by Growth Timing

These four symptoms each point to a different category of source, and every category needs to be confirmed with a single-variable comparison on the same task:

ID Symptom Main suspected source The one variable to switch When to take the reading
2.1 High from the very first turn, no load AGENTS.md, workspace memory, MCP tool catalog Turn one injection on / off After the first short answer finishes
2.2 Jumps after an attachment is sent Attachment scope, follow-up file reads Line-range excerpt ↔ whole file When the first response of that kind ends
2.3 Climbs in steps after tool runs Tool result size and repeated results Compact summary ↔ long log At the first tool result and after
2.4 Rises gently across many turns History getting re-included Continue an old session ↔ new session with a handoff When the task completes

2.1 High from the Start: Checking ZCode’s Default Injections

Start two brand-new tasks from the same repo commit, using the same GLM-5.4 channel and reasoning tier. Send the same very short development request to both, asking for a one-sentence restatement of the goal and instructing the model not to call any tools. Once the first turn finishes, note the water level — that’s your empty-load baseline.

When ZCode starts a task, it concatenates one AGENTS.md from the user’s global directory and another from the workspace root. With workspace memory enabled, new sessions in the same project automatically load the matching memory index. And the more MCP tools you have, the longer the tool catalog attached to the request becomes. In your comparison, keep the project, commit, and task description fixed, and switch only one thing at a time — for example, toggling workspace memory on or off, or starting and stopping a set of MCP services.

If you suspect the tool catalog, go to Settings → Behavior & Tools → Tool Search and choose “Auto” to load tools on demand. If Auto mode turns out to be the problem, compare against local mode next. For this group you absolutely want to take readings from a fresh session, so you can rule out interference from old history.

2.2 Attachment-Induced Jump: Verify What GLM-5.4 Actually Receives

Start two fresh sessions with the same prompt and workspace. In one, include only a short excerpt pinned to a line range; in the other, use a single complete file instead. Test documents, screenshots, entire folders, and full past conversation sessions separately—don’t mix them in the same group.

ZCode’s @ can reference files, directories, plugins, and past conversations. After you reference a directory, the Agent may keep analyzing the directory structure and reading the files inside it. Even if a large pasted block gets converted into an attachment tag, the full content is still handed to the Agent. So fix the measurement point at the end of the first response of the same type.

When recording, put the attachment name, byte count, type, reference scope, and subsequently triggered tools in separate columns. That way, you can see whether the attachment itself is pushing up the high-water mark, or whether it’s the follow-up reads triggered by the attachment.

2.3 Post-Tool Step-Up: Check ZCode Tool Receipt Size and Duplication

Prepare a fixed sample in the diagnostic workspace that contains no sensitive information. Have the same read-only tool return a concise error summary and a long log, respectively. Both groups use the same tool definition and the same verification question; check the first receipt and the occupancy changes after it.

Record the tool name, call order, result character count, return path, and content fingerprint. If the same file version or the same response fingerprint shows up repeatedly across multiple turns, replace the entire receipt with an error count, the first failure point, nearby lines, and the full log path. This preserves a traceability entry point while reducing repeated occupancy. After the replacement, run through the same sequence and compare again.

Reasoning intensity needs to be recorded separately. The low, high, and highest options in the model menu are reasoning intensity levels, and the default is highest. If input sizes are similar but output or cumulative usage increases as the level goes up, record it as a reasoning intensity effect. Also, the Zhipu API docs state that starting with GLM-5.4, thinking is retained across turns by default, and thinking.clear_thinking defaults to false. This is a convention at the model interface layer; for the desktop app, attribution should still be based on the actual visible call trace.

2.4 Multi-turn gradual climb: verifying ZCode history reattachment

First, write a short handoff describing the task you’re working on — including the repo commit, the goal, key file line numbers, verified results, and acceptance criteria. Then run two groups with the same verification prompt: one continues from the old session, and the other starts a fresh session carrying only this handoff. Fix the file scope and tools, and compare the water level when each group finishes, along with whether they can produce the same evidence.

When you need an empty-history baseline, you have to use a genuinely brand-new task. Auxiliary conversations opened with /side and /btw inherit the main session’s history. Forking carries along the history from before the fork point. /reload reloads the current task’s MCP, skills, plugins, and instruction config, but keeps the history — and it may interrupt a reply or subtask that’s currently running. So replacement-style experiments should run after execution has finished, then be compared against a fresh session under identical conditions.


3 Persisting and validating ZCode context attribution

3.1 Record Fields and Helper Scripts

Record one row per observation point. Suggested fields are below:

Field group Details
Identification Time, session, turn
Environment Client version, provider, window, max output, reasoning level
Variables Setting changes in this run, prompt or attachment source
Tools Tool name, receipt length, content fingerprint
Readings Usage level before and after the change, compaction prompt, task output for the current turn

If the interface only shows percentages, look at the magnitude of change within the same window and at the same display precision. If you use actual input counts returned by the same protocol, save the original field names, and don’t mix input and total usage in one column. Help → Export logs in the upper-right corner lets you save the log bundle. Diagnostic data from in-app issue reports may also include that day’s model invocation trace. Save the timestamps and redacted snippets related to that turn as cross-evidence for the interface readings.

The minimal script below calculates the theoretical compaction point and the marginal difference for the two comparison sets. It doesn’t need network access:

def compaction_point(window=1_000_000, max_output=128_000, reserve=13_000):
    # ZCode rule: window − min(max_output, 21,000) − about 13,000
    return window - min(max_output, 21_000) - reserve

def marginal(before_k, after_k):
    return after_k - before_k  # Represents only the marginal increase from "this operation and its subsequent processing"

print(compaction_point())       # 966000 (theoretical example)
print(marginal(11, 43), "K")    # Illustrative values, not measured
# If the script needs to call a model for receipt summaries, configure an OpenAI-compatible endpoint:
BASE_URL = "https://api.apiyi.com/v1"

When a receipt is too long, you can first compress the redacted logs outside ZCode into “error count + first failure point + neighboring lines + log path”, then hand them to the Agent. The full script is below. The summary model here only handles peripheral processing and doesn’t take part in GLM-5.4’s attribution judgment:

View the full logging and receipt-summary script
import csv, hashlib, datetime
import openai

client = openai.OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.apiyi.com/v1"
)

FIELDS = ["time", "session", "turn", "version", "provider", "window",
          "max_output", "effort", "change", "source", "tool",
          "receipt_chars", "fingerprint", "before", "after", "compacted", "output"]

def fingerprint(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]

def summarize_log(log_text: str, log_path: str) -> str:
    """For redacted samples only: compress long logs into a traceable error summary"""
    resp = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "输出:错误计数、首个失败点、邻近5行、不改写原文。"},
            {"role": "user", "content": log_text[:60000]},
        ],
        max_tokens=800,
    )
    return resp.choices[0].message.content + f"\n完整日志:{log_path}"

def record(path: str, **row):
    row.setdefault("time", datetime.datetime.now().isoformat(timespec="seconds"))
    with open(path, "a", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=FIELDS)
        if f.tell() == 0:
            w.writeheader()
        w.writerow({k: row.get(k, "") for k in FIELDS})

if __name__ == "__main__":
    log = open("sample_test.log", encoding="utf-8").read()
    record("observations.csv", session="A", turn=2, version="4.0.0",
           provider="Coding Plan", window=1_000_000, max_output=128_000,
           effort="最高", change="回执=全文", tool="run_tests",
           receipt_chars=len(log), fingerprint=fingerprint(log),
           before="11K", after="43K", compacted="否")
    print(summarize_log(log, "logs/sample_test.log"))

Tip: The summarization model in the helper script can be called through APIYI apiyi.com. One Key lets you switch between OpenAI, Claude, Gemini, and other models, and new users get a free testing quota — handy for the text cleanup around the edges of diagnosis. Note that whatever you send must be a desensitized sample.

3.2 How to Read the Results

Below is an illustrative record. It’s here to explain the interpretation method, not to report a result that was actually produced. Two fresh sessions under identical conditions both sit at around 8K after their first short answer. The same test receipt reaches about 11K after returning a summary, and about 43K after returning the full text. That’s a gap of roughly 32K, and it should be labeled “the marginal growth of this receipt and its subsequent processing” — you can’t use the level difference to precisely back out the token count of the log itself.

Next, swap the full text for a summary that includes error locations. If the key conclusions still match and the growth narrows across repeated comparisons, you can then list “the scope of what’s read back from the receipt” as the main controllable factor. The method works the same way for other sources:

  • An empty first turn is noticeably high, and it drops after you disable one particular tool group — the evidence points to the tool catalog.
  • Growth shows up only in long conversations, while short handoffs still pass acceptance — the evidence points to accumulated history.

3.3 Compaction Measurement Basis and GLM-5.4 Channel Comparison

Compaction changes the measurement basis. The difference before and after compaction can only be recorded as the compaction effect—don’t mix it into the earlier growth calculation. To figure out what compaction preserved, record key file locations, open items, and the next acceptance command before /compact. After compaction, ask the same set of questions and check whether the answers match.

The channel comparison works like this:

Channel Purpose Diagnostic role Notes
Zhipu Coding Plan (plan authorization) ZCode auto-selects the channel Attribution baseline GLM-5.4 is already available officially
Zhipu Coding dedicated endpoint (API key) Manual endpoint configuration Same-vendor control Fields and quota are subject to the actual agreement
Other third-party channels Custom provider Needs separate comparison Calibrate the context window first, then compare against the official vendor path
APIYI apiyi.com (OpenAI-compatible) Peripheral tasks such as diagnostic scripts and log summaries Not an attribution baseline for GLM-5.4 Used to organize evidence, not as a replacement for official vendor readings

If the context window is already calibrated and only third-party channels compact frequently on lightweight tasks, run a separate comparison on the official Coding Plan path as described in the official FAQ, and check whether the usage returned by the proxy is abnormal. The attribution record should also spell out the usage-level inflection point, the triggering operation, and the scope of evidence, so it’s easy to hand off to the model service provider or ZCode support.

Common Questions About GLM-5.4 and ZCode Context Troubleshooting

Q1: Why does GLM-5.4 compress in ZCode before it even reaches 966K?

The trigger factors in a live estimate of this round’s tool results, so compression can happen before the input box level reaches that point. Also check whether the max output is below 21,000, and whether there’s any manually entered window override.

Q2: Can the peak in app usage tell me directly how much a single attachment consumed?

No. App usage is a summary estimated from local records, so it’s only good for spotting abnormal time windows. To determine how much one attachment uses, you need to compare the conversation level before and after using the same measurement basis.

Q3: What should I do if the default window shows up as very small?

First update the client, refresh the recommended value in model settings, then check for any manually entered override. Once you’ve confirmed everything is correct, restore it to 1,000,000 in the proper GLM-5.4 entry.

Q4: Can I get an empty-history baseline using /side or a fork?

No. `/side` and `/btw` inherit the main conversation’s history, and a fork carries over the history from before the fork point. An empty baseline requires a genuinely brand-new task.

Q5: How do I quickly get the model invocation in the diagnostic script running?

Set base_url to `https://api.apiyi.com/v1`, then use an APIYI (apiyi.com) key and the free quota to run the summary script. It only processes redacted logs, and GLM-5.4 readings should still be taken from the official channel.

Q6: What are the limitations of this approach?

The level difference includes subsequent processing, so it can’t be converted precisely into token counts. When the interface only shows percentages, you can only compare the order of magnitude of changes. Reasoning intensity and cross-turn thinking retention also affect usage, so those need to be recorded separately. Usage fields returned by third-party channels may differ from the official ones.


GLM-5.4 ZCode Context Troubleshooting Key Takeaways

  • Calibrate before comparing: If version, model, window, and max output aren’t pinned down, the readings aren’t comparable.
  • Three readings, three jobs: The level gauge tells you timing, app usage gives you the totals, the plan page shows the quota.
  • Default compaction point is around 966K: That’s the theoretical figure for a 1M window with max output no lower than 21K.
  • Four tracks by timing: Startup maps to injection, attachments map to scope, tool calls map to receipts, multi-turn maps to history.
  • Only count marginal growth in the deltas: Record the delta before and after compaction separately as the compaction effect.
  • Peripheral cleanup can go through APIYI: Auxiliary tasks like log summarization can use the unified endpoint at apiyi.com, but the attribution baseline stays on the vendor’s native channel.

One last testing method: swap the suspected source for a leaner version and repeat the comparison in a fresh session under the same conditions. If the key conclusions hold and the growth narrows steadily, you can mark that source as the main controllable factor. If the conclusions change, the removed content was essential to the task, and you should move on to a different variable.


📚 References

  1. ZCode v4.0.0 release notes: Version and GLM-5.4 preset information
    • Link: zcode.z.ai/cn/changelog
  2. Zhipu GLM-5.4 model card: Context, max output, and input modalities
    • Link: docs.bigmodel.cn/cn/guide/models/glm-5.4
  3. ZCode model settings and endpoints: Window, max output, and Coding interface
    • Link: zcode.z.ai/cn/docs/configuration
  4. ZCode usage stats and FAQ: App usage, compaction rules, default capacity troubleshooting
    • Link: zcode.z.ai/cn/docs/usage-stats, zcode.z.ai/cn/docs/qa
  5. ZCode Agent, memory, MCP, and commands: Injection, attachments, auxiliary conversations, /compact, /reload
    • Link: zcode.z.ai/cn/docs/agents, zcode.z.ai/cn/docs/memory, zcode.z.ai/cn/docs/mcp-services, zcode.z.ai/cn/docs/commands
  6. Zhipu thinking mode: The default policy for thinking.clear_thinking
    • Link: docs.z.ai/guides/capabilities/thinking-mode
  7. ZCode logs and feedback: Exporting logs and diagnostic materials
    • Link: zcode.z.ai/cn/docs/feedback

Author: APIYI technical team
Technical discussion: Feel free to reach us on the APIYI apiyi.com homepage. For more integration material, check out the docs.apiyi.com documentation center.

Related Articles

Similar Posts