Skip to content

feat(go-models): unify OpenAI-compatible token usage extraction - #17629

Closed
jay77721 wants to merge 5 commits into
infiniflow:mainfrom
jay77721:feat/openai-usage-parser-v2
Closed

jay77721 wants to merge 5 commits into
infiniflow:mainfrom
jay77721:feat/openai-usage-parser-v2

Conversation

@jay77721

Copy link
Copy Markdown
Member

Summary

Related to #17284.

  • Add usage_parser.go with extractOpenAIUsage / extractOpenAIStreamUsage
    that try multiple field names (prompt_tokens/input_tokens,
    completion_tokens/output_tokens) for cross-provider compatibility.
  • Add parser_config.go with ParserConfig struct and OpenAIParserConfig
    constant to map protocols to parsers.
  • Add response_handler.go with HandleNonStreamingResponse and
    HandleStreamingResponse as single entry points that extract usage,
    populate chatConfig.UsageResult, and emit a StreamUsage log.
  • Extend base_model.go with doRequest / doStreamRequest to remove
    per-driver HTTP boilerplate.
  • Migrate deepseek, groq, longcat, nvidia, siliconflow drivers to the
    shared handlers, cutting ~100 lines per driver and adding a
    consistent StreamUsage log line (model + prompt + completion + total).
  • Add usage_parser_test.go covering 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
/ ChatStreamlyWithSender with the shared handlers.

Testing

  • bash build.sh --test ./internal/entity/models/... passes.
  • Manual testing with deepseek/nvidia confirms StreamUsage log appears
    with correct model name and token counts.

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>>
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 31, 2026
@jay77721 jay77721 added the ci Continue Integration label Jul 31, 2026
jay77721 added 2 commits July 31, 2026 16:50
- 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>>
@jay77721 jay77721 removed the ci Continue Integration label Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4d5265b0-3706-4e2f-adc0-864527b97c35

📥 Commits

Reviewing files that changed from the base of the PR and between 46865eb and 31cf4cd.

📒 Files selected for processing (1)
  • internal/entity/models/usage_parser_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/entity/models/usage_parser_test.go

📝 Walkthrough

Walkthrough

The 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.

Changes

Model response unification

Layer / File(s) Summary
Token usage contracts and parsers
internal/common/model_type.go, internal/entity/models/types.go, internal/entity/models/parser_config.go, internal/entity/models/usage_parser.go, internal/entity/models/usage_parser_test.go, internal/entity/models/base_model.go
Token usage now includes cache-read and cache-write counters. Parsers extract provider-specific fields and derive totals when needed.
Shared request and response handlers
internal/entity/models/base_model.go, internal/entity/models/response_handler.go
Base model helpers send authorized JSON requests and streams. Shared handlers parse responses, forward content and reasoning, accumulate tool calls, track usage, and emit stream completion events.
Provider handler integration
internal/entity/models/deepseek.go, internal/entity/models/groq.go, internal/entity/models/longcat.go, internal/entity/models/nvidia.go, internal/entity/models/siliconflow.go
Provider chat methods now use shared request and response handling. NVIDIA also uses mustMarshal for stream request serialization.

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
Loading

Possibly related PRs

Suggested labels: 🧪 test

Suggested reviewers: jinhai-cn, haruko386, hz-186

Poem

A rabbit counts each cached read,
Shared handlers serve each need.
Streams carry thought and tool-call flow,
Usage totals rise and show.
“Done!” hops softly at the end.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 76.92% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: unified token usage extraction for Go model drivers.
Description check ✅ Passed The description includes a clear summary, implementation details, migration scope, and testing results that match the required template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@jay77721 jay77721 added the ci Continue Integration label Jul 31, 2026
@jay77721
jay77721 marked this pull request as draft July 31, 2026 08:51
@jay77721
jay77721 marked this pull request as ready for review July 31, 2026 08:51

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 lift

Streaming request execution is not converged. This change adds BaseModel.doStreamRequest and 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 through doStreamRequest, and extend the helper with optional headers so Groq keeps Accept: text/event-stream.

  • internal/entity/models/deepseek.go#L195-L222: replace the inline block with a doStreamRequest call whose handler invokes HandleStreamingResponse.
  • internal/entity/models/groq.go#L159-L186: replace the inline block with doStreamRequest, and pass the Accept: text/event-stream header through the helper.
  • internal/entity/models/nvidia.go#L137-L159: replace the inline block with doStreamRequest, which also removes the mustMarshal call site.
  • internal/entity/models/siliconflow.go#L155-L182: replace the inline block with doStreamRequest.

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 win

Add 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 win

Cover the remaining extraction paths.

The tests exercise two cache-read paths only. Add cases for extractCacheWriteTokens, for the nested input_tokens_details.cached_tokens path, and for a json.Number value, since extractToken handles that type explicitly. If you remove CacheWriteTokens as suggested in internal/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 win

The 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 win

The 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 sets Accept: 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 win

Bound the response body size.

doRequest now serves five drivers and reads the whole body with no cap. A large or hostile upstream response allocates without limit. LongCatModel.ListModels already caps its read with io.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 maxResponseBytes next to nonStreamCallTimeout.

🤖 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 win

Collapse the two identical parser bodies.

extractOpenAIUsage and extractOpenAIStreamUsage differ 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 win

The 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 win

The streaming request block duplicates doStreamRequest.

LongCatModel.ChatStreamlyWithSender already routes through l.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 win

Remove the unused provider response structs. DeepSeekChatResponse and SiliconflowChatResponse are 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 win

Guard against a nil cfg or nil parser callback.

Both exported handlers dereference cfg without a check: line 43 calls cfg.ResponseParser, and line 91 calls cfg.StreamParser. A caller that passes nil, or a ParserConfig with 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 win

Fix 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 != nil and result["model"] is a string, while recordResponseUsage runs unconditionally. Callers that pass a nil chatConfig lose 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 win

Unexport the response handlers.

HandleNonStreamingResponse and HandleStreamingResponse are only called from within package models, so make them package-private helpers and rename them to handleNonStreamingResponse / 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 win

Remove the unused CacheWriteTokens field.

CacheWriteTokens is set during usage parsing but is never consumed, while CacheReadTokens is propagated through model-usage collection. Drop internal/entity/models/types.go:78 and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4f05866 and 46865eb.

📒 Files selected for processing (12)
  • internal/common/model_type.go
  • internal/entity/models/base_model.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/groq.go
  • internal/entity/models/longcat.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/parser_config.go
  • internal/entity/models/response_handler.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/entity/models/usage_parser.go
  • internal/entity/models/usage_parser_test.go

Comment on lines +188 to +195
// 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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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: delete mustMarshal.
  • internal/entity/models/nvidia.go#L140-L143: marshal reqBody inline 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.

Comment on lines +98 to +100
if apiErr, ok := event["error"]; ok {
return fmt.Errorf("upstream stream error: %v", apiErr)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
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.

Comment on lines +84 to +97
// 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"},
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


🏁 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'
fi

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


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


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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. ☯️ refactor Pull request that refactor/refine code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant