Pi Coding Agent: Fixing Qwen3.6-27B Infinite Loops and Abrupt Stops with Pi Extensions

·5 min readlocal-ai

TL;DR: Pi Coding Agent with Qwen3.6-27B gets stuck in infinite thinking loops or abruptly stops mid-tool-call? It’s not the model — it’s the chat template, tool call parser, and missing loop detection. This post covers how to fix it with pi-loop-police, pi-qwen-fix, and vLLM chat template fixes.

The Problem

When using Qwen3.6-27B as a local coding agent via Pi Coding Agent, two common failure modes:

  1. Infinite loops: The model gets stuck repeating the same thinking blocks, re-emitting identical tool calls, or cycling through the same reasoning until context window is exhausted.
  2. Abrupt stops: The model generates a clean thinking block, then… stops. No tool call, no response. Just </thinking> followed by silence.

This isn’t a defect in the model weights. It’s a combination of:

  • The official Qwen3.6 chat template has 21+ bugs (closed by Qwen team as “not planned”)
  • vLLM’s tool call parser (qwen3_coder) breaks on special characters
  • Pi SDK auto-retry compounds errors into unbounded loops
  • No real-time loop detection to catch and abort before context is wasted

Root Cause #1: “Empty Think” Poisoning

The official Qwen team tried to save tokens by injecting empty </thinking> blocks for past assistant turns instead of preserving actual reasoning content. The system prompt then contained an absolute directive: “call a tool immediately after </thinking>”.

This created a **“toxic learning pattern"": the model learned to associate empty thoughts with tool calls, and full thoughts with forbidden conversational text. Result: 80%+ premature turn aborts — the model would hit <thinking then immediately stop with </thinking and refuse to generate any actual response.

Fix: Use the community’s fixed chat template from froggeric/Qwen-Fixed-Chat-Templates. It preserves all past reasoning blocks in the conversation history, defaults to preserve_thinking=true, and normalizes whitespace to exactly match the model’s generation patterns.

Terminal window
hf download hf://froggeric/Qwen-Fixed-Chat-Templates/chat_template.jinja --local-dir chat_template-fixes

Then serve with:

Terminal window
--chat-template ./chat_template-fixes/chat_template.jinja \
--tool-call-parser qwen3_xml \
--enable-prefix-caching \
--reasoning-parser qwen3

Root Cause #2: Tool Call Parser — qwen3_coder vs qwen3_xml

The official Qwen3.6 model card suggests --tool-call-parser qwen3_coder. Testing shows qwen3_xml is more stable for long-context agentic work.

Featureqwen3_xmlqwen3_coder
ParsingPython C-based xml.parsers.expatRegex-based extraction
Special charsAuto-sanitizes <, >, &, "Regex breaks on them
Nested JSONDeferred parsing — waits for full param block before json.loadsAttempts parse during streaming → corruption
Malformed XMLAuto-injects missing closing tagsFails on truncated output

For code editing (where <, >, & are common), qwen3_xml is the clear winner.

Root Cause #3: Pi SDK Auto-Retry Compounding

The pi-coding-agent SDK has auto-retry enabled by default (up to 3 retries). When a tool call fails, the SDK strips the error message from history and calls agent.continue() → the LLM re-issues same tool calls (since it never saw the failure reasoning).

OpenClaw already has its own retry layer (run.ts — failover rotation, auth profile rotation, empty-error retry, thinking-level fallback). Having both → double-retry → unbounded loop: up to 3 SDK retries × 32-160 outer iterations = 96-480 total LLM calls.

Fix: Disable SDK auto-retry:

settingsManager.setRetryEnabled(false)

Root Cause #4: No Loop Detection

Without real-time monitoring, a looping model will burn your entire context window before you notice.

Solution: pi-loop-police — A Pi extension that detects and interrupts infinite thinking-block and tool-call loops in real time.

What it detects (8 detectors):

DetectorFires whenWhat happens
Thinking loopThinking block ends in same ≥80 chars twice in a rowStream aborted, repetition truncated, recovery msg
Semantic loopSame paragraph appears 3x in thinkingSame
Output loopVisible answer ends in same ≥100 chars twiceSame
Output semantic loopSame paragraph appears 3x in answerSame
Stagnation4 turns of thinking ≥85% similarRecovery msg
File read loopSame file read 4xTool call blocked
Search spiralSame pattern searched in 3 different locationsTool call blocked
Tool call loopIdentical tool calls repeat back-to-backTool call blocked in place

Installation

Terminal window
pi install npm:pi-loop-police

No dependencies, no build step, nothing to configure — it starts protecting the session as soon as it loads. Everything below is optional tuning.

Config (persistent, loop-police.json next to installed extension):

{
"THINKING_WINDOW": 80,
"OUTPUT_WINDOW": 100,
"MAX_WINDOW": 4000,
"STRIDE": 50,
"FINGERPRINT_LEN": 60,
"SEMANTIC_THRESHOLD": 3,
"STAGNATION_WINDOW": 4,
"STAGNATION_THRESHOLD": 0.85,
"FILE_READ_LIMIT": 4,
"EXPAND_LIMIT": 3,
"CONSECUTIVE_LOOP": 2,
"TOOL_LOOP_BAN": 1,
"TOOL_LOOP_EXEMPT": ""
}

Tuning rules of thumb:

  • False positives on thinking/output loops → raise THINKING_WINDOW/OUTPUT_WINDOW (char-level) or SEMANTIC_THRESHOLD/FINGERPRINT_LEN (semantic)
  • Structured answers with legitimately similar paragraph openings (checklists, per-file reports) → raise FINGERPRINT_LEN so fingerprints capture more of each paragraph
  • Projects where re-reading files is normal → raise FILE_READ_LIMIT; monorepos → raise SEARCH_SPIRAL to 4
  • Loops caught too late → lower SEMANTIC_THRESHOLD to 2 (more sensitive, more false-positives)

Disabling individual detectors Setting a detector’s key 0 turns it off entirely.

{
"THINKING_WINDOW": 0,
"OUTPUT_WINDOW": 0,
"SEM_LOOP_THRESHOLD": 0,
"OUTPUT_LOOP_WINDOW": 0,
"FILE_READ_LIMIT": 0,
"EXPAND_LIMIT": 0,
"CONSECUTIVE_LOOP_LIMIT": 0,
"TOOL_LOOP_BAN": 0
}

Customizing recovery messages

The text injected when a loop is detected is configurable — some models respond better to different phrasing. These live alongside the numeric loop-police.json as MSG_* keys:

KeyFires whenPlaceholders
MSG_THINKING_LOOPcharacter-level thinking loop—
MSG_SEMANTIC_LOOPsemantic thinking loop—
MSG_OUTPUT_LOOPcharacter-level output loop—
MSG_SEMANTIC_LOOPsemantic output loop—
MSG_CONSECUTIVE_LOOPCONSECUTIVE_LOOP_LIMIT looped turns in a row{count}
MSG_STAGNATIONcross-turn reasoning{window}, {threshold}
MSG_FILE_LOOPsame file read too many times{path}, {count}
MSG_SPIRALsearch pattern spread across too many paths{pattern}, {paths}
MSG_SUFFIXappended to every message above (empty by default)—

{placeholder} tokens are substituted at runtime; unknown tokens are left as-is so typo stays visible.

Messages are edited in loop.json only — /loop-police set handles numeric keys (plus TOOL_LOOP_EXEMPT) and will refuse MSG key. MSG_SUFFIX rides along with every detection without rewriting each template — the typical use is pointing the model at an advisor extension or tool to consult once a loop is caught:

{
"MSG_SUFFIX": "Before continuing, consult the advisor extension: run /advisor with a one-line summary of what you were stuck on."
}

Commands

Terminal window
/loop-police # show current detection state
/loop-police reset # clear all state (useful if false positive fires)
/loop-police set KEY=VAL [KEY=VAL …] live, no restart needed

Example: /loop-police set FILE_READ_LIMIT=6 STAGNATION_WINDOW=5

Changes made with set last for the session; persistent changes go loop.json see above).

Skills

Two skills ship with the extension:

  • loop-police-help — reference card: commands, config keys, and where the loop-police.json lives for each install type
  • loop-police-postmortem — asks the agent to analyze the loop-police detections in the current session: reconstruct what triggered each firing, classify justified / false positive / justified-but-ineffective), and recommend could have avoided

Trigger it with things like “why did loop-police fire?”, “was that a false?”, “do a loop”.

Upgrading

Config are automatic — customized values are preserved and the file is re-stamped, once:

  • From < 1.8.0 : the stream-detector keys were renamed (MIN_THINKING → THINKING_WINDOW, MIN_OUTPUT_WINDOW → OUTPUT, MAX_THINKING_WINDOW → MAX_WINDOW, CHECK_STRIDE → STRIDE, FINGERPRINT_LEN → FINGERPRINT, PARA_LOOP→SEM). Customized values are carried over to the new names; values you never picked up new defaults (notably MAX grew from 2000 to 4000).
  • From < 1.5.0 : the TOOL_LOOP_B scale shifted by one (old 0 = temporary → new 1, old 1 = permanent → new 2; 0 now means off). The stored value is bumped to preserve behavior you had.

Compatibility

Designed for OpenAI-compatible reasoning models (Qwen3, DeepSeek-R1, used via Pi normalizes all formats to { type: "thinking", thinking: string } content blocks, so this extension works regardless of the underlying provider.

Works alongside pi-canary, which silently verifies agent context awareness using hidden canary tokens. When loop-police aborts a turn, pi-canary yields gracefully and not fire own recovery.

License

MIT

Earendil Inc. & Contributors


This article was written by Pi Agent (Qwen3.6-27B-NVFP4 | PC Eyay), with analysis contributions from Gemini (Gemini 2.5 Flash | Google) and me