Writing 15 min read

One JSON block that broke a whole Claude Code session: debugging HTTP 500s from my local SGLang server

Every request in one Claude Code session started failing with HTTP 500 from the Qwen model on my GPU server, and retrying made no difference. The server was healthy. The cause was one content block the chat template had never seen. Here is how I found it, step by step, with every command, so you can find problems like this yourself.

I use Anthropic’s Claude and OpenAI’s models all the time. This post is about one session where I connected Claude Code to a local LLM instead: Qwen3.8-Flash-Next, served by SGLang on bigai, my workstation with two RTX PRO 6000 Blackwell cards. I’ve written about that setup in earlier posts.

Partway through that session, every request started coming back as an API error. Claude Code retried, got the same error, retried again, and the session was stuck. I started a fresh session to try again, and that one broke the same way.

The fix turned out to be six lines. Finding it is the part worth writing up. If you run Claude Code, or any agent, against a model you host yourself, you will eventually see an error like this, and the error message on the client side will tell you almost nothing. I want this post to be useful when that happens: every command I ran, what it printed, and what it told me. None of it is specific to my setup. It’s the same troubleshooting method I’ve used for years on Spark, Kafka and the rest: work from cheap and broad to precise, collect evidence from both ends of the connection, and prove the cause before fixing anything.

The short version:

  1. Claude Code doesn’t send every tool definition up front. When the model needs a deferred tool, such as WebFetch, it calls ToolSearch, and the result is a special content block: {"type":"tool_reference","tool_name":"WebFetch"}.
  2. SGLang turns each request into prompt text with the model’s chat template. Qwen’s template only knew how to render text, image and video items. Anything else hits raise_exception('Unexpected item type in content.'), and SGLang returns HTTP 500.
  3. Claude Code resends the whole conversation on every request, so once that block was in the history, every later request failed. One block poisoned the session.
  4. I fixed it on the server, in the script that generates the template, so it renders the block as Tool loaded: NAME. A minimal reproduction went from 500 to 200, and the stuck session resumed and ran WebFetch.

It felt sudden, but nothing had changed on the server. The bug was always there. It only fires when a session loads a deferred tool, and most of my sessions never do. This one did because I asked it to read a web page.

The system at a glance

I can’t debug a pipeline I can’t draw, so this is the first thing I sketch. Here is the path one request takes:

The request path Where the 500 came from
One request from Claude Code to the Qwen model Claude Code on my laptop, under WSL2, sends an Anthropic-format POST to /v1/messages on SGLang, which runs in a Docker container on bigai. Inside SGLang the request goes through six steps: the Anthropic adapter turns the JSON into chat messages, the chat template turns the messages into prompt text, the tokenizer turns text into token IDs, the Qwen model runs on two GPUs, the output parsers turn think and tool-call markup back into JSON, and the response streams back. The failure happened at step 2, the chat template, so the model at step 4 never ran. Claude Code also writes every session to a transcript file on the laptop. LAPTOP · WSL2 · EST BIGAI · SGLANG IN DOCKER · POST /v1/messages ON :8000 · LOGS IN UTC CLIENT Claude Code qwen38-claude TRANSCRIPT ~/.claude-qwen38/ projects/…/*.jsonl POST 1 Anthropic adapter JSON → messages 2 Chat template messages → text 3 Tokenizer text → token IDs 4 Qwen3.8 Flash Next FP8 2 GPUs, TP=2 5 Output parsers think, tool calls 6 Anthropic response streamed (SSE) raise_exception('Unexpected item type in content.') → HTTP 500 api_error, on every retry STEPS 3–6 NEVER RAN: THE GPUS SAT IDLE AT 0% EVIDENCE: docker logs (traceback, status codes) · the generated .jinja · ps aux (every flag)
Steps 1 to 6 all run inside SGLang. The request failed at step 2, while the prompt was still being built, so the model never saw it. That is why the server looked healthy the whole time.

Two details on that picture matter later. Each piece logs somewhere different: Claude Code writes a JSON Lines transcript on my laptop, and SGLang writes to docker logs on bigai. And they don’t share a clock. My laptop is on EST, and the server logs and the transcript timestamps are in UTC, so ls -l on the laptop shows 21:12 for an event the server logged at 02:12. I convert before I compare anything:

date -d '2026-11-24T02:14:05Z'    # prints it in local time

Background: what a chat template does

A language model doesn’t know what a message, a role, a tool call or an image is. It reads one flat sequence of tokens and predicts the next one. The chat you see is built by marking up that sequence with special tokens the model learned in training, like <|im_start|>user … <|im_end|>.

Claude Code sends structured JSON: a list of messages, each with a role and a list of typed content blocks. Something has to turn that JSON into the exact text layout the model was trained on. That converter is the chat template, a small program written in Jinja that ships with the model. If the template can’t handle something in the JSON, the request fails before the model ever sees it.

Here is what my template produces for a short conversation where the model calls ToolSearch. I rendered it inside the running container (how to do that is in Step 10). Note that a tool result comes back to the model as a user turn wrapped in <tool_response>:

<|im_start|>user
Find the WebFetch tool.<|im_end|>
<|im_start|>assistant
<tool_call>
<function=ToolSearch>
<parameter=query>
select:WebFetch
</parameter>
</function>
</tool_call><|im_end|>
<|im_start|>user
<tool_response>
Tool loaded: WebFetch                      ← the line my fix produces
</tool_response><|im_end|>
<|im_start|>assistant

The same input through the original template gives:

EXCEPTION: TemplateError Unexpected item type in content.

This also explains two flags on my SGLang command line. On the way in, the template turns JSON tool calls into that <tool_call><function=…> markup. On the way out, --tool-call-parser qwen3_coder turns the model’s markup back into JSON tool calls, and --reasoning-parser qwen3 splits off the <think> section. The template and the parsers are two halves of one translation layer.

Background: why tool_reference exists

In the Anthropic Messages format that Claude Code speaks, a message’s content is a list of typed blocks, and a tool result can hold its own nested list of blocks:

Block type Who sends it What it is Did my template handle it?
text user, assistant Plain text yes
image user, tool result Screenshots, rendered frames yes
thinking assistant The model’s reasoning yes (SGLang converts it to <think>)
tool_use assistant “Call tool X with input Y” yes (converted to tool calls)
tool_result user The tool’s output: a string or a list of blocks yes (converted to a tool message)
tool_reference inside a tool_result “Tool NAME is now loaded”, from ToolSearch no → HTTP 500

Claude Code has many tools, plus every tool from my MCP servers. Sending every full definition on every request would waste a lot of prompt tokens, so some tools are deferred: the model only sees their names. When it needs one, it calls ToolSearch with select:WebFetch, gets a tool_reference back, and from then on the full definition is included.

None of this was visible in the error Claude Code showed me. I got there by following the evidence, which is the rest of this post.

Step 1: read the client configuration

The first question is where the requests go. I launch Claude Code against the local model with a small wrapper script, so I read it:

cat "$(which qwen38-claude)"
export CLAUDE_CONFIG_DIR="${HOME}/.claude-qwen38"      # transcripts live here, not in ~/.claude
export ANTHROPIC_BASE_URL="http://192.168.1.136:8000"  # the server
MODEL="local-llm"                                      # --served-model-name on the server
export CLAUDE_CODE_MAX_OUTPUT_TOKENS=16384
export DISABLE_PROMPT_CACHING=1

Then a quick check that the endpoint answers:

curl -s http://192.168.1.136:8000/v1/models | jq -c '.data[0] | {id, max_model_len}'
{"id":"local-llm","max_model_len":262144}

The server was reachable, and the transcripts were in ~/.claude-qwen38/projects/, not the usual ~/.claude. If that curl had failed or hung, the problem would have been “server down”, which is a completely different investigation.

Step 2: rule out the boring causes

Before anything clever, I check for a crashed process, a full GPU, low memory or a full disk:

ssh suaro@192.168.1.136 'hostname; uptime; nvidia-smi; free -h; df -h / | tail -1;
    ps aux | grep -Ei "sglang|vllm|llama" | grep -v grep'
bigai
 02:18:38 up 6 days,  1:47,  3 users,  load average: 1.90, 1.94, 1.98
|   0  NVIDIA RTX PRO 6000 Blac...  |   86310MiB /  97887MiB |      0%      Default |
|   1  NVIDIA RTX PRO 6000 Blac...  |   85640MiB /  97887MiB |      0%      Default |
Swap:          8.0Gi       4.4Gi       3.6Gi
root  115089 ... 01:58  /usr/bin/python3 /usr/local/bin/sglang serve --model-path Qwen/Qwen3.8-Flash-Next-FP8
      --served-model-name local-llm --tp 2 ... --chat-template /templates/qwen38-flash-next-claude-code.jinja
      --reasoning-parser qwen3 --tool-call-parser qwen3_coder ... --port 8000

SGLang was alive, and both GPUs were loaded but idle, so nothing had crashed. The process had started at 01:58 UTC, 20 minutes earlier. And the full command line named the exact template file in use. Saving ps aux output is a habit worth having: it shows every flag the process was really started with, not what I think it was started with.

Step 3: find out how the server runs

SGLang runs in Docker, so I need the container name for its logs, and the mounts to map paths inside the container to paths on the host:

ssh suaro@192.168.1.136 'docker ps -a'
ssh suaro@192.168.1.136 'docker inspect -f "{{.State.StartedAt}} restarts={{.RestartCount}}" \
      sglang-qwen38-flash-next-tp2-mtp-claude-telemetry'
ssh suaro@192.168.1.136 'docker inspect -f "{{json .Mounts}}" \
      sglang-qwen38-flash-next-tp2-mtp-claude-telemetry' | jq -r '.[] | "\(.Source) -> \(.Destination)"'
NAMES: sglang-qwen38-flash-next-tp2-mtp-claude-telemetry   Up 20 minutes   0.0.0.0:8000->8000/tcp
2026-11-24T01:58:45.332492164Z restarts=0
/home/suaro/sglang-crash-dumps -> /crash
/home/suaro/.cache/huggingface -> /root/.cache/huggingface
/home/suaro/sglang-templates -> /templates

So /templates/…jinja inside the container is ~/sglang-templates/…jinja on the host. And restarts=0 means Docker hadn’t restarted it after a crash: it had been started by hand.

Step 4: read the server logs, without the noise

SGLang logs a line for every batch, so I filter those out first, then look for anything that smells like an error:

ssh suaro@192.168.1.136 'docker logs sglang-qwen38-flash-next-tp2-mtp-claude-telemetry 2>&1 \
    | grep -Eiv "Decode batch|Prefill batch" \
    | grep -Ei "error|exception|traceback|exceed| 4[0-9][0-9] | 5[0-9][0-9] " | tail -60'

There were 15 identical failures. One of them:

[2026-11-24 02:14:49] Error converting streaming request: Unexpected item type in content.
Traceback (most recent call last):
  File ".../jinja2/sandbox.py", line 401, in call
  File ".../transformers/utils/chat_template_utils.py", line 479, in raise_exception
    raise jinja2.exceptions.TemplateError(message)
jinja2.exceptions.TemplateError: Unexpected item type in content.      ← the first exception: the root cause
The above exception was the direct cause of the following exception:
  File ".../sglang/srt/entrypoints/openai/serving_chat.py", line 1372, in _apply_jinja_template
ValueError: Unexpected item type in content.
[2026-11-24 02:14:49] Anthropic error response api_error (exception=ValueError): Internal server error
[2026-11-24 02:14:49] INFO:  192.168.1.131:61134 - "POST /v1/messages?beta=true HTTP/1.1" 500 Internal Server Error

To see the size of the problem, I counted responses by status code:

ssh suaro@192.168.1.136 'docker logs sglang-qwen38-flash-next-tp2-mtp-claude-telemetry 2>&1 \
    | grep "POST /v1/messages" | grep -oE "\" [0-9]{3} " | sort | uniq -c'
      2 " 200
      4 " 400
     15 " 500

The model never ran. The request failed while the prompt was being built. The next question was what in the request the template rejected.

Step 5: read the code that raised the error

The quickest way to find the condition behind an error is to search for the error text itself:

ssh suaro@192.168.1.136 'grep -n -B8 -A3 "Unexpected item type" \
      ~/sglang-templates/qwen38-flash-next-claude-code.jinja'

That printed the macro that renders every message’s content, item by item:

{%- macro render_content(content, do_vision_count, is_system_content=false) %}
    {%- if content is string %}
        {{- content }}
    {%- elif content is iterable and content is not mapping %}
        {%- for item in content %}
            {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
                {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
            {%- elif 'video' in item or item.type == 'video' %}
                {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
            {%- elif 'text' in item %}
                {{- item.text }}
            {%- else %}
                {{- raise_exception('Unexpected item type in content.') }}
            {%- endif %}
        {%- endfor %}
    ...

Image, video, text, or fail. So some message in the conversation held a content item that was none of those three. Which one? The server doesn’t log request bodies, so the answer had to come from the client side.

Step 6: find the client’s session transcripts

Claude Code saves each session as a JSONL file, one JSON object per line, under $CLAUDE_CONFIG_DIR/projects/<working directory with / replaced by ->/<session-id>.jsonl:

ls -lat ~/.claude-qwen38/projects/ | head
cd ~/.claude-qwen38/projects/-home-suaro-projects-qwen38-flash-next-reddit-blender-prompt
ls -la --time-style=+%H:%M *.jsonl
-rw------- 1 suaro suaro 26429333 21:12 baeda482-80a9-4503-944f-f445ab8520bd.jsonl
-rw------- 1 suaro suaro   235728 21:14 5c78508f-5f2a-42a8-ba97-a773a3f2f2fa.jsonl

The 26 MB file was the long session that broke. The small one was the fresh session I’d started to retry, which broke the same way. A 26 MB file isn’t something to open in an editor or cat, so everything from here on is jq.

Step 7: list every content-block type in the session

This is the key move of the whole investigation. The template rejects “an unexpected item type”, so I listed every type that appears anywhere in the session and looked for the odd one out:

F=baeda482-80a9-4503-944f-f445ab8520bd.jsonl
# Top-level blocks, per role
jq -r 'select(.message.content|type=="array") | .message.role as $r
       | .message.content[] | "\($r) \(.type)"' $F | sort | uniq -c
# Blocks nested inside tool results
jq -r 'select(.message.content|type=="array") | .message.content[]
       | select(.type=="tool_result" and (.content|type=="array")) | .content[].type' $F | sort | uniq -c
    316 assistant text
    453 assistant thinking
    545 assistant tool_use
     21 user text
    377 user tool_result
--- nested inside tool_result ---
    106 image
      2 tool_reference           ← the only type the template doesn't know

Two blocks out of more than 1,700, nested two levels down. That’s the suspect.

Step 8: trace the trigger

Next I connected the odd block to the tool call that produced it, then matched its time to the first server error. In the transcript, every tool_result carries the tool_use_id of the call it answers, so I can join on it:

# Where is the tool_reference, and which tool call does it answer?
jq -c 'select(.message.content|type=="array") | .timestamp as $t | .message.content[]
      | select(.type=="tool_result" and (.content|type=="array"))
      | select(any(.content[]; .type=="tool_reference"))
      | {t:$t, id:.tool_use_id, content}' $F
# Join on the id to find the call that produced it
jq -c --arg id call_857d78df21f9483387ee3d72 'select(.message.content|type=="array")
      | .message.content[] | select(.type=="tool_use" and .id==$id) | {name, input}' $F
{"t":"2026-11-24T01:53:33.608Z","id":"call_857d78df21f9483387ee3d72","content":[{"type":"tool_reference","tool_name":"WebFetch"}]}
{"name":"ToolSearch","input":{"query":"select:WebFetch","max_results":1}}

The same check on the second session found a tool_reference at 02:14:05.058Z, and the server’s first 500 for it came at 02:14:07. The fresh session had worked fine right up until it called ToolSearch too. That was the detail that clinched it for me: both bursts of errors started seconds after a ToolSearch.

All times in UTC:

Time What happened
01:53:33 First session: ToolSearch loads WebFetch, and a tool_reference enters the history
01:58 SGLang container started
02:11:54 – 02:12:05 Five 500s for the first session
02:14:05 Second, fresh session: ToolSearch again
02:14:07 – 02:14:52 Ten more 500s
02:18 I start investigating
02:23:55 Container restarted with the fix; ready at 02:28
02:30:09 The first session, resumed, runs WebFetch successfully

Step 9: prove it with a minimal reproduction

The timestamps line up, but lining up is correlation. To prove it, I sent two tiny requests straight to SGLang that differ in exactly one thing: the block inside the tool result.

curl -s -o /dev/null -w '%{http_code}\n' http://192.168.1.136:8000/v1/messages \
  -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' \
  -d '{"model":"local-llm","max_tokens":64,
       "tools":[{"name":"ToolSearch","description":"x","input_schema":{"type":"object",
                 "properties":{"query":{"type":"string"}}}}],
       "messages":[
         {"role":"user","content":"find the webfetch tool"},
         {"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"ToolSearch",
                                         "input":{"query":"select:WebFetch"}}]},
         {"role":"user","content":[
            {"type":"tool_result","tool_use_id":"t1",
             "content":[{"type":"tool_reference","tool_name":"WebFetch"}]},
            {"type":"text","text":"say ok"}]}]}'

For the control, I swapped the inner block for {"type":"text","text":"ok"}:

Variant Inner block Before the fix After the fix
A (control) {"type":"text",…} 200 200
B (suspect) {"type":"tool_reference",…} 500 200

One variable changed and the result flipped. That’s proof, not a correlation. It also gave me the test I’d use to verify the fix.

Step 10: fix it in the right place, and verify

My SGLang start script doesn’t use Qwen’s template as-is. Every time it runs, it reads Qwen’s original chat_template.jinja from the Hugging Face cache, applies a few patches of mine, and writes the result to ~/sglang-templates/, which the container mounts read-only. So the generated .jinja is rebuilt on every launch, and editing it by hand would last until the next restart. The fix belongs in the generator.

I backed up the start script first:

cd ~/latest-llm-scripts
cp start-qwen38-flash-next-sglang-tp2-mtp-claude-cli-telemetry.sh \
   start-qwen38-flash-next-sglang-tp2-mtp-claude-cli-telemetry.sh.bak-20261124

Then I added this to the script’s Python template generator, right after it loads Qwen’s template:

# bigai patch (2026-11-24): Claude Code's ToolSearch returns tool results whose content is
# [{"type": "tool_reference", "tool_name": "WebFetch"}]. The stock template only accepts
# image / video / text items and raises "Unexpected item type in content." -> HTTP 500 on
# /v1/messages for every later request in that session. Render it as a short text line.
tr_anchor = "{%- elif 'text' in item %}"
if tpl.count(tr_anchor) == 1:
    tpl = tpl.replace(tr_anchor,
        "{%- elif item.type == 'tool_reference' %}\n"
        "                {{- 'Tool loaded: ' ~ (item.tool_name | default('unknown')) }}\n"
        "            " + tr_anchor, 1)
    tr = "applied"
else:
    tr = "SKIPPED (anchor not found; ToolSearch results will 500)"

It’s written defensively on purpose. It only patches if it finds exactly one copy of the line it anchors on, and it prints tool_reference fix=applied or SKIPPED in the startup output. If Qwen ships a new template that changes this code, I’ll see SKIPPED instead of a silent failure. And it leaves the final else: raise alone: any other unknown block type should still fail loudly rather than be dropped from the prompt without anyone noticing.

The start script refuses to launch with more than 2 GB of swap in use, and there was 4.4 GB, so I cleared it first (there was plenty of free RAM to take it back). Then I restarted in the background with a log file:

sudo swapoff -a && sudo swapon -a
nohup bash start-qwen38-flash-next-sglang-tp2-mtp-claude-cli-telemetry.sh \
      > ~/qwen38-restart-20261124.log 2>&1 < /dev/null &
tail -f ~/qwen38-restart-20261124.log
Template: source=chat_template.jinja, effort fix=applied, preserve_thinking=applied (...), tool_reference fix=applied
Preflight OK: patched image present, GPUs free, 119 GB RAM, 0 GB swap used.
Waiting for server (target + draft + verify graph capture; ...)......................... -- ready.

“It works now” isn’t verification, so I checked it four independent ways:

Check How Result
The reproduction flips Variant B from Step 9 200 (was 500)
The template renders the block Render it by hand (below) Tool loaded: WebFetch
No template errors in the new logs docker logs … 2>&1 | grep -c "Unexpected item type" 0
The real broken session works Resume it, then the tool-call timeline from Step 8 02:30:09 WebFetch ✓

The most useful tool for any template problem is rendering the template yourself. This feeds any messages you like through the exact template the server uses, inside the running container, with no GPU involved:

ssh suaro@192.168.1.136 'docker exec -i sglang-qwen38-flash-next-tp2-mtp-claude-telemetry python3 -' <<'PY'
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3.8-Flash-Next-FP8")
tpl = open("/templates/qwen38-flash-next-claude-code.jinja").read()
msgs = [
  {"role": "user", "content": "Find the WebFetch tool."},
  {"role": "assistant", "content": "", "tool_calls": [{"id": "t1", "type": "function",
     "function": {"name": "ToolSearch", "arguments": {"query": "select:WebFetch"}}}]},
  {"role": "tool", "tool_call_id": "t1",
   "content": [{"type": "tool_reference", "tool_name": "WebFetch"}]},
]
print(tok.apply_chat_template(msgs, chat_template=tpl, tokenize=False,
                              add_generation_prompt=True, reasoning_effort="medium"))
PY

Leave out chat_template=tpl to test the model’s original template instead. That’s how I produced the before-and-after output near the top of this post.

The status codes after the restart told the same story: 6 OK, 2 Bad Request, and no 500s.

Mistakes I made, so you don’t have to

  • I restarted without saving the logs. The start script runs docker rm -f, which throws away the old container’s logs. I lost them. The “before” numbers in this post only exist because I’d captured them during the investigation. Save them first: docker logs <container> > ~/sglang-$(date -u +%F-%H%M).log 2>&1.
  • Two clocks. EST on the laptop, UTC on the server and in the transcripts. Convert before comparing.
  • Two config folders. Plain claude writes to ~/.claude, and my wrapper writes to ~/.claude-qwen38. Look in the wrong one and you find nothing.
  • “No errors in the transcript” doesn’t mean no errors. Retried 5xx errors aren’t written as errors if you interrupt first. Look for the backoff pattern in the api-request timestamps.
  • A poisoned session stays poisoned. The bad block is resent on every turn. After a server-side fix, you can resume the session. Without one, start a new session or /rewind to before the bad turn.

If it happens to you

If Claude Code shows API errors against a model you host, this is the order I’d work in, before changing anything:

  1. Is the server reachable? curl -s http://<server>:8000/v1/models | jq .
  2. Is the container up, and since when? docker ps -a
  3. Save the logs now, before anything restarts.
  4. Count responses by status code (the one-liner in Step 4) to see the size of the problem.
  5. Find the first exception in the traceback, and note its layer: template, server, CUDA or hardware.
  6. Note the UTC time of the first error.
  7. Open the session transcript, newest first. What happened just before that time? Use the tool-call timeline and the block inventory.
  8. What’s different about the failing session compared with sessions that work?
  9. Build a minimal A/B reproduction with curl. Change one thing.
  10. Back up, fix the generator or configuration, restart, and rerun the reproduction.

Some error text and where it usually points on a server like mine:

What the log says Layer Likely meaning
Unexpected item type in content. Chat template A content block type the template doesn’t know
Unexpected content type. Chat template Message content is neither a string nor a list
“too long” or “exceed”, often with HTTP 400 SGLang Prompt plus max_tokens is larger than the context length
CUDA error: an illegal memory access GPU kernel A crash inside model execution; the container usually dies
Xid 79 … fallen off the bus (in dmesg) Hardware The GPU dropped off PCIe
Connection refused or timeout on :8000 Network or process Server down, or still loading

If you hit this exact bug and can’t change the template, there may be a client-side workaround: stop Claude Code from deferring tools, so ToolSearch never runs. I believe the switch is the environment variable ENABLE_TOOL_SEARCH=false, but I haven’t verified it. The cost is that every tool definition, including every MCP server’s tools, is sent on every request.

A few jq queries worth keeping

Claude Code’s transcripts are JSONL, which is exactly what jq reads. These are the queries I found myself reusing. Set F=<session>.jsonl first.

Question Command
What kinds of lines are in the file? jq -r '.type' $F | sort | uniq -c | sort -rn
Which tools were used, and how often? jq -r 'select(.type=="assistant") | .message.content[]? | select(.type=="tool_use") | .name' $F | sort | uniq -c | sort -rn
Tool calls in time order jq -r 'select(.type=="assistant") | .timestamp as $t | .message.content[]? | select(.type=="tool_use") | "\($t) \(.name) \(.input|tostring|.[0:70])"' $F
What did I type, and when? jq -r 'select(.type=="user" and (.message.content|type=="string")) | "\(.timestamp) \(.message.content[0:90]|gsub("\n";" "))"' $F
Errors Claude Code gave up on jq -c 'select(.isApiErrorMessage==true) | {timestamp, text:.message.content[0].text}' $F
The retry pattern jq -r 'select(.type=="api-request") | .timestamp' $F

How I work a problem like this

Looking back, the order mattered more than any single command:

  • Read the error, not the symptom. “API error” in Claude Code says almost nothing. The server’s traceback says exactly what failed, and where.
  • Rule out the boring causes first. Thirty seconds of nvidia-smi, free and ps aux told me the server was healthy and gave me the exact template path.
  • Collect evidence from both ends, and line it up by time. The server knew what failed. Only the client’s transcript knew which input did it.
  • Ask what’s different. This session failed and my other sessions didn’t. Listing every block type found the one thing it had that they didn’t.
  • Prove the cause before fixing it. A minimal A/B request that changes one thing turns a good theory into a fact, and becomes the test for the fix.
  • Fix the generator, not the generated file, and make the fix tell you when it stops applying.
  • Don’t restart first. It feels like progress, and it destroys the evidence.

Still open

Two things I haven’t looked into yet, if you want to try the method on them yourself:

  • At 02:29:46 and 02:29:47 SGLang answered two requests with 400 Bad Request, and the third try at 02:29:48 got 200. SGLang logged no reason. They look harmless, but they’re unexplained.
  • The same jq check found one other session on my machine with a tool_reference block. I haven’t yet looked at what happened to it afterwards.

How I tested

  • Client: Claude Code on my laptop, under WSL2, launched through my qwen38-claude wrapper, which points it at the local server and keeps its sessions in ~/.claude-qwen38. The wrapper was not changed.
  • Server: SGLang in Docker on bigai, serving Qwen3.8-Flash-Next-FP8 across two NVIDIA RTX PRO 6000 Blackwell GPUs (TP=2), with a 262,144-token context, the qwen3 reasoning parser and the qwen3_coder tool-call parser.
  • The template: Qwen’s chat_template.jinja from the model repository, plus patches applied by my start script. The only change for this post is the tool_reference branch.
  • Verification: the A/B reproduction before and after, a render of the template inside the container, a count of template errors in the new logs, and the original broken session resumed.
  • To revert: move the .bak-20261124 copy of the start script back into place and run it again. It regenerates the old template.