Skip to content

Go: implement provider: volcengine - #14460

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main
Apr 29, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

implement volcengine provider

Type of change

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Apr 29, 2026
@coderabbitai

coderabbitai Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The PR adds thinking/reasoning configuration to VolcEngine's model settings and implements the Chat and ChatStreamlyWithSender methods for the VolcEngine provider. These methods handle HTTP request construction, JSON marshaling, streaming via SSE, and extraction of both content and reasoning_content fields.

Changes

Cohort / File(s) Summary
Configuration Update
conf/models/volcengine.json
Enabled thinking behavior for doubao-seed-2-0-pro-260215 by adding thinking.default_value and thinking.clear_thinking settings.
Core Implementation
internal/entity/models/volcengine.go
Implemented Chat (non-streaming) and ChatStreamlyWithSender (streaming) methods with HTTP POST request handling, JSON marshaling/unmarshaling, SSE parsing via line scanner, extraction of content and reasoning_content with newline trimming, and structured logging for streaming events.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Chat Method
    participant HTTP Client
    participant VolcEngine API
    participant Response Parser

    Client->>Chat Method: Call Chat(context, message)
    Chat Method->>Chat Method: Validate message
    Chat Method->>Chat Method: Construct JSON payload<br/>(model, messages, thinking settings)
    Chat Method->>HTTP Client: POST with Bearer auth
    HTTP Client->>VolcEngine API: Send request
    VolcEngine API-->>HTTP Client: Response (HTTP 200)
    HTTP Client-->>Chat Method: Response body
    Chat Method->>Response Parser: Unmarshal JSON
    Response Parser->>Response Parser: Extract choices[0].message
    Response Parser->>Response Parser: Extract content and<br/>reasoning_content
    Response Parser-->>Chat Method: Parsed content
    Chat Method-->>Client: Return ChatResponse
Loading
sequenceDiagram
    participant Client
    participant StreamChat Method
    participant HTTP Client
    participant VolcEngine API
    participant SSE Parser
    participant Sender

    Client->>StreamChat Method: Call ChatStreamlyWithSender(context, message, sender)
    StreamChat Method->>StreamChat Method: Construct streaming<br/>JSON payload
    StreamChat Method->>HTTP Client: POST with Bearer auth
    HTTP Client->>VolcEngine API: Send request
    VolcEngine API-->>HTTP Client: SSE stream (HTTP 200)
    HTTP Client->>SSE Parser: Line scanner
    loop For each data: line
        SSE Parser->>SSE Parser: Unmarshal JSON
        SSE Parser->>SSE Parser: Extract choices[0].delta
        SSE Parser->>SSE Parser: Extract content and<br/>reasoning_content
        SSE Parser->>Sender: Send streamed content
    end
    SSE Parser->>SSE Parser: Check for [DONE]<br/>or finish_reason
    SSE Parser->>Sender: Emit final [DONE]
    Sender-->>Client: Stream complete
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Go: implement provider: Moonshot #14433: Implements similar Chat and ChatStreamlyWithSender patterns with reasoning_content extraction and SSE parsing for another provider.
  • Go: add volcengine #14409: Direct predecessor that establishes the VolcEngine integration; this PR extends it with method implementations and thinking configuration.

Suggested labels

size:L

Poem

🐰 Hops through streams of thought so deep,
VolcEngine's reasoning takes a leap,
Chats that think and answers flow,
Where content and reason dance and glow! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: implement provider: volcengine' is directly related to the changeset, which implements the VolcEngine provider with configuration and Go implementation.
Description check ✅ Passed The description addresses the required template sections: 'What problem does this PR solve?' is answered with 'implement volcengine provider', and 'Type of change' is correctly marked as 'New Feature'.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

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

@Haruko386 Haruko386 added the ci Continue Integration label Apr 29, 2026
@Haruko386
Haruko386 marked this pull request as draft April 29, 2026 06:10

@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

🧹 Nitpick comments (3)
internal/entity/models/volcengine.go (3)

102-121: Unnecessary break statements in Go switch.

Go switch cases don't fall through by default, so these break statements are redundant. Removing them improves readability.

♻️ Proposed cleanup
 			switch *modelConfig.Effort {
 			case "none", "minimal":
 				thinkingFlag = "disabled"
 				reqBody["reasoning_effort"] = "minimal"
-				break
 			case "low":
 				thinkingFlag = "enabled"
 				reqBody["reasoning_effort"] = "low"
-				break
 			case "medium":
 				thinkingFlag = "enabled"
 				reqBody["reasoning_effort"] = "medium"
-				break
 			case "auto", "default":
 				thinkingFlag = "enabled"
 				reqBody["reasoning_effort"] = "medium"
-				break
 			case "high":
 				thinkingFlag = "enabled"
 				reqBody["reasoning_effort"] = "high"
-				break
 			default:
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/volcengine.go` around lines 102 - 121, Remove the
redundant `break` statements inside the switch that sets `thinkingFlag` and
`reqBody["reasoning_effort"]` (the switch handling
"none","minimal","low","medium","auto","default","high") because Go switch cases
do not fall through by default; simply keep each case's assignments and delete
the `break` lines to improve readability in the function where `thinkingFlag`
and `reqBody` are set.

324-324: Verbose logging: consider using Debug level.

Logging every SSE line at Info level will generate excessive logs in production. Consider logger.Debug instead, or remove this line entirely.

♻️ Proposed fix
-		logger.Info(line)
+		logger.Debug(line)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/volcengine.go` at line 324, The SSE handler currently
logs every received line with logger.Info(line), which is too verbose for
production; update that call to logger.Debug(line) (or remove it entirely) so
per-line SSE data is only logged at debug level; locate the usage of
logger.Info(line) in the volcengine SSE handling code (the logger variable and
the line string) and replace it accordingly.

259-294: Consider extracting duplicated thinking/effort logic.

The thinking/effort switch logic (lines 98-133 in Chat and lines 259-294 here) is nearly identical. Consider extracting to a helper function to reduce duplication.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/volcengine.go` around lines 259 - 294, The duplicated
thinking/effort mapping in volcengine.go and Chat should be extracted into a
single helper (e.g., buildThinkingOptions or mapThinkingFromModelConfig) that
accepts the ModelConfig (or the pointers used: modelConfig.Thinking and
modelConfig.Effort) and returns (map[string]interface{}, error) or the thinking
and reasoning_effort values; replace the inline switch in volcengine.go and the
equivalent switch in Chat to call this helper, propagate any error (e.g.,
invalid effort level) and set reqBody["thinking"] and
reqBody["reasoning_effort"] from the helper's return values. Ensure the helper
is placed in a common package/file accessible to both callers and keep the same
semantics for "none/minimal" -> disabled + minimal, "auto/default" -> enabled +
medium, etc.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/entity/models/volcengine.go`:
- Line 307: The Authorization header set dereferences apiConfig.ApiKey without a
nil check; update the code around the req.Header.Set call to first verify
apiConfig.ApiKey != nil and handle the nil case (return an error, log and abort
request, or skip adding the header) so you don't dereference a nil pointer —
apply the same pattern used in Chat; reference the apiConfig.ApiKey symbol and
the req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
expression when making the change.
- Around line 360-365: The conditional that checks delta["content"] is wrong:
change the guard "ok || content != \"\"" to require both a successful type
assertion and non-empty content by using "ok && content != \"\"", matching the
reasoning_content branch; update the check around the variable content (from
delta["content"].(string)) before calling sender(&content, nil) so empty strings
are not sent.
- Around line 259-294: The nil-pointer risk occurs because modelConfig.Effort is
dereferenced when modelConfig.Thinking is true; change the logic in the block
handling modelConfig.Thinking so you first check modelConfig.Effort for nil (or
provide a safe default value) before using *modelConfig.Effort in the switch;
update the switch on effort to use the guarded value (or default like
"auto"/"default") and ensure reqBody["reasoning_effort"] and reqBody["thinking"]
are set consistently when effort is nil to avoid panics in the code paths that
use modelConfig.Effort and reqBody.
- Around line 234-236: The code currently lets modelConfig.Stream override the
streaming flag in the request body, which can disable streaming in
ChatStreamlyWithSender; remove the conditional that sets reqBody["stream"] from
modelConfig.Stream (or always set reqBody["stream"] = true) so that the
streaming flag cannot be turned off—update the logic around reqBody and
modelConfig.Stream in ChatStreamlyWithSender (and any helper constructing
reqBody) to ensure streaming remains enabled.
- Around line 98-133: The code dereferences modelConfig.Effort inside the block
guarded only by modelConfig.Thinking, which can panic if Effort is nil; update
the logic in the block that references modelConfig.Thinking (and builds
thinkingFlag and reqBody) to first check if modelConfig.Effort is nil and handle
that case (either set a safe default effort like "default"/"medium" or return a
clear error), then switch on *modelConfig.Effort; ensure reqBody["thinking"] is
still set consistently and keep the same symbols (modelConfig.Thinking,
modelConfig.Effort, thinkingFlag, reqBody) so the code never dereferences Effort
when nil.
- Line 146: The code sets the Authorization header by dereferencing
apiConfig.ApiKey without a nil check, which can panic; update the logic around
the req.Header.Set call (the Authorization header construction using fmt.Sprintf
and apiConfig.ApiKey) to first verify apiConfig.ApiKey != nil (and optionally
that *apiConfig.ApiKey is not empty) and only set the header when present,
otherwise handle the missing key path (return an error or skip setting the
header) so dereferencing is avoided.
- Line 222: The URL in the Chat function is hardcoded as "chat/completions"
instead of using the configured suffix; change the construction of url
(currently using fmt.Sprintf("%s/chat/completions", z.BaseURL[region])) to use
z.URLSuffix.Chat so the base + suffix pattern is consistent with other calls
(use z.BaseURL[region] combined with z.URLSuffix.Chat, ensuring no duplicate
slashes). Update the code path in the Chat function where url is built to
reference z.URLSuffix.Chat.

---

Nitpick comments:
In `@internal/entity/models/volcengine.go`:
- Around line 102-121: Remove the redundant `break` statements inside the switch
that sets `thinkingFlag` and `reqBody["reasoning_effort"]` (the switch handling
"none","minimal","low","medium","auto","default","high") because Go switch cases
do not fall through by default; simply keep each case's assignments and delete
the `break` lines to improve readability in the function where `thinkingFlag`
and `reqBody` are set.
- Line 324: The SSE handler currently logs every received line with
logger.Info(line), which is too verbose for production; update that call to
logger.Debug(line) (or remove it entirely) so per-line SSE data is only logged
at debug level; locate the usage of logger.Info(line) in the volcengine SSE
handling code (the logger variable and the line string) and replace it
accordingly.
- Around line 259-294: The duplicated thinking/effort mapping in volcengine.go
and Chat should be extracted into a single helper (e.g., buildThinkingOptions or
mapThinkingFromModelConfig) that accepts the ModelConfig (or the pointers used:
modelConfig.Thinking and modelConfig.Effort) and returns
(map[string]interface{}, error) or the thinking and reasoning_effort values;
replace the inline switch in volcengine.go and the equivalent switch in Chat to
call this helper, propagate any error (e.g., invalid effort level) and set
reqBody["thinking"] and reqBody["reasoning_effort"] from the helper's return
values. Ensure the helper is placed in a common package/file accessible to both
callers and keep the same semantics for "none/minimal" -> disabled + minimal,
"auto/default" -> enabled + medium, etc.
🪄 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

Run ID: cd8d347d-54b9-4e86-ad86-7a701807ac32

📥 Commits

Reviewing files that changed from the base of the PR and between a7ce1b1 and d4a78ac.

📒 Files selected for processing (2)
  • conf/models/volcengine.json
  • internal/entity/models/volcengine.go

Comment on lines +98 to +133
if modelConfig.Thinking != nil {
if *modelConfig.Thinking {
var thinkingFlag string
switch *modelConfig.Effort {
case "none", "minimal":
thinkingFlag = "disabled"
reqBody["reasoning_effort"] = "minimal"
break
case "low":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "low"
break
case "medium":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "auto", "default":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "high":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "high"
break
default:
return nil, fmt.Errorf("invalid effort level")
}
reqBody["thinking"] = map[string]interface{}{
"type": thinkingFlag,
}
} else {
reqBody["thinking"] = map[string]interface{}{
"type": "disabled",
}
}
}

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.

⚠️ Potential issue | 🟠 Major

Potential nil pointer dereference on modelConfig.Effort.

If modelConfig.Thinking is not nil and *modelConfig.Thinking is true, but modelConfig.Effort is nil, dereferencing *modelConfig.Effort on line 101 will cause a panic.

🛡️ Proposed fix to add nil check
 	if modelConfig.Thinking != nil {
 		if *modelConfig.Thinking {
+			if modelConfig.Effort == nil {
+				return nil, fmt.Errorf("effort is required when thinking is enabled")
+			}
 			var thinkingFlag string
 			switch *modelConfig.Effort {
📝 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 modelConfig.Thinking != nil {
if *modelConfig.Thinking {
var thinkingFlag string
switch *modelConfig.Effort {
case "none", "minimal":
thinkingFlag = "disabled"
reqBody["reasoning_effort"] = "minimal"
break
case "low":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "low"
break
case "medium":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "auto", "default":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "high":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "high"
break
default:
return nil, fmt.Errorf("invalid effort level")
}
reqBody["thinking"] = map[string]interface{}{
"type": thinkingFlag,
}
} else {
reqBody["thinking"] = map[string]interface{}{
"type": "disabled",
}
}
}
if modelConfig.Thinking != nil {
if *modelConfig.Thinking {
if modelConfig.Effort == nil {
return nil, fmt.Errorf("effort is required when thinking is enabled")
}
var thinkingFlag string
switch *modelConfig.Effort {
case "none", "minimal":
thinkingFlag = "disabled"
reqBody["reasoning_effort"] = "minimal"
break
case "low":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "low"
break
case "medium":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "auto", "default":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "high":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "high"
break
default:
return nil, fmt.Errorf("invalid effort level")
}
reqBody["thinking"] = map[string]interface{}{
"type": thinkingFlag,
}
} else {
reqBody["thinking"] = map[string]interface{}{
"type": "disabled",
}
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/volcengine.go` around lines 98 - 133, The code
dereferences modelConfig.Effort inside the block guarded only by
modelConfig.Thinking, which can panic if Effort is nil; update the logic in the
block that references modelConfig.Thinking (and builds thinkingFlag and reqBody)
to first check if modelConfig.Effort is nil and handle that case (either set a
safe default effort like "default"/"medium" or return a clear error), then
switch on *modelConfig.Effort; ensure reqBody["thinking"] is still set
consistently and keep the same symbols (modelConfig.Thinking,
modelConfig.Effort, thinkingFlag, reqBody) so the code never dereferences Effort
when nil.

}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))

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.

⚠️ Potential issue | 🟡 Minor

Missing nil check for apiConfig.ApiKey.

Dereferencing *apiConfig.ApiKey without a nil check could cause a panic if the API key is not provided.

🛡️ Proposed fix
+	if apiConfig.ApiKey == nil {
+		return nil, fmt.Errorf("API key is required")
+	}
+
 	req.Header.Set("Content-Type", "application/json")
 	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/volcengine.go` at line 146, The code sets the
Authorization header by dereferencing apiConfig.ApiKey without a nil check,
which can panic; update the logic around the req.Header.Set call (the
Authorization header construction using fmt.Sprintf and apiConfig.ApiKey) to
first verify apiConfig.ApiKey != nil (and optionally that *apiConfig.ApiKey is
not empty) and only set the header when present, otherwise handle the missing
key path (return an error or skip setting the header) so dereferencing is
avoided.

region = *apiConfig.Region
}

url := fmt.Sprintf("%s/chat/completions", z.BaseURL[region])

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.

⚠️ Potential issue | 🟡 Minor

URL path hardcoded instead of using URLSuffix.

The Chat function uses z.URLSuffix.Chat (line 70) but this function hardcodes chat/completions. Use the suffix for consistency.

♻️ Proposed fix
-	url := fmt.Sprintf("%s/chat/completions", z.BaseURL[region])
+	url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat)
📝 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
url := fmt.Sprintf("%s/chat/completions", z.BaseURL[region])
url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/volcengine.go` at line 222, The URL in the Chat
function is hardcoded as "chat/completions" instead of using the configured
suffix; change the construction of url (currently using
fmt.Sprintf("%s/chat/completions", z.BaseURL[region])) to use z.URLSuffix.Chat
so the base + suffix pattern is consistent with other calls (use
z.BaseURL[region] combined with z.URLSuffix.Chat, ensuring no duplicate
slashes). Update the code path in the Chat function where url is built to
reference z.URLSuffix.Chat.

Comment on lines +234 to +236
if modelConfig.Stream != nil {
reqBody["stream"] = *modelConfig.Stream
}

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.

⚠️ Potential issue | 🟡 Minor

Stream override could disable streaming.

This streaming function initializes stream: true but then allows modelConfig.Stream to potentially set it to false. For a function named ChatStreamlyWithSender, streaming should always be enabled. Consider removing this override.

♻️ Proposed fix - remove the override
-	if modelConfig.Stream != nil {
-		reqBody["stream"] = *modelConfig.Stream
-	}
📝 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 modelConfig.Stream != nil {
reqBody["stream"] = *modelConfig.Stream
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/volcengine.go` around lines 234 - 236, The code
currently lets modelConfig.Stream override the streaming flag in the request
body, which can disable streaming in ChatStreamlyWithSender; remove the
conditional that sets reqBody["stream"] from modelConfig.Stream (or always set
reqBody["stream"] = true) so that the streaming flag cannot be turned off—update
the logic around reqBody and modelConfig.Stream in ChatStreamlyWithSender (and
any helper constructing reqBody) to ensure streaming remains enabled.

Comment on lines +259 to +294
if modelConfig.Thinking != nil {
if *modelConfig.Thinking {
var thinkingFlag string
switch *modelConfig.Effort {
case "none", "minimal":
thinkingFlag = "disabled"
reqBody["reasoning_effort"] = "minimal"
break
case "low":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "low"
break
case "medium":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "auto", "default":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "high":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "high"
break
default:
return fmt.Errorf("invalid effort level")
}
reqBody["thinking"] = map[string]interface{}{
"type": thinkingFlag,
}
} else {
reqBody["thinking"] = map[string]interface{}{
"type": "disabled",
}
}
}

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.

⚠️ Potential issue | 🟠 Major

Same nil pointer dereference risk on modelConfig.Effort.

Same issue as in Chat: if modelConfig.Thinking is true but modelConfig.Effort is nil, line 262 will panic.

🛡️ Proposed fix
 	if modelConfig.Thinking != nil {
 		if *modelConfig.Thinking {
+			if modelConfig.Effort == nil {
+				return fmt.Errorf("effort is required when thinking is enabled")
+			}
 			var thinkingFlag string
 			switch *modelConfig.Effort {
📝 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 modelConfig.Thinking != nil {
if *modelConfig.Thinking {
var thinkingFlag string
switch *modelConfig.Effort {
case "none", "minimal":
thinkingFlag = "disabled"
reqBody["reasoning_effort"] = "minimal"
break
case "low":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "low"
break
case "medium":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "auto", "default":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "high":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "high"
break
default:
return fmt.Errorf("invalid effort level")
}
reqBody["thinking"] = map[string]interface{}{
"type": thinkingFlag,
}
} else {
reqBody["thinking"] = map[string]interface{}{
"type": "disabled",
}
}
}
if modelConfig.Thinking != nil {
if *modelConfig.Thinking {
if modelConfig.Effort == nil {
return fmt.Errorf("effort is required when thinking is enabled")
}
var thinkingFlag string
switch *modelConfig.Effort {
case "none", "minimal":
thinkingFlag = "disabled"
reqBody["reasoning_effort"] = "minimal"
break
case "low":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "low"
break
case "medium":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "auto", "default":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "medium"
break
case "high":
thinkingFlag = "enabled"
reqBody["reasoning_effort"] = "high"
break
default:
return fmt.Errorf("invalid effort level")
}
reqBody["thinking"] = map[string]interface{}{
"type": thinkingFlag,
}
} else {
reqBody["thinking"] = map[string]interface{}{
"type": "disabled",
}
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/volcengine.go` around lines 259 - 294, The nil-pointer
risk occurs because modelConfig.Effort is dereferenced when modelConfig.Thinking
is true; change the logic in the block handling modelConfig.Thinking so you
first check modelConfig.Effort for nil (or provide a safe default value) before
using *modelConfig.Effort in the switch; update the switch on effort to use the
guarded value (or default like "auto"/"default") and ensure
reqBody["reasoning_effort"] and reqBody["thinking"] are set consistently when
effort is nil to avoid panics in the code paths that use modelConfig.Effort and
reqBody.

}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))

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.

⚠️ Potential issue | 🟡 Minor

Missing nil check for apiConfig.ApiKey.

Same issue as in Chat - add a nil check before dereferencing.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/volcengine.go` at line 307, The Authorization header
set dereferences apiConfig.ApiKey without a nil check; update the code around
the req.Header.Set call to first verify apiConfig.ApiKey != nil and handle the
nil case (return an error, log and abort request, or skip adding the header) so
you don't dereference a nil pointer — apply the same pattern used in Chat;
reference the apiConfig.ApiKey symbol and the req.Header.Set("Authorization",
fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) expression when making the change.

Comment on lines +360 to +365
content, ok := delta["content"].(string)
if ok || content != "" {
if err := sender(&content, nil); err != nil {
return err
}
}

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.

⚠️ Potential issue | 🟠 Major

Logic error: || should be &&.

Line 361 uses ok || content != "" while line 368 uses ok && reasoningContent != "". The || will evaluate to true whenever ok is true, sending empty content strings to the sender. This is inconsistent with the reasoning_content handling and likely a typo.

🐛 Proposed fix
 		content, ok := delta["content"].(string)
-		if ok || content != "" {
+		if ok && content != "" {
 			if err := sender(&content, nil); err != nil {
 				return err
 			}
 		}
📝 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
content, ok := delta["content"].(string)
if ok || content != "" {
if err := sender(&content, nil); err != nil {
return err
}
}
content, ok := delta["content"].(string)
if ok && content != "" {
if err := sender(&content, nil); err != nil {
return err
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/volcengine.go` around lines 360 - 365, The conditional
that checks delta["content"] is wrong: change the guard "ok || content != \"\""
to require both a successful type assertion and non-empty content by using "ok
&& content != \"\"", matching the reasoning_content branch; update the check
around the variable content (from delta["content"].(string)) before calling
sender(&content, nil) so empty strings are not sent.

@Haruko386
Haruko386 marked this pull request as ready for review April 29, 2026 06:15
@codecov

codecov Bot commented Apr 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (b493a33) to head (d4a78ac).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14460   +/-   ##
=======================================
  Coverage   95.30%   95.30%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          670      670           
  Misses         16       16           
  Partials       17       17           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit decf673 into infiniflow:main Apr 29, 2026
1 check passed
TIMBLOCKER pushed a commit to TIMBLOCKER/kira that referenced this pull request Apr 29, 2026
### What problem does this PR solve?

implement `volcengine` provider 

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
@coderabbitai coderabbitai Bot mentioned this pull request Apr 30, 2026
2 of 6 tasks
@davidv399 davidv399 mentioned this pull request Apr 30, 2026
1 task done
JinHai-CN added a commit that referenced this pull request May 6, 2026
Closes #14552 

### What problem does this PR solve?

Add a Go driver for xAI (Grok models).

The config file conf/models/xai.json has been in the repo since the
early Go provider work, but internal/entity/models/factory.go had no
case for "xai". So any xAI request fell through to the dummy driver
and never reached the API. This PR adds the missing driver and wires it
up.

### What this PR includes

- New file internal/entity/models/xai.go with an XAIModel that
implements the ModelDriver interface.
- factory.go: route the "xai" provider name to NewXAIModel.

### How the driver works

- xAI exposes an OpenAI-compatible API at https://api.x.ai/v1.
- ChatWithMessages and ChatStreamlyWithSender post to /chat/completions
in the same shape the moonshot and deepseek drivers use.
- ListModels and CheckConnection call /models to confirm the API key
works and to list available model ids.
- reasoning_content is passed through for grok-3-mini and other xAI
reasoning models, both in the non-stream and stream paths.
- Encode, Rerank, and Balance are not part of the public xAI API at the
moment, so they return a clear "not implemented" or "no such method"
error.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- go build ./internal/entity/models/... in a clean go 1.25 image (the
  go.mod minimum) returns exit 0 with no errors.
- Method set of XAIModel matches the ModelDriver interface: NewInstance,
  Name, ChatWithMessages, ChatStreamlyWithSender, Encode, Rerank,
  ListModels, Balance, CheckConnection.
- Pattern parity with the merged moonshot (#14433), volcengine (#14460),
  minimax (#14478), and vllm (#14532) PRs.

---------

Co-authored-by: Jin Hai <[email protected]>
@pandadev66 pandadev66 mentioned this pull request May 7, 2026
1 task done
JinHai-CN pushed a commit that referenced this pull request May 7, 2026
### What problem does this PR solve?

Add a Go driver for OpenAI (GPT models).

The config file conf/models/openai.json has been in the repo for a while
with the full GPT-5 model list, but
internal/entity/models/factory.go had no case for "openai". So any
tenant that configured OpenAI as a model provider in the Go layer fell
through to the default branch and got the dummy driver. Chat, list
models, and check connection all returned dummy responses instead of
reaching the API.

OpenAI is the most commonly requested provider and the JSON config
already ships with the repo, so this gap is high impact even though the
JSON has been there for some time.

### What this PR includes

- New file internal/entity/models/openai.go with an OpenAIModel that
implements the ModelDriver interface.
- factory.go: route the "openai" provider name to NewOpenAIModel.
- conf/models/openai.json: add "models": "models" under url_suffix so
ListModels can hit /v1/models with no hardcoded fallback.

### How the driver works

- OpenAI exposes the canonical OpenAI-compatible API at
https://api.openai.com/v1.
- ChatWithMessages and ChatStreamlyWithSender post to /chat/completions
in the same shape the moonshot, vllm, and xai drivers use.
- ListModels and CheckConnection call /models to list available ids and
confirm the API key works.
- reasoning_content is passed through for the o-series and other
reasoning models, in both the non-stream and stream paths.
- Encode (embeddings) is left as "not implemented" for now, the same way
the other recent provider drivers do it. Rerank and Balance are not part
of OpenAI's public API surface in this layer and return a clear "not
implemented" or "no such method" error.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- go build ./internal/entity/models/... in a clean go 1.25 image (the
go.mod minimum) returns exit 0 with no errors.
- Method set of OpenAIModel matches the ModelDriver interface:
NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode,
Rerank, ListModels, Balance, CheckConnection.
- Pattern parity with the merged moonshot (#14433), volcengine (#14460),
minimax (#14478), vllm (#14532), xai (#14550), and lm-studio (#14586)
PRs.

Closes #14604
TIMBLOCKER pushed a commit to TIMBLOCKER/kira that referenced this pull request May 7, 2026
### What problem does this PR solve?

implement `volcengine` provider 

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### What problem does this PR solve?

Add a Go driver for OpenAI (GPT models).

The config file conf/models/openai.json has been in the repo for a while
with the full GPT-5 model list, but
internal/entity/models/factory.go had no case for "openai". So any
tenant that configured OpenAI as a model provider in the Go layer fell
through to the default branch and got the dummy driver. Chat, list
models, and check connection all returned dummy responses instead of
reaching the API.

OpenAI is the most commonly requested provider and the JSON config
already ships with the repo, so this gap is high impact even though the
JSON has been there for some time.

### What this PR includes

- New file internal/entity/models/openai.go with an OpenAIModel that
implements the ModelDriver interface.
- factory.go: route the "openai" provider name to NewOpenAIModel.
- conf/models/openai.json: add "models": "models" under url_suffix so
ListModels can hit /v1/models with no hardcoded fallback.

### How the driver works

- OpenAI exposes the canonical OpenAI-compatible API at
https://api.openai.com/v1.
- ChatWithMessages and ChatStreamlyWithSender post to /chat/completions
in the same shape the moonshot, vllm, and xai drivers use.
- ListModels and CheckConnection call /models to list available ids and
confirm the API key works.
- reasoning_content is passed through for the o-series and other
reasoning models, in both the non-stream and stream paths.
- Encode (embeddings) is left as "not implemented" for now, the same way
the other recent provider drivers do it. Rerank and Balance are not part
of OpenAI's public API surface in this layer and return a clear "not
implemented" or "no such method" error.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- go build ./internal/entity/models/... in a clean go 1.25 image (the
go.mod minimum) returns exit 0 with no errors.
- Method set of OpenAIModel matches the ModelDriver interface:
NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode,
Rerank, ListModels, Balance, CheckConnection.
- Pattern parity with the merged moonshot (infiniflow#14433), volcengine (infiniflow#14460),
minimax (infiniflow#14478), vllm (infiniflow#14532), xai (infiniflow#14550), and lm-studio (infiniflow#14586)
PRs.

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

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants