Skip to content

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

Merged
JinHai-CN merged 9 commits into
infiniflow:mainfrom
jay77721:feat/openai-usage-parser-v3
Jul 31, 2026
Merged

JinHai-CN merged 9 commits into
infiniflow:mainfrom
jay77721:feat/openai-usage-parser-v3

Conversation

@jay77721

Copy link
Copy Markdown
Member

Summary

Relate to #17284 .

  • 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, cutting ~100 lines.
  • Add usage_parser_test.go.

Testing

  • bash build.sh --test ./internal/entity/models/... passes.
  • Manual testing with deepseek confirms StreamUsage log appears.

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>>
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 31, 2026
@jay77721 jay77721 added the ci Continue Integration label Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Shared chat handling

Layer / File(s) Summary
Shared HTTP request helpers
internal/entity/models/base_model.go, internal/entity/models/common_test.go
BaseModel now provides timed JSON POST helpers for complete and streaming responses. The helpers set authorization headers, handle non-200 responses, wrap errors, and support JSON marshaling. Tests verify headers and successful streaming requests.
Response and usage parsing
internal/entity/models/parser_config.go, internal/entity/models/usage_parser.go, internal/entity/models/response_handler.go, internal/entity/models/usage_parser_test.go
The code adds OpenAI-compatible parser configuration, token-usage extraction, non-streaming response handling, SSE processing, content and tool-call extraction, request ID handling, and usage-parser tests.
DeepSeek shared-handler integration
internal/entity/models/deepseek.go
DeepSeek delegates non-streaming and streaming execution and response processing to the shared helpers while retaining request construction and effort 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]
Loading

Possibly related PRs

Suggested labels: 💞 feature, ☯️ refactor, 🧪 test

Suggested reviewers: haruko386

Poem

I hop through streams where tokens flow,
Shared handlers parse what providers show.
DeepSeek sends its payload bright,
JSON and SSE now share the way.
Usage counts return with every day. 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 identifies the main change: unified OpenAI-compatible token usage extraction.
Description check ✅ Passed The description includes the required Summary section, explains the changes, and documents testing results.
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.

@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: 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 win

Add a default case to the non-streaming effort switch.

The streaming path at Lines 183-184 rejects an unknown effort with invalid effort level. This switch has no default case. If Effort holds an unknown value, thinkingFlag stays 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 win

Use BaseModel.doStreamRequest for the streaming path.

The non-streaming path already uses d.baseModel.doRequest, but DeepSeekModel.ChatStreamlyWithSender still repeats request construction, timeout handing, headers, httpClient.Do, and status checking. Replace that block with d.baseModel.doStreamRequest and pass HandleStreamingResponse as 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9db2e23 and 959ae29.

📒 Files selected for processing (6)
  • internal/entity/models/base_model.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/parser_config.go
  • internal/entity/models/response_handler.go
  • internal/entity/models/usage_parser.go
  • internal/entity/models/usage_parser_test.go

Comment thread internal/entity/models/base_model.go Resolved
Comment thread internal/entity/models/base_model.go Resolved
Comment thread internal/entity/models/base_model.go Resolved
Comment thread internal/entity/models/base_model.go Resolved
Comment thread internal/entity/models/usage_parser.go Resolved
jay77721 and others added 2 commits July 31, 2026 17:29
…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]>
@jay77721
jay77721 marked this pull request as draft July 31, 2026 09:29
@jay77721
jay77721 marked this pull request as ready for review July 31, 2026 09:29
Haruko386 and others added 2 commits July 31, 2026 17:32
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@jay77721
jay77721 marked this pull request as draft July 31, 2026 09:34
@jay77721
jay77721 marked this pull request as ready for review July 31, 2026 09:34
@Haruko386 Haruko386 added the 💞 feature Feature request, pull request that fullfill a new feature. label Jul 31, 2026

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

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

📥 Commits

Reviewing files that changed from the base of the PR and between b78f79d and 16507f8.

📒 Files selected for processing (3)
  • internal/entity/models/base_model.go
  • internal/entity/models/common_test.go
  • internal/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

Comment on lines +124 to +127
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)

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

🏁 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.go

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


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

@JinHai-CN
JinHai-CN merged commit fe02c9b into infiniflow:main Jul 31, 2026
3 checks passed
JinHai-CN pushed a commit that referenced this pull request Aug 3, 2026
#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.
JinHai-CN pushed a commit that referenced this pull request Aug 3, 2026
…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]>
JinHai-CN pushed a commit that referenced this pull request Aug 3, 2026
…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]>
JinHai-CN pushed a commit that referenced this pull request Aug 3, 2026
…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]>
JinHai-CN pushed a commit that referenced this pull request Aug 3, 2026
…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]>
JinHai-CN pushed a commit that referenced this pull request Aug 3, 2026
…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]>
JinHai-CN pushed a commit that referenced this pull request Aug 4, 2026
…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]>
@jay77721
jay77721 deleted the feat/openai-usage-parser-v3 branch August 5, 2026 07:17
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. size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants