Repository navigation
Go: implement provider: 302.AI, JieKouAI - #15000
Conversation
📝 WalkthroughWalkthroughThis PR adds support for two new AI model providers—JieKouAI and 302.AI—by contributing configuration files that define their endpoints and model registries, Go driver implementations that handle chat (with streaming and thinking/reasoning), embeddings, reranking, and specialized operations like audio transcription and OCR, and factory registration to route provider names to the correct drivers. ChangesJieKouAI and 302.AI Provider Integration
Sequence DiagramssequenceDiagram
participant Client
participant JieKouAIDriver
participant JieKouAIAPI
Client->>JieKouAIDriver: ChatWithMessages(messages, config)
JieKouAIDriver->>JieKouAIAPI: POST /v1/chat/completions with enable_thinking
JieKouAIAPI-->>JieKouAIDriver: reasoning_content + content
JieKouAIDriver-->>Client: ChatResponse with reasoning
Client->>JieKouAIDriver: ChatStreamlyWithSender(messages, sender callback)
JieKouAIDriver->>JieKouAIAPI: POST /v1/chat/completions stream=true
JieKouAIAPI-->>JieKouAIDriver: SSE data: events with delta.reasoning_content/content
JieKouAIDriver->>JieKouAIDriver: Parse each data: line
JieKouAIDriver->>Client: sender(reasoning, content) per delta
JieKouAIDriver-->>Client: sender([DONE]) final marker
Client->>JieKouAIDriver: Embed(texts, model)
JieKouAIDriver->>JieKouAIAPI: POST /v1/embeddings
JieKouAIAPI-->>JieKouAIDriver: data[].embedding
JieKouAIDriver-->>Client: []EmbeddingData
sequenceDiagram
participant Client
participant AI302Driver
participant AI302API
participant MinerU
Client->>AI302Driver: ChatStreamlyWithSender(messages, sender)
AI302API-->>AI302Driver: SSE delta.content + delta.reasoning_content
AI302Driver-->>Client: sender(reasoning, content) chunks
Client->>AI302Driver: TranscribeAudio(file)
AI302Driver->>AI302API: POST /v1/audio/transcriptions multipart/form-data
AI302API-->>AI302Driver: text
AI302Driver-->>Client: ASRResponse
Client->>AI302Driver: OCRFile(content/url)
AI302Driver->>AI302API: POST /v1/ocr document_url
AI302API-->>AI302Driver: pages[].markdown
AI302Driver-->>Client: OCRFileResponse.Text
Client->>AI302Driver: ParseFile(documentURL)
AI302Driver->>AI302API: POST /v1/parse document_url
AI302API->>MinerU: Submit task
MinerU-->>AI302API: taskID
AI302API-->>AI302Driver: taskID
AI302Driver-->>Client: ParseFileResponse with taskID
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: 12
🤖 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 212-216: ChatStreamlyWithSender dereferences *apiConfig.ApiKey
without nil-checks; add explicit validation at the start of
ChatStreamlyWithSender that apiConfig != nil and apiConfig.ApiKey != nil and
*apiConfig.ApiKey != "" (return a clear error like "apiConfig or ApiKey is
nil/empty"), then use the validated api key variable wherever *apiConfig.ApiKey
was used (or call a small helper getAPIKey(apiConfig) that performs the same
checks) so no further dereferences occur without validation.
- Around line 192-202: The current block around reasonContent in function
handling chatModelConfig (checking chatModelConfig.Thinking) treats a missing or
null messageMap["reasoning_content"] as a type assertion failure; change it so
that if the key is absent or value is nil you set reasonContent = "" (empty) and
only perform the string type assertion when the value exists and is non-nil;
update the logic that reads messageMap["reasoning_content"] so it first checks
presence (e.g., val, exists := messageMap["reasoning_content"]) and only returns
an error if the value exists but is not a string, otherwise treat missing/null
as empty and keep the existing newline-trimming behavior.
- Around line 378-406: The Embed method in AI302Model dereferences modelName and
apiConfig.ApiKey without validating them; add nil/empty checks at the start of
Embed (function AI302Model.Embed) to return a clear error if modelName is nil or
empty and if apiConfig is nil or apiConfig.ApiKey is nil/empty (also validate
apiConfig.Region use if needed), so subsequent uses of *modelName and
*apiConfig.ApiKey are safe; update any existing early-return for empty texts to
occur after these validations and ensure error messages reference the parameter
names (modelName, apiConfig.ApiKey) for clarity.
- Around line 844-850: The code block that builds models from result["data"]
uses unsafe type assertions (result["data"].([]interface{}),
model.(map[string]interface{}), modelMap["id"].(string)) which can panic; update
the logic in the function that populates the models slice to use comma-ok style
checks: first assert result["data"] is a []interface{} (ok check), iterate and
for each item assert it's a map[string]interface{} (ok check), then assert the
"id" value is a string (ok check); on any failed assertion either skip that
entry or return/propagate an error/log a warning instead of letting the code
panic, ensuring models (the slice) is built only from validated values.
- Around line 449-484: In AI302Model.Rerank, add nil checks and clear error
returns for rerankConfig, modelName, and apiConfig/ApiKey before dereferencing
them; remove the redundant topN assignment so you only set topN once (use
rerankConfig.TopN when rerankConfig != nil and non-zero, otherwise keep
default), validate modelName is non-nil before using *modelName, and validate
apiConfig and apiConfig.ApiKey are non-nil/non-empty before using
*apiConfig.ApiKey; update error messages to indicate which parameter was nil
(referencing symbols: Rerank, rerankConfig, topN, modelName, apiConfig, ApiKey).
- Around line 524-605: The TranscribeAudio method dereferences apiConfig.ApiKey
without validating apiConfig and ApiKey; update TranscribeAudio to check that
apiConfig is non-nil and apiConfig.ApiKey is non-nil and not empty before using
it (return a clear error like "api key is missing"), and only set the
Authorization header when the key is present; reference the TranscribeAudio
function and the APIConfig.ApiKey field to locate where to add this validation
and early return.
- Around line 650-693: The OCRFile method dereferences apiConfig and
apiConfig.ApiKey without checking for nil/empty; add validation at the start of
AI302Model.OCRFile to ensure apiConfig is not nil and apiConfig.ApiKey is
non-nil and non-empty, returning an error like "api key is required" if
validation fails; update any early-return logic before using apiConfig.Region
and before setting the Authorization header so that apiConfig and its ApiKey are
guaranteed valid when used.
In `@internal/entity/models/jiekouai.go`:
- Around line 192-196: The ChatStreamlyWithSender function is missing validation
for apiConfig and apiConfig.ApiKey and directly dereferences *apiConfig.ApiKey
(risking a panic); modify ChatStreamlyWithSender to mirror ChatWithMessages by
first checking that apiConfig is not nil and that apiConfig.ApiKey is not
nil/empty before using it, and return a clear error (e.g., "api key is
required") if validation fails; update any code paths that assume
apiConfig.ApiKey (around the dereference near the current access) to only run
after these checks so the function safely handles nil apiConfig or nil ApiKey.
- Around line 560-566: The loop unconditionally type-asserts result["data"] and
elements to concrete types which can panic; update the code that builds models
(the variable models and the loop over result["data"]) to safely check types
using the comma-ok idiom (e.g., verify result["data"] is a []interface{} before
iterating and each element is a map[string]interface{} and that "id" is a
string), handle nil or unexpected types by skipping invalid entries or returning
an error, and ensure no direct type assertions remain without checks so the code
in jiekouai.go is robust to malformed API responses.
- Around line 172-182: When thinking is enabled (check chatModelConfig and
chatModelConfig.Thinking) avoid failing when messageMap["reasoning_content"] is
missing or not a string: instead of returning fmt.Errorf on failed type
assertion, treat reasonContent as an empty string by default; use a safe trim
(e.g. strings.TrimPrefix) to remove a leading '\n' from reasonContent rather
than indexing, and keep the rest of the flow unchanged—update the logic around
the reasonContent variable and the messageMap["reasoning_content"] assertion to
implement this behavior.
- Around line 417-452: In JieKouAIModel.Rerank: avoid nil dereferences and
remove redundant assignment by first validating inputs (check rerankConfig !=
nil before accessing rerankConfig.TopN, check modelName != nil before using
*modelName, and check apiConfig != nil and apiConfig.ApiKey != nil and
*apiConfig.ApiKey != "" before using it), compute topN with a single conditional
that falls back to a sensible default when rerankConfig is nil or TopN is zero
(e.g., topN := defaultTopN; if rerankConfig != nil && rerankConfig.TopN != 0 {
topN = rerankConfig.TopN }), and only then build reqBody and set the
Authorization header (req.Header.Set with the validated API key); this removes
the dead/redundant lines and prevents panics from nil pointers.
- Around line 346-374: In JieKouAIModel.Embed, add nil checks for modelName and
apiConfig (and apiConfig.ApiKey) before dereferencing to avoid panics: validate
modelName != nil and non-empty, and apiConfig != nil and apiConfig.ApiKey != nil
(or non-empty) and return a proper nil slice with an error (nil,
fmt.Errorf(...)) instead of returning an empty slice and an error; update the
code paths that use *modelName and *apiConfig.ApiKey (and any header-setting
code) to occur only after these validations.
🪄 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: 2f3b8fbb-c6d1-4e4c-b938-969a1224005a
⛔ Files ignored due to path filters (2)
internal/test.pdfis excluded by!**/*.pdfinternal/test.wavis excluded by!**/*.wav
📒 Files selected for processing (5)
conf/models/302ai.jsonconf/models/jiekouai.jsoninternal/entity/models/302ai.gointernal/entity/models/factory.gointernal/entity/models/jiekouai.go
| var reasonContent string | ||
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | ||
| reasonContent, ok = messageMap["reasoning_content"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid content format") | ||
| } | ||
| // if first char of reasonContent is \n remove the '\n' | ||
| if reasonContent != "" && reasonContent[0] == '\n' { | ||
| reasonContent = reasonContent[1:] | ||
| } | ||
| } |
There was a problem hiding this comment.
Fragile handling when reasoning_content is missing or null.
Same issue as in JieKouAI: when thinking is enabled, if the API response doesn't include reasoning_content, the type assertion fails and returns a misleading error. Consider treating missing reasoning content as empty.
Proposed fix
var reasonContent string
if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
- reasonContent, ok = messageMap["reasoning_content"].(string)
- if !ok {
- return nil, fmt.Errorf("invalid content format")
- }
+ if rc, ok := messageMap["reasoning_content"].(string); ok {
+ reasonContent = rc
+ }
// if first char of reasonContent is \n remove the '\n'
if reasonContent != "" && reasonContent[0] == '\n' {
reasonContent = reasonContent[1:]
}
}🤖 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 192 - 202, The current block
around reasonContent in function handling chatModelConfig (checking
chatModelConfig.Thinking) treats a missing or null
messageMap["reasoning_content"] as a type assertion failure; change it so that
if the key is absent or value is nil you set reasonContent = "" (empty) and only
perform the string type assertion when the value exists and is non-nil; update
the logic that reads messageMap["reasoning_content"] so it first checks presence
(e.g., val, exists := messageMap["reasoning_content"]) and only returns an error
if the value exists but is not a string, otherwise treat missing/null as empty
and keep the existing newline-trimming behavior.
| 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") | ||
| } | ||
|
|
There was a problem hiding this comment.
Missing API key validation in streaming chat.
ChatStreamlyWithSender directly dereferences *apiConfig.ApiKey at line 296 without validating that apiConfig and apiConfig.ApiKey are non-nil.
Proposed 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 len(messages) == 0 {
return fmt.Errorf("messages is empty")
}Also applies to: 296-296
🤖 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 - 216,
ChatStreamlyWithSender dereferences *apiConfig.ApiKey without nil-checks; add
explicit validation at the start of ChatStreamlyWithSender that apiConfig != nil
and apiConfig.ApiKey != nil and *apiConfig.ApiKey != "" (return a clear error
like "apiConfig or ApiKey is nil/empty"), then use the validated api key
variable wherever *apiConfig.ApiKey was used (or call a small helper
getAPIKey(apiConfig) that performs the same checks) so no further dereferences
occur without validation.
| 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, | ||
| } | ||
|
|
||
| jsonData, err := json.Marshal(reqBody) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to marshal request: %w", err) | ||
| } | ||
|
|
||
| req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
There was a problem hiding this comment.
Nil pointer dereference risks.
modelName is dereferenced at line 391 and apiConfig.ApiKey at line 406 without nil checks. Add validation at the start of the function.
Proposed fix
func (a *AI302Model) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return nil, fmt.Errorf("api key is required")
+ }
+ if modelName == nil || *modelName == "" {
+ return nil, fmt.Errorf("model name is required")
+ }
if len(texts) == 0 {
return []EmbeddingData{}, 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 378 - 406, The Embed method in
AI302Model dereferences modelName and apiConfig.ApiKey without validating them;
add nil/empty checks at the start of Embed (function AI302Model.Embed) to return
a clear error if modelName is nil or empty and if apiConfig is nil or
apiConfig.ApiKey is nil/empty (also validate apiConfig.Region use if needed), so
subsequent uses of *modelName and *apiConfig.ApiKey are safe; update any
existing early-return for empty texts to occur after these validations and
ensure error messages reference the parameter names (modelName,
apiConfig.ApiKey) for clarity.
| func (a *AI302Model) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) { | ||
| if len(documents) == 0 { | ||
| return &RerankResponse{}, 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.Rerank) | ||
|
|
||
| var topN = rerankConfig.TopN | ||
| if rerankConfig.TopN != 0 { | ||
| topN = rerankConfig.TopN | ||
| } | ||
|
|
||
| reqBody := map[string]interface{}{ | ||
| "model": *modelName, | ||
| "query": query, | ||
| "documents": documents, | ||
| "top_n": topN, | ||
| } | ||
|
|
||
| jsonData, err := json.Marshal(reqBody) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to marshal request: %w", err) | ||
| } | ||
|
|
||
| req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
There was a problem hiding this comment.
Multiple nil pointer risks and dead code.
Same issues as JieKouAI:
rerankConfigdereferenced at line 461 without nil check- Lines 461-464 are redundant (topN assigned twice to same value)
modelNamedereferenced at line 467 without nil checkapiConfig.ApiKeydereferenced at line 484 without nil check
Proposed fix
func (a *AI302Model) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) {
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return nil, fmt.Errorf("api key is required")
+ }
+ if modelName == nil || *modelName == "" {
+ return nil, fmt.Errorf("model name is required")
+ }
if len(documents) == 0 {
return &RerankResponse{}, 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.Rerank)
- var topN = rerankConfig.TopN
- if rerankConfig.TopN != 0 {
- topN = rerankConfig.TopN
+ var topN int
+ if rerankConfig != nil && rerankConfig.TopN != 0 {
+ topN = rerankConfig.TopN
}🤖 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 449 - 484, In
AI302Model.Rerank, add nil checks and clear error returns for rerankConfig,
modelName, and apiConfig/ApiKey before dereferencing them; remove the redundant
topN assignment so you only set topN once (use rerankConfig.TopN when
rerankConfig != nil and non-zero, otherwise keep default), validate modelName is
non-nil before using *modelName, and validate apiConfig and apiConfig.ApiKey are
non-nil/non-empty before using *apiConfig.ApiKey; update error messages to
indicate which parameter was nil (referencing symbols: Rerank, rerankConfig,
topN, modelName, apiConfig, ApiKey).
| func (a *AI302Model) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) { | ||
| if file == nil || *file == "" { | ||
| return nil, fmt.Errorf("file is missing") | ||
| } | ||
|
|
||
| region := "default" | ||
| if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| } | ||
|
|
||
| url := fmt.Sprintf("%s/%s", a.BaseURL[region], a.URLSuffix.ASR) | ||
|
|
||
| // multipart body | ||
| var body bytes.Buffer | ||
| writer := multipart.NewWriter(&body) | ||
|
|
||
| // open audio file | ||
| audioFile, err := os.Open(*file) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to open audio file: %w", err) | ||
| } | ||
| defer audioFile.Close() | ||
|
|
||
| // create multipart file field | ||
| part, err := writer.CreateFormFile( | ||
| "file", | ||
| filepath.Base(*file), | ||
| ) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create multipart file: %w", err) | ||
| } | ||
|
|
||
| // copy file content | ||
| if _, err = io.Copy(part, audioFile); err != nil { | ||
| return nil, fmt.Errorf("failed to copy audio data: %w", err) | ||
| } | ||
|
|
||
| // model field | ||
| if err := writer.WriteField("model", *modelName); err != nil { | ||
| return nil, fmt.Errorf("failed to write model field: %w", err) | ||
| } | ||
|
|
||
| // extra params | ||
| if asrConfig != nil && asrConfig.Params != nil { | ||
| for key, value := range asrConfig.Params { | ||
|
|
||
| var val string | ||
|
|
||
| switch v := value.(type) { | ||
| case string: | ||
| val = v | ||
| case bool: | ||
| val = strconv.FormatBool(v) | ||
| case int: | ||
| val = strconv.Itoa(v) | ||
| case int64: | ||
| val = strconv.FormatInt(v, 10) | ||
| case float32: | ||
| val = strconv.FormatFloat(float64(v), 'f', -1, 32) | ||
| case float64: | ||
| val = strconv.FormatFloat(v, 'f', -1, 64) | ||
| default: | ||
| val = fmt.Sprintf("%v", v) | ||
| } | ||
|
|
||
| if err = writer.WriteField(key, val); err != nil { | ||
| return nil, fmt.Errorf("failed to write field %s: %w", key, err) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if err = writer.Close(); err != nil { | ||
| return nil, fmt.Errorf("failed to close multipart writer: %w", err) | ||
| } | ||
|
|
||
| // build request | ||
| req, err := http.NewRequest("POST", url, &body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
There was a problem hiding this comment.
Missing API key validation in TranscribeAudio.
apiConfig.ApiKey is dereferenced at line 605 without validating that apiConfig and apiConfig.ApiKey are non-nil.
Proposed fix
func (a *AI302Model) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) {
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return nil, fmt.Errorf("api key is required")
+ }
if file == nil || *file == "" {
return nil, fmt.Errorf("file is missing")
}📝 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.
| func (a *AI302Model) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) { | |
| if file == nil || *file == "" { | |
| return nil, fmt.Errorf("file is missing") | |
| } | |
| region := "default" | |
| if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { | |
| region = *apiConfig.Region | |
| } | |
| url := fmt.Sprintf("%s/%s", a.BaseURL[region], a.URLSuffix.ASR) | |
| // multipart body | |
| var body bytes.Buffer | |
| writer := multipart.NewWriter(&body) | |
| // open audio file | |
| audioFile, err := os.Open(*file) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to open audio file: %w", err) | |
| } | |
| defer audioFile.Close() | |
| // create multipart file field | |
| part, err := writer.CreateFormFile( | |
| "file", | |
| filepath.Base(*file), | |
| ) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to create multipart file: %w", err) | |
| } | |
| // copy file content | |
| if _, err = io.Copy(part, audioFile); err != nil { | |
| return nil, fmt.Errorf("failed to copy audio data: %w", err) | |
| } | |
| // model field | |
| if err := writer.WriteField("model", *modelName); err != nil { | |
| return nil, fmt.Errorf("failed to write model field: %w", err) | |
| } | |
| // extra params | |
| if asrConfig != nil && asrConfig.Params != nil { | |
| for key, value := range asrConfig.Params { | |
| var val string | |
| switch v := value.(type) { | |
| case string: | |
| val = v | |
| case bool: | |
| val = strconv.FormatBool(v) | |
| case int: | |
| val = strconv.Itoa(v) | |
| case int64: | |
| val = strconv.FormatInt(v, 10) | |
| case float32: | |
| val = strconv.FormatFloat(float64(v), 'f', -1, 32) | |
| case float64: | |
| val = strconv.FormatFloat(v, 'f', -1, 64) | |
| default: | |
| val = fmt.Sprintf("%v", v) | |
| } | |
| if err = writer.WriteField(key, val); err != nil { | |
| return nil, fmt.Errorf("failed to write field %s: %w", key, err) | |
| } | |
| } | |
| } | |
| if err = writer.Close(); err != nil { | |
| return nil, fmt.Errorf("failed to close multipart writer: %w", err) | |
| } | |
| // build request | |
| req, err := http.NewRequest("POST", url, &body) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to create request: %w", err) | |
| } | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | |
| func (a *AI302Model) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) { | |
| if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { | |
| return nil, fmt.Errorf("api key is required") | |
| } | |
| if file == nil || *file == "" { | |
| return nil, fmt.Errorf("file is missing") | |
| } | |
| region := "default" | |
| if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { | |
| region = *apiConfig.Region | |
| } | |
| url := fmt.Sprintf("%s/%s", a.BaseURL[region], a.URLSuffix.ASR) | |
| // multipart body | |
| var body bytes.Buffer | |
| writer := multipart.NewWriter(&body) | |
| // open audio file | |
| audioFile, err := os.Open(*file) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to open audio file: %w", err) | |
| } | |
| defer audioFile.Close() | |
| // create multipart file field | |
| part, err := writer.CreateFormFile( | |
| "file", | |
| filepath.Base(*file), | |
| ) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to create multipart file: %w", err) | |
| } | |
| // copy file content | |
| if _, err = io.Copy(part, audioFile); err != nil { | |
| return nil, fmt.Errorf("failed to copy audio data: %w", err) | |
| } | |
| // model field | |
| if err := writer.WriteField("model", *modelName); err != nil { | |
| return nil, fmt.Errorf("failed to write model field: %w", err) | |
| } | |
| // extra params | |
| if asrConfig != nil && asrConfig.Params != nil { | |
| for key, value := range asrConfig.Params { | |
| var val string | |
| switch v := value.(type) { | |
| case string: | |
| val = v | |
| case bool: | |
| val = strconv.FormatBool(v) | |
| case int: | |
| val = strconv.Itoa(v) | |
| case int64: | |
| val = strconv.FormatInt(v, 10) | |
| case float32: | |
| val = strconv.FormatFloat(float64(v), 'f', -1, 32) | |
| case float64: | |
| val = strconv.FormatFloat(v, 'f', -1, 64) | |
| default: | |
| val = fmt.Sprintf("%v", v) | |
| } | |
| if err = writer.WriteField(key, val); err != nil { | |
| return nil, fmt.Errorf("failed to write field %s: %w", key, err) | |
| } | |
| } | |
| } | |
| if err = writer.Close(); err != nil { | |
| return nil, fmt.Errorf("failed to close multipart writer: %w", err) | |
| } | |
| // build request | |
| req, err := http.NewRequest("POST", url, &body) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to create request: %w", err) | |
| } | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
🤖 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 524 - 605, The TranscribeAudio
method dereferences apiConfig.ApiKey without validating apiConfig and ApiKey;
update TranscribeAudio to check that apiConfig is non-nil and apiConfig.ApiKey
is non-nil and not empty before using it (return a clear error like "api key is
missing"), and only set the Authorization header when the key is present;
reference the TranscribeAudio function and the APIConfig.ApiKey field to locate
where to add this validation and early return.
| var reasonContent string | ||
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | ||
| reasonContent, ok = messageMap["reasoning_content"].(string) | ||
| if !ok { | ||
| return nil, fmt.Errorf("invalid content format") | ||
| } | ||
| // if first char of reasonContent is \n remove the '\n' | ||
| if reasonContent != "" && reasonContent[0] == '\n' { | ||
| reasonContent = reasonContent[1:] | ||
| } | ||
| } |
There was a problem hiding this comment.
Fragile handling when reasoning_content is missing or null.
When thinking is enabled, if the API response doesn't include reasoning_content (or it's null), the type assertion fails and returns a misleading error. Consider making this more resilient by treating missing reasoning content as empty rather than erroring.
Proposed fix
var reasonContent string
if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking {
- reasonContent, ok = messageMap["reasoning_content"].(string)
- if !ok {
- return nil, fmt.Errorf("invalid content format")
- }
+ if rc, ok := messageMap["reasoning_content"].(string); ok {
+ reasonContent = rc
+ }
// if first char of reasonContent is \n remove the '\n'
if reasonContent != "" && reasonContent[0] == '\n' {
reasonContent = reasonContent[1:]
}
}📝 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.
| var reasonContent string | |
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | |
| reasonContent, ok = messageMap["reasoning_content"].(string) | |
| if !ok { | |
| return nil, fmt.Errorf("invalid content format") | |
| } | |
| // if first char of reasonContent is \n remove the '\n' | |
| if reasonContent != "" && reasonContent[0] == '\n' { | |
| reasonContent = reasonContent[1:] | |
| } | |
| } | |
| var reasonContent string | |
| if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { | |
| if rc, ok := messageMap["reasoning_content"].(string); ok { | |
| reasonContent = rc | |
| } | |
| // if first char of reasonContent is \n remove the '\n' | |
| if reasonContent != "" && reasonContent[0] == '\n' { | |
| reasonContent = reasonContent[1:] | |
| } | |
| } |
🤖 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 172 - 182, When thinking is
enabled (check chatModelConfig and chatModelConfig.Thinking) avoid failing when
messageMap["reasoning_content"] is missing or not a string: instead of returning
fmt.Errorf on failed type assertion, treat reasonContent as an empty string by
default; use a safe trim (e.g. strings.TrimPrefix) to remove a leading '\n' from
reasonContent rather than indexing, and keep the rest of the flow
unchanged—update the logic around the reasonContent variable and the
messageMap["reasoning_content"] assertion to implement this behavior.
| 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") | ||
| } | ||
|
|
There was a problem hiding this comment.
Missing API key validation in streaming chat.
ChatWithMessages validates that apiConfig.ApiKey is non-nil (line 58), but ChatStreamlyWithSender only checks apiConfig.Region and directly dereferences *apiConfig.ApiKey at line 264 without validation. This will panic if apiConfig or apiConfig.ApiKey is nil.
Proposed fix
func (j *JieKouAIModel) 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 len(messages) == 0 {
return fmt.Errorf("messages is empty")
}Also applies to: 264-264
🤖 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 - 196, The
ChatStreamlyWithSender function is missing validation for apiConfig and
apiConfig.ApiKey and directly dereferences *apiConfig.ApiKey (risking a panic);
modify ChatStreamlyWithSender to mirror ChatWithMessages by first checking that
apiConfig is not nil and that apiConfig.ApiKey is not nil/empty before using it,
and return a clear error (e.g., "api key is required") if validation fails;
update any code paths that assume apiConfig.ApiKey (around the dereference near
the current access) to only run after these checks so the function safely
handles nil apiConfig or nil ApiKey.
| 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, | ||
| } | ||
|
|
||
| jsonData, err := json.Marshal(reqBody) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to marshal request: %w", err) | ||
| } | ||
|
|
||
| req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
There was a problem hiding this comment.
Nil pointer dereference risks and inconsistent error handling.
modelNameis dereferenced at line 359 without nil checkapiConfig.ApiKeyis dereferenced at line 374 without nil check- Line 348 returns both an empty slice and an error, which is inconsistent (typically return
nil, err)
Proposed fix
func (j *JieKouAIModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return nil, fmt.Errorf("api key is required")
+ }
+ if modelName == nil || *modelName == "" {
+ return nil, fmt.Errorf("model name is required")
+ }
if len(texts) == 0 {
- return []EmbeddingData{}, fmt.Errorf("texts is empty")
+ return nil, fmt.Errorf("texts is empty")
}📝 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.
| 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, | |
| } | |
| jsonData, err := json.Marshal(reqBody) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to marshal request: %w", err) | |
| } | |
| req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to create request: %w", err) | |
| } | |
| req.Header.Set("Content-Type", "application/json") | |
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | |
| func (j *JieKouAIModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) { | |
| if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { | |
| return nil, fmt.Errorf("api key is required") | |
| } | |
| if modelName == nil || *modelName == "" { | |
| return nil, fmt.Errorf("model name is required") | |
| } | |
| if len(texts) == 0 { | |
| return nil, 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, | |
| } | |
| jsonData, err := json.Marshal(reqBody) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to marshal request: %w", err) | |
| } | |
| req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) | |
| if err != nil { | |
| return nil, fmt.Errorf("failed to create request: %w", err) | |
| } | |
| 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 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 - 374, In
JieKouAIModel.Embed, add nil checks for modelName and apiConfig (and
apiConfig.ApiKey) before dereferencing to avoid panics: validate modelName !=
nil and non-empty, and apiConfig != nil and apiConfig.ApiKey != nil (or
non-empty) and return a proper nil slice with an error (nil, fmt.Errorf(...))
instead of returning an empty slice and an error; update the code paths that use
*modelName and *apiConfig.ApiKey (and any header-setting code) to occur only
after these validations.
| func (j *JieKouAIModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) { | ||
| if len(documents) == 0 { | ||
| return &RerankResponse{}, nil | ||
| } | ||
|
|
||
| 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.Rerank) | ||
|
|
||
| var topN = rerankConfig.TopN | ||
| if rerankConfig.TopN != 0 { | ||
| topN = rerankConfig.TopN | ||
| } | ||
|
|
||
| reqBody := map[string]interface{}{ | ||
| "model": *modelName, | ||
| "query": query, | ||
| "documents": documents, | ||
| "top_n": topN, | ||
| } | ||
|
|
||
| jsonData, err := json.Marshal(reqBody) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to marshal request: %w", err) | ||
| } | ||
|
|
||
| req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
There was a problem hiding this comment.
Multiple nil pointer risks and dead code.
rerankConfigis dereferenced at line 429 without nil check - will panic if nil- Lines 429-432 are redundant:
topNis assigned, then conditionally re-assigned to the same value modelNamedereferenced at line 435 without nil checkapiConfig.ApiKeydereferenced at line 452 without nil check
Proposed fix
func (j *JieKouAIModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) {
+ if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" {
+ return nil, fmt.Errorf("api key is required")
+ }
+ if modelName == nil || *modelName == "" {
+ return nil, fmt.Errorf("model name is required")
+ }
if len(documents) == 0 {
return &RerankResponse{}, nil
}
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.Rerank)
- var topN = rerankConfig.TopN
- if rerankConfig.TopN != 0 {
- topN = rerankConfig.TopN
+ var topN int
+ if rerankConfig != nil && rerankConfig.TopN != 0 {
+ topN = rerankConfig.TopN
}🤖 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 417 - 452, In
JieKouAIModel.Rerank: avoid nil dereferences and remove redundant assignment by
first validating inputs (check rerankConfig != nil before accessing
rerankConfig.TopN, check modelName != nil before using *modelName, and check
apiConfig != nil and apiConfig.ApiKey != nil and *apiConfig.ApiKey != "" before
using it), compute topN with a single conditional that falls back to a sensible
default when rerankConfig is nil or TopN is zero (e.g., topN := defaultTopN; if
rerankConfig != nil && rerankConfig.TopN != 0 { topN = rerankConfig.TopN }), and
only then build reqBody and set the Authorization header (req.Header.Set with
the validated API key); this removes the dead/redundant lines and prevents
panics from nil pointers.
| // 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.
Unsafe type assertions may cause panics.
The type assertions at lines 562-564 don't use the comma-ok idiom. If the API returns an unexpected format (e.g., result["data"] is nil or not a slice), this will panic at runtime.
Proposed fix
// 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)
+ data, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("unexpected response format: missing or invalid 'data' field")
+ }
+ for _, model := range data {
+ modelMap, ok := model.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ if modelID, ok := modelMap["id"].(string); ok {
+ models = append(models, modelID)
+ }
}🤖 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 560 - 566, The loop
unconditionally type-asserts result["data"] and elements to concrete types which
can panic; update the code that builds models (the variable models and the loop
over result["data"]) to safely check types using the comma-ok idiom (e.g.,
verify result["data"] is a []interface{} before iterating and each element is a
map[string]interface{} and that "id" is a string), handle nil or unexpected
types by skipping invalid entries or returning an error, and ensure no direct
type assertions remain without checks so the code in jiekouai.go is robust to
malformed API responses.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15000 +/- ##
=======================================
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:
|
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