Repository navigation
Conversation
… 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>
1897122 to
84464c5
Compare
2951461586
left a comment
There was a problem hiding this comment.
必改 4 项,改完后合入。分支已拉下来实测:go build / go vet / gofmt -l 干净,22 包 go test ./... 全绿,覆盖率门禁 respstate 86.6% / server 79.3% 通过。方向认同,问题在工具配对。
P1 ① chat 形状:裁完会留下孤立的 role:"tool"
dropOrphanToolOutputs 只识别 Responses 的 function_call / function_call_output,不识别 chat 的 role:"tool"。裁剪点落在 assistant(tool_calls) 与 tool 之间时,输出变成:
[system user MARKER tool assistant user]
marker 是 user 角色,紧跟一条 tool → OpenAI 兼容上游必然 400(messages with role 'tool' must be a response to a preceding message with 'tool_calls')。
复现:EnforceLimits(items, "m", 320000, "", nil, 0, true),扫 DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW 150–500,15 个窗口值命中。
P1 ② Anthropic 形状:tool_result 失去 tool_use
[user MARKER user:tool_result assistant user]
tool_result 块保留、配对的 tool_use 被裁掉 → Anthropic 侧 400。11 个窗口值命中。
①② 的修法:让 dropOrphanToolOutputs 同时识别 role:"tool"(chat)与 content 数组里的 tool_use / tool_result(Anthropic),或者让裁剪点避开工具对边界。这两条正好是 PR 描述里声称已覆盖的场景("dropOrphanToolOutputs cleans up split function_call / function_call_output pairs"),不能留到后续。
P2 ③ truncation 被转发到上游
chat.go / anthropic.go 判完 allowAuto 后没把它从 payload 里删掉,紧接着 json.Marshal(payload) 直接发上游。客户端按文档写 "truncation":"disabled" 就会把这个上游不认识的字段带出去(400 This request cannot be accepted 的风险)。Marshal 前删掉即可,或者改成走请求头。
P2 ④ 默认值与已写死的契约冲突
README.md 第十节写的是「/v1/chat/completions 与 /v1/messages 保持透明代理,超限只记日志」,本 PR 把默认改成自动截断却没改文档。方向可以接受(静默砍头确实更糟),请同批更新 README.md / README.en.md / docs/changes.md。
顺带
msgs, _ := payload["messages"].([]any)吞掉类型断言失败;失败时会把messages写成null发上游;- Anthropic 顶层
system没计入固定开销(instructions=""),tooLongMessage里的 token 数会偏低,只影响错误信息准不准; - 建议补两个 handler 级测试:超限 400 路径、
truncation:"disabled"退出路径——目前 5 个单测只覆盖了纯函数。
已核对,不是问题
sessionAffinity的prefixDigest只看 model + system + tools,截断不会造成会话粘性漂移;perModelContextWindow里没有 40k 条目(40k 是字节闸的表现),max_tokens预扣不会造成过度截断。
Problem
Upstream DeepAI silently truncates the beginning of oversized request bodies (issue #7: ~196 KB body limit,
usage.prompt_tokenspegs near 40k). The/v1/responsesendpoint already handles this correctly viaprevious_response_idreplay +truncation: "auto". But the two stateless endpoints —/v1/chat/completionsand/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 ofReplayinto a standalone, reusable function:(items, OK)when within budget(items, TooLong, msg)when over budget and auto-truncation is off(truncated items, OK)when over budget and auto-truncation is on(items, TooLong, msg)when even after truncation it still overflowsWire it into both stateless endpoints:
chat.goandanthropic.gocallEnforceLimitson the (already chat-shaped)messagesarray before forwarding. The semantics are identical to/v1/responses:(中間的對話歷史因超過上下文長度已由網關自動省略)marker at the cutdropOrphanToolOutputscleans up splitfunction_call/function_call_outputpairsDefaults
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/responsesflow unchanged —Replaystill owns its own logic;EnforceLimitsreuses the same helpers (truncateHistoryByCosts,historyTruncMarker,EffectiveContextWindow,ContextBodyBytes)DEEPAI2API_CONTEXT_BODY_BYTES,DEEPAI2API_EFFECTIVE_CONTEXT_WINDOW,DEEPAI2API_CONTEXT_WINDOWSoverridesReplayusesTests
internal/respstate/enforce_test.go:TooLongwhenallowAuto=falsemax_output_tokensreserve edge casego test ./...— all 23 packages passgo vet ./...— cleanclaude-haiku-5-5returns HTTP 200 with the codeword correctly recalled (vs. silent memory loss before);"truncation": "disabled"returns 400 as expectedFiles
internal/respstate/enforce.go— newinternal/respstate/enforce_test.go— newinternal/server/chat.go— addEnforceLimitscall before marshalinternal/server/anthropic.go— same, afterAnthropicToChatPayload🤖 Generated with Claude Code