Repository navigation
feat(go-models): unify OpenAI-compatible token usage extraction - #17634
Conversation
Consolidate duplicate HTTP request, response parsing, and usage extraction code into shared helpers for OpenAI-compatible drivers. - Add usage_parser.go: extractOpenAIUsage / extractOpenAIStreamUsage with multi-field fallback (prompt_tokens/input_tokens, completion_tokens/output_tokens). - 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 driver to shared handlers. - Add usage_parser_test.go. Co-authored-by: jay <<EMAIL>>
📝 WalkthroughWalkthroughDeepSeek requests now use shared HTTP, response, streaming, and token-usage handlers. The change adds OpenAI-compatible parser configuration, centralized SSE processing, response extraction, error handling, and usage-parser tests. ChangesShared chat handling
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant DeepSeek
participant BaseModel
participant ResponseHandler
participant Sender
DeepSeek->>BaseModel: Submit JSON chat request
BaseModel->>ResponseHandler: Pass successful response body
ResponseHandler->>Sender: Send content and reasoning deltas
ResponseHandler->>Sender: Send accumulated tool calls and [DONE]
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: 7
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)
110-126: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAdd a
defaultcase to the non-streaming effort switch.The streaming path at Lines 183-184 rejects an unknown effort with
invalid effort level. This switch has nodefaultcase. IfEffortholds an unknown value,thinkingFlagstays empty and the driver sends"thinking": {"type": ""}upstream. The two paths must behave the same way.🐛 Proposed fix to reject unknown effort values
case "max": thinkingFlag = "enabled" reqBody["reasoning_effort"] = "max" + default: + return nil, fmt.Errorf("invalid effort level") }🤖 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 110 - 126, The non-streaming effort switch must reject unknown effort values instead of leaving thinkingFlag empty. Update the switch around the effort handling to add a default branch that returns the same “invalid effort level” error used by the streaming path, while preserving all existing recognized effort mappings.
🧹 Nitpick comments (1)
internal/entity/models/deepseek.go (1)
222-222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
BaseModel.doStreamRequestfor the streaming path.The non-streaming path already uses
d.baseModel.doRequest, butDeepSeekModel.ChatStreamlyWithSenderstill repeats request construction, timeout handing, headers,httpClient.Do, and status checking. Replace that block withd.baseModel.doStreamRequestand passHandleStreamingResponseas the response-handler callback.🤖 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` at line 222, Update DeepSeekModel.ChatStreamlyWithSender to replace its duplicated streaming request construction, timeout handling, headers, HTTP execution, and status checks with d.baseModel.doStreamRequest. Pass HandleStreamingResponse as the response-handler callback while preserving the existing model usage, chat configuration, parser configuration, and sender arguments.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 151-185: Extract the shared JSON marshaling, POST request
creation, and header-setting logic from BaseModel.doRequest and
BaseModel.doStreamRequest into one reusable helper, then update both methods to
use it. Preserve each method’s existing response handling and error behavior
while ensuring request construction has a single implementation path.
- Around line 187-194: Delete the unused mustMarshal function, including its
panic-based JSON marshaling logic. Keep the existing error handling in doRequest
and doStreamRequest unchanged.
- Around line 161-167: Guard the apiConfig.ApiKey dereference in the shared
doRequest and doStreamRequest helpers, matching BearerAuth’s nil handling so
missing keys do not panic when AllowEmptyAPIKey is enabled. Alternatively,
remove AllowEmptyAPIKey from local-only drivers that invoke these helpers, while
preserving valid Authorization behavior when an API key exists.
- Around line 196-227: The DeepSeek streaming method duplicates request setup
instead of using the existing helper. Update
DeepSeekModel.ChatStreamlyWithSender to delegate its streaming request to
doStreamRequest, passing the same context, URL, API configuration, request body,
timeout, and response handler; preserve the existing ChatStreamlyWithSender
behavior while making doStreamRequest its single request path.
In `@internal/entity/models/response_handler.go`:
- Around line 98-100: Update the error-field check in the response handler to
require both key presence and a non-nil value before returning an upstream
stream error. Mirror the existing guard pattern from extractOpenAIStreamUsage,
while continuing to return the formatted error for non-nil event["error"]
values.
- Around line 54-62: Update the usage-handling block around recordResponseUsage
so common.Info("StreamUsage", ...) executes whenever usage is non-nil,
regardless of whether result["model"] is a string. Preserve the model value when
available, but provide an appropriate fallback for missing or non-string model
fields while keeping chatConfig.UsageResult assignment unchanged.
In `@internal/entity/models/usage_parser.go`:
- Around line 24-40: Deduplicate the token-field extraction shared by
extractOpenAIUsage and extractOpenAIStreamUsage by introducing or reusing a
helper that accepts the already-obtained rawUsage map and returns TokenUsage.
Keep each function responsible only for retrieving rawUsage from its outer map,
then delegate PromptTokens, CompletionTokens, and TotalTokens
calculation—including the total fallback—to the shared helper.
---
Outside diff comments:
In `@internal/entity/models/deepseek.go`:
- Around line 110-126: The non-streaming effort switch must reject unknown
effort values instead of leaving thinkingFlag empty. Update the switch around
the effort handling to add a default branch that returns the same “invalid
effort level” error used by the streaming path, while preserving all existing
recognized effort mappings.
---
Nitpick comments:
In `@internal/entity/models/deepseek.go`:
- Line 222: Update DeepSeekModel.ChatStreamlyWithSender to replace its
duplicated streaming request construction, timeout handling, headers, HTTP
execution, and status checks with d.baseModel.doStreamRequest. Pass
HandleStreamingResponse as the response-handler callback while preserving the
existing model usage, chat configuration, parser configuration, and sender
arguments.
🪄 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: 57c66078-adf5-44fc-a39e-2ace9db2af7c
📒 Files selected for processing (6)
internal/entity/models/base_model.gointernal/entity/models/deepseek.gointernal/entity/models/parser_config.gointernal/entity/models/response_handler.gointernal/entity/models/usage_parser.gointernal/entity/models/usage_parser_test.go
…ge fields The shared TokenUsage struct only carries PromptTokens/CompletionTokens/ TotalTokens, and extractOpenAIUsage never populates cache fields. Drop the two cache-related cases and the CacheReadTokens/CacheWriteTokens assertions so the test matches the implemented scope and the package builds. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/common_test.go`:
- Around line 124-127: Replace the t.Fatalf assertions inside the
httptest.NewServer handler callbacks at the authorization, Content-Type, and
line 144 checks with t.Errorf, while preserving the outer t.Fatalf calls at the
response assertions around lines 135 and 156.
🪄 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: dd97d27a-7bc4-4323-b266-36c5eec831a3
📒 Files selected for processing (3)
internal/entity/models/base_model.gointernal/entity/models/common_test.gointernal/entity/models/usage_parser.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/entity/models/usage_parser.go
- internal/entity/models/base_model.go
| t.Fatalf("Authorization = %q, want %q", got, tt.wantHeader) | ||
| } | ||
| if got := r.Header.Get("Content-Type"); got != "application/json" { | ||
| t.Fatalf("Content-Type = %q, want application/json", got) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
# Inspect Fatal* calls near HTTP handler callbacks.
rg -n -C 10 \
'http\.HandlerFunc|t\.(Fatal|Fatalf|Fatalln|FailNow)\(' \
internal/entity/models --glob '*_test.go' || true
# Expected: no Fatal* call inside an http.HandlerFunc callback.Repository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
# Inspect the targeted common_test.go ranges and nearby callback structure.
sed -n '90,160p' internal/entity/models/common_test.go
# Locate t.Fatalf lines in the common_test handlers to avoid reading unrelated output.
rg -n 't\.Fatalf|http\.HandlerFunc|httptest\.NewServer' internal/entity/models/common_test.goRepository: infiniflow/ragflow
Length of output: 3527
🌐 Web query:
Go testing.T Fatalf FailNow behavior called from HTTP handler goroutine httptest handler
💡 Result:
In Go, methods such as t.Fatal, t.Fatalf, t.FailNow, t.Skip, and t.SkipNow must be called only from the goroutine that is running the test or benchmark function [1][2]. Calling these methods from a different goroutine—such as one spawned by an HTTP handler or a background process—is a violation of the testing package's design and will not behave as expected [1][3][4]. Specifically, these methods use runtime.Goexit to terminate the execution of the calling goroutine [1][5]. If called from a separate goroutine (e.g., inside an http.Handler processing a request on a httptest.Server), only that specific handler goroutine will exit, while the test goroutine itself will continue running [1][5][6]. This often leads to tests that appear to pass despite failures, or unpredictable behavior during cleanup and teardown [3][4][6]. To correctly handle failures from a background or handler goroutine, you should: 1. Capture the failure state or error message within the spawned goroutine. 2. Communicate that information back to the main test goroutine using a channel [4][6]. 3. Check the channel in the main test goroutine and call t.Fatal or t.Errorf there [4][6]. When using httptest.ResponseRecorder for unit testing, the handler runs in the same goroutine as the test [7][8], so calling t.Fatal directly is safe. However, when using httptest.NewServer, the server runs the handler in its own goroutine [9]. In this case, you must rely on the communication pattern described above if you need to fail the test based on handler-side logic [4][6].
Citations:
- 1: https://pkg.go.dev/testing
- 2: https://go.dev/src/testing/testing.go?m=text
- 3: testing: detect t.FailNow() called from wrong goroutine golang/go#24678
- 4: fix: remove use of testing.T.FailNow() inside goroutine IBM/sarama#1601
- 5: https://github.com/golang/go/blob/master/src/testing/testing.go
- 6: security/advancedtls: test.Fatal() can only be used in test goroutine instead of its child grpc/grpc-go#3587
- 7: https://www.willem.dev/articles/testing-http-handlers-using-httptest/
- 8: https://www.application-architect.com/posts/go-httptest-testing-http-handlers/
- 9: https://github.com/golang/go/blob/master/src/net/http/httptest/server.go
Use t.Errorf inside httptest.NewServer handler callbacks.
Handlers started by httptest.NewServer run in a server goroutine. t.Fatalf calls FailNow and exits that handler goroutine, so a failed assertion can leave the response unwritten and allow the test goroutine to continue to a later assertion. Replace the handler assertions at internal/entity/models/common_test.go:124, :127, and :144 with t.Errorf, and keep the outer t.Fatalf calls at :135 and :156.
🤖 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/common_test.go` around lines 124 - 127, Replace the
t.Fatalf assertions inside the httptest.NewServer handler callbacks at the
authorization, Content-Type, and line 144 checks with t.Errorf, while preserving
the outer t.Fatalf calls at the response assertions around lines 135 and 156.
Source: Learnings
#17643) ## Summary Relate to #17284 Migrate four OpenAI-compatible drivers (`nvidia`, `siliconflow`, `groq`, `longcat`) to use the unified response handlers (`HandleNonStreamingResponse` / `HandleStreamingResponse`), following the same pattern established by `deepseek` in #17634. - Cut ~100 lines per driver (541 lines removed, 19 added across 4 files). - `nvidia` now extracts token usage (previously had none). - All four drivers produce the unified `StreamUsage` log.
…17696) ## Summary Relate to #17284 Migrate 10 OpenAI-compatible drivers (`302ai`, `aliyun`, `astraflow`, `avian`, `azure_openai`, `baichuan`, `baidu`, `cometapi`, `deepinfra`, `futurmix`) to use the unified response handlers (`HandleNonStreamingResponse` / `HandleStreamingResponse`), following the same pattern established by `deepseek` in #17634. - Cut ~150 lines per driver (1507 lines removed, 144 added across 10 files). - No functional changes — pure deduplication of HTTP plumbing. - Each driver now routes through `baseModel.doRequest()` and `HandleNonStreamingResponse()`. --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…17697) ## Summary Relate to #17284 Migrate 10 OpenAI-compatible drivers (`gitee`, `gpustack`, `greenpt`, `huaweicloud`, `huggingface`, `hunyuan`, `jiekouai`, `jina`, `lmstudio`, `localai`) to use the unified response handlers (`HandleNonStreamingResponse` / `HandleStreamingResponse`), following the same pattern established by `deepseek` in #17634. - Cut ~150 lines per driver (1398 lines removed, 155 added across 10 files). - `greenpt` gains `ChatWithMessages` + `ChatStreamlyWithSender` required by the unified handler infrastructure. - All other drivers: pure deduplication of HTTP plumbing. --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…17698) ## Summary Relate to #17284 Migrate 10 OpenAI-compatible drivers (`minimax`, `mistral`, `modelscope`, `moonshot`, `n1n`, `novita`, `ollama`, `openai`, `openai_api_compatible`, `openrouter`) to use the unified response handlers (`HandleNonStreamingResponse` / `HandleStreamingResponse`), following the same pattern established by `deepseek` in #17634. - Cut ~150 lines per driver (1692 lines removed, 172 added across 10 files). - `openai_api_compatible` gains `ChatWithMessages` + `ChatStreamlyWithSender` required by the unified handler infrastructure. - `openai` driver preserves `reasoning_content` extraction for o-series models. - All drivers: pure deduplication of HTTP plumbing. --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…17699) ## Summary Relate to #17284 Migrate 10 OpenAI-compatible drivers (`orcarouter`, `perplexity`, `ppio`, `qiniu`, `ragcon`, `stepfun`, `togetherai`, `tokenhub`, `tokenpony`, `upstage`) to use the unified response handlers (`HandleNonStreamingResponse` / `HandleStreamingResponse`), following the same pattern established by `deepseek` in #17634. - Cut ~150 lines per driver (1436 lines removed, 62 added across 10 files). - No functional changes — pure deduplication of HTTP plumbing. - Each driver now routes through `baseModel.doRequest()` and `HandleNonStreamingResponse()`. --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…17700) ## Summary Relate to #17284. Completes the batch 5 migration of 7 OpenAI-compatible drivers (`vllm`, `volcengine`, `xai`, `xiaomi`, `xinference`, `xunfei`, `zhipu-ai`) onto the unified request/response helpers (`doRequest`/`doStreamRequest` + `HandleNonStreamingResponse`/`HandleStreamingResponse` + `ParserConfig`), established by `deepseek` in #17634. This branch is rebased on the current `pr/migrate-models-batch5` and fixes the issues in the previous state of the PR. Co-authored-by: Haruko386 <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…ding (#17775) ## Summary Relate to #17284. Completes the migration of the four non-OpenAI-compatible model drivers (`anthropic`, `cohere`, `google`, `bedrock`) onto the shared usage-recording path. Earlier batches (#17634, #17643, #17696–#17700) covered only the OpenAI-compatible cluster; these four providers ship wire formats that do not fit the OpenAI `choices[0].delta` / `usage` block template and so were left for a separate pass. Per the maintainer's guidance for this batch, each driver is migrated on its own terms rather than forced through a single template. The shared machinery used is intentionally small: `recordResponseUsage`, `parseChatCompletionResponse`, `BaseModel.newJSONPostRequest`, and the existing `authHeader` hook for non-Bearer auth. Co-authored-by: Haruko386 <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Summary
Relate to #17284 .
usage_parser.go:extractOpenAIUsage/extractOpenAIStreamUsagewith multi-field fallback (
prompt_tokens/input_tokens,completion_tokens/output_tokens).parser_config.go:ParserConfigstruct andOpenAIParserConfig.response_handler.go:HandleNonStreamingResponse/HandleStreamingResponseas single entry points that extract usage,populate
chatConfig.UsageResult, and emit aStreamUsagelog.base_model.gowithdoRequest/doStreamRequest.deepseekdriver to shared handlers, cutting ~100 lines.usage_parser_test.go.Testing
bash build.sh --test ./internal/entity/models/...passes.StreamUsagelog appears.