Skip to content

feat(server): auto-truncate oversized history on /v1/chat/completions and /v1/messages - #10

Open
ihsieh31 wants to merge 1 commit into
2951461586:mainfrom
ihsieh31:feat/auto-truncate-chat-and-messages
Open

ihsieh31 wants to merge 1 commit into
2951461586:mainfrom
ihsieh31:feat/auto-truncate-chat-and-messages

Conversation

@ihsieh31

Copy link
Copy Markdown
Contributor

Problem

Upstream DeepAI silently truncates the beginning of oversized request bodies (issue #7: ~196 KB body limit, usage.prompt_tokens pegs near 40k). The /v1/responses endpoint already handles this correctly via previous_response_id replay + truncation: "auto". But the two stateless endpoints — /v1/chat/completions and /v1/messages — forwarded payloads unchanged, so long conversations quietly "forgot" their earliest turns.

What this does

New respstate.EnforceLimits — pulls the dual-gate (token + byte) truncation logic out of Replay into a standalone, reusable function:

  • Returns (items, OK) when within budget
  • Returns (items, TooLong, msg) when over budget and auto-truncation is off
  • Returns (truncated items, OK) when over budget and auto-truncation is on
  • Returns (items, TooLong, msg) when even after truncation it still overflows

Wire it into both stateless endpoints: chat.go and anthropic.go call EnforceLimits on the (already chat-shaped) messages array before forwarding. The semantics are identical to /v1/responses:

  • Keep system prefix + first user message + newest tail
  • Insert the same (中間的對話歷史因超過上下文長度已由網關自動省略) marker at the cut
  • dropOrphanToolOutputs cleans up split function_call / function_call_output pairs

Defaults

Auto-truncation is ON by default — silent upstream truncation is strictly worse than a marked mid-cut, and existing clients (Claude Code, Continue, etc.) get memory-loss protection with no changes needed.

Clients that prefer strict behavior can opt out per-request:

{ "model": "...", "messages": [...], "truncation": "disabled" }

which surfaces a 400 with the exact overflow numbers (mirroring the existing truncation: "auto" opt-in on /v1/responses).

Compatibility

  • /v1/responses flow unchanged — Replay still owns its own logic; EnforceLimits reuses the same helpers (truncateHistoryByCosts, historyTruncMarker, EffectiveContextWindow, ContextBodyBytes)
  • No new env vars; honors DEEPAI2API_CONTEXT_BODY_BYTES, DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW, DEEPAI2API_CONTEXT_WINDOWS overrides
  • Marker text identical to the one Replay uses

Tests

  • 5 new unit tests in internal/respstate/enforce_test.go:
    • under-budget passthrough
    • strict TooLong when allowAuto=false
    • auto-truncate path produces marker + preserves head/tail
    • byte-cap-only mode (token gate disabled)
    • max_output_tokens reserve edge case
  • go test ./... — all 23 packages pass
  • go vet ./... — clean
  • End-to-end: 250 KB body against claude-haiku-5-5 returns HTTP 200 with the codeword correctly recalled (vs. silent memory loss before); "truncation": "disabled" returns 400 as expected

Files

  • internal/respstate/enforce.go — new
  • internal/respstate/enforce_test.go — new
  • internal/server/chat.go — add EnforceLimits call before marshal
  • internal/server/anthropic.go — same, after AnthropicToChatPayload

🤖 Generated with Claude Code

… and /v1/messages

Problem
-------
The upstream DeepAI gateway silently truncates the *beginning* of oversized
request bodies (issue 2951461586#7). On /v1/responses we already handle this via the
previous_response_id replay path with explicit truncation:"auto". But the
two stateless endpoints — /v1/chat/completions and /v1/messages — forwarded
requests unchanged, so a long conversation silently "forgot" its early turns.

What this does
--------------
- New respstate.EnforceLimits: a standalone function that applies the same
  token + byte dual-gate logic Replay uses, but takes a flat item list. It
  returns the original items, the truncated items, or TooLong + reason.
- /v1/chat/completions and /v1/messages now run EnforceLimits on their
  (already chat-shaped) messages array before forwarding. The truncation
  semantics match /v1/responses: keep system prefix + first user msg +
  newest tail, insert a 「中間的對話歷史因超過上下文長度已由網關自動省略」
  marker at the cut, and drop orphan tool outputs via the same helper.

Defaults
--------
Auto-truncation is ON by default — silent upstream truncation is strictly
worse than a marked mid-cut. Clients that want strict behavior can send
  "truncation": "disabled"
which surfaces a 400 with the exact overflow numbers (mirroring the
existing truncation:"auto" opt-in on /v1/responses).

Compatibility
-------------
- /v1/responses flow unchanged; Replay still owns its own logic.
- The marker text is identical to the one Replay uses.
- No new env vars; honors the existing DEEPAI2API_CONTEXT_BODY_BYTES and
  DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW / DEEPAI2API_CONTEXT_WINDOWS
  overrides via EffectiveContextWindow + ContextBodyBytes.

Tests
-----
- 5 new unit tests in respstate/enforce_test.go cover: under-budget
  passthrough, strict TooLong, auto-truncate path, byte-cap-only mode,
  and the output-reserve edge case.
- go test ./... — all packages pass.
- End-to-end: 250 KB body against claude-haiku-5-5 returns HTTP 200 with
  the codeword still recalled; "disabled" returns 400 as expected.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@ihsieh31
ihsieh31 force-pushed the feat/auto-truncate-chat-and-messages branch from 1897122 to 84464c5 Compare November 30, 2026 14:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant