Skip to content

fix(agents): clamp max_completion_tokens to context window for proxy-like openai-completions endpoints - #85889

Merged
steipete merged 6 commits into
openclaw:mainfrom
rendrag-git:fix/clamp-max-completion-tokens-for-proxy-like
May 24, 2026
Merged

steipete merged 6 commits into
openclaw:mainfrom
rendrag-git:fix/clamp-max-completion-tokens-for-proxy-like

Conversation

@rendrag-git

@rendrag-git rendrag-git commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • Problem: OpenClaw can emit an OpenAI Chat Completions output budget that does not fit inside strict OpenAI-compatible server context limits. vLLM, LocalAI, llama.cpp, LM Studio, DashScope, GLM, Kimi, StepFun-style providers, and similar servers reject this before generation with HTTP 400 when prompt + max_completion_tokens exceeds their effective context.
  • Why it matters: Local vLLM and other strict OpenAI-compatible users can see every prompt fail before the model is called. Issue [Bug]: max_tokens not subtracting used input tokens, causing API "too large" errors #83086 reports this shape against StepFun step-router-v1 with context=262144.
  • What changed: After 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-aware estimateStringChars helper 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.
  • Debug proof hook: When the clamp fires, model transport debug logging now emits [completions] clamp_max_tokens ... requested=... output=... effectiveContext=... estimatedInput=.... Enable OPENCLAW_DEBUG_MODEL_TRANSPORT=1 to capture the computed outbound cap during live vLLM/strict-provider verification.
  • What did NOT change (scope boundary): Native OpenAI, Azure OpenAI, and OpenRouter behavior remains gated away from this proxy-like clamp. No provider-specific tokenizer or new stream wrapper was added.

Why a new fix instead of extending #85008

  • Canonical seam: buildOpenAICompletionsParams is the single function that produces the wire payload. Fixing here covers every caller in one place.
  • Clamp stream max tokens to remaining context window #85008's interceptor at pi-embedded-runner/extra-params.ts only covers traffic through the embedded runner. Gateway openclaw infer model run and external plugin-SDK consumers do not benefit.
  • Estimator ownership: The builder now uses OpenClaw's existing CJK-aware token-pressure helper instead of a standalone raw chars / 4 estimate. This keeps the clamp aligned with the repo's documented non-Latin token-pressure behavior.
  • Effective context ownership: The clamp respects contextTokens before contextWindow, matching the documented runtime cap used by model config and compaction paths.
  • Pattern precedent: Same usesExplicitProxyLikeEndpoint plumbing 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)

  • Bug fix

Scope (select all touched areas)

  • Gateway / orchestration
  • Integrations

Linked Issue/PR

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-stack running 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-*.js bundle on the pmg gateway. vLLM router served qwen3-5-122b-a10b-nvfp4; max_model_len was initially 131072 and later 237568 after a vLLM rollout. Model registered as vllm/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.maxTokens set higher than the effective context. The live route hit the clamp branch, reduced max_completion_tokens to the remaining budget, and vLLM accepted the request.

  • Latest-head proof hook for repeat capture: Current head 1d389c2b5b adds a gated debug line in the same clamp branch:

    [completions] clamp_max_tokens provider=vllm api=openai-completions model=qwen3-5-122b-a10b-nvfp4 requested=250000 output=... effectiveContext=... estimatedInput=...
    

    Enable OPENCLAW_DEBUG_MODEL_TRANSPORT=1 on the live gateway to capture the computed outbound cap alongside the existing [model-fetch] response ... status=200 line.

  • Evidence after fix: Redacted runtime logs from the pmg gateway showed the live Discord -> embedded runner -> openai-completions trace returning HTTP 200:

    [model-fetch] start provider=vllm api=openai-completions
      model=qwen3-5-122b-a10b-nvfp4 method=POST
      url=http://<redacted-vllm-router>/v1/chat/completions
    [model-fetch] response provider=vllm
      model=qwen3-5-122b-a10b-nvfp4 status=200 elapsedMs=122
      contentType=text/event-stream; charset=utf-8
    embedded run agent end: runId=... isError=false
    textPreview="Hey! Testing received. How can I help you today?"
    
  • Observed result after fix: vLLM returned HTTP 200 with Content-Type: text/event-stream and 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=131072 on the unpatched gateway, captured during diagnostic write-up at docs/diagnostics/vllm-openclaw-payload-compat-2026-05-23.md.

Root Cause (if applicable)

  • Root cause: buildOpenAICompletionsParams set max_completion_tokens from resolveOpenAICompletionsMaxTokens(model, options) with no awareness of prompt size or the effective runtime context cap. When maxTokens was at or above the available server context, the wire request asked for more output than strict servers could accept with the prompt.
  • Missing detection / guardrail: No test covered proxy-like endpoints where maxTokens exceeded the remaining budget after prompt input, CJK prompt text, many short messages, or contextTokens lower than contextWindow.
  • Contributing context: Wildcard discovery in models.providers.<vllm>.models = [] can populate per-model maxTokens from provider defaults that match or exceed server max_model_len.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
  • Target test or file: src/agents/openai-transport-stream.test.ts
  • Scenarios locked in by the tests in this PR:
    1. Proxy-like endpoint + substantial ASCII prompt + oversized maxTokens -> max_completion_tokens clamped to remaining budget.
    2. Proxy-like endpoint + CJK prompt -> input estimate uses CJK-aware adjusted chars.
    3. Proxy-like endpoint + many one-character messages -> estimator rounds after summing, not per fragment.
    4. Proxy-like endpoint + lower contextTokens -> clamp uses contextTokens before contextWindow.
    5. Proxy-like endpoint + maxTokens already fitting -> unchanged.
    6. Native OpenAI endpoint + oversized 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_tokens is 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)

Before:
maxTokens = 250000, effectiveContext = 237568, estimatedInput = 45000
  -> max_completion_tokens: 250000
  -> strict server HTTP 400

After (proxy-like endpoint only):
maxTokens = 250000, effectiveContext = 237568, estimatedInput = 45000
  -> max_completion_tokens: 192567
  -> HTTP 200

contextTokens lower than contextWindow:
contextTokens = 4096, contextWindow = 131072, estimatedInput = 2
  -> max_completion_tokens: 4093

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No (only payload field value bound on existing calls)
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Repro + Verification

Environment

  • Local unit proof: Codex worktree /home/ubuntu/projects/openclaw/.worktrees/clamp-max-tokens, Node/Vitest via repo wrapper.
  • Live behavior proof: Ubuntu 22.04 inside incus container oc-stack, OpenClaw 2026.5.18 plus this patch lineage, vLLM serving qwen3-5-122b-a10b-nvfp4, Discord channel bound to the pm agent.

Steps

  1. Configure a vLLM or similar proxy-like OpenAI-compatible provider with a model entry where maxTokens exceeds the effective remaining context.
  2. Optionally enable OPENCLAW_DEBUG_MODEL_TRANSPORT=1 to capture [completions] clamp_max_tokens ....
  3. Send a Discord message through the bound agent or run an equivalent gateway request.

Expected

  • Gateway log shows the clamp debug line when enabled.
  • Gateway log shows [model-fetch] response ... status=200.
  • Outbound output cap is reduced to the remaining effective budget.

Actual

  • Matches expected in the live vLLM route.

Evidence

  • Failing log before + passing live behavior after
  • Trace/log snippets
  • Focused regression tests
  • Local structured review

Verification Commands

pnpm install
node scripts/run-vitest.mjs src/agents/openai-transport-stream.test.ts
.agents/skills/autoreview/scripts/autoreview --mode local
git diff --check

Latest local results on head 1d389c2b5b:

Test Files  2 passed (2)
Tests       382 passed (382)

autoreview clean: no accepted/actionable findings reported
overall: patch is correct (0.84)

Human Verification (required)

  • Verified scenarios: End-to-end Discord -> pm agent -> embedded runner -> openai-completions transport against live vLLM with maxTokens above the effective context; vLLM accepts the request and the model replies normally.
  • Edge cases checked: maxTokens below budget is unchanged; CJK prompt estimate; many short messages; contextTokens lower than contextWindow; native OpenAI path unchanged by unit test.
  • What I did not verify: StepFun step-router-v1 from [Bug]: max_tokens not subtracting used input tokens, causing API "too large" errors #83086 (no account); native OpenAI live with intentionally oversized output cap.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes for native providers; proxy-like strict providers now receive a smaller, valid output cap where the old payload could fail.
  • Config/env changes? No
  • Migration needed? No

Risks and Mitigations

  • Risk: The heuristic can still differ from a provider's exact tokenizer.
    • Mitigation: The estimate uses the repo's CJK-aware token-pressure helper and a safety margin; wrong-high trims output, wrong-low is what could allow server rejection.
  • Risk: Very long prompts can still leave only a tiny output budget.
    • Mitigation: The clamp floors at 1 token instead of sending an invalid oversized output cap; compaction/pre-prompt pressure remains responsible for broader prompt reduction.
  • Risk: Users intentionally configured very large maxTokens for proxy-like providers.
    • Mitigation: The clamp only reduces values that exceed remaining effective context and would be rejected by strict servers.

AI-assisted PR. Investigation, patch authoring, local tests, PR body refresh, and review closeout used Codex. Real behavior proof is from the maintainer's local vLLM/Discord setup; live logs were redacted before inclusion.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S proof: supplied External PR includes structured after-fix real behavior proof. labels May 24, 2026
@clawsweeper

clawsweeper Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

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
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

PR Surface
Source +88, Tests +197. Total +285 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 91 3 +88
Tests 1 197 0 +197
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 288 3 +285

Summary
The PR adds a remaining-effective-context clamp for proxy-like OpenAI Completions max_completion_tokens/max_tokens payloads and adds focused transport regression tests.

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
Overall: 🐚 platinum hermit
Proof: 🐚 platinum hermit
Patch quality: 🐚 platinum hermit
Summary: Focused bug fix with useful live logs and regression coverage; remaining review attention is the intentional proxy-provider compatibility behavior.

Rank-up moves:

  • none
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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
Sufficient (logs): The PR body includes redacted live vLLM runtime logs for a Discord-to-openai-completions route with before-failure and after-HTTP-200 evidence, and the latest head has a successful real-behavior-proof check.

Risk before merge

  • Merging intentionally reduces output caps for proxy-like OpenAI-compatible providers when the previous configured cap exceeds the remaining effective context budget.
  • The estimator is heuristic, so unusual provider tokenizers may still reject some prompts or trim output more than an exact tokenizer would.
  • I did not run tests locally because this was a read-only review; the PR body reports focused Vitest and autoreview results, and GitHub shows lint/proof checks for the head SHA.

Maintainer options:

  1. Accept Proxy Clamp Semantics (recommended)
    Land if maintainers agree proxy-like OpenAI-compatible endpoints should receive a bounded output cap whenever the configured budget would exceed effective context.
  2. Require More Provider Proof
    Pause if maintainers want StepFun-specific or additional strict-provider live proof before changing output caps across proxy-like endpoints.

Next step before merge
No automated repair is indicated; maintainers should make the compatibility/merge decision and rely on required checks before landing.

Security
Cleared: The diff only changes token-cap calculation and colocated tests; I found no new permissions, dependency, secret-handling, workflow, or supply-chain surface.

Review details

Best 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:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes redacted live vLLM runtime logs for a Discord-to-openai-completions route with before-failure and after-HTTP-200 evidence, and the latest head has a successful real-behavior-proof check.
  • add rating: 🐚 platinum hermit: Current PR rating is 🐚 platinum hermit because proof is 🐚 platinum hermit, patch quality is 🐚 platinum hermit, and Focused bug fix with useful live logs and regression coverage; remaining review attention is the intentional proxy-provider compatibility behavior.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The PR body includes redacted live vLLM runtime logs for a Discord-to-openai-completions route with before-failure and after-HTTP-200 evidence, and the latest head has a successful real-behavior-proof check.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The linked bug can make strict OpenAI-compatible agent calls fail repeatedly before any model output is returned.
  • merge-risk: 🚨 compatibility: The PR changes the effective output-token budget sent to existing proxy-like OpenAI-compatible provider setups.
  • rating: 🐚 platinum hermit: Current PR rating is 🐚 platinum hermit because proof is 🐚 platinum hermit, patch quality is 🐚 platinum hermit, and Focused bug fix with useful live logs and regression coverage; remaining review attention is the intentional proxy-provider compatibility behavior.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The PR body includes redacted live vLLM runtime logs for a Discord-to-openai-completions route with before-failure and after-HTTP-200 evidence, and the latest head has a successful real-behavior-proof check.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes redacted live vLLM runtime logs for a Discord-to-openai-completions route with before-failure and after-HTTP-200 evidence, and the latest head has a successful real-behavior-proof check.

What I checked:

  • Current main forwards max tokens directly: Current main resolves effectiveMaxTokens and assigns it directly to max_tokens or max_completion_tokens, with no prompt-size or effective-context guard. (src/agents/openai-transport-stream.ts:3373, 31145e0dd984)
  • PR clamps at canonical builder seam: PR head computes effectiveContextTokens, estimates input pressure with the CJK-aware helper, clamps the output budget to max(1, effectiveContextTokens - estimatedInputTokens - 1), and logs when the clamp fires. (src/agents/openai-transport-stream.ts:3450, 1d389c2b5bf6)
  • Tests cover the repaired edge cases: The PR adds regression tests for the StepFun-style high-input case, CJK-aware estimates, summed rounding, contextTokens before contextWindow, fitting proxy budgets, and unchanged native OpenAI behavior. (src/agents/openai-transport-stream.test.ts:4769, 1d389c2b5bf6)
  • Effective context contract: Docs define contextTokens as the optional smaller runtime context cap, and existing pre-prompt pressure code uses CJK-aware token pressure helpers. Public docs: docs/gateway/config-tools.md. (docs/gateway/config-tools.md:531, 31145e0dd984)
  • Real behavior proof context: The PR body reports a live Discord -> embedded runner -> openai-completions route against vLLM with model.maxTokens above effective context, before 400-class strict-server rejection, and after-patch HTTP 200 plus a normal assistant reply; the latest check run also reports Real behavior proof success for head 1d389c2b5b. (1d389c2b5bf6)
  • Feature history: Git history ties the OpenAI transport builder seam to the provider transport adapter refactor, and recent merged work in the same builder covered proxy-like OpenAI Completions compatibility. (src/agents/openai-transport-stream.ts:3401, 4798e125f40c)

Likely related people:

  • Vincent Koc: Introduced the LLM transport adapter seam that added buildOpenAICompletionsParams and the central OpenAI transport test surface. (role: introduced behavior; confidence: high; commits: 4798e125f40c; files: src/agents/openai-transport-stream.ts, src/agents/openai-transport-stream.test.ts)
  • rendrag-git: Recently landed the adjacent proxy-like OpenAI Completions empty-tools fix in the same payload builder and test file. (role: recent adjacent contributor; confidence: medium; commits: 75081569b047, 69e8039f9ad7; files: src/agents/openai-transport-stream.ts, src/agents/openai-transport-stream.test.ts)
  • Logan Ye: Merged support-tools compatibility changes in the same OpenAI Completions payload builder path shortly before this PR. (role: recent area contributor; confidence: medium; commits: 76a025c2fd85; files: src/agents/openai-transport-stream.ts, src/agents/openai-transport-stream.test.ts)
  • Peter Steinberger: Recent history shows merges/refactors around the builder and CJK token-pressure helper used by this PR. (role: recent merger and adjacent owner; confidence: medium; commits: 69e8039f9ad7, 971ecabe80b6; files: src/agents/openai-transport-stream.ts, src/utils/cjk-chars.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against 31145e0dd984.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels May 24, 2026
@clawsweeper

clawsweeper Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

✨ Hatched: 🥚 common Frosted Signal Puff

Hatch command

Comment @clawsweeper hatch when this PR is hatchable.

Hatchability rules:

  • Merged PRs are hatchable.
  • Open PRs are hatchable when they are status: 👀 ready for maintainer look, status: 🚀 automerge armed, or labeled clawsweeper:automerge.
  • Closed unmerged PRs are hatchable only when one of those hatchable labels is still present in the durable record.

Rarity: 🥚 common.
Trait: hums during re-review.
Image traits: location green-check meadow; accessory rollback rope; palette charcoal, cyan, and signal green; mood calm; pose sitting proudly on a smooth stone; shell woven fiber shell; lighting tiny status-light glow; background gentle dashboard dots.
Share on X: post this hatch
Copy: My PR egg hatched a 🥚 common Frosted Signal Puff in ClawSweeper.

What is this egg doing here?
  • Eggs appear after the PR passes real-behavior proof. It is here for vibes, not verdicts: it does not change labels, ratings, merge decisions, or automation.
  • The shell reacts to review momentum: open follow-up work warms it up, re-review makes it wobble, and a clean final review lets it hatch.
  • Hatchability usually comes from sufficient real-behavior proof, no blocking P0/P1/P2 findings, no security attention needed, and clean correctness. A merged PR is already final, so merge makes the egg hatchable independently.
  • The hatch is seeded from this repository and PR number, so the same PR keeps the same creature; the reviewed head SHA can only change safe visual details.
  • Rarity is just collectible sparkle: 🥚 common, 🌱 uncommon, 💎 rare, ✨ glimmer, and 🌈 legendary.

@rendrag-git

Copy link
Copy Markdown
Contributor Author

@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 contextWindow=262144 and maxTokens=262144 → max_completion_tokens bounded by remaining budget). Same canonical seam, same compat gating, ~30 LOC added for the estimator helper.

Updated PR body explains the change from the original contextWindow - 1 cap and the math used.

@clawsweeper

clawsweeper Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@rendrag-git

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Updated proof: captured live runtime evidence of the clamp actively firing, not just being installed. Bumped model.maxTokens to 250000 on a vLLM model with contextWindow=237568, sent Discord messages through the pm agent, and recorded 5 consecutive calls where the outbound max_completion_tokens was reduced from 250000 to remainingBudget (~191k–193k, varying with input) and vLLM accepted each with HTTP 200 within ~145ms. Trace lines are in the updated PR body. Instrumentation was added via a single console.log inside the patched block, captured, and removed; live bundle now contains only the production patch.

Also addressed:

  • Codex review caught an impossible-assertion bug in the long-input unit test (estimator overflow against a 1M-char prompt → Math.max(1, negative) floored to 1). Reduced prompt to 200k chars (62.5k estimated tokens) so the assertion cap == contextWindow - estimatedInputTokens - 1 evaluates cleanly.
  • check-lint curly-rule failures fixed (added braces around two if (...) continue; lines in the estimator).

@clawsweeper

clawsweeper Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added size: M triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. proof: supplied External PR includes structured after-fix real behavior proof. and removed size: S proof: supplied External PR includes structured after-fix real behavior proof. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 24, 2026
@rendrag-git

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels May 24, 2026
@steipete steipete self-assigned this May 24, 2026
@rendrag-git

Copy link
Copy Markdown
Contributor Author

@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.
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 24, 2026
@steipete
steipete force-pushed the fix/clamp-max-completion-tokens-for-proxy-like branch from 2a6cdca to 3fcc40c Compare May 24, 2026 03:50
@steipete

Copy link
Copy Markdown
Contributor

Verification for rebased head 3fcc40c6e5d163348d3cf787f7bc966e52417c84:

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:

  • node scripts/run-vitest.mjs src/agents/openai-transport-stream.test.ts - 2 files, 384 tests passed.
  • .agents/skills/autoreview/scripts/autoreview --mode branch --base origin/main - clean, no accepted/actionable findings.
  • git diff --check - clean.
  • pnpm exec oxfmt --check --threads=1 src/agents/openai-transport-stream.ts src/agents/openai-transport-stream.test.ts CHANGELOG.md - passed.
  • env -u OPENCLAW_TESTBOX pnpm check:changed - passed.
  • gh pr checks 85889 --repo openclaw/openclaw --watch --interval 30 - relevant checks passed.

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.

@steipete
steipete merged commit 1d1a7c2 into openclaw:main May 24, 2026
98 checks passed
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…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]>
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
…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]>
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
…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]>
obviyus added a commit that referenced this pull request Sep 25, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 26, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: max_tokens not subtracting used input tokens, causing API "too large" errors

2 participants