Repository navigation
Conversation
Consolidate duplicate HTTP request, response parsing, and usage extraction code across OpenAI-compatible drivers into shared helpers. - Add usage_parser.go: extractOpenAIUsage / extractOpenAIStreamUsage with multi-field fallback (prompt_tokens/input_tokens, completion_tokens/output_tokens) for cross-provider compatibility. - Add parser_config.go: ParserConfig struct and OpenAIParserConfig. - Add response_handler.go: HandleNonStreamingResponse / HandleStreamingResponse as single entry points that extract usage, populate chatConfig.UsageResult, and emit a StreamUsage log. - Extend base_model.go with doRequest / doStreamRequest. - Migrate deepseek, groq, longcat, nvidia, siliconflow drivers, cutting ~100 lines per driver. - Add usage_parser_test.go. Co-authored-by: jay <<EMAIL>>
- Extend TokenUsage with CacheReadTokens / CacheWriteTokens. - Add extractCacheReadTokens / extractCacheWriteTokens with multi-path fallback (DeepSeek prompt_cache_hit_tokens, Anthropic cache_read_input_tokens, OpenAI prompt_tokens_details.cached_tokens, etc.). - Propagate CacheReadTokens to ModelUsage and StreamUsage log. - Add cache-related test cases to usage_parser_test.go. Co-authored-by: jay <<EMAIL>>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe change adds cache-token usage fields, shared authorized request helpers, configurable OpenAI-compatible usage parsers, and centralized non-streaming and streaming response handlers. Five model integrations now use these shared components. ChangesModel response unification
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant ProviderChat
participant BaseModel
participant ResponseHandler
participant Sender
Client->>ProviderChat: submit chat request
ProviderChat->>BaseModel: send authorized JSON POST
BaseModel->>ResponseHandler: provide response body or stream
ResponseHandler->>Sender: forward content, reasoning, and tool calls
ResponseHandler->>ProviderChat: return usage and completion status
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/entity/models/deepseek.go (1)
195-222: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy liftStreaming request execution is not converged. This change adds
BaseModel.doStreamRequestand uses it in LongCat only. Four other drivers keep an inline marshal, timeout, request, bearer-header, status-check, and close sequence, so two request paths now coexist. Route all of them throughdoStreamRequest, and extend the helper with optional headers so Groq keepsAccept: text/event-stream.
internal/entity/models/deepseek.go#L195-L222: replace the inline block with adoStreamRequestcall whose handler invokesHandleStreamingResponse.internal/entity/models/groq.go#L159-L186: replace the inline block withdoStreamRequest, and pass theAccept: text/event-streamheader through the helper.internal/entity/models/nvidia.go#L137-L159: replace the inline block withdoStreamRequest, which also removes themustMarshalcall site.internal/entity/models/siliconflow.go#L155-L182: replace the inline block withdoStreamRequest.As per coding guidelines: "When old and new implementations coexist, converge to one implementation path unless an external contract requires compatibility."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/deepseek.go` around lines 195 - 222, Converge streaming requests on BaseModel.doStreamRequest by replacing the inline request sequences in internal/entity/models/deepseek.go:195-222, internal/entity/models/groq.go:159-186, internal/entity/models/nvidia.go:137-159, and internal/entity/models/siliconflow.go:155-182; have each handler invoke HandleStreamingResponse, remove nvidia’s mustMarshal call site, and extend doStreamRequest to accept optional headers so Groq preserves Accept: text/event-stream.Source: Coding guidelines
🧹 Nitpick comments (13)
internal/entity/models/usage_parser_test.go (2)
1-5: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd the Apache license header.
The other new files in this change (
parser_config.go,usage_parser.go,response_handler.go) start with the Apache 2.0 header. Add the same header here for consistency.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/usage_parser_test.go` around lines 1 - 5, Add the repository’s standard Apache 2.0 license header at the beginning of the usage_parser_test.go file, before the package declaration, matching the header used in parser_config.go, usage_parser.go, and response_handler.go.
45-84: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCover the remaining extraction paths.
The tests exercise two cache-read paths only. Add cases for
extractCacheWriteTokens, for the nestedinput_tokens_details.cached_tokenspath, and for ajson.Numbervalue, sinceextractTokenhandles that type explicitly. If you removeCacheWriteTokensas suggested ininternal/entity/models/types.go, drop the write-path case instead.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/usage_parser_test.go` around lines 45 - 84, Extend the usage-parser table tests to cover extractCacheWriteTokens, nested input_tokens_details.cached_tokens, and a cache/token value represented by json.Number, using the expected TokenUsage fields and successful parsing assertions. If CacheWriteTokens has been removed from the model, omit the cache-write case while retaining the other two extraction paths.internal/entity/models/nvidia.go (1)
137-159: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe streaming request block duplicates
doStreamRequest.LongCat routes streaming through
doStreamRequest. This driver keeps its own timeout, request, status, and close sequence.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/nvidia.go` around lines 137 - 159, Replace the duplicated streaming request logic in the NVIDIA driver with the existing doStreamRequest helper used by the LongCat route. Update the surrounding method to pass the required request, timeout, response-handling, and sender parameters through doStreamRequest, preserving the current streaming behavior and error propagation.Source: Coding guidelines
internal/entity/models/groq.go (1)
159-186: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe streaming request block duplicates
doStreamRequest.This driver keeps its own marshal, timeout, request, status, and close sequence while LongCat uses
doStreamRequest. Note that convergence needs header support in the helper, because this driver setsAccept: text/event-stream.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/groq.go` around lines 159 - 186, Refactor the streaming request flow to reuse the existing doStreamRequest helper instead of duplicating marshaling, timeout, request creation, response validation, and body closing in this driver. Extend doStreamRequest to support the required request headers, including Accept: text/event-stream, then update the caller to pass the headers and preserve HandleStreamingResponse behavior.Source: Coding guidelines
internal/entity/models/base_model.go (1)
176-183: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winBound the response body size.
doRequestnow serves five drivers and reads the whole body with no cap. A large or hostile upstream response allocates without limit.LongCatModel.ListModelsalready caps its read withio.LimitReader. Apply the same pattern here.🛡️ Proposed change
- body, err := io.ReadAll(resp.Body) + body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes)) if err != nil { return nil, fmt.Errorf("failed to read response: %w", err) }Declare
maxResponseBytesnext tononStreamCallTimeout.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/base_model.go` around lines 176 - 183, Update doRequest to cap response-body reads using io.LimitReader, matching the bounded-read pattern in LongCatModel.ListModels. Define and use maxResponseBytes alongside nonStreamCallTimeout, then pass the limited reader to io.ReadAll while preserving the existing error and status handling.internal/entity/models/usage_parser.go (1)
24-66: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCollapse the two identical parser bodies.
extractOpenAIUsageandextractOpenAIStreamUsagediffer only in the parameter name. Extract one helper and let both entry points call it.As per coding guidelines: "collapse duplicate implementations".
♻️ Proposed refactor
+func parseOpenAIUsageBlock(m map[string]any) (*TokenUsage, bool) { + rawUsage, ok := m["usage"].(map[string]any) + if !ok { + return nil, false + } + usage := &TokenUsage{} + usage.PromptTokens = extractToken(rawUsage, "prompt_tokens", "input_tokens") + usage.CompletionTokens = extractToken(rawUsage, "completion_tokens", "output_tokens") + usage.TotalTokens = extractToken(rawUsage, "total_tokens") + if usage.TotalTokens == 0 { + usage.TotalTokens = usage.PromptTokens + usage.CompletionTokens + } + usage.CacheReadTokens = extractCacheReadTokens(rawUsage) + usage.CacheWriteTokens = extractCacheWriteTokens(rawUsage) + return usage, true +} + +func extractOpenAIUsage(body map[string]any) (*TokenUsage, bool) { + return parseOpenAIUsageBlock(body) +} + +func extractOpenAIStreamUsage(event map[string]any) (*TokenUsage, bool) { + return parseOpenAIUsageBlock(event) +}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/usage_parser.go` around lines 24 - 66, Collapse the duplicated parsing logic in extractOpenAIUsage and extractOpenAIStreamUsage into a shared helper that accepts the usage map and returns (*TokenUsage, bool). Update both entry points to perform their existing usage-field extraction and delegate to that helper, preserving the current missing/null behavior for streaming usage and all token/cache calculations.Source: Coding guidelines
internal/entity/models/siliconflow.go (1)
155-182: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe streaming request block duplicates
doStreamRequest.LongCat routes streaming through
doStreamRequest. This driver keeps its own marshal, timeout, request, status, and close sequence.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/siliconflow.go` around lines 155 - 182, Replace the duplicated streaming request sequence in the SiliconFlow driver with the existing doStreamRequest helper, passing the required request, timeout, response, and streaming-parser inputs so behavior remains consistent with LongCat. Remove the local marshal, timeout, HTTP request, status handling, and body-closing logic while preserving the existing OpenAIParserConfig and sender flow.Source: Coding guidelines
internal/entity/models/deepseek.go (2)
195-222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe streaming request block duplicates
doStreamRequest.
LongCatModel.ChatStreamlyWithSenderalready routes throughl.baseModel.doStreamRequest. This driver keeps its own marshal, timeout, request, status, and close sequence. Two paths now do the same work.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/deepseek.go` around lines 195 - 222, Update the streaming request flow in LongCatModel.ChatStreamlyWithSender to delegate to the existing baseModel.doStreamRequest helper instead of duplicating JSON marshaling, timeout setup, HTTP request creation, status handling, and response closing. Preserve the current request payload, headers, parser configuration, model usage, and sender arguments when invoking the shared helper.Source: Coding guidelines
136-141: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the unused provider response structs.
DeepSeekChatResponseandSiliconflowChatResponseare only declared in their package files and are no longer used by the shared response handlers.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/deepseek.go` around lines 136 - 141, Remove the unused DeepSeekChatResponse declaration from internal/entity/models/deepseek.go and the unused SiliconflowChatResponse declaration from internal/entity/models/siliconflow.go; the shared HandleNonStreamingResponse flow already handles provider responses, so leave the request methods unchanged.Source: Coding guidelines
internal/entity/models/response_handler.go (3)
41-45: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winGuard against a nil
cfgor nil parser callback.Both exported handlers dereference
cfgwithout a check: line 43 callscfg.ResponseParser, and line 91 callscfg.StreamParser. A caller that passesnil, or aParserConfigwith one callback unset, causes a nil dereference. Validate once at each entry point.🛡️ Proposed change
+ if cfg == nil || cfg.ResponseParser == nil { + return nil, fmt.Errorf("parser config is required") + } + var result map[string]any if err := json.Unmarshal(body, &result); err != nil { return nil, fmt.Errorf("failed to parse response: %w", err) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/response_handler.go` around lines 41 - 45, Update both exported handler entry points in response_handler.go to validate cfg and the callback they use before dereferencing them: the non-streaming handler must reject nil cfg or nil cfg.ResponseParser, and the streaming handler must reject nil cfg or nil cfg.StreamParser. Return the existing handler error/result convention for invalid configuration, while preserving normal parsing behavior for valid callbacks.
54-62: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winFix the log name and the log condition on the non-streaming path.
Two problems exist here:
- The message is "StreamUsage" for a non-streaming response.
- The log is emitted only when
chatConfig != nilandresult["model"]is a string, whilerecordResponseUsageruns unconditionally. Callers that pass a nilchatConfiglose the usage log for no functional reason.Log the usage independently of
chatConfig, and use a distinct message such as "ChatUsage".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/response_handler.go` around lines 54 - 62, Update the non-streaming usage handling around recordResponseUsage to emit the usage log independently of chatConfig and model type checks, so nil chatConfig callers still produce it. Keep the chatConfig.UsageResult assignment conditional, and change the log message from “StreamUsage” to “ChatUsage”.
30-35: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUnexport the response handlers.
HandleNonStreamingResponseandHandleStreamingResponseare only called from within packagemodels, so make them package-private helpers and rename them tohandleNonStreamingResponse/handleStreamingResponse.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/response_handler.go` around lines 30 - 35, Rename HandleNonStreamingResponse and HandleStreamingResponse to the package-private handleNonStreamingResponse and handleStreamingResponse, and update all call sites within package models to use the new names while preserving their behavior and signatures.Source: Coding guidelines
internal/entity/models/types.go (1)
77-78: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the unused
CacheWriteTokensfield.
CacheWriteTokensis set during usage parsing but is never consumed, whileCacheReadTokensis propagated through model-usage collection. Dropinternal/entity/models/types.go:78and remove the parser code/tests that write it; keep this surface only when a consumer exists.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/types.go` around lines 77 - 78, Remove the unused CacheWriteTokens field from the relevant model type, then update usage-parsing logic and its tests to stop writing or asserting that field. Preserve CacheReadTokens and its existing propagation through model-usage collection.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/base_model.go`:
- Around line 188-195: The panic-based mustMarshal helper in
internal/entity/models/base_model.go lines 188-195 must be deleted. In
internal/entity/models/nvidia.go lines 140-143, update the NVIDIA request flow
to marshal reqBody directly, handle the returned error, and return it with
contextual wrapping instead of panicking; preserve the existing successful
request path.
In `@internal/entity/models/response_handler.go`:
- Around line 98-100: Update the error handling in the response handler to abort
only when the "error" field is present with a non-nil value; treat an "error":
null chunk as a normal stream event and continue processing the response.
Preserve the existing upstream stream error formatting for actual errors.
In `@internal/entity/models/usage_parser.go`:
- Around line 84-97: Update extractCacheWriteTokens so prompt_cache_miss_tokens
is no longer treated as a cache-write value; remove it from the direct
extraction keys or route it through the CacheReadMissTokens parsing path. Keep
cache_creation_input_tokens and the supported nested cache-write paths,
including input_tokens_details.cache_write_tokens, aligned with the
implementation and documentation.
---
Outside diff comments:
In `@internal/entity/models/deepseek.go`:
- Around line 195-222: Converge streaming requests on BaseModel.doStreamRequest
by replacing the inline request sequences in
internal/entity/models/deepseek.go:195-222,
internal/entity/models/groq.go:159-186,
internal/entity/models/nvidia.go:137-159, and
internal/entity/models/siliconflow.go:155-182; have each handler invoke
HandleStreamingResponse, remove nvidia’s mustMarshal call site, and extend
doStreamRequest to accept optional headers so Groq preserves Accept:
text/event-stream.
---
Nitpick comments:
In `@internal/entity/models/base_model.go`:
- Around line 176-183: Update doRequest to cap response-body reads using
io.LimitReader, matching the bounded-read pattern in LongCatModel.ListModels.
Define and use maxResponseBytes alongside nonStreamCallTimeout, then pass the
limited reader to io.ReadAll while preserving the existing error and status
handling.
In `@internal/entity/models/deepseek.go`:
- Around line 195-222: Update the streaming request flow in
LongCatModel.ChatStreamlyWithSender to delegate to the existing
baseModel.doStreamRequest helper instead of duplicating JSON marshaling, timeout
setup, HTTP request creation, status handling, and response closing. Preserve
the current request payload, headers, parser configuration, model usage, and
sender arguments when invoking the shared helper.
- Around line 136-141: Remove the unused DeepSeekChatResponse declaration from
internal/entity/models/deepseek.go and the unused SiliconflowChatResponse
declaration from internal/entity/models/siliconflow.go; the shared
HandleNonStreamingResponse flow already handles provider responses, so leave the
request methods unchanged.
In `@internal/entity/models/groq.go`:
- Around line 159-186: Refactor the streaming request flow to reuse the existing
doStreamRequest helper instead of duplicating marshaling, timeout, request
creation, response validation, and body closing in this driver. Extend
doStreamRequest to support the required request headers, including Accept:
text/event-stream, then update the caller to pass the headers and preserve
HandleStreamingResponse behavior.
In `@internal/entity/models/nvidia.go`:
- Around line 137-159: Replace the duplicated streaming request logic in the
NVIDIA driver with the existing doStreamRequest helper used by the LongCat
route. Update the surrounding method to pass the required request, timeout,
response-handling, and sender parameters through doStreamRequest, preserving the
current streaming behavior and error propagation.
In `@internal/entity/models/response_handler.go`:
- Around line 41-45: Update both exported handler entry points in
response_handler.go to validate cfg and the callback they use before
dereferencing them: the non-streaming handler must reject nil cfg or nil
cfg.ResponseParser, and the streaming handler must reject nil cfg or nil
cfg.StreamParser. Return the existing handler error/result convention for
invalid configuration, while preserving normal parsing behavior for valid
callbacks.
- Around line 54-62: Update the non-streaming usage handling around
recordResponseUsage to emit the usage log independently of chatConfig and model
type checks, so nil chatConfig callers still produce it. Keep the
chatConfig.UsageResult assignment conditional, and change the log message from
“StreamUsage” to “ChatUsage”.
- Around line 30-35: Rename HandleNonStreamingResponse and
HandleStreamingResponse to the package-private handleNonStreamingResponse and
handleStreamingResponse, and update all call sites within package models to use
the new names while preserving their behavior and signatures.
In `@internal/entity/models/siliconflow.go`:
- Around line 155-182: Replace the duplicated streaming request sequence in the
SiliconFlow driver with the existing doStreamRequest helper, passing the
required request, timeout, response, and streaming-parser inputs so behavior
remains consistent with LongCat. Remove the local marshal, timeout, HTTP
request, status handling, and body-closing logic while preserving the existing
OpenAIParserConfig and sender flow.
In `@internal/entity/models/types.go`:
- Around line 77-78: Remove the unused CacheWriteTokens field from the relevant
model type, then update usage-parsing logic and its tests to stop writing or
asserting that field. Preserve CacheReadTokens and its existing propagation
through model-usage collection.
In `@internal/entity/models/usage_parser_test.go`:
- Around line 1-5: Add the repository’s standard Apache 2.0 license header at
the beginning of the usage_parser_test.go file, before the package declaration,
matching the header used in parser_config.go, usage_parser.go, and
response_handler.go.
- Around line 45-84: Extend the usage-parser table tests to cover
extractCacheWriteTokens, nested input_tokens_details.cached_tokens, and a
cache/token value represented by json.Number, using the expected TokenUsage
fields and successful parsing assertions. If CacheWriteTokens has been removed
from the model, omit the cache-write case while retaining the other two
extraction paths.
In `@internal/entity/models/usage_parser.go`:
- Around line 24-66: Collapse the duplicated parsing logic in extractOpenAIUsage
and extractOpenAIStreamUsage into a shared helper that accepts the usage map and
returns (*TokenUsage, bool). Update both entry points to perform their existing
usage-field extraction and delegate to that helper, preserving the current
missing/null behavior for streaming usage and all token/cache calculations.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b1976aa4-ce11-4fb4-bec6-9a94f3d8d579
📒 Files selected for processing (12)
internal/common/model_type.gointernal/entity/models/base_model.gointernal/entity/models/deepseek.gointernal/entity/models/groq.gointernal/entity/models/longcat.gointernal/entity/models/nvidia.gointernal/entity/models/parser_config.gointernal/entity/models/response_handler.gointernal/entity/models/siliconflow.gointernal/entity/models/types.gointernal/entity/models/usage_parser.gointernal/entity/models/usage_parser_test.go
| // mustMarshal marshals v to JSON, panicking on error. | ||
| func mustMarshal(v any) []byte { | ||
| b, err := json.Marshal(v) | ||
| if err != nil { | ||
| panic(fmt.Sprintf("failed to marshal: %v", err)) | ||
| } | ||
| return b | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Panic-based marshaling replaces a recoverable error. mustMarshal turns a json.Marshal failure into a panic, and the NVIDIA streaming path is its only caller. reqBody carries caller-supplied ChatConfig.Tools values, so the failure is reachable and would abort the process instead of returning an error.
internal/entity/models/base_model.go#L188-L195: deletemustMarshal.internal/entity/models/nvidia.go#L140-L143: marshalreqBodyinline and return a wrapped error, as the other drivers do.
📍 Affects 2 files
internal/entity/models/base_model.go#L188-L195(this comment)internal/entity/models/nvidia.go#L140-L143
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/base_model.go` around lines 188 - 195, The panic-based
mustMarshal helper in internal/entity/models/base_model.go lines 188-195 must be
deleted. In internal/entity/models/nvidia.go lines 140-143, update the NVIDIA
request flow to marshal reqBody directly, handle the returned error, and return
it with contextual wrapping instead of panicking; preserve the existing
successful request path.
| if apiErr, ok := event["error"]; ok { | ||
| return fmt.Errorf("upstream stream error: %v", apiErr) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
An "error": null chunk aborts a healthy stream.
The check tests key presence only. Several OpenAI-compatible providers include "error": null in normal chunks. In that case the handler returns upstream stream error: <nil> and discards the response.
🐛 Proposed fix
- if apiErr, ok := event["error"]; ok {
+ if apiErr, ok := event["error"]; ok && apiErr != nil {
return fmt.Errorf("upstream stream error: %v", apiErr)
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if apiErr, ok := event["error"]; ok { | |
| return fmt.Errorf("upstream stream error: %v", apiErr) | |
| } | |
| if apiErr, ok := event["error"]; ok && apiErr != nil { | |
| return fmt.Errorf("upstream stream error: %v", apiErr) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/response_handler.go` around lines 98 - 100, Update the
error handling in the response handler to abort only when the "error" field is
present with a non-nil value; treat an "error": null chunk as a normal stream
event and continue processing the response. Preserve the existing upstream
stream error formatting for actual errors.
| // extractCacheWriteTokens extracts cache-write tokens from the usage block. | ||
| // Providers expose this field under different paths: | ||
| // - DeepSeek: usage.prompt_cache_miss_tokens | ||
| // - Anthropic-compat: usage.cache_creation_input_tokens | ||
| // - input_tokens_details.cache_write_tokens | ||
| func extractCacheWriteTokens(rawUsage map[string]any) int { | ||
| if v := extractToken(rawUsage, "prompt_cache_miss_tokens", "cache_creation_input_tokens"); v > 0 { | ||
| return v | ||
| } | ||
| return extractNestedToken(rawUsage, | ||
| []string{"prompt_tokens_details", "cache_creation_tokens"}, | ||
| []string{"input_tokens_details", "cache_write_tokens"}, | ||
| ) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
DeepSeek API usage prompt_cache_miss_tokens meaning context caching
💡 Result:
In the DeepSeek API, prompt_cache_miss_tokens refers to the number of input tokens in a request that did not match a previously persisted context cache prefix and therefore required full processing [1][2]. Context caching in DeepSeek is an automatic, server-side feature that optimizes requests by identifying and storing recurring prompt prefixes [2][3]. When a new request begins with a prefix that matches a previously cached unit, the system serves those tokens from the cache instead of recomputing them [2][3]. The API usage object provides two specific fields to track this behavior [1][4]: 1. prompt_cache_hit_tokens: Represents the tokens that were successfully served from the context cache [1][2]. These tokens are typically billed at a significantly lower rate than standard input tokens [3]. 2. prompt_cache_miss_tokens: Represents the tokens that were not found in the cache and were processed normally [1][2]. Together, these fields account for the total prompt tokens: prompt_tokens = prompt_cache_hit_tokens + prompt_cache_miss_tokens [1][4]. Key points regarding these metrics: - Automatic Tracking: Caching is enabled by default, and developers monitor its efficiency by observing these fields in the API response usage metadata [4][3][5]. - Billing: Cost optimization is achieved by maximizing cache hits, as cache-hit tokens are cheaper than cache-miss (standard) tokens [2][3]. - Optimization: To improve cache hit rates, developers should keep stable, reusable content (such as system prompts or frequently used documents) at the beginning of the prompt, as the cache matches prefixes sequentially [2][4][3]. [1], [2], [4], [3], [5]
Citations:
- 1: https://chat-deep.ai/docs/deepseek-token-usage-fields/
- 2: https://deepseek-usa.ai/docs/deepseek-context-caching/
- 3: https://deepseekai.guide/api/deepseek-api-context-caching/
- 4: https://chat-deep.ai/docs/deepseek-context-caching/
- 5: https://deepseekv4.network/deepseek-context-caching
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Files matching usage_parser.go:"
fd -a 'usage_parser\.go$' . || true
file="$(fd 'usage_parser\.go$' . | head -n 1 || true)"
if [ -n "$file" ]; then
echo
echo "Outline:"
ast-grep outline "$file" || true
echo
echo "Relevant lines:"
nl -ba "$file" | sed -n '1,140p'
fiRepository: infiniflow/ragflow
Length of output: 770
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="internal/entity/models/usage_parser.go"
echo "Relevant lines 1-160:"
awk '{printf "%5d %s\n", NR, $0}' "$file" | sed -n '1,160p'
echo
echo "Search for cache_write/cache_creation/prompt_cache_miss usage in codebase:"
grep -RIn "cache_write_tokens|cache_creation_tokens|cache_creation_input_tokens|prompt_cache_miss_tokens|prompt_cache_hit_tokens|\*TokenUsage" .Repository: infiniflow/ragflow
Length of output: 6028
🌐 Web query:
Anthropic API cache_creation_input_tokens cache_write_tokens usage context caching
💡 Result:
Anthropic's prompt caching feature allows developers to cache frequently used context (such as large documents, system prompts, or tool definitions) to reduce latency and costs [1][2]. When you implement prompt caching, the API response provides specific usage metrics that help track costs and verify cache performance [1][3]. Key Token Metrics The response usage object includes fields to track how tokens are handled: cache_creation_input_tokens: The number of tokens written to the cache for the first time [1][3]. These tokens are billed at a premium (typically 1.25x the base input token price) [4][5]. cache_read_input_tokens: The number of tokens retrieved from an existing cache entry [1][3]. These are significantly cheaper, billed at approximately 0.1x the base input token price [4][2][5]. input_tokens: The number of tokens that were neither read from nor written to the cache (e.g., the prompt content after the last cache breakpoint) [1][3]. These are billed at the standard input token rate [1][6]. Total Input Calculation You can determine the total input tokens processed in a request using the following formula [1]: total_input_tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens Caching Mechanics and Best Practices - Cache Control: You enable caching by adding a cache_control block to your request, either automatically at the top level or manually on specific content blocks for finer control [3][4][7]. - Cache Hierarchy: Caching follows a prefix-match model. The order of content is critical: tools, system, and then messages [7]. Any byte change within the cached prefix invalidates it [3]. - TTL (Time-to-Live): By default, cache entries have a 5-minute TTL, which refreshes with every hit [4][7]. A 1-hour TTL option is available at a higher write premium (typically 2.0x base input price) for workflows with longer intervals between requests [8][4][5]. - Verification: If your cache is working correctly, you should see cache_read_input_tokens populated in your usage metrics [6]. If you consistently see only cache_creation_input_tokens, the cache may be invalidating due to silent changes (e.g., dynamic timestamps) or expiring between requests [3][6].
Citations:
- 1: https://platform.claude.com/docs/en/build-with-claude/prompt-caching
- 2: https://www.anthropic.com/news/prompt-caching?s=09
- 3: https://github.com/anthropics/skills/blob/main/skills/claude-api/python/claude-api/README.md
- 4: https://github.com/anthropics/anthropic-cookbook/blob/main/misc/prompt_caching.ipynb
- 5: https://buzzai.cc/docs/concepts/prompt-caching
- 6: https://enterprisedna.co/resources/guides/guide-anthropic-prompt-caching/
- 7: https://platform.claude.com/docs/en/build-with-claude/prompt-caching?asuniq=d15bcc99&f80ce999_sort_date=desc
- 8: https://github.com/anthropics/anthropic-sdk-python/blob/main/src/anthropic/types/cache_creation.py
🌐 Web query:
OpenAI API usage prompt_tokens_details cache_creation_tokens prompt_tokens_details cached_tokens cache write tokens
💡 Result:
In the OpenAI API, prompt caching usage details are provided within the usage.prompt_tokens_details object (for Chat Completions) or usage.input_tokens_details (for the Responses API) to help developers monitor cache efficiency and billing [1][2]. Key fields include: - cached_tokens: Represents the number of input tokens that were read from the server-side cache during a request [1][2]. These tokens are typically billed at a discounted rate [3]. This field is returned for all requests, including those with fewer than 1,024 tokens (where it will be zero) [1][4]. - cache_write_tokens: Available on newer model families (such as GPT-5.6 and later), this field reports the number of prompt tokens that were written to the cache during the request [1][2]. For these models, cache writes may incur a cost (e.g., 1.25× the uncached input token rate) [1][2]. These fields allow developers to compare cache-write volumes against subsequent cache hits to measure net costs, optimize prompt structure, and verify that caching is effectively applied [1][2][3]. If cached_tokens is zero on repeated requests with identical content, it often indicates that the cache key has been invalidated by changes such as reordering, whitespace variations, or model mismatches [5]. Note: The usage object provides a breakdown of token usage but is distinct from the final billing calculation, which is handled via your account's usage dashboard based on the specific pricing tier of the model used [6][7]. Always refer to the official OpenAI pricing documentation for the most current information on how read and write tokens affect your specific model [6].
Citations:
- 1: https://developers.openai.com/api/docs/guides/prompt-caching?prompt-cache-api=responses
- 2: https://developers.openai.com/api/docs/guides/prompt-caching
- 3: https://muneebdev.com/prompt-caching-in-openai-api/
- 4: https://raw.githubusercontent.com/openai/openai-cookbook/main/examples/Prompt_Caching101.ipynb
- 5: https://theneuralbase.com/openai/learn/advanced/what-prompt-caching-is-openai-s-server-side-cache/
- 6: https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/prompt-caching
- 7: https://community.openai.com/t/question-about-gpt-5-6-api-cache-read-write-token-billing/1386256/2
Remove DeepSeek cache writes from prompt_cache_miss_tokens.
DeepSeek prompt_cache_miss_tokens is the number of input tokens that did not match the context cache, not the number of tokens written to the cache. The current code assigns DeepSeek cache misses directly to CacheWriteTokens; remove this mapping or map it to CacheReadMissTokens instead. Also align line 88 with the nested paths read by the code: input_tokens_details.cache_write_tokens, not input_tokens_details.cached_tokens.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/usage_parser.go` around lines 84 - 97, Update
extractCacheWriteTokens so prompt_cache_miss_tokens is no longer treated as a
cache-write value; remove it from the direct extraction keys or route it through
the CacheReadMissTokens parsing path. Keep cache_creation_input_tokens and the
supported nested cache-write paths, including
input_tokens_details.cache_write_tokens, aligned with the implementation and
documentation.
Summary
Related to #17284.
usage_parser.gowithextractOpenAIUsage/extractOpenAIStreamUsagethat try multiple field names (
prompt_tokens/input_tokens,completion_tokens/output_tokens) for cross-provider compatibility.parser_config.gowithParserConfigstruct andOpenAIParserConfigconstant to map protocols to parsers.
response_handler.gowithHandleNonStreamingResponseandHandleStreamingResponseas single entry points that extract usage,populate
chatConfig.UsageResult, and emit aStreamUsagelog.base_model.gowithdoRequest/doStreamRequestto removeper-driver HTTP boilerplate.
deepseek,groq,longcat,nvidia,siliconflowdrivers to theshared handlers, cutting ~100 lines per driver and adding a
consistent
StreamUsagelog line (model + prompt + completion + total).usage_parser_test.gocovering standard format, total fallback,missing usage key, and multi-type numeric parsing.
Drivers not yet migrated continue to work unchanged; they can be
switched over incrementally by replacing their body of
ChatWithMessages/
ChatStreamlyWithSenderwith the shared handlers.Testing
bash build.sh --test ./internal/entity/models/...passes.StreamUsagelog appearswith correct model name and token counts.