Repository navigation
Go: add file parse command - #14892
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThis PR extends RAGFlow with document parsing, task listing, and task status retrieval capabilities. It updates the ChangesDocument parsing and task management implementation
Configuration, release notes, and cleanup
🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 |
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (3)
internal/entity/models/baidu.go (1)
629-631: 💤 Low valueConsider consistent receiver naming.
The new methods use receiver name
zwhile the existingOCRFilemethod (line 624) usesb. For consistency within theBaiduModeltype, consider using the same receiver name throughout the file.Also applies to: 697-703
🤖 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/baidu.go` around lines 629 - 631, The receiver name for methods on BaiduModel is inconsistent: change the receiver from z to b in the ParseFile method (func (z *BaiduModel) ParseFile...) and the other methods referenced around lines 697-703 so they all use the same receiver identifier as OCRFile (func (b *BaiduModel) OCRFile...), ensuring consistent receiver naming (b) across BaiduModel methods like ParseFile and the ones near 697-703.internal/entity/models/types.go (2)
156-157: 💤 Low valueDocument the empty ParseFileConfig struct.
ParseFileConfigis currently an empty struct. Following the pattern ofOCRConfig(also empty), this appears intentional for future configuration options. Adding a brief comment would clarify this design decision.📝 Suggested documentation
+// ParseFileConfig holds configuration for file parsing operations. +// Currently empty; reserved for future parsing parameters. type ParseFileConfig struct { }🤖 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/types.go` around lines 156 - 157, Add a brief doc comment above the empty ParseFileConfig struct to state it's intentionally empty for future configuration (matching the existing pattern used for OCRConfig); mention that it serves as a placeholder for future parsing options so readers won't treat its emptiness as an oversight, and ensure the comment is placed immediately above the ParseFileConfig declaration.
81-82: ⚡ Quick winDocument the empty ParseFileResponse struct.
ParseFileResponseis currently an empty struct with no fields. If this is intentional (e.g., reserved for future extension or the actual result is returned through a different mechanism like task IDs), please add a comment documenting this design choice. Otherwise, consider whether fields likeTaskID stringorStatus stringshould be added now.📝 Suggested documentation
+// ParseFileResponse is the response from ParseFile operations. +// Currently empty as file parsing is asynchronous; callers should +// use ListTasks and ShowTask to retrieve results. type ParseFileResponse struct { }🤖 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/types.go` around lines 81 - 82, ParseFileResponse is currently an empty struct; either document it as intentionally reserved or add the expected response fields—add a Go doc comment above the ParseFileResponse type explaining that it is intentionally empty/placeholder (e.g., "reserved for future use" or "response communicated via task IDs elsewhere"), or if the response should carry data, add explicit fields such as TaskID string and Status string (and any other needed fields) to the ParseFileResponse struct so its purpose is clear; update the type declaration for ParseFileResponse accordingly.
🤖 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/cli/response.go`:
- Around line 346-353: TaskResponse.PrintOut currently does unchecked
type-assert r.Data["segments"].([]interface{}) and v.(map[string]interface{})
which can panic on malformed responses; change it to safely validate types using
the "ok" comma-ok form: verify r.Data["segments"] exists and is a []interface{}
(assign to segmentsRaw with ok), and for each element check it is a
map[string]interface{} before appending to segments (skip or substitute an empty
map on failure). If the top-level key is missing or wrong type, treat segments
as empty slice (or log a warning) then call PrintTableSimpleByFormat(segments,
r.OutputFormat) as before. Ensure all references match TaskResponse.PrintOut,
r.Data["segments"], segmentsRaw and segments.
In `@internal/cli/user_command.go`:
- Around line 2423-2433: The current block in ShowTaskUserCommand
unconditionally returns an error if cmd.Params["composite_instance_name"] is
missing; change it to treat composite_instance_name as optional: if present
parse "instance@provider" into instanceName and providerName (keeping the
existing validation and error when format is invalid), but if absent do not
return an error—leave instanceName/providerName empty (or nil) so SHOW TASK
<task_id> can proceed; update any downstream usage to handle empty
providerName/instanceName accordingly.
In `@internal/entity/models/gitee.go`:
- Around line 813-821: The ParseFile path discards the upstream task/result by
creating and returning an empty ParseFileResponse instead of the data obtained
from g.getParseFile and the giteeParseFileResp; update the function to capture
and propagate the parsed result: call g.getParseFile (already invoked) and use
its returned data (or the final result from the poll using
giteeParseFileResp.TaskID) to populate and return a proper ParseFileResponse
rather than a zero-value; ensure you map fields from the upstream response into
ParseFileResponse and return that populated struct from the function.
- Around line 845-873: In getParseFile, remove the defer resp.Body.Close()
inside the retry loop (which leaks connections) and instead close the response
body explicitly after reading it each iteration; after reading and unmarshalling
the body (into result) evaluate the parsed status/result and return the
successful parsed value immediately (or an appropriate error) instead of falling
through to return nil, nil; ensure each loop iteration always closes resp.Body
even on errors and only sleeps/retries when a retry is warranted.
- Line 827: The code builds the polling URL with a hardcoded "/task/%s/status"
path (see the url := fmt.Sprintf(...) line using baseURL and taskID); change it
to use the provider-configured URL suffix contract instead of the literal
string—compose the URL by trimming baseURL and then appending the configured
URLSuffix (or calling the helper that formats URLSuffix with taskID) so
provider-specific suffixes are honored; update references around baseURL, taskID
and URLSuffix (or the existing URL-building helper) to format/replace the task
ID into the configured suffix rather than using the hardcoded path.
In `@internal/handler/providers.go`:
- Around line 1469-1507: The handler currently calls
h.modelProviderService.ParseFile without validating the parse source; add a
request-shape check before invoking ParseFile to ensure exactly one of
req.Content or req.URL is supplied (reject when both are missing or both are
present/empty). If validation fails, return a 400 JSON response (c.JSON) with a
clear message like "Either content or url must be provided, but not both" and
stop processing; perform the check just before the call to
h.modelProviderService.ParseFile so req.Content and req.URL are validated in the
same place where provider/instance/model are already checked.
In `@internal/server/config.go`:
- Around line 726-741: The minio_0 branch populates
globalConfig.StorageEngine.Minio but omits the Region field; update the
MinioConfig initialization in the minio_0 block to set Region:
minioConfig.GetString("region") (same as the existing minio block) and ensure
you reference MinioConfig, minioConfig, and globalConfig.StorageEngine.Minio;
additionally, add a simple guard or log/warning when both "minio" and "minio_0"
config sections are present so one does not silently overwrite the other (e.g.,
check v.IsSet("minio") && v.IsSet("minio_0") and emit a warning or decide
precedence).
In `@internal/service/model_service.go`:
- Around line 1801-1813: ParseFile currently selects the model driver
inconsistently and may call NewInstance with an empty base_url, producing a
broken instance; update the logic so both branches follow the same rule: only
construct a new instance via NewInstance when a non-empty base_url (or other
local override) is present, otherwise use providerInfo.ModelDriver.ParseFile
directly. Specifically, in ParseFile adjust the not-found branch to honor any
local base_url override (parse extra["base_url"] / base_url variable) instead of
skipping it, and in the active-instance branch guard the NewInstance call (and
assignment of apiConfig.ApiKey/Region) so it is only invoked when base_url is
non-empty; apply the same fix to the second occurrence around the other
ParseFile call (the 1833-1849 region) to keep behavior consistent.
---
Nitpick comments:
In `@internal/entity/models/baidu.go`:
- Around line 629-631: The receiver name for methods on BaiduModel is
inconsistent: change the receiver from z to b in the ParseFile method (func (z
*BaiduModel) ParseFile...) and the other methods referenced around lines 697-703
so they all use the same receiver identifier as OCRFile (func (b *BaiduModel)
OCRFile...), ensuring consistent receiver naming (b) across BaiduModel methods
like ParseFile and the ones near 697-703.
In `@internal/entity/models/types.go`:
- Around line 156-157: Add a brief doc comment above the empty ParseFileConfig
struct to state it's intentionally empty for future configuration (matching the
existing pattern used for OCRConfig); mention that it serves as a placeholder
for future parsing options so readers won't treat its emptiness as an oversight,
and ensure the comment is placed immediately above the ParseFileConfig
declaration.
- Around line 81-82: ParseFileResponse is currently an empty struct; either
document it as intentionally reserved or add the expected response fields—add a
Go doc comment above the ParseFileResponse type explaining that it is
intentionally empty/placeholder (e.g., "reserved for future use" or "response
communicated via task IDs elsewhere"), or if the response should carry data, add
explicit fields such as TaskID string and Status string (and any other needed
fields) to the ParseFileResponse struct so its purpose is clear; update the type
declaration for ParseFileResponse accordingly.
🪄 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: 4c689864-8b3c-47be-98f4-0efeb8a1ba44
📒 Files selected for processing (46)
conf/models/gitee.jsondocs/release_notes.mdinternal/cli/client.gointernal/cli/lexer.gointernal/cli/response.gointernal/cli/types.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/engine/elasticsearch/index.gointernal/entity/models/aliyun.gointernal/entity/models/baichuan.gointernal/entity/models/baidu.gointernal/entity/models/cohere.gointernal/entity/models/deepseek.gointernal/entity/models/dummy.gointernal/entity/models/fishaudio.gointernal/entity/models/gitee.gointernal/entity/models/google.gointernal/entity/models/huggingface.gointernal/entity/models/jina.gointernal/entity/models/lmstudio.gointernal/entity/models/localai.gointernal/entity/models/longcat.gointernal/entity/models/minimax.gointernal/entity/models/mistral.gointernal/entity/models/moonshot.gointernal/entity/models/novita.gointernal/entity/models/nvidia.gointernal/entity/models/ollama.gointernal/entity/models/openai.gointernal/entity/models/openrouter.gointernal/entity/models/siliconflow.gointernal/entity/models/stepfun.gointernal/entity/models/types.gointernal/entity/models/upstage.gointernal/entity/models/vllm.gointernal/entity/models/volcengine.gointernal/entity/models/voyage.gointernal/entity/models/xai.gointernal/entity/models/zhipu-ai.gointernal/handler/memory.gointernal/handler/providers.gointernal/router/router.gointernal/server/config.gointernal/service/model_service.goweb/src/utils/api.ts
| func (r *TaskResponse) PrintOut() { | ||
| if r.Code == 0 { | ||
| segmentsRaw := r.Data["segments"].([]interface{}) | ||
| segments := make([]map[string]interface{}, len(segmentsRaw)) | ||
| for i, v := range segmentsRaw { | ||
| segments[i] = v.(map[string]interface{}) | ||
| } | ||
| PrintTableSimpleByFormat(segments, r.OutputFormat) |
There was a problem hiding this comment.
Prevent panic in task output formatting.
On Line 348 and Line 351, unchecked assertions (r.Data["segments"].([]interface{}), v.(map[string]interface{})) can crash the CLI on malformed or partial responses.
Proposed fix
func (r *TaskResponse) PrintOut() {
if r.Code == 0 {
- segmentsRaw := r.Data["segments"].([]interface{})
- segments := make([]map[string]interface{}, len(segmentsRaw))
- for i, v := range segmentsRaw {
- segments[i] = v.(map[string]interface{})
- }
+ raw, ok := r.Data["segments"]
+ if !ok {
+ fmt.Println("ERROR")
+ fmt.Println("invalid task response: missing segments")
+ return
+ }
+ segmentsRaw, ok := raw.([]interface{})
+ if !ok {
+ fmt.Println("ERROR")
+ fmt.Println("invalid task response: segments is not an array")
+ return
+ }
+ segments := make([]map[string]interface{}, 0, len(segmentsRaw))
+ for _, v := range segmentsRaw {
+ item, ok := v.(map[string]interface{})
+ if !ok {
+ fmt.Println("ERROR")
+ fmt.Println("invalid task response: segment item is not an object")
+ return
+ }
+ segments = append(segments, item)
+ }
PrintTableSimpleByFormat(segments, r.OutputFormat)
} else {
fmt.Println("ERROR")
fmt.Printf("%d, %s\n", r.Code, r.Message)
}
}📝 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 (r *TaskResponse) PrintOut() { | |
| if r.Code == 0 { | |
| segmentsRaw := r.Data["segments"].([]interface{}) | |
| segments := make([]map[string]interface{}, len(segmentsRaw)) | |
| for i, v := range segmentsRaw { | |
| segments[i] = v.(map[string]interface{}) | |
| } | |
| PrintTableSimpleByFormat(segments, r.OutputFormat) | |
| func (r *TaskResponse) PrintOut() { | |
| if r.Code == 0 { | |
| raw, ok := r.Data["segments"] | |
| if !ok { | |
| fmt.Println("ERROR") | |
| fmt.Println("invalid task response: missing segments") | |
| return | |
| } | |
| segmentsRaw, ok := raw.([]interface{}) | |
| if !ok { | |
| fmt.Println("ERROR") | |
| fmt.Println("invalid task response: segments is not an array") | |
| return | |
| } | |
| segments := make([]map[string]interface{}, 0, len(segmentsRaw)) | |
| for _, v := range segmentsRaw { | |
| item, ok := v.(map[string]interface{}) | |
| if !ok { | |
| fmt.Println("ERROR") | |
| fmt.Println("invalid task response: segment item is not an object") | |
| return | |
| } | |
| segments = append(segments, item) | |
| } | |
| PrintTableSimpleByFormat(segments, r.OutputFormat) | |
| } else { | |
| fmt.Println("ERROR") | |
| fmt.Printf("%d, %s\n", r.Code, r.Message) | |
| } | |
| } |
🤖 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/cli/response.go` around lines 346 - 353, TaskResponse.PrintOut
currently does unchecked type-assert r.Data["segments"].([]interface{}) and
v.(map[string]interface{}) which can panic on malformed responses; change it to
safely validate types using the "ok" comma-ok form: verify r.Data["segments"]
exists and is a []interface{} (assign to segmentsRaw with ok), and for each
element check it is a map[string]interface{} before appending to segments (skip
or substitute an empty map on failure). If the top-level key is missing or wrong
type, treat segments as empty slice (or log a warning) then call
PrintTableSimpleByFormat(segments, r.OutputFormat) as before. Ensure all
references match TaskResponse.PrintOut, r.Data["segments"], segmentsRaw and
segments.
| // Check if composite_instance_name is provided in command | ||
| if compositeModelName, ok := cmd.Params["composite_instance_name"].(string); ok && compositeModelName != "" { | ||
| names := strings.Split(compositeModelName, "@") | ||
| if len(names) != 2 { | ||
| return nil, fmt.Errorf("model name must be in format 'instance@provider'") | ||
| } | ||
| providerName = names[1] | ||
| instanceName = names[0] | ||
| } else { | ||
| return nil, fmt.Errorf("no provider name or instance name") | ||
| } |
There was a problem hiding this comment.
Handle SHOW TASK <task_id> without forcing composite instance input.
ShowTaskUserCommand currently hard-fails when composite_instance_name is absent. That breaks the parser path that emits only task_id for SHOW TASK ....
Proposed fix
- // Check if composite_instance_name is provided in command
- if compositeModelName, ok := cmd.Params["composite_instance_name"].(string); ok && compositeModelName != "" {
+ // Check if composite_instance_name is provided in command
+ if compositeModelName, ok := cmd.Params["composite_instance_name"].(string); ok && compositeModelName != "" {
names := strings.Split(compositeModelName, "@")
if len(names) != 2 {
return nil, fmt.Errorf("model name must be in format 'instance@provider'")
}
providerName = names[1]
instanceName = names[0]
+ } else if c.CurrentModel != nil {
+ // Fallback for SHOW TASK <task_id> when current model is set
+ providerName = c.CurrentModel.Provider
+ instanceName = c.CurrentModel.Instance
} else {
- return nil, fmt.Errorf("no provider name or instance name")
+ return nil, fmt.Errorf("no provider/instance context; provide 'instance@provider' or run 'USE MODEL' first")
}🤖 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/cli/user_command.go` around lines 2423 - 2433, The current block in
ShowTaskUserCommand unconditionally returns an error if
cmd.Params["composite_instance_name"] is missing; change it to treat
composite_instance_name as optional: if present parse "instance@provider" into
instanceName and providerName (keeping the existing validation and error when
format is invalid), but if absent do not return an error—leave
instanceName/providerName empty (or nil) so SHOW TASK <task_id> can proceed;
update any downstream usage to handle empty providerName/instanceName
accordingly.
| _, err = g.getParseFile(&baseURL, apiConfig.ApiKey, &giteeParseFileResp.TaskID, 5*time.Second, 10) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| var parseFileResponse = ParseFileResponse{} | ||
|
|
||
| return &parseFileResponse, nil | ||
| } |
There was a problem hiding this comment.
ParseFile returns an empty payload even after successful submission/polling.
The method currently discards upstream task/result data and always returns an empty ParseFileResponse, which makes the new parse command effectively unusable for callers.
🤖 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/gitee.go` around lines 813 - 821, The ParseFile path
discards the upstream task/result by creating and returning an empty
ParseFileResponse instead of the data obtained from g.getParseFile and the
giteeParseFileResp; update the function to capture and propagate the parsed
result: call g.getParseFile (already invoked) and use its returned data (or the
final result from the poll using giteeParseFileResp.TaskID) to populate and
return a proper ParseFileResponse rather than a zero-value; ensure you map
fields from the upstream response into ParseFileResponse and return that
populated struct from the function.
| } | ||
|
|
||
| func (g *GiteeModel) getParseFile(baseURL *string, apiKey, taskID *string, timeOut time.Duration, count int) (*giteeGetParseFileResponse, error) { | ||
| url := fmt.Sprintf("%s/task/%s/status", strings.TrimSuffix(*baseURL, "/"), *taskID) |
There was a problem hiding this comment.
Avoid hardcoded task status path; use configured URL suffix contract.
/task/%s/status is hardcoded, so any provider-specific path change in config will break polling even if URLSuffix is correct.
Suggested fix
- url := fmt.Sprintf("%s/task/%s/status", strings.TrimSuffix(*baseURL, "/"), *taskID)
+ url := fmt.Sprintf("%s/%s/%s/status", strings.TrimSuffix(*baseURL, "/"), g.URLSuffix.Task, *taskID)📝 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.
| url := fmt.Sprintf("%s/task/%s/status", strings.TrimSuffix(*baseURL, "/"), *taskID) | |
| url := fmt.Sprintf("%s/%s/%s/status", strings.TrimSuffix(*baseURL, "/"), g.URLSuffix.Task, *taskID) |
🤖 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/gitee.go` at line 827, The code builds the polling URL
with a hardcoded "/task/%s/status" path (see the url := fmt.Sprintf(...) line
using baseURL and taskID); change it to use the provider-configured URL suffix
contract instead of the literal string—compose the URL by trimming baseURL and
then appending the configured URLSuffix (or calling the helper that formats
URLSuffix with taskID) so provider-specific suffixes are honored; update
references around baseURL, taskID and URLSuffix (or the existing URL-building
helper) to format/replace the task ID into the configured suffix rather than
using the hardcoded path.
| for i := 0; i < count; i++ { | ||
| resp, err = g.httpClient.Do(req) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to send request: %w", err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| var body []byte | ||
| body, err = io.ReadAll(resp.Body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read response: %w", err) | ||
| } | ||
|
|
||
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body)) | ||
| } | ||
|
|
||
| // Parse response | ||
| var result map[string]interface{} | ||
| if err = json.Unmarshal(body, &result); err != nil { | ||
| return nil, fmt.Errorf("failed to parse response: %w", err) | ||
| } | ||
|
|
||
| time.Sleep(timeOut) | ||
| } | ||
|
|
||
| // if resp show the file is ok, download it. otherwise, provide timeout info | ||
| return nil, nil | ||
| } |
There was a problem hiding this comment.
Polling helper never resolves completion and leaks response bodies across retries.
getParseFile defers resp.Body.Close() inside the retry loop and never evaluates parsed status/result before returning nil, nil. This can exhaust idle connections and always loses parse output.
Suggested fix
- var resp *http.Response
for i := 0; i < count; i++ {
- resp, err = g.httpClient.Do(req)
+ resp, err := g.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
- defer resp.Body.Close()
- var body []byte
- body, err = io.ReadAll(resp.Body)
+ body, err := io.ReadAll(resp.Body)
+ resp.Body.Close()
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
@@
- // Parse response
+ // Parse response and break/return once terminal status is observed.
var result map[string]interface{}
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
+ // TODO: inspect result["status"] and return parsed response when done.
time.Sleep(timeOut)
}
- // if resp show the file is ok, download it. otherwise, provide timeout info
- return nil, nil
+ return nil, fmt.Errorf("parse task %s did not reach terminal state after %d polls", *taskID, count)🤖 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/gitee.go` around lines 845 - 873, In getParseFile,
remove the defer resp.Body.Close() inside the retry loop (which leaks
connections) and instead close the response body explicitly after reading it
each iteration; after reading and unmarshalling the body (into result) evaluate
the parsed status/result and return the successful parsed value immediately (or
an appropriate error) instead of falling through to return nil, nil; ensure each
loop iteration always closes resp.Body even on errors and only sleeps/retries
when a retry is warranted.
| if req.ProviderName == nil || *req.ProviderName == "" { | ||
| c.JSON(http.StatusBadRequest, gin.H{ | ||
| "code": 400, | ||
| "message": "Provider name is required", | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| if req.InstanceName == nil || *req.InstanceName == "" { | ||
| c.JSON(http.StatusBadRequest, gin.H{ | ||
| "code": 400, | ||
| "message": "Instance name is required", | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| if req.ModelName == nil || *req.ModelName == "" { | ||
| c.JSON(http.StatusBadRequest, gin.H{ | ||
| "code": 400, | ||
| "message": "Model name is required", | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| userID := c.GetString("user_id") | ||
|
|
||
| apiConfig := models.APIConfig{ | ||
| ApiKey: nil, | ||
| Region: nil, | ||
| } | ||
|
|
||
| parseFileConfig := models.ParseFileConfig{} | ||
|
|
||
| // Non-stream response | ||
| var response *models.ParseFileResponse | ||
| var errorCode common.ErrorCode | ||
| var err error | ||
|
|
||
| response, errorCode, err = h.modelProviderService.ParseFile(*req.ProviderName, *req.InstanceName, *req.ModelName, userID, req.Content, req.URL, &apiConfig, &parseFileConfig) |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Add request-shape validation for parse source fields.
ParseFile validates provider/instance/model but does not validate the parse source. On Line 1469 onward, requests with neither content nor url (or with both) are accepted and deferred to deeper layers.
Proposed fix
func (h *ProviderHandler) ParseFile(c *gin.Context) {
var req ParseFileRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@
if req.ModelName == nil || *req.ModelName == "" {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "Model name is required",
})
return
}
+
+ hasContent := len(req.Content) > 0
+ hasURL := req.URL != nil && strings.TrimSpace(*req.URL) != ""
+ if hasContent == hasURL {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "code": common.CodeBadRequest,
+ "message": "Exactly one of content or url must be provided",
+ })
+ return
+ }
userID := c.GetString("user_id")🤖 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/handler/providers.go` around lines 1469 - 1507, The handler
currently calls h.modelProviderService.ParseFile without validating the parse
source; add a request-shape check before invoking ParseFile to ensure exactly
one of req.Content or req.URL is supplied (reject when both are missing or both
are present/empty). If validation fails, return a 400 JSON response (c.JSON)
with a clear message like "Either content or url must be provided, but not both"
and stop processing; perform the check just before the call to
h.modelProviderService.ParseFile so req.Content and req.URL are validated in the
same place where provider/instance/model are already checked.
| if v.IsSet("minio_0") { | ||
| minioConfig := v.Sub("minio_0") | ||
| if minioConfig != nil { | ||
| if globalConfig.StorageEngine.Minio == nil { | ||
| globalConfig.StorageEngine.Minio = &MinioConfig{ | ||
| Host: minioConfig.GetString("host"), | ||
| User: minioConfig.GetString("user"), | ||
| Password: minioConfig.GetString("password"), | ||
| Secure: minioConfig.GetBool("secure"), | ||
| PrefixPath: minioConfig.GetString("prefix_path"), | ||
| Verify: minioConfig.GetBool("verify"), | ||
| Bucket: minioConfig.GetString("bucket"), | ||
| } | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
The minio_0 block is missing Region field assignment.
The existing minio section (line 719) sets Region: minioConfig.GetString("region"), but the new minio_0 block omits this field. If minio_0 is intended for backward compatibility with older configs that lacked region support, this is acceptable; otherwise, Region should be set here too for consistency.
Additionally, if both minio and minio_0 sections exist in the config file, the last one processed silently overwrites globalConfig.StorageEngine.Minio with no validation or warning. Consider adding a check to prevent conflicting configuration sections or document the precedence order.
🔧 Proposed fix to add Region field
if v.IsSet("minio_0") {
minioConfig := v.Sub("minio_0")
if minioConfig != nil {
if globalConfig.StorageEngine.Minio == nil {
globalConfig.StorageEngine.Minio = &MinioConfig{
Host: minioConfig.GetString("host"),
User: minioConfig.GetString("user"),
Password: minioConfig.GetString("password"),
Secure: minioConfig.GetBool("secure"),
PrefixPath: minioConfig.GetString("prefix_path"),
Verify: minioConfig.GetBool("verify"),
+ Region: minioConfig.GetString("region"),
Bucket: minioConfig.GetString("bucket"),
}
}
}
}📝 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.
| if v.IsSet("minio_0") { | |
| minioConfig := v.Sub("minio_0") | |
| if minioConfig != nil { | |
| if globalConfig.StorageEngine.Minio == nil { | |
| globalConfig.StorageEngine.Minio = &MinioConfig{ | |
| Host: minioConfig.GetString("host"), | |
| User: minioConfig.GetString("user"), | |
| Password: minioConfig.GetString("password"), | |
| Secure: minioConfig.GetBool("secure"), | |
| PrefixPath: minioConfig.GetString("prefix_path"), | |
| Verify: minioConfig.GetBool("verify"), | |
| Bucket: minioConfig.GetString("bucket"), | |
| } | |
| } | |
| } | |
| } | |
| if v.IsSet("minio_0") { | |
| minioConfig := v.Sub("minio_0") | |
| if minioConfig != nil { | |
| if globalConfig.StorageEngine.Minio == nil { | |
| globalConfig.StorageEngine.Minio = &MinioConfig{ | |
| Host: minioConfig.GetString("host"), | |
| User: minioConfig.GetString("user"), | |
| Password: minioConfig.GetString("password"), | |
| Secure: minioConfig.GetBool("secure"), | |
| PrefixPath: minioConfig.GetString("prefix_path"), | |
| Verify: minioConfig.GetBool("verify"), | |
| Region: minioConfig.GetString("region"), | |
| Bucket: minioConfig.GetString("bucket"), | |
| } | |
| } | |
| } | |
| } |
🤖 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/server/config.go` around lines 726 - 741, The minio_0 branch
populates globalConfig.StorageEngine.Minio but omits the Region field; update
the MinioConfig initialization in the minio_0 block to set Region:
minioConfig.GetString("region") (same as the existing minio block) and ensure
you reference MinioConfig, minioConfig, and globalConfig.StorageEngine.Minio;
additionally, add a simple guard or log/warning when both "minio" and "minio_0"
config sections are present so one does not silently overwrite the other (e.g.,
check v.IsSet("minio") && v.IsSet("minio_0") and emit a warning or decide
precedence).
| var extra map[string]string | ||
| err = json.Unmarshal([]byte(instance.Extra), &extra) | ||
| if err != nil { | ||
| return nil, common.CodeServerError, err | ||
| } | ||
|
|
||
| region := extra["region"] | ||
| apiConfig.Region = ®ion | ||
| apiConfig.ApiKey = &instance.APIKey | ||
|
|
||
| var response *modelModule.ParseFileResponse | ||
| response, err = providerInfo.ModelDriver.ParseFile(&modelName, content, url, apiConfig, parseFileConfig) | ||
| if err != nil { |
There was a problem hiding this comment.
ParseFile chooses the driver inconsistently and can construct a broken instance when base_url is empty.
In the not-found branch, ParseFile skips local base_url override entirely; in the active branch it always calls NewInstance even when base_url is empty. This diverges from the existing service pattern and can break parse calls for both local and hosted configs.
Suggested fix
+ driver := providerInfo.ModelDriver
+ if baseURL, ok := extra["base_url"]; ok && baseURL != "" {
+ newURL := map[string]string{region: baseURL}
+ driver = driver.NewInstance(newURL)
+ }
@@
- response, err = providerInfo.ModelDriver.ParseFile(&modelName, content, url, apiConfig, parseFileConfig)
+ response, err = driver.ParseFile(&modelName, content, url, apiConfig, parseFileConfig)
@@
- newURL := map[string]string{
- region: extra["base_url"],
- }
- newProviderInfo := providerInfo.ModelDriver.NewInstance(newURL)
+ driver := providerInfo.ModelDriver
+ if baseURL, ok := extra["base_url"]; ok && baseURL != "" {
+ newURL := map[string]string{region: baseURL}
+ driver = driver.NewInstance(newURL)
+ }
@@
- response, err = newProviderInfo.ParseFile(&modelName, content, url, apiConfig, parseFileConfig)
+ response, err = driver.ParseFile(&modelName, content, url, apiConfig, parseFileConfig)Also applies to: 1833-1849
🤖 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/service/model_service.go` around lines 1801 - 1813, ParseFile
currently selects the model driver inconsistently and may call NewInstance with
an empty base_url, producing a broken instance; update the logic so both
branches follow the same rule: only construct a new instance via NewInstance
when a non-empty base_url (or other local override) is present, otherwise use
providerInfo.ModelDriver.ParseFile directly. Specifically, in ParseFile adjust
the not-found branch to honor any local base_url override (parse
extra["base_url"] / base_url variable) instead of skipping it, and in the
active-instance branch guard the NewInstance call (and assignment of
apiConfig.ApiKey/Region) so it is only invoked when base_url is non-empty; apply
the same fix to the second occurrence around the other ParseFile call (the
1833-1849 region) to keep behavior consistent.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14892 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
Type of change