Repository navigation
Go: implement provider: 302.AI and JieKou-AI - #15034
Conversation
📝 WalkthroughWalkthroughAdds full support for two new model providers (302.AI, JieKouAI), extends CometAPI with TTS/ASR implementations, and registers providers in the model factory; changes include provider JSON configs and complete Go driver implementations. ChangesMulti-provider AI model support expansion
Sequence Diagram(s)The sequence diagrams are embedded in the hidden review stack artifact above, showing request/response flows for provider chat, streaming, embeddings, rerank, ASR, TTS, and file parsing/task operations. Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 11
🤖 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/302ai.go`:
- Around line 378-393: Several methods in AI302Model (e.g., Embed) are
dereferencing pointer inputs without checks and can panic (e.g., *modelName in
Embed, rerankConfig.TopN in rerank methods, *apiConfig.ApiKey in methods that
use APIConfig). Fix by validating pointer parameters at the top of each non-chat
method: return a clear error if modelName, apiConfig, apiConfig.ApiKey,
rerankConfig or its fields (TopN) are nil/empty before any dereference; replace
direct usages like *modelName, rerankConfig.TopN, *apiConfig.ApiKey with
safe-checked values after validation. Update functions such as Embed and the
rerank and API-using methods in AI302Model to perform these guards and return
errors instead of panicking.
- Line 313: Replace the info-level raw SSE log call common.Info(line) so it no
longer writes full stream chunks; either remove it or downgrade to debug (e.g.,
common.Debug(...)) and/or pass the payload through a sanitizer/redactor function
(e.g., RedactSSE(line) or trim to metadata/length) before logging, so
prompts/model outputs are not stored in info logs.
- Around line 212-220: In AI302Model.ChatStreamlyWithSender ensure apiConfig and
its ApiKey are validated before any dereference (check apiConfig != nil and
apiConfig.ApiKey != nil and *apiConfig.ApiKey != "" and return a descriptive
error if missing) and validate the sender callback (check sender != nil and
return an error before attempting to call it) so calls that currently
dereference apiConfig.ApiKey or invoke sender (references in the function around
where apiConfig.ApiKey is used and where sender is invoked) cannot panic; apply
the same nil checks to the other occurrences noted (the nearby usages around the
ApiKey dereference and the sender invocation).
- Around line 839-849: The code that converts result["data"] into models uses
unchecked type assertions (result["data"].([]interface{}),
model.(map[string]interface{}), modelMap["id"].(string)); replace these with
safe, checked assertions and clear errors: first assert result["data"] is
present and is a []interface{} (or return a descriptive fmt.Errorf), then for
each item assert it is a map[string]interface{} (or skip/return an error), then
check that map["id"] exists and is a string before appending to models;
reference the variables result, models, model (loop variable), modelMap and
modelName when adding these guards and return an informative error when any
assertion fails.
In `@internal/entity/models/cometapi.go`:
- Around line 662-663: The code dereferences pointers (apiConfig, modelName)
directly before use (e.g., the WriteField call that does
writer.WriteField("model", *modelName)), which can panic; add explicit nil
checks at the start of the ASR/TTS request-building routines in
internal/entity/models/cometapi.go (where writer.WriteField("model", *modelName)
and similar calls at the other noted locations occur), returning a clear
validation error (e.g., fmt.Errorf("missing modelName") or an appropriate
validation error) if apiConfig or modelName is nil, and only proceed to call
writer.WriteField and other dereferences after those checks pass.
- Around line 722-726: The error string returned in the fmt.Errorf call that
currently says "SiliconFlow ASR error" in cometapi.go is the wrong provider
name; update that message to the correct provider name (e.g., "CometAPI ASR
error") in the fmt.Errorf call that returns the ASR error (the return statement
immediately before the SiliconFlow response parsing) and sweep for any other
occurrences of "SiliconFlow ASR error" in the CometAPI driver to replace with
the correct provider label to avoid misleading logs.
- Around line 700-703: The HTTP requests created with http.NewRequest (e.g., the
req variable created at the http.NewRequest calls) lack context deadlines and
can hang; replace those calls with http.NewRequestWithContext using a context
created via context.WithTimeout (choose an appropriate timeout or use a
configured value), defer cancel() and use that ctx when building the request,
and propagate the same change to the other occurrences noted (the
http.NewRequest at the other call sites around the ASR/TTS methods). Locate the
http.NewRequest usages in cometapi.go (the req creation sites) and swap to
NewRequestWithContext(ctx, ...) where ctx comes from
context.WithTimeout(parentCtx, timeout) or the incoming method context if
present.
In `@internal/entity/models/jiekouai.go`:
- Line 281: Remove the raw SSE content logging by eliminating or replacing the
call to common.Info(line); instead log a redacted or high-level summary (e.g.,
event type, length, or masked content) or downgrade to debug-level without
payloads. Locate the common.Info(line) invocation (the log of variable `line`)
and either remove it or change it to a safe/logging helper that returns a
sanitized string (no user/model data) before logging, ensuring no raw stream
data is written to info logs.
- Around line 192-200: The ChatStreamlyWithSender method can panic because
apiConfig.ApiKey is dereferenced without checking apiConfig and sender is
invoked without nil checks; in JieKouAIModel.ChatStreamlyWithSender add upfront
validation to return a clear error if apiConfig is nil or apiConfig.ApiKey is
nil/empty, and return an error if the sender callback is nil, and then use the
validated values for any later dereferences and calls (references: method
ChatStreamlyWithSender, apiConfig.ApiKey dereference around lines ~264-265, and
sender invocations around ~319-327).
- Around line 555-565: The code currently performs unsafe type assertions on
result["data"] and its elements (result["data"].([]interface{}),
model.(map[string]interface{}), modelMap["id"].(string)) which can panic on
malformed upstream JSON; change the parsing to safe checks: verify
result["data"] exists and is a []interface{} (using the comma-ok form), iterate
with type-assertion guards for each element ensuring it's a
map[string]interface{} (or handle map[string]interface{} vs
map[interface{}]interface{}), check that the "id" key exists and convert it to
string safely (handle cases where it may be json.Number or other types), skip or
return a clear error for invalid entries instead of panicking, and populate
models accordingly (update the loop around model, modelMap, and modelName to use
these safe checks).
- Around line 346-360: In methods like Embed (JieKouAIModel.Embed), Rerank (the
function using rerankConfig.TopN) and any callers that dereference
apiConfig.ApiKey, add explicit nil checks before dereferencing pointers:
validate modelName != nil and *modelName != "" in Embed, validate apiConfig !=
nil and apiConfig.ApiKey != nil (and non-empty) before using *apiConfig.ApiKey,
and validate rerankConfig != nil before accessing rerankConfig.TopN; on any
nil/invalid pointer return a clear typed error (e.g., fmt.Errorf with contextual
message) instead of letting a panic occur. Ensure these checks reference the
exact symbols: JieKouAIModel.Embed, rerankConfig.TopN, and apiConfig.ApiKey so
the fixes are applied in the three indicated regions (around the current Embed
block and the blocks that handle rerankConfig and apiConfig).
🪄 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: dc49d4bd-8b10-491f-9dbd-0faa021a3ff1
📒 Files selected for processing (7)
conf/models/302ai.jsonconf/models/cometapi.jsonconf/models/jiekouai.jsoninternal/entity/models/302ai.gointernal/entity/models/cometapi.gointernal/entity/models/factory.gointernal/entity/models/jiekouai.go
| func (a *AI302Model) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error { | ||
| if len(messages) == 0 { | ||
| return fmt.Errorf("messages is empty") | ||
| } | ||
|
|
||
| var region = "default" | ||
| if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } |
There was a problem hiding this comment.
Validate apiConfig and sender before streaming.
Line 296 dereferences apiConfig.ApiKey without nil checks, and Lines 351/358 call sender without validating it. Both can panic at runtime.
Suggested fix
func (a *AI302Model) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error {
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return fmt.Errorf("api key is required")
+ }
+ if sender == nil {
+ return fmt.Errorf("sender is required")
+ }
if len(messages) == 0 {
return fmt.Errorf("messages is empty")
}Also applies to: 295-297, 351-359
🤖 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/302ai.go` around lines 212 - 220, In
AI302Model.ChatStreamlyWithSender ensure apiConfig and its ApiKey are validated
before any dereference (check apiConfig != nil and apiConfig.ApiKey != nil and
*apiConfig.ApiKey != "" and return a descriptive error if missing) and validate
the sender callback (check sender != nil and return an error before attempting
to call it) so calls that currently dereference apiConfig.ApiKey or invoke
sender (references in the function around where apiConfig.ApiKey is used and
where sender is invoked) cannot panic; apply the same nil checks to the other
occurrences noted (the nearby usages around the ApiKey dereference and the
sender invocation).
| scanner := bufio.NewScanner(resp.Body) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| common.Info(line) |
There was a problem hiding this comment.
Avoid logging raw SSE payloads at info level.
Line 313 logs full stream chunks, which can include prompts/model output and leak sensitive content into logs.
🤖 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/302ai.go` at line 313, Replace the info-level raw SSE
log call common.Info(line) so it no longer writes full stream chunks; either
remove it or downgrade to debug (e.g., common.Debug(...)) and/or pass the
payload through a sanitizer/redactor function (e.g., RedactSSE(line) or trim to
metadata/length) before logging, so prompts/model outputs are not stored in info
logs.
| func (a *AI302Model) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) { | ||
| if len(texts) == 0 { | ||
| return []EmbeddingData{}, nil | ||
| } | ||
|
|
||
| var region = "default" | ||
| if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", a.BaseURL[region], a.URLSuffix.Embedding) | ||
|
|
||
| reqBody := map[string]interface{}{ | ||
| "model": *modelName, | ||
| "input": texts, | ||
| } |
There was a problem hiding this comment.
Guard pointer inputs across non-chat methods to prevent panics.
There are unchecked dereferences in multiple methods (e.g., Line 391 *modelName, Line 461 rerankConfig.TopN, Line 821 *apiConfig.ApiKey). Invalid caller input will crash instead of returning a normal error.
Also applies to: 449-471, 524-535, 650-673, 800-822
🤖 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/302ai.go` around lines 378 - 393, Several methods in
AI302Model (e.g., Embed) are dereferencing pointer inputs without checks and can
panic (e.g., *modelName in Embed, rerankConfig.TopN in rerank methods,
*apiConfig.ApiKey in methods that use APIConfig). Fix by validating pointer
parameters at the top of each non-chat method: return a clear error if
modelName, apiConfig, apiConfig.ApiKey, rerankConfig or its fields (TopN) are
nil/empty before any dereference; replace direct usages like *modelName,
rerankConfig.TopN, *apiConfig.ApiKey with safe-checked values after validation.
Update functions such as Embed and the rerank and API-using methods in
AI302Model to perform these guards and return errors instead of panicking.
| var result map[string]interface{} | ||
| if err = json.Unmarshal(body, &result); err != nil { | ||
| return nil, fmt.Errorf("failed to parse response: %w", err) | ||
| } | ||
|
|
||
| // convert result["data"] to []map[string]interface{} | ||
| models := make([]string, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) |
There was a problem hiding this comment.
Replace unchecked JSON type assertions in model parsing.
Lines 846-848 assert external response fields directly (result["data"].([]interface{}), model.(map[string]interface{}), ["id"].(string)). Any upstream shape change will panic this path.
🤖 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/302ai.go` around lines 839 - 849, The code that
converts result["data"] into models uses unchecked type assertions
(result["data"].([]interface{}), model.(map[string]interface{}),
modelMap["id"].(string)); replace these with safe, checked assertions and clear
errors: first assert result["data"] is present and is a []interface{} (or return
a descriptive fmt.Errorf), then for each item assert it is a
map[string]interface{} (or skip/return an error), then check that map["id"]
exists and is a string before appending to models; reference the variables
result, models, model (loop variable), modelMap and modelName when adding these
guards and return an informative error when any assertion fails.
| if err := writer.WriteField("model", *modelName); err != nil { | ||
| return nil, fmt.Errorf("failed to write model field: %w", err) |
There was a problem hiding this comment.
Validate apiConfig and modelName before dereference in ASR/TTS.
These lines dereference pointers directly; nil values will panic (instead of returning user-facing validation errors).
Also applies to: 705-706, 755-756, 779-780
🤖 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/cometapi.go` around lines 662 - 663, The code
dereferences pointers (apiConfig, modelName) directly before use (e.g., the
WriteField call that does writer.WriteField("model", *modelName)), which can
panic; add explicit nil checks at the start of the ASR/TTS request-building
routines in internal/entity/models/cometapi.go (where writer.WriteField("model",
*modelName) and similar calls at the other noted locations occur), returning a
clear validation error (e.g., fmt.Errorf("missing modelName") or an appropriate
validation error) if apiConfig or modelName is nil, and only proceed to call
writer.WriteField and other dereferences after those checks pass.
| return nil, fmt.Errorf("SiliconFlow ASR error: %s - %s", resp.Status, string(respBody)) | ||
| } | ||
|
|
||
| // SiliconFlow response | ||
| var result struct { |
There was a problem hiding this comment.
Fix provider name in ASR error text.
Line 722 reports "SiliconFlow ASR error" in the CometAPI driver, which makes troubleshooting misleading.
🤖 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/cometapi.go` around lines 722 - 726, The error string
returned in the fmt.Errorf call that currently says "SiliconFlow ASR error" in
cometapi.go is the wrong provider name; update that message to the correct
provider name (e.g., "CometAPI ASR error") in the fmt.Errorf call that returns
the ASR error (the return statement immediately before the SiliconFlow response
parsing) and sweep for any other occurrences of "SiliconFlow ASR error" in the
CometAPI driver to replace with the correct provider label to avoid misleading
logs.
| func (j *JieKouAIModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error { | ||
| if len(messages) == 0 { | ||
| return fmt.Errorf("messages is empty") | ||
| } | ||
|
|
||
| var region = "default" | ||
| if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } |
There was a problem hiding this comment.
Validate apiConfig and sender before streaming.
Line 264 dereferences apiConfig.ApiKey without guard, and Lines 319/326 call sender without nil validation. This can panic on invalid input.
Also applies to: 264-265, 319-327
🤖 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/jiekouai.go` around lines 192 - 200, The
ChatStreamlyWithSender method can panic because apiConfig.ApiKey is dereferenced
without checking apiConfig and sender is invoked without nil checks; in
JieKouAIModel.ChatStreamlyWithSender add upfront validation to return a clear
error if apiConfig is nil or apiConfig.ApiKey is nil/empty, and return an error
if the sender callback is nil, and then use the validated values for any later
dereferences and calls (references: method ChatStreamlyWithSender,
apiConfig.ApiKey dereference around lines ~264-265, and sender invocations
around ~319-327).
| scanner := bufio.NewScanner(resp.Body) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| common.Info(line) |
There was a problem hiding this comment.
Remove raw stream logging from info logs.
Line 281 logs raw SSE content, which may contain user/model data and create privacy/compliance risk in production logs.
🤖 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/jiekouai.go` at line 281, Remove the raw SSE content
logging by eliminating or replacing the call to common.Info(line); instead log a
redacted or high-level summary (e.g., event type, length, or masked content) or
downgrade to debug-level without payloads. Locate the common.Info(line)
invocation (the log of variable `line`) and either remove it or change it to a
safe/logging helper that returns a sanitized string (no user/model data) before
logging, ensuring no raw stream data is written to info logs.
| func (j *JieKouAIModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) { | ||
| if len(texts) == 0 { | ||
| return []EmbeddingData{}, fmt.Errorf("texts is empty") | ||
| } | ||
|
|
||
| var region = "default" | ||
| if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", strings.TrimSuffix(j.BaseURL[region], "/"), j.URLSuffix.Embedding) | ||
|
|
||
| reqBody := map[string]interface{}{ | ||
| "model": *modelName, | ||
| "input": texts, |
There was a problem hiding this comment.
Add missing nil checks for pointer configs and model pointers.
Several methods dereference pointers without validation (for example Line 359 *modelName, Line 429 rerankConfig.TopN, Line 537 *apiConfig.ApiKey), which can crash instead of returning a typed error.
Also applies to: 417-439, 516-537
🤖 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/jiekouai.go` around lines 346 - 360, In methods like
Embed (JieKouAIModel.Embed), Rerank (the function using rerankConfig.TopN) and
any callers that dereference apiConfig.ApiKey, add explicit nil checks before
dereferencing pointers: validate modelName != nil and *modelName != "" in Embed,
validate apiConfig != nil and apiConfig.ApiKey != nil (and non-empty) before
using *apiConfig.ApiKey, and validate rerankConfig != nil before accessing
rerankConfig.TopN; on any nil/invalid pointer return a clear typed error (e.g.,
fmt.Errorf with contextual message) instead of letting a panic occur. Ensure
these checks reference the exact symbols: JieKouAIModel.Embed,
rerankConfig.TopN, and apiConfig.ApiKey so the fixes are applied in the three
indicated regions (around the current Embed block and the blocks that handle
rerankConfig and apiConfig).
| var result map[string]interface{} | ||
| if err = json.Unmarshal(body, &result); err != nil { | ||
| return nil, fmt.Errorf("failed to parse response: %w", err) | ||
| } | ||
|
|
||
| // convert result["data"] to []map[string]interface{} | ||
| models := make([]string, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) |
There was a problem hiding this comment.
Use safe parsing for external model-catalog JSON.
The direct assertions in Lines 562-564 can panic if the upstream payload is non-conforming or error-shaped.
🤖 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/jiekouai.go` around lines 555 - 565, The code
currently performs unsafe type assertions on result["data"] and its elements
(result["data"].([]interface{}), model.(map[string]interface{}),
modelMap["id"].(string)) which can panic on malformed upstream JSON; change the
parsing to safe checks: verify result["data"] exists and is a []interface{}
(using the comma-ok form), iterate with type-assertion guards for each element
ensuring it's a map[string]interface{} (or handle map[string]interface{} vs
map[interface{}]interface{}), check that the "id" key exists and convert it to
string safely (handle cases where it may be json.Number or other types), skip or
return a clear error for invalid entries instead of panicking, and populate
models accordingly (update the loop around model, modelMap, and modelName to use
these safe checks).
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15034 +/- ##
=======================================
Coverage 93.12% 93.12%
=======================================
Files 10 10
Lines 713 713
Branches 116 116
=======================================
Hits 664 664
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 9
🤖 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/302ai.go`:
- Around line 97-100: The ChatWithMessages request currently includes
chatModelConfig.Stream into the outgoing reqBody which can trigger upstream SSE
while the code expects a single JSON response; in the ChatWithMessages handler
ensure you do not set the "stream" field when building reqBody (either omit the
key entirely or override it to false) — locate the code that reads
chatModelConfig.Stream and stops adding reqBody["stream"] when preparing the
request for ChatWithMessages (reference symbols: ChatWithMessages,
chatModelConfig.Stream, reqBody).
- Around line 855-857: The Balance method on type AI302Model currently returns a
"no such method" error; implement it to actually fetch and return the account
balance using the 302.AI API: use the existing APIConfig parameter, construct
and send the appropriate HTTP request (or call the shared client helper used by
other models), parse the JSON response into a map[string]interface{} and return
it, and return any encountered error; update the AI302Model.Balance
implementation to mirror the pattern used by other model implementations (refer
to other models' Balance methods for request/response handling and error
wrapping) and keep function signature Balance(apiConfig *APIConfig)
(map[string]interface{}, error).
- Around line 241-244: The ChatStreamlyWithSender method currently respects
modelConfig.Stream and may set reqBody["stream"] = false which breaks the SSE
parsing; always keep streaming enabled by ensuring reqBody["stream"] is set to
true (or never set to false) regardless of modelConfig.Stream inside
ChatStreamlyWithSender so the SSE parser continues to receive a stream; update
the block that references modelConfig and Stream (the code that sets
reqBody["stream"]) to unconditionally enable streaming.
- Around line 369-375: The code currently sends the endOfStream "[DONE]" marker
before checking scanner.Err(), which can make truncated reads appear successful;
change the control flow in the function that uses scanner and sender so you
first finish scanning, check err := scanner.Err(), and only if err == nil call
sender(&endOfStream, nil) and return nil, otherwise return the scanner error
without sending the "[DONE]" marker (reference the symbols scanner, sender and
endOfStream to locate the change).
In `@internal/entity/models/factory.go`:
- Around line 112-115: The switch in factory.go currently matches the driver
identifier "302.ai" but AI302Model.Name() returns "302ai", causing round-trips
to fall back to NewDummyModel; update the switch in the function that returns
models to accept the driver's own identifier by adding a case for "302ai" (or
replace "302.ai" with "302ai"), so that NewAI302Model(baseURL, urlSuffix) is
returned when the model name equals AI302Model.Name(); ensure the case uses the
exact string returned by AI302Model.Name() to avoid future mismatches
(references: NewAI302Model, AI302Model.Name, NewDummyModel).
In `@internal/entity/models/jiekouai.go`:
- Around line 337-343: The code currently sends the OpenAI terminal marker
endOfStream ("[DONE]") before checking scanner.Err(), which can mark a truncated
stream as complete; change the order so you first evaluate scanner.Err() (call
scanner.Err() and return any non-nil error) and only call sender(&endOfStream,
nil) if scanner.Err() is nil (i.e., the scan succeeded). Update the block around
sender, endOfStream and scanner.Err() to perform the error check first and then
emit the "[DONE]" marker using sender.
- Around line 89-92: In ChatWithMessages stop flipping the request into SSE mode
by copying chatModelConfig.Stream into reqBody; specifically remove or ignore
the assignment that sets reqBody["stream"] from chatModelConfig.Stream so this
method does not enable streaming itself (reference ChatWithMessages,
chatModelConfig.Stream, and reqBody["stream"]); streaming should only be
enabled/handled by the caller/transport layer or by dedicated streaming code
path that properly decodes SSE, not by this JSON decode path.
- Around line 111-115: The request builders only set reqBody["enable_thinking"]
when chatModelConfig.Thinking is true, so a false value never gets forwarded;
update both places using chatModelConfig.Thinking to check for non-nil and
always set reqBody["enable_thinking"]=*chatModelConfig.Thinking when Thinking !=
nil (instead of only when true) so false is explicitly sent; locate the
occurrences referencing chatModelConfig.Thinking and reqBody["enable_thinking"]
in this file and apply the same change in the other builder occurrence as well.
- Around line 221-224: The code currently writes reqBody["stream"] from
modelConfig.Stream even when false, which causes ChatStreamlyWithSender to parse
SSE for non-stream responses; change the logic so you only set reqBody["stream"]
= true when modelConfig.Stream is non-nil and true (i.e., if modelConfig != nil
&& modelConfig.Stream != nil && *modelConfig.Stream == true) and do not set or
send the "stream" field when modelConfig.Stream is nil or false so streaming
mode remains the default for ChatStreamlyWithSender and normal JSON responses
are not treated as SSE.
🪄 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: 0f5fb4bf-f415-4050-b424-8daa5a1cb289
📒 Files selected for processing (7)
conf/models/302ai.jsonconf/models/cometapi.jsonconf/models/jiekouai.jsoninternal/entity/models/302ai.gointernal/entity/models/cometapi.gointernal/entity/models/factory.gointernal/entity/models/jiekouai.go
✅ Files skipped from review due to trivial changes (1)
- conf/models/cometapi.json
| if chatModelConfig != nil { | ||
| if chatModelConfig.Stream != nil { | ||
| reqBody["stream"] = *chatModelConfig.Stream | ||
| } |
There was a problem hiding this comment.
Don't let ChatWithMessages request a stream.
If chatModelConfig.Stream is true, this path asks upstream for SSE and then tries to parse the response as a single JSON object.
🤖 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/302ai.go` around lines 97 - 100, The ChatWithMessages
request currently includes chatModelConfig.Stream into the outgoing reqBody
which can trigger upstream SSE while the code expects a single JSON response; in
the ChatWithMessages handler ensure you do not set the "stream" field when
building reqBody (either omit the key entirely or override it to false) — locate
the code that reads chatModelConfig.Stream and stops adding reqBody["stream"]
when preparing the request for ChatWithMessages (reference symbols:
ChatWithMessages, chatModelConfig.Stream, reqBody).
| if modelConfig != nil { | ||
| if modelConfig.Stream != nil { | ||
| reqBody["stream"] = *modelConfig.Stream | ||
| } |
There was a problem hiding this comment.
Keep streaming enabled in ChatStreamlyWithSender.
This method still parses the response as SSE, so honoring modelConfig.Stream=false will make it consume a normal JSON body with the wrong parser.
🤖 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/302ai.go` around lines 241 - 244, The
ChatStreamlyWithSender method currently respects modelConfig.Stream and may set
reqBody["stream"] = false which breaks the SSE parsing; always keep streaming
enabled by ensuring reqBody["stream"] is set to true (or never set to false)
regardless of modelConfig.Stream inside ChatStreamlyWithSender so the SSE parser
continues to receive a stream; update the block that references modelConfig and
Stream (the code that sets reqBody["stream"]) to unconditionally enable
streaming.
| // Send [DONE] marker for OpenAI compatibility | ||
| endOfStream := "[DONE]" | ||
| if err = sender(&endOfStream, nil); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| return scanner.Err() |
There was a problem hiding this comment.
Emit [DONE] only after the scan succeeds.
A read error currently sends the terminal marker first, so callers can treat a truncated stream as a successful completion.
Suggested fix
- // Send [DONE] marker for OpenAI compatibility
- endOfStream := "[DONE]"
- if err = sender(&endOfStream, nil); err != nil {
- return err
- }
-
- return scanner.Err()
+ if err := scanner.Err(); err != nil {
+ return err
+ }
+
+ endOfStream := "[DONE]"
+ return sender(&endOfStream, nil)📝 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.
| // Send [DONE] marker for OpenAI compatibility | |
| endOfStream := "[DONE]" | |
| if err = sender(&endOfStream, nil); err != nil { | |
| return err | |
| } | |
| return scanner.Err() | |
| if err := scanner.Err(); err != nil { | |
| return err | |
| } | |
| endOfStream := "[DONE]" | |
| return sender(&endOfStream, nil) |
🤖 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/302ai.go` around lines 369 - 375, The code currently
sends the endOfStream "[DONE]" marker before checking scanner.Err(), which can
make truncated reads appear successful; change the control flow in the function
that uses scanner and sender so you first finish scanning, check err :=
scanner.Err(), and only if err == nil call sender(&endOfStream, nil) and return
nil, otherwise return the scanner error without sending the "[DONE]" marker
(reference the symbols scanner, sender and endOfStream to locate the change).
| func (a *AI302Model) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { | ||
| return nil, fmt.Errorf("%s no such method", a.Name()) | ||
| } |
There was a problem hiding this comment.
Balance is still unimplemented.
The PR objective says 302.AI balance is supported, but this method still returns no such method.
🤖 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/302ai.go` around lines 855 - 857, The Balance method
on type AI302Model currently returns a "no such method" error; implement it to
actually fetch and return the account balance using the 302.AI API: use the
existing APIConfig parameter, construct and send the appropriate HTTP request
(or call the shared client helper used by other models), parse the JSON response
into a map[string]interface{} and return it, and return any encountered error;
update the AI302Model.Balance implementation to mirror the pattern used by other
model implementations (refer to other models' Balance methods for
request/response handling and error wrapping) and keep function signature
Balance(apiConfig *APIConfig) (map[string]interface{}, error).
| case "jiekouai": | ||
| return NewJieKouAIModel(baseURL, urlSuffix), nil | ||
| case "302.ai": | ||
| return NewAI302Model(baseURL, urlSuffix), nil |
There was a problem hiding this comment.
Accept the driver's own 302.AI identifier.
AI302Model.Name() returns "302ai", but this switch only matches "302.ai". Any code that round-trips through Name() will fall through to NewDummyModel.
Suggested fix
- case "302.ai":
+ case "302.ai", "302ai":
return NewAI302Model(baseURL, urlSuffix), nil📝 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.
| case "jiekouai": | |
| return NewJieKouAIModel(baseURL, urlSuffix), nil | |
| case "302.ai": | |
| return NewAI302Model(baseURL, urlSuffix), nil | |
| case "jiekouai": | |
| return NewJieKouAIModel(baseURL, urlSuffix), nil | |
| case "302.ai", "302ai": | |
| return NewAI302Model(baseURL, urlSuffix), nil |
🤖 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/factory.go` around lines 112 - 115, The switch in
factory.go currently matches the driver identifier "302.ai" but
AI302Model.Name() returns "302ai", causing round-trips to fall back to
NewDummyModel; update the switch in the function that returns models to accept
the driver's own identifier by adding a case for "302ai" (or replace "302.ai"
with "302ai"), so that NewAI302Model(baseURL, urlSuffix) is returned when the
model name equals AI302Model.Name(); ensure the case uses the exact string
returned by AI302Model.Name() to avoid future mismatches (references:
NewAI302Model, AI302Model.Name, NewDummyModel).
| if chatModelConfig != nil { | ||
| if chatModelConfig.Stream != nil { | ||
| reqBody["stream"] = *chatModelConfig.Stream | ||
| } |
There was a problem hiding this comment.
Don't let ChatWithMessages switch itself into streaming mode.
If chatModelConfig.Stream is true, this method requests SSE and then tries to decode it as one JSON payload.
🤖 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/jiekouai.go` around lines 89 - 92, In ChatWithMessages
stop flipping the request into SSE mode by copying chatModelConfig.Stream into
reqBody; specifically remove or ignore the assignment that sets
reqBody["stream"] from chatModelConfig.Stream so this method does not enable
streaming itself (reference ChatWithMessages, chatModelConfig.Stream, and
reqBody["stream"]); streaming should only be enabled/handled by the
caller/transport layer or by dedicated streaming code path that properly decodes
SSE, not by this JSON decode path.
| if chatModelConfig.Thinking != nil { | ||
| if *chatModelConfig.Thinking { | ||
| reqBody["enable_thinking"] = *chatModelConfig.Thinking | ||
| } | ||
| } |
There was a problem hiding this comment.
Forward Thinking=false explicitly.
Both request builders only set enable_thinking when it is true, so callers cannot actually disable reasoning for models that default to it.
Suggested fix
- if chatModelConfig.Thinking != nil {
- if *chatModelConfig.Thinking {
- reqBody["enable_thinking"] = *chatModelConfig.Thinking
- }
- }
+ if chatModelConfig.Thinking != nil {
+ reqBody["enable_thinking"] = *chatModelConfig.Thinking
+ }- if modelConfig.Thinking != nil {
- if *modelConfig.Thinking {
- reqBody["enable_thinking"] = *modelConfig.Thinking
- }
- }
+ if modelConfig.Thinking != nil {
+ reqBody["enable_thinking"] = *modelConfig.Thinking
+ }Also applies to: 246-249
🤖 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/jiekouai.go` around lines 111 - 115, The request
builders only set reqBody["enable_thinking"] when chatModelConfig.Thinking is
true, so a false value never gets forwarded; update both places using
chatModelConfig.Thinking to check for non-nil and always set
reqBody["enable_thinking"]=*chatModelConfig.Thinking when Thinking != nil
(instead of only when true) so false is explicitly sent; locate the occurrences
referencing chatModelConfig.Thinking and reqBody["enable_thinking"] in this file
and apply the same change in the other builder occurrence as well.
| if modelConfig != nil { | ||
| if modelConfig.Stream != nil { | ||
| reqBody["stream"] = *modelConfig.Stream | ||
| } |
There was a problem hiding this comment.
Keep ChatStreamlyWithSender in streaming mode.
This code always parses SSE events, so honoring modelConfig.Stream=false will make a normal JSON response look like an empty 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/jiekouai.go` around lines 221 - 224, The code
currently writes reqBody["stream"] from modelConfig.Stream even when false,
which causes ChatStreamlyWithSender to parse SSE for non-stream responses;
change the logic so you only set reqBody["stream"] = true when
modelConfig.Stream is non-nil and true (i.e., if modelConfig != nil &&
modelConfig.Stream != nil && *modelConfig.Stream == true) and do not set or send
the "stream" field when modelConfig.Stream is nil or false so streaming mode
remains the default for ChatStreamlyWithSender and normal JSON responses are not
treated as SSE.
| // Send [DONE] marker for OpenAI compatibility | ||
| endOfStream := "[DONE]" | ||
| if err = sender(&endOfStream, nil); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| return scanner.Err() |
There was a problem hiding this comment.
Emit [DONE] only after the scan succeeds.
A read error currently sends the terminal marker first, so downstream code can mark a truncated stream as complete.
🤖 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/jiekouai.go` around lines 337 - 343, The code
currently sends the OpenAI terminal marker endOfStream ("[DONE]") before
checking scanner.Err(), which can mark a truncated stream as complete; change
the order so you first evaluate scanner.Err() (call scanner.Err() and return any
non-nil error) and only call sender(&endOfStream, nil) if scanner.Err() is nil
(i.e., the scan succeeded). Update the block around sender, endOfStream and
scanner.Err() to perform the error check first and then emit the "[DONE]" marker
using sender.
What problem does this PR solve?
This PR implement implement provider 302.AI and JieKouAI
The following functionalities are now supported:
302.ai
List Tasks!JieKouAI
Verified examples from the CLI:
Type of change