Repository navigation
fix(agents): clamp max_completion_tokens to context window for proxy-like openai-completions endpoints - #85889
Conversation
|
Codex review: needs maintainer review before merge. Latest ClawSweeper review: 2026-05-24 02:47 UTC / May 23, 2026, 10:47 PM ET. Workflow note: Future ClawSweeper reviews update this same comment in place. How this review workflow works
PR Surface View PR surface stats
Summary Reproducibility: yes. Current main source shows the builder forwarding the resolved output cap directly, and the linked report plus PR proof describe strict providers rejecting prompt plus output budgets that exceed the context window. PR rating Rank-up moves:
What the crustacean ranks mean
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics. Real behavior proof Risk before merge
Maintainer options:
Next step before merge Security Review detailsBest possible solution: Land the canonical builder-level clamp after maintainers accept the proxy-provider compatibility semantics and required checks pass, then let the linked bug close through the PR. Do we have a high-confidence way to reproduce the issue? Yes. Current main source shows the builder forwarding the resolved output cap directly, and the linked report plus PR proof describe strict providers rejecting prompt plus output budgets that exceed the context window. Is this the best way to solve the issue? Yes. The canonical builder seam is the narrow maintainable fix because it covers gateway, embedded runner, and SDK consumers without adding provider-specific wrappers; the compatibility tradeoff remains maintainer-owned. Label changes:
Label justifications:
What I checked:
Likely related people:
Codex review notes: model gpt-5.5, reasoning high; reviewed against 31145e0dd984. |
|
ClawSweeper PR egg ✨ Hatched: 🥚 common Frosted Signal Puff Hatch commandComment Hatchability rules:
Rarity: 🥚 common. What is this egg doing here?
|
|
@clawsweeper re-review Reworked the clamp to subtract estimated input tokens per ClawSweeper's findings. New unit test covers the high-input #83086 shape (1M-char prompt with Updated PR body explains the change from the original |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review Updated proof: captured live runtime evidence of the clamp actively firing, not just being installed. Bumped Also addressed:
|
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper hatch |
CI check-lint flagged two missing braces on single-statement if/continue lines in estimateOpenAICompletionsInputTokens.
Codex review caught that the previous test used a 1M-char prompt that pushed estimated input tokens (312k) above the 262k context window, so the clamp floored to 1 via Math.max(1, ...) and the assertion 'cap <= ctx - input - 1' became impossible (1 <= -200357 is false). Reduce prompt to 200k chars (62.5k estimated input tokens), pin the assertion to the exact derived cap value (262144 - 62500 - 1 = 199643), and keep the '<contextWindow' sanity assertion.
2a6cdca to
3fcc40c
Compare
|
Verification for rebased head Behavior addressed: proxy-like OpenAI Chat Completions output caps now subtract the estimated final outbound request payload after compatibility transforms, instead of the raw pre-transform context. This keeps strict local/API-compatible servers from rejecting prompts that already consume part of the context window without over-clamping dropped replay turns. Exact steps or command run after this patch:
CI proof:
What was not tested: no live StepFun account was used locally; coverage is by the existing PR repro/proof plus local regression coverage and CI. |
…claw#85889) Clamp proxy-like OpenAI Chat Completions output caps against the estimated final outbound request payload after compatibility transforms. This prevents strict local/API-compatible servers from rejecting requests whose prompt already consumes part of the effective context window, while avoiding over-clamping dropped replay turns. Co-authored-by: rendrag-git <[email protected]>
…claw#85889) Clamp proxy-like OpenAI Chat Completions output caps against the estimated final outbound request payload after compatibility transforms. This prevents strict local/API-compatible servers from rejecting requests whose prompt already consumes part of the effective context window, while avoiding over-clamping dropped replay turns. Co-authored-by: rendrag-git <[email protected]>
…claw#85889) Clamp proxy-like OpenAI Chat Completions output caps against the estimated final outbound request payload after compatibility transforms. This prevents strict local/API-compatible servers from rejecting requests whose prompt already consumes part of the effective context window, while avoiding over-clamping dropped replay turns. Co-authored-by: rendrag-git <[email protected]>
…ed (#157673) Closes #157307 ## What Problem This Solves Fixes sessions getting stuck without a useful reply when an OpenAI-compatible proxy prompt consumes its configured context budget. ## User Impact Exhausted thinking-enabled requests enter existing bounded compaction recovery instead of repeatedly sending a one-token output limit. Normal budgets and deliberately short completions that fit remain unchanged. No configuration or migration is required. ## Why This Change Was Made Replace the insufficient-budget warning with a context-overflow error before provider I/O, using the existing 16-token useful-output floor for reasoning-capable models with thinking not disabled, only when context pressure reduces the requested budget. Non-reasoning and thinking-off requests retain the existing clamping and one-token fallback exactly, including when the estimate leaves zero or negative space. This preserves useful short replies while recovering reasoning-only stalls, using existing model.reasoning metadata and the already-resolved request thinking mode rather than a new heuristic. Any broader estimated-budget policy is outside this fix and remains a separate follow-up. Keep the context cap and the payload-aware clamping introduced by #85889; reuse the diagnostic floor from #140902. Recovery remains owned by the existing runtime, with its existing attempt limits. Maintainer decision: thinking-enabled requests reduced below the existing 16-token floor enter bounded overflow recovery. The conservative estimate can compact a request the provider tokenizer might have fit; if the prompt cannot be compacted, the turn fails visibly rather than silently looping on one-token reasoning-only replies. Non-reasoning and thinking-off behavior, including the ordinary insufficient-budget warning and one-token fallback, is unchanged. ## Evidence - Real isolated Gateway against a scripted loopback OpenAI-compatible reasoning provider, configured with contextTokens=16384 and maxTokens=2048, with thinking explicitly enabled for the final red/green. Synthetic history filled the session through normal agent turns. - Before: normal requests used max_tokens=2048; the next two turns sent six requests with max_tokens=1, received reasoning-only output, and failed without compaction. - After: the same stored session invoked compaction (summary budgets 1638 and 1024), retried with max_tokens=2048, and returned NORMAL_REPLY. The following turn also returned NORMAL_REPLY at 2048. No one-token request was sent after the fix. - The fixture initially emitted an invalid compaction summary, correctly rejected by the existing quality guard; after matching its required headings and pending ask, recovery completed without editing session state or changing configuration. - Regression cases for exhausted and sub-floor thinking-enabled budgets fail against the original producer (3 failures) and pass with the fix. The useful-floor boundary and an intentional one-token request are preserved. - After merging repaired main, repeated the real Gateway red/green with the narrowed guard: the baseline again sent six one-token requests across two failed turns; the candidate compacted and returned normal 2048-budget replies on recovery and the following turn. - Non-reasoning Gateway control: the same near-cap prompt returned OK with max_tokens=15 on both baseline and candidate, with no compaction. Focused tests also preserve the 1-token boundary. - Thinking-disabled Gateway control: a reasoning-capable Qwen-compatible model with --thinking off sent enable_thinking=false, retained max_tokens=15, and returned OK. The existing Qwen reasoning test now exercises a fixed near-cap system prompt with thinking off versus on. - Focused tests after the final refinement: 20 parameter tests, 20 reasoning-policy tests, and 44 overflow-recovery tests passed (40.57s wall combined after merging repaired main). Full suites were not run locally. Co-authored-by: Ayaan Zaidi <[email protected]>
…ed (openclaw#157673) Closes openclaw#157307 ## What Problem This Solves Fixes sessions getting stuck without a useful reply when an OpenAI-compatible proxy prompt consumes its configured context budget. ## User Impact Exhausted thinking-enabled requests enter existing bounded compaction recovery instead of repeatedly sending a one-token output limit. Normal budgets and deliberately short completions that fit remain unchanged. No configuration or migration is required. ## Why This Change Was Made Replace the insufficient-budget warning with a context-overflow error before provider I/O, using the existing 16-token useful-output floor for reasoning-capable models with thinking not disabled, only when context pressure reduces the requested budget. Non-reasoning and thinking-off requests retain the existing clamping and one-token fallback exactly, including when the estimate leaves zero or negative space. This preserves useful short replies while recovering reasoning-only stalls, using existing model.reasoning metadata and the already-resolved request thinking mode rather than a new heuristic. Any broader estimated-budget policy is outside this fix and remains a separate follow-up. Keep the context cap and the payload-aware clamping introduced by openclaw#85889; reuse the diagnostic floor from openclaw#140902. Recovery remains owned by the existing runtime, with its existing attempt limits. Maintainer decision: thinking-enabled requests reduced below the existing 16-token floor enter bounded overflow recovery. The conservative estimate can compact a request the provider tokenizer might have fit; if the prompt cannot be compacted, the turn fails visibly rather than silently looping on one-token reasoning-only replies. Non-reasoning and thinking-off behavior, including the ordinary insufficient-budget warning and one-token fallback, is unchanged. ## Evidence - Real isolated Gateway against a scripted loopback OpenAI-compatible reasoning provider, configured with contextTokens=16384 and maxTokens=2048, with thinking explicitly enabled for the final red/green. Synthetic history filled the session through normal agent turns. - Before: normal requests used max_tokens=2048; the next two turns sent six requests with max_tokens=1, received reasoning-only output, and failed without compaction. - After: the same stored session invoked compaction (summary budgets 1638 and 1024), retried with max_tokens=2048, and returned NORMAL_REPLY. The following turn also returned NORMAL_REPLY at 2048. No one-token request was sent after the fix. - The fixture initially emitted an invalid compaction summary, correctly rejected by the existing quality guard; after matching its required headings and pending ask, recovery completed without editing session state or changing configuration. - Regression cases for exhausted and sub-floor thinking-enabled budgets fail against the original producer (3 failures) and pass with the fix. The useful-floor boundary and an intentional one-token request are preserved. - After merging repaired main, repeated the real Gateway red/green with the narrowed guard: the baseline again sent six one-token requests across two failed turns; the candidate compacted and returned normal 2048-budget replies on recovery and the following turn. - Non-reasoning Gateway control: the same near-cap prompt returned OK with max_tokens=15 on both baseline and candidate, with no compaction. Focused tests also preserve the 1-token boundary. - Thinking-disabled Gateway control: a reasoning-capable Qwen-compatible model with --thinking off sent enable_thinking=false, retained max_tokens=15, and returned OK. The existing Qwen reasoning test now exercises a fixed near-cap system prompt with thinking off versus on. - Focused tests after the final refinement: 20 parameter tests, 20 reasoning-policy tests, and 44 overflow-recovery tests passed (40.57s wall combined after merging repaired main). Full suites were not run locally. Co-authored-by: Ayaan Zaidi <[email protected]>
Summary
Supersedes #85008 with a smaller patch at the canonical seam (
buildOpenAICompletionsParams), which covers gateway, embedded runner, and public plugin-SDK consumers (extensions/zai,extensions/xiaomi,extensions/deepseek) in one change. Fixes #83086.prompt + max_completion_tokensexceeds their effective context.context=262144.resolveOpenAICompletionsMaxTokens, proxy-like OpenAI Completions payloads now clamp the resolved output budget to the remaining effective context budget:max(1, (contextTokens ?? contextWindow) - estimatedInputTokens - 1). The input estimate uses the repo's shared CJK-awareestimateStringCharshelper and applies the safety margin after summing adjusted input chars, so non-Latin prompts are not undercounted and many short messages are not overcounted by per-fragment rounding.[completions] clamp_max_tokens ... requested=... output=... effectiveContext=... estimatedInput=.... EnableOPENCLAW_DEBUG_MODEL_TRANSPORT=1to capture the computed outbound cap during live vLLM/strict-provider verification.Why a new fix instead of extending #85008
buildOpenAICompletionsParamsis the single function that produces the wire payload. Fixing here covers every caller in one place.pi-embedded-runner/extra-params.tsonly covers traffic through the embedded runner. Gatewayopenclaw infer model runand external plugin-SDK consumers do not benefit.chars / 4estimate. This keeps the clamp aligned with the repo's documented non-Latin token-pressure behavior.contextTokensbeforecontextWindow, matching the documented runtime cap used by model config and compaction paths.usesExplicitProxyLikeEndpointplumbing as fix(agents): default proxy completions tool choice #71472 and the empty-tools fix in fix(agents): omit empty tools array for proxy-like openai-completions endpoints #85835. It drops into existing compat infrastructure with no new wrapper.Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
usesExplicitProxyLikeEndpointcompat plumbing, same builder, empty-tools fix)supportsModelToolsgate)Real behavior proof (required for external PRs)
Behavior or issue addressed: vLLM rejects OpenClaw OpenAI-compatible chat completions when the outbound output budget does not fit the server's effective context.
Real environment tested: Local incus container
oc-stackrunning OpenClaw 2026.5.18 with this patch lineage and the empty-tools fix from fix(agents): omit empty tools array for proxy-like openai-completions endpoints #85835 applied to the live/usr/lib/node_modules/openclaw/dist/openai-transport-stream-*.jsbundle on the pmg gateway. vLLM router servedqwen3-5-122b-a10b-nvfp4;max_model_lenwas initially 131072 and later 237568 after a vLLM rollout. Model registered asvllm/qwen3-5-122b-a10b-nvfp4. Route taken: Discord channel -> pm agent -> embedded runner -> openai-completions transport.Exact steps or command run after this patch: Sent ordinary Discord messages in the pm channel with
model.maxTokensset higher than the effective context. The live route hit the clamp branch, reducedmax_completion_tokensto the remaining budget, and vLLM accepted the request.Latest-head proof hook for repeat capture: Current head
1d389c2b5badds a gated debug line in the same clamp branch:Enable
OPENCLAW_DEBUG_MODEL_TRANSPORT=1on the live gateway to capture the computed outbound cap alongside the existing[model-fetch] response ... status=200line.Evidence after fix: Redacted runtime logs from the pmg gateway showed the live Discord -> embedded runner -> openai-completions trace returning HTTP 200:
Observed result after fix: vLLM returned HTTP 200 with
Content-Type: text/event-streamand the model produced a normal assistant reply. Before the patch lineage, the same path returned HTTP 400 with the strict-server context-length rejection.What was not tested: StepFun step-router-v1 specifically (no account); native OpenAI live with an intentionally oversized output cap.
Before evidence: vLLM access log returning
HTTP 400 ... max_completion_tokens=131072 cannot be greater than max_model_len=131072on the unpatched gateway, captured during diagnostic write-up atdocs/diagnostics/vllm-openclaw-payload-compat-2026-05-23.md.Root Cause (if applicable)
buildOpenAICompletionsParamssetmax_completion_tokensfromresolveOpenAICompletionsMaxTokens(model, options)with no awareness of prompt size or the effective runtime context cap. WhenmaxTokenswas at or above the available server context, the wire request asked for more output than strict servers could accept with the prompt.maxTokensexceeded the remaining budget after prompt input, CJK prompt text, many short messages, orcontextTokenslower thancontextWindow.models.providers.<vllm>.models = []can populate per-modelmaxTokensfrom provider defaults that match or exceed servermax_model_len.Regression Test Plan (if applicable)
src/agents/openai-transport-stream.test.tsmaxTokens->max_completion_tokensclamped to remaining budget.contextTokens-> clamp usescontextTokensbeforecontextWindow.maxTokensalready fitting -> unchanged.maxTokens-> unchanged existing behavior.User-visible / Behavior Changes
For OpenAI-compatible endpoints routed through a proxy-like/non-native route (vLLM, LocalAI, llama.cpp, LM Studio, DashScope, GLM, Kimi, StepFun-style providers, and similar), outbound
max_completion_tokensis now capped to the remaining effective context budget when the configured output cap would otherwise exceed it. Native OpenAI, Azure OpenAI, and OpenRouter behavior remains outside this clamp.Diagram (if applicable)
Security Impact (required)
NoNoNo(only payload field value bound on existing calls)NoNoRepro + Verification
Environment
/home/ubuntu/projects/openclaw/.worktrees/clamp-max-tokens, Node/Vitest via repo wrapper.oc-stack, OpenClaw 2026.5.18 plus this patch lineage, vLLM servingqwen3-5-122b-a10b-nvfp4, Discord channel bound to the pm agent.Steps
maxTokensexceeds the effective remaining context.OPENCLAW_DEBUG_MODEL_TRANSPORT=1to capture[completions] clamp_max_tokens ....Expected
[model-fetch] response ... status=200.Actual
Evidence
Verification Commands
Latest local results on head
1d389c2b5b:Human Verification (required)
maxTokensabove the effective context; vLLM accepts the request and the model replies normally.maxTokensbelow budget is unchanged; CJK prompt estimate; many short messages;contextTokenslower thancontextWindow; native OpenAI path unchanged by unit test.Review Conversations
Compatibility / Migration
Yesfor native providers; proxy-like strict providers now receive a smaller, valid output cap where the old payload could fail.NoNoRisks and Mitigations
maxTokensfor proxy-like providers.