Skip to content

Implement OpenAI chat completions in GO - #16177

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
qinling0210:openai_chat_go
Jun 18, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
qinling0210:openai_chat_go

Conversation

@qinling0210

@qinling0210 qinling0210 commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Implement OpenAI chat completions in GO

POST /api/v1/openai/<chat_id>/chat/completions

OpenAI chat cli: internal/development.md

Type of change

  • Refactoring

@qinling0210 qinling0210 self-assigned this Jun 18, 2026
@coderabbitai

coderabbitai Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds an OpenAI-compatible chat completions API and CLI command, routes completion through the shared pipeline, expands tool-calling and retrieval helpers, adds SQL execution backends for Elasticsearch and Infinity, and introduces timing, tracing, tokenizer, and content-processing support.

Changes

OpenAI chat and pipeline updates

Layer / File(s) Summary
API and CLI surface
cmd/server_main.go, internal/router/router.go, internal/handler/openai_chat.go, internal/cli/*, internal/development.md
Adds the authenticated OpenAI-compatible chat completions route, request validation at the HTTP boundary, CLI parsing/dispatch/help/output support for OPENAI_CHAT, and matching command documentation.
OpenAI chat service and model contracts
internal/service/openai_chat.go, internal/service/openai_chat_test.go, internal/entity/models/types.go, internal/entity/models/chat_tools.go, internal/entity/models/openai.go, internal/entity/models/siliconflow.go, internal/common/metadata_utils.go, internal/service/metadata_filter.go, internal/service/model_service.go, internal/service/tenant.go
Implements OpenAI-style request normalization, generation-config merging, message filtering, reference enrichment, SSE chunk formatting, tool-aware model contracts, and service tests for request and stream behavior.
Chat session pipeline, prompt config, timing, and tracing
internal/service/chat.go, internal/service/chat_session.go, internal/service/chat_session_test.go, internal/service/chat_pipeline_test.go, internal/common/timer.go, internal/common/timer_test.go, internal/service/langfuse.go
Moves chat session completion onto the shared pipeline, makes prompt-config fields optional with conditional persistence, adds timer and Langfuse helpers, and rewrites tests around pipeline-driven completion and reference formatting.
SQL execution and SQL-backed reference handling
internal/engine/engine.go, internal/engine/global.go, internal/engine/elasticsearch/sql.go, internal/engine/elasticsearch/sql_test.go, internal/engine/infinity/chunk.go, internal/engine/infinity/client.go, internal/engine/infinity/metadata.go, internal/engine/infinity/sql.go, internal/engine/infinity/sql_test.go, api/db/services/dialog_service.py
Adds RunSQL to document engines, wires tokenizer registration into engine startup, implements SQL execution for Elasticsearch and Infinity, specializes Infinity metadata queries, updates Python SQL prompt guidance and retrieval logging, and expands SQL/reference test coverage.
Retrieval, research, tokenizer, and content utilities
internal/service/deep_researcher.go, internal/service/toc_enhancer.go, internal/service/toc_enhancer_test.go, internal/tokenizer/*, internal/service/generator.go, internal/service/file.go, internal/service/nlp/retrieval.go, internal/service/citation.go, internal/service/kb_prompt.go, internal/service/kb_prompt_test.go, internal/service/kg/scoring.go, internal/service/ask_service.go, go.mod, rag/prompts/generator.py, internal/common/multimodal.go
Adds recursive research and TOC enhancement flows, tokenizer-based token counting, question refinement, file-content extraction, chunk-vector fetching, citation normalization helpers, multimodal content handling, and related supporting changes across retrieval and prompt utilities.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Suggested labels

💞 feature

Suggested reviewers

  • JinHai-CN
  • Haruko386

Poem

🐇 I tapped a prompt with twitching paw,
and streams of answers hopped in awe.
New routes, new tools, new SQL trails,
with token-counting cottontail tales.
In burrowed logs the timings sing—
a carrot-bright refactor spring.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 67.94% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is minimal and somewhat vague. While it identifies the problem (implementing OpenAI chat completions) and lists the endpoint, it lacks substantive details about implementation scope, design decisions, or motivation. Expand the description to explain the implementation approach, key changes, motivation for the refactoring classification, and why this feature is needed.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title "Implement OpenAI chat completions in GO" clearly and specifically describes the main feature added: OpenAI chat completions functionality in Go.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@qinling0210
qinling0210 marked this pull request as ready for review June 18, 2026 05:42
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jun 18, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/service/chat.go (1)

389-400: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Initialize missing PromptConfig before defaulting.

If prompt_config is omitted, req.PromptConfig is nil; applyPromptDefaults(promptConfig) and later promptConfig.Parameters dereference it and can panic instead of applying defaults.

🐛 Proposed fix
 	promptConfig := req.PromptConfig
+	if promptConfig == nil {
+		promptConfig = &PromptConfig{}
+	}
 
 	// Process kb_ids
 	kbIDs := req.KBIDs
🤖 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/chat.go` around lines 389 - 400, The promptConfig variable
can be nil if prompt_config is omitted from the request, which causes a panic
when applyPromptDefaults attempts to dereference it. Initialize promptConfig to
an empty or default PromptConfig struct if it is nil, similar to how kbIDs is
handled in the code block. Add a nil check after assigning promptConfig from
req.PromptConfig, and if it is nil, create a new instance before calling
applyPromptDefaults.
🟠 Major comments (18)
internal/cli/user_command.go-3958-3966 (1)

3958-3966: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Streaming path suppresses answer output in CLI.

This function sets streamed: true, but it does not print deltas live. In internal/cli/response.go, Line 695–Line 702, streamed responses skip Thinking: and Answer: output, so users can end up seeing no final answer.

💡 Suggested fix
 	return &OpenAIChatResponse{
 		Duration:  resp.Duration,
 		Reasoning: fullReason,
 		Data: &openAIChatData{
 			Model:   resolvedMod,
 			Choices: []openAIChatChoice{{Message: openAIChatMessage{Content: fullContent, ReasoningContent: fullReason}}},
 		},
-		streamed: true,
+		streamed: false,
 		raw:      resp.Body,
 	}, 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/cli/user_command.go` around lines 3958 - 3966, The
OpenAIChatResponse struct being created in this function sets streamed to true,
which causes the response handler in response.go to skip printing the final
Thinking and Answer output (lines 695-702). To fix this, modify the streaming
response handling logic in response.go to ensure the final Answer is printed to
the user even when streamed is true. This may involve either adjusting the
condition that skips output for streamed responses or adding a separate print
statement after streaming completes to display the final answer content from the
fullContent or fullReason variables.
internal/cli/user_command.go-3930-3947 (1)

3930-3947: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle delta.final_content in SSE parsing.

The parser ignores delta.final_content. Your server’s final SSE chunk can carry final answer there, so content may be lost when intermediate delta.content chunks are absent.

💡 Suggested fix
 		var chunk struct {
 			Model   string `json:"model"`
 			Choices []struct {
 				Delta struct {
 					Content          string `json:"content"`
 					ReasoningContent string `json:"reasoning_content"`
+					FinalContent     string `json:"final_content"`
 				} `json:"delta"`
 				FinishReason string `json:"finish_reason"`
 			} `json:"choices"`
 			Usage *openAIChatUsage `json:"usage"`
 		}
@@
 		if len(chunk.Choices) > 0 {
-			if d := chunk.Choices[0].Delta.Content; d != "" {
-				fullContent += d
+			delta := chunk.Choices[0].Delta
+			if delta.FinalContent != "" {
+				fullContent = delta.FinalContent
+			} else if delta.Content != "" {
+				fullContent += delta.Content
 			}
-			if r := chunk.Choices[0].Delta.ReasoningContent; r != "" {
+			if r := delta.ReasoningContent; r != "" {
 				fullReason += r
 			}
 		}
🤖 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 3930 - 3947, The SSE parser in the
Delta struct is missing handling for the final_content field that the server may
send in its final chunk. Add a FinalContent string field to the Delta struct
definition (alongside the existing Content and ReasoningContent fields), then
update the content accumulation logic where you check
chunk.Choices[0].Delta.Content to also check for and append
chunk.Choices[0].Delta.FinalContent to the fullContent variable, ensuring that
final answer content is captured even when intermediate delta.content chunks are
absent.
internal/handler/openai_chat.go-59-63 (1)

59-63: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Cap request body size before io.ReadAll.

io.ReadAll(c.Request.Body) is unbounded here. A large payload can exhaust memory and degrade API availability.

💡 Suggested fix
+const maxOpenAIChatBodyBytes = 2 << 20 // 2 MiB
+
-	bodyBytes, err := io.ReadAll(c.Request.Body)
+	bodyBytes, err := io.ReadAll(io.LimitReader(c.Request.Body, maxOpenAIChatBodyBytes+1))
 	if err != nil {
 		jsonError(c, common.CodeArgumentError, err.Error())
 		return
 	}
+	if len(bodyBytes) > maxOpenAIChatBodyBytes {
+		jsonError(c, common.CodeArgumentError, "request body is too large")
+		return
+	}
🤖 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/openai_chat.go` around lines 59 - 63, The io.ReadAll call
reading from c.Request.Body is unbounded and can cause memory exhaustion with
large payloads. Wrap c.Request.Body with a size limit before calling io.ReadAll
to prevent excessive memory consumption. Use http.MaxBytesReader or
io.LimitedReader to enforce a reasonable maximum request body size that matches
your API requirements, then apply io.ReadAll on the limited reader.
internal/service/openai_chat.go-388-393 (1)

388-393: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use isContentDelta in the stream loop to prevent sentinel leakage.

At Line 388, any non-empty result.Answer (including "[DONE]") is appended and emitted as user-visible content. isContentDelta already encodes the required filter but is currently bypassed.

Proposed fix
-				if result.Answer != "" {
+				if isContentDelta(&result.Answer) {
 					delta := result.Answer
 					fullContent += delta
 					completionTok += tokenizer.NumTokensFromString(delta)
 					events <- OpenAIStreamEvent{Kind: OpenAIEventContent, Delta: delta}
🤖 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/openai_chat.go` around lines 388 - 393, The condition that
checks if result.Answer is not empty is currently bypassing the isContentDelta
filter, which allows sentinel values like "[DONE]" to leak into the user-visible
content stream. Wrap the content handling logic (where fullContent is appended,
tokens are counted, and the OpenAIStreamEvent is emitted) with an additional
check using isContentDelta to ensure only valid content deltas are processed and
emitted, preventing sentinel values from being exposed to the client.
internal/service/openai_chat.go-228-245 (1)

228-245: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle empty model as the default sentinel before explicit-model checks.

At Line 235, "" satisfies req.Model != "model", so the explicit-model path runs and Line 240 calls GetAPIKeyFromInstance with an invalid composite name, returning "Cannot use specified model" instead of using the dialog/default model.

Proposed fix
-	resolvedModel := req.Model
-	if req.Model == "model" {
+	modelInput := strings.TrimSpace(req.Model)
+	if modelInput == "" {
+		modelInput = "model"
+	}
+	resolvedModel := modelInput
+	if modelInput == "model" {
 		resolvedModel = dialog.LLMID
 		if resolvedModel == "" {
 			resolvedModel = "model"
 		}
 	}
-	if req.Model != "model" {
+	if modelInput != "model" {
 		if _, _, _, _, mErr := s.pipeline.ModelProviderSvc.GetChatModelConfig(dialog.TenantID, resolvedModel); mErr != nil {
-			s.writeArgError(c, fmt.Sprintf("`llm_id` %s doesn't exist", req.Model))
+			s.writeArgError(c, fmt.Sprintf("`llm_id` %s doesn't exist", modelInput))
 			return
 		}
-		apiKey, apiErr := s.tenantLLMSvc.GetAPIKeyFromInstance(dialog.TenantID, req.Model)
+		apiKey, apiErr := s.tenantLLMSvc.GetAPIKeyFromInstance(dialog.TenantID, modelInput)
 		if apiErr != nil || apiKey == "" {
-			s.writeDataError(c, fmt.Sprintf("Cannot use specified model %s.", req.Model))
+			s.writeDataError(c, fmt.Sprintf("Cannot use specified model %s.", modelInput))
 			return
 		}
 		dialog.LLMID = resolvedModel
 	}
🤖 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/openai_chat.go` around lines 228 - 245, The issue is that an
empty string satisfies the condition `req.Model != "model"` at line 235, causing
empty model identifiers to be treated as explicit models and entering the
validation path where GetAPIKeyFromInstance is called with an invalid model
name. Fix this by modifying the condition at line 235 to also check that
req.Model is not empty, so the explicit-model validation path is only executed
for non-empty, non-default model values. This ensures that empty strings and the
default sentinel "model" are both handled as defaults and use the dialog.LLMID
fallback instead of triggering the error path.
internal/entity/models/openai.go-415-422 (1)

415-422: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Non-deterministic tool call ordering when populating ToolCallsResult.

Go map iteration order is undefined. The accumulated tool calls are indexed by int (the index field from SSE deltas), but iterating over the map with for _, tc := range accumulatedToolCalls may produce tool calls in random order, breaking downstream consumers that expect the original order.

🔧 Proposed fix to preserve ordering
 	if len(accumulatedToolCalls) > 0 && chatModelConfig != nil {
-		tcs := make([]map[string]interface{}, 0, len(accumulatedToolCalls))
-		for _, tc := range accumulatedToolCalls {
-			tcs = append(tcs, tc)
+		// Preserve tool call order by index
+		maxIdx := -1
+		for idx := range accumulatedToolCalls {
+			if idx > maxIdx {
+				maxIdx = idx
+			}
+		}
+		tcs := make([]map[string]interface{}, 0, len(accumulatedToolCalls))
+		for i := 0; i <= maxIdx; i++ {
+			if tc, ok := accumulatedToolCalls[i]; ok {
+				tcs = append(tcs, tc)
+			}
 		}
 		chatModelConfig.ToolCallsResult = &tcs
 	}
🤖 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/openai.go` around lines 415 - 422, The iteration over
the `accumulatedToolCalls` map using `for _, tc := range accumulatedToolCalls`
produces non-deterministic ordering because Go maps have undefined iteration
order. To fix this, extract the integer keys (indices) from the
`accumulatedToolCalls` map, sort them in ascending order, and then iterate
through the sorted indices to build the `tcs` slice in the correct deterministic
order. This ensures tool calls are appended to the ToolCallsResult in their
original sequence as indicated by the index field.
internal/entity/models/types.go-254-273 (1)

254-273: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Silent failure when tools JSON marshaling fails.

If json.Marshal(tools) fails on line 263, toolsJSON remains empty but ToolConfig is still assigned. This silently corrupts the tool binding—downstream code will see ToolConfig != nil but Tools == "", causing json.Unmarshal to fail in ChatWithTools/ChatStreamlyWithTools.

Consider returning an error or logging the failure:

🛠️ Proposed fix to surface marshaling errors
-func (cm *ChatModel) BindTools(session ToolCallSession, tools interface{}) {
+func (cm *ChatModel) BindTools(session ToolCallSession, tools interface{}) error {
 	// Serialize tools to JSON if it's a list/map.
 	toolsJSON := ""
 	switch v := tools.(type) {
 	case string:
 		toolsJSON = v
 	case []byte:
 		toolsJSON = string(v)
 	default:
-		if b, err := json.Marshal(tools); err == nil {
-			toolsJSON = string(b)
+		b, err := json.Marshal(tools)
+		if err != nil {
+			return fmt.Errorf("BindTools: failed to marshal tools: %w", err)
 		}
+		toolsJSON = string(b)
 	}
+	if toolsJSON == "" {
+		return fmt.Errorf("BindTools: tools JSON is empty")
+	}
 	cm.ToolConfig = &ToolConfig{
 		Tools:           toolsJSON,
 		MaxRounds:       defaultMaxRounds,
 		MaxRetries:      defaultMaxRetries,
 		ToolCallSession: session,
 	}
+	return 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/types.go` around lines 254 - 273, The BindTools method
on ChatModel silently ignores errors when json.Marshal fails in the default case
of the type switch, leaving toolsJSON empty while still assigning ToolConfig
with the empty Tools field. This causes downstream failures. Modify the method
to handle the json.Marshal error appropriately by either changing the method
signature to return an error and returning early when marshaling fails, or by
logging the error before assigning ToolConfig. Ensure that ToolConfig is only
assigned when tools are successfully serialized.
internal/entity/models/chat_tools.go-243-276 (1)

243-276: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Nil session dereference in concurrent goroutines.

appendToolResults calls session.ToolCall(...) on line 265 without checking if session is nil. If cm.ToolConfig.ToolCallSession is nil (which ChatWithTools doesn't explicitly guard against after the ToolConfig != nil check), this will panic inside the goroutine.

🛡️ Proposed fix to guard nil session
 func appendToolResults(history []Message, toolCalls []map[string]interface{}, session ToolCallSession, tokenCount *int) []Message {
+	if session == nil {
+		// No session to execute tool calls; append error results
+		history = append(history, Message{
+			Role:      "assistant",
+			Content:   nil,
+			ToolCalls: toolCalls,
+		})
+		for _, tc := range toolCalls {
+			tcID, _ := tc["id"].(string)
+			history = append(history, Message{
+				Role:       "tool",
+				Content:    "Error: no tool call session available",
+				ToolCallID: tcID,
+			})
+		}
+		return history
+	}
 	var mu sync.Mutex
🤖 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/chat_tools.go` around lines 243 - 276, The concurrent
goroutine spawned in the loop that processes toolCalls calls
session.ToolCall(name, args) without checking if session is nil, which will
panic if cm.ToolConfig.ToolCallSession is nil. Add a nil check for session
before invoking session.ToolCall, and when session is nil, handle it
appropriately by setting result.content to an error message indicating that the
tool session is not available.
internal/service/chat_session.go-397-399 (1)

397-399: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Marshal dynamic SSE error payloads.

Line 398 interpolates err.Error() directly into a JSON literal; provider errors containing quotes or newlines will produce malformed SSE JSON. Build the payload and json.Marshal it instead.

🐛 Proposed fix
 	resultChan, err := s.pipeline.AsyncChat(ctx, dialog, messages, true, chatModelConfig)
 	if err != nil {
-		streamChan <- fmt.Sprintf("data: %s\n\n", fmt.Sprintf(`{"code": 500, "message": "%s", "data": {"answer": "**ERROR**: %s", "reference": []}}`, err.Error(), err.Error()))
+		payload, _ := json.Marshal(map[string]interface{}{
+			"code":    500,
+			"message": err.Error(),
+			"data": map[string]interface{}{
+				"answer":    "**ERROR**: " + err.Error(),
+				"reference": []interface{}{},
+			},
+		})
+		streamChan <- fmt.Sprintf("data: %s\n\n", string(payload))
 		return err
 	}
🤖 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/chat_session.go` around lines 397 - 399, The error payload
on the streamChan assignment is constructing JSON through string interpolation
of err.Error() directly into a JSON literal, which will produce malformed JSON
if the error contains quotes or newlines. Instead, create a struct or map to
represent the error response data with fields for code, message, and the answer
with error details, then use json.Marshal to safely serialize it to JSON before
formatting it as SSE data with the "data: " prefix. This ensures special
characters in errors are properly escaped.
internal/service/citation.go-36-39 (1)

36-39: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

HasCitationMarkers can false-positive on non-citation bracketed numbers.

Because Line 38 allows bare "[N]", Line 302 returns true for text like "[2024]". In the chat pipeline gate, that can skip citation insertion even when no valid chunk citation exists.

💡 Proposed fix
 var CitationMarkerPattern = regexp.MustCompile(`\[(?:ID:\s*)?([0-9\x{0660}-\x{0669}\x{06F0}-\x{06F9}]+)\]`)
+var strictCitationMarkerPattern = regexp.MustCompile(`\[ID:\s*([0-9\x{0660}-\x{0669}\x{06F0}-\x{06F9}]+)\]`)
@@
 func HasCitationMarkers(answer string) bool {
 	if answer == "" {
 		return false
 	}
-	return CitationMarkerPattern.MatchString(normalizeArabicDigits(answer))
+	return strictCitationMarkerPattern.MatchString(normalizeArabicDigits(answer))
 }

Also applies to: 297-303

🤖 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/citation.go` around lines 36 - 39, The CitationMarkerPattern
regex at line 38 uses optional "ID:" prefix with the `(?:ID:\s*)?` construct,
causing it to match bare bracketed numbers like "[2024]" which are not actual
citations, leading to false positives in HasCitationMarkers function. To fix
this, modify the CitationMarkerPattern regex to require the "ID:" prefix to be
mandatory rather than optional, removing the question mark after the
non-capturing group so that only properly formatted citation markers like
"[ID:N]" are matched, preventing the false positive matches on dates or other
bracketed numbers in the text.
internal/engine/elasticsearch/sql.go-140-164 (1)

140-164: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Guard response format before JSON decoding.

Line 142 accepts arbitrary format, but Lines 156-164 always decode JSON. Any non-json format path will fail after a successful SQL call.

💡 Proposed fix
 func (e *elasticsearchEngine) runSQLOnce(ctx context.Context, sqlText string, format string) ([]map[string]interface{}, error) {
 	ctx, cancel := context.WithTimeout(ctx, esSQLRequestTimeout)
 	defer cancel()
+
+	format = strings.TrimSpace(strings.ToLower(format))
+	if format == "" {
+		format = "json"
+	}
+	if format != "json" {
+		return nil, fmt.Errorf("unsupported SQL format %q: only json is supported", format)
+	}
 
 	body := map[string]interface{}{
 		"query":      sqlText,
 		"fetch_size": esSQLFetchSize,
 	}
🤖 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/engine/elasticsearch/sql.go` around lines 140 - 164, The code
accepts an arbitrary format parameter in the esapi.SQLQueryRequest but
unconditionally attempts to decode the response body as JSON in the
json.NewDecoder block. This will fail for non-JSON formats. Add a guard
condition before the JSON decoding logic to verify that the format is JSON (or
empty, if JSON is the default), and either skip JSON decoding for other formats
or return an appropriate error if non-JSON formats are not supported. Reference
the format variable and the json.NewDecoder(res.Body).Decode call to locate
where this check needs to be added.
internal/service/toc_enhancer.go-536-538 (1)

536-538: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Results truncated without sorting by score first.

The scoreEntries function truncates result to limit entries without sorting by score. This could arbitrarily drop high-scoring entries in favor of lower-scoring ones that happened to appear earlier in the map iteration order.

🐛 Proposed fix
+	// Sort by score descending before truncating
+	sort.Slice(result, func(i, j int) bool {
+		return result[i].Score > result[j].Score
+	})
 	if limit > 0 && len(result) > limit {
 		result = result[:limit]
 	}
🤖 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/toc_enhancer.go` around lines 536 - 538, In the scoreEntries
function, the result is being truncated to the limit without sorting by score
first, which means lower-scoring entries that appeared earlier in map iteration
could be kept while higher-scoring entries are dropped. Before the truncation
logic (the if statement that checks if limit is greater than 0), sort the result
slice by score in descending order so that when the limit is applied, the
highest-scoring entries are preserved.
api/db/services/dialog_service.py-762-774 (1)

762-774: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Potential KeyError when knowledges contains only empty strings.

Line 772 checks if knowledges but line 766 only sets kwargs["knowledge"] when knowledge_text is truthy. If knowledges = [""], then:

  • knowledge_text = "" (falsy) → kwargs["knowledge"] is not set
  • knowledges is truthy → condition on line 772 passes
  • Line 773 accesses kwargs["knowledge"] → KeyError
🐛 Proposed fix
-    if knowledges and "{knowledge}" not in prompt_config.get("system", ""):
+    if knowledge_text and "{knowledge}" not in prompt_config.get("system", ""):
         system_content += kwargs["knowledge"]
🤖 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 `@api/db/services/dialog_service.py` around lines 762 - 774, The condition on
line 772 checks if knowledges is truthy, but this does not guarantee that
kwargs["knowledge"] was set because kwargs["knowledge"] is only assigned when
knowledge_text is truthy (line 764-765). If knowledges contains only empty
strings, knowledge_text will be empty (falsy) and kwargs["knowledge"] won't be
set, causing a KeyError when accessed on line 773. Change the condition from
checking `if knowledges` to checking `if knowledge_text` to ensure that
kwargs["knowledge"] was actually populated before attempting to access it.
internal/service/nlp/retrieval.go-1090-1096 (1)

1090-1096: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate dim before allocating vectors.

dim is not guarded; a negative value will panic at Line 1114 (make([]float64, dim)).

💡 Suggested fix
 func (s *RetrievalService) FetchChunkVectors(ctx context.Context, chunkIDs []string, tenantIDs []string, kbIDs []string, dim int) (map[string][]float64, error) {
+	if dim <= 0 {
+		return nil, fmt.Errorf("FetchChunkVectors: invalid dim %d", dim)
+	}
 	if len(chunkIDs) == 0 {
 		return map[string][]float64{}, nil
 	}

Also applies to: 1114-1114

🤖 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/nlp/retrieval.go` around lines 1090 - 1096, The
FetchChunkVectors function does not validate the dim parameter, which could be
negative and cause a panic when make([]float64, dim) is called at line 1114. Add
a validation check at the start of the FetchChunkVectors function to ensure dim
is greater than 0, and return an appropriate error if the validation fails
(similar to the existing check for empty chunkIDs). This prevents runtime panics
from invalid dimension values.
internal/service/generator.go-309-316 (1)

309-316: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle non-string message content in question reconstruction.

Line 314 and Line 369 only read content as string. For multimodal messages (content as array/object), this path drops user text and can return an empty fallback question.

💡 Suggested fix
+func contentToText(v interface{}) string {
+	switch c := v.(type) {
+	case string:
+		return c
+	case []interface{}:
+		var parts []string
+		for _, it := range c {
+			if m, ok := it.(map[string]interface{}); ok {
+				if t, _ := m["type"].(string); t == "text" {
+					if txt, _ := m["text"].(string); txt != "" {
+						parts = append(parts, txt)
+					}
+				}
+			}
+		}
+		return strings.TrimSpace(strings.Join(parts, " "))
+	default:
+		return ""
+	}
+}
...
-		content, _ := m["content"].(string)
+		content := contentToText(m["content"])
...
-			if c, ok := messages[i]["content"].(string); ok {
-				return c
-			}
-			return ""
+			return contentToText(messages[i]["content"])

Also applies to: 365-373

🤖 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/generator.go` around lines 309 - 316, The code in the
message processing loop silently discards the error when converting the content
field to a string using type assertion, which causes multimodal messages where
content is an array or object to be skipped entirely, resulting in lost user
text and potentially empty question reconstruction. Modify the content
extraction logic to handle multiple content types: check if content is a string
and use it directly, or if it is an array or object (for multimodal messages),
extract and concatenate the text portions appropriately, ensuring that all
message content is preserved in the convLines regardless of whether the original
message content was a simple string or a complex multimodal structure.
internal/service/deep_researcher.go-711-722 (1)

711-722: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

kbPrompt truncation/formatting uses mismatched chunk lists.

You tokenize/filter knowledges, but later format chunksRaw[:chunksNum]. If some raw chunks have empty content (or truncation occurs), this can include wrong chunks and drop valid ones.

💡 Suggested fix
-	var knowledges []string
+	type selectedChunk struct {
+		chunk map[string]interface{}
+		text  string
+	}
+	var selected []selectedChunk
 	for _, m := range chunksRaw {
 		text := getMapString(m, "content")
 		if text == "" {
 			text = getMapString(m, "content_with_weight")
 		}
 		if text == "" {
 			continue
 		}
-		knowledges = append(knowledges, text)
+		selected = append(selected, selectedChunk{chunk: m, text: text})
 	}
 
-	if len(knowledges) == 0 {
+	if len(selected) == 0 {
 		return nil
 	}
 
 	// Truncate at 97% token budget.
 	usedTokens := 0
-	chunksNum := 0
-	for i, c := range knowledges {
-		usedTokens += tokenizer.NumTokensFromString(c)
-		chunksNum++
-		if usedTokens > int(float64(maxTokens)*0.97) {
-			knowledges = knowledges[:i]
+	kept := make([]selectedChunk, 0, len(selected))
+	for _, sc := range selected {
+		next := usedTokens + tokenizer.NumTokensFromString(sc.text)
+		if next > int(float64(maxTokens)*0.97) {
 			common.Warn("kb_prompt: truncating chunks",
-				zap.Int("kept", len(knowledges)),
+				zap.Int("kept", len(kept)),
 				zap.Int("total", len(chunksRaw)))
 			break
 		}
+		usedTokens = next
+		kept = append(kept, sc)
 	}
 
 	// Format each chunk.
-	knowledges = nil // reuse
-	for i, m := range chunksRaw[:chunksNum] {
+	knowledges := make([]string, 0, len(kept))
+	for i, sc := range kept {
+		m := sc.chunk
...
-		text := getMapString(m, "content")
-		if text == "" {
-			text = getMapString(m, "content_with_weight")
-		}
-		cnt += text
+		cnt += sc.text
 		knowledges = append(knowledges, cnt)
 	}

Also applies to: 729-746

🤖 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/deep_researcher.go` around lines 711 - 722, The code
extracts filtered content into the `knowledges` list by skipping chunks with
empty content fields, but later formats the kbPrompt using
`chunksRaw[:chunksNum]` which includes all raw chunks (including the ones that
were skipped). This mismatch means the prompt may contain wrong chunks or miss
valid ones. Track which raw chunks are actually added to the `knowledges` list
during the extraction loop, then use those same filtered chunks (not
`chunksRaw[:chunksNum]`) when formatting the prompt. You can either store the
indices of valid chunks and reference them later, or build a parallel filtered
chunks list alongside `knowledges`.
internal/service/nlp/retrieval.go-1113-1151 (1)

1113-1151: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Populate zero vectors for all requested chunk IDs, not only hits.

The function comment says missing chunks get zero vectors, but the map is currently filled only for chunks returned by Search. Missing IDs are omitted.

💡 Suggested fix
-	out := make(map[string][]float64, len(chunkIDs))
-	zero := make([]float64, dim)
+	out := make(map[string][]float64, len(chunkIDs))
+	for _, cid := range chunkIDs {
+		out[cid] = make([]float64, dim)
+	}
...
-		if len(vec) != dim {
-			vec = zero
-		}
-		out[cid] = vec
+		if len(vec) == dim {
+			out[cid] = vec
+		}
🤖 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/nlp/retrieval.go` around lines 1113 - 1151, The current code
only populates the output map with chunks that are actually returned in
result.Chunks, but according to the function comment, all requested chunk IDs
should be included in the output map with zero vectors for missing ones. Add a
loop before the existing chunk processing loop that iterates through all
chunkIDs and initializes each one in the out map with the zero vector. Then the
existing loop that processes result.Chunks will overwrite these zero vectors
with actual data for chunks that are found, while leaving zero vectors for any
requested IDs that were not returned in the results.
internal/service/deep_researcher.go-428-453 (1)

428-453: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle non-200 Tavily responses explicitly.

The code parses response JSON without checking StatusCode. Auth/rate-limit/server errors can be silently downgraded to “no results”.

💡 Suggested fix
 	resp, err := client.Do(req)
 	if err != nil {
 		return nil, fmt.Errorf("tavily call: %w", err)
 	}
 	defer resp.Body.Close()
 
 	body, err := io.ReadAll(resp.Body)
 	if err != nil {
 		return nil, fmt.Errorf("tavily read: %w", err)
 	}
+	if resp.StatusCode != http.StatusOK {
+		msg := strings.TrimSpace(string(body))
+		if len(msg) > 512 {
+			msg = msg[:512]
+		}
+		return nil, fmt.Errorf("tavily call failed with status %d: %s", resp.StatusCode, msg)
+	}
🤖 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/deep_researcher.go` around lines 428 - 453, The code does
not validate the HTTP status code from the Tavily API response before attempting
to parse it, which allows authentication failures, rate limits, and server
errors to be silently treated as empty results. After the client.Do(req) call
succeeds and before calling io.ReadAll(resp.Body), check resp.StatusCode to
ensure it indicates success (typically http.StatusOK or 200). If the status code
indicates an error, return an appropriate error wrapping the status code and
potentially the response body to provide debugging context instead of proceeding
to parse the body as JSON.
🟡 Minor comments (11)
internal/cli/user_parser.go-4893-4977 (1)

4893-4977: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Normalize OPENAI_CHAT option names before option dispatch.

handleOption only matches lowercase keys, but option names are passed with original casing. Inputs like OPENAI_CHAT ... MODEL 'x' can fail as unknown options. Normalize once via strings.ToLower(name) in handleOption.

Proposed fix
 handleOption := func(name string) error {
-	switch name {
+	switch strings.ToLower(name) {
 	case "model", "system":
 		v, err := p.parseQuotedString()
🤖 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_parser.go` around lines 4893 - 4977, The handleOption
function receives option names with original casing (e.g., "MODEL",
"Temperature") but the switch statement only matches lowercase keys like
"model", "system", etc., causing valid options with different casing to fall
through to the default case and report unknown option errors. Normalize the name
parameter to lowercase using strings.ToLower() at the beginning of the
handleOption function, before the switch statement, so that all case variations
of valid options are properly matched against the switch cases.
internal/development.md-163-163 (1)

163-163: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add language identifiers to fenced code blocks (MD040).

These fenced blocks are missing a language token (for example text or bash), which is triggering markdownlint warnings.

Also applies to: 169-169, 175-175, 179-179, 184-184, 189-189, 194-194, 200-200, 205-205, 380-380, 411-411, 506-506

🤖 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/development.md` at line 163, Add language identifiers to all fenced
code blocks in the development.md file that are currently missing them. For each
opening code fence (the triple backticks) throughout the file at the specified
line numbers (163, 169, 175, 179, 184, 189, 194, 200, 205, 380, 411, 506),
append an appropriate language token such as `bash`, `text`, `python`,
`javascript`, or whichever language corresponds to the code block content. This
will resolve the markdownlint MD040 warnings related to missing language
identifiers.

Source: Linters/SAST tools

internal/common/multimodal.go-75-77 (1)

75-77: ⚠️ Potential issue | 🟡 Minor

URL-sourced images lack MediaType, breaking Gemini API calls.

At line 76, parseDataURIOrB64 returns a URL source without setting MediaType. Later, RenderContentPartsForFactory for Gemini (lines 293–299) passes this empty MediaType as mime_type in the file_data object. The Gemini API requires mime_type to be set in file_data structures; sending an empty string will cause API errors. Compare this to data URI sources (line 67) which default to "image/png" and raw base64 sources (line 86) which also default to "image/png". URL sources should receive a similar default.

🤖 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/common/multimodal.go` around lines 75 - 77, The ContentSource
returned for URL-based images in the parseDataURIOrB64 function lacks a
MediaType field, which causes the Gemini API to receive an empty mime_type value
that it requires. Add a default MediaType value to the ContentSource returned
when the URL condition is met (the strings.HasPrefix checks for "http://" or
"https://"), setting it to "image/png" to match the default behavior already
applied to data URI sources at line 67 and base64 sources at line 86.
internal/service/chat.go-242-247 (1)

242-247: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Only default system when it is omitted.

System is now pointer-based, but Line 244 treats an explicit empty string as missing and replaces it with the default prompt. That prevents callers from intentionally creating a dialog with no system prompt.

🐛 Proposed fix
-	if p.System == nil || *p.System == "" {
+	if p.System == nil {
 		s := pyDefaultSystemPrompt
 		p.System = &s
 	}
🤖 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/chat.go` around lines 242 - 247, In the applyPromptDefaults
function, the condition currently checks both if p.System is nil OR if it equals
an empty string. Remove the empty string check from the condition so it only
checks if p.System is nil, allowing callers to intentionally set an empty string
system prompt without it being replaced with the default pyDefaultSystemPrompt
value.
internal/common/timer_test.go-41-46 (1)

41-46: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Relax sleep-based upper bounds to reduce CI flakiness.

The < 50ms ceilings around tiny sleeps are brittle under runtime jitter. Prefer lower-bound-only checks (or substantially wider upper bounds).

Suggested change
- if got < 4*time.Millisecond || got > 50*time.Millisecond {
+ if got < 4*time.Millisecond {
  	t.Errorf("PhaseCheckLLM = %v, want ~5ms", got)
  }
...
- if got < 2*time.Millisecond || got > 50*time.Millisecond {
+ if got < 2*time.Millisecond {
  	t.Errorf("PhaseBindModels = %v, want ~3ms", got)
  }
...
- if got < 2*time.Millisecond || got > 50*time.Millisecond {
+ if got < 2*time.Millisecond {
  	t.Errorf("PhaseGenerateAnswer = %v, want ~3ms", got)
  }
...
- if got < 5*time.Millisecond || got > 50*time.Millisecond {
+ if got < 5*time.Millisecond {
  	t.Errorf("PhasePreRetrieval = %v, want ~6ms (outer span)", got)
  }

Also applies to: 74-80

🤖 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/common/timer_test.go` around lines 41 - 46, The upper bound checks
in the timer test assertions (the `got > 50*time.Millisecond` conditions for
PhaseCheckLLM and PhaseBindModels, as well as similar assertions at lines 74-80)
are too strict and cause test flakiness due to runtime jitter. Either remove the
upper bound checks entirely and rely only on lower bound assertions, or
substantially increase the upper bounds to be more lenient and accommodate
system variability. This applies to all timing assertions in the test file where
strict upper bounds are currently enforced against small sleep durations.
internal/service/chat_pipeline_test.go-535-540 (1)

535-540: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Assert reference-map types explicitly to avoid false-positive tests.

These assertions ignore the type-assert ok value, so a type drift in ref["chunks"], ref["doc_aggs"], or ref["total"] can still pass via zero-values. Fail fast on !ok before semantic checks.

Suggested fix pattern
- if chunks, _ := ref["chunks"].([]map[string]interface{}); len(chunks) != 0 {
- 	t.Errorf("scalar branch chunks = %v, want empty", chunks)
- }
- if total, _ := ref["total"].(int); total != 1 {
- 	t.Errorf("scalar branch total = %d, want 1", total)
- }
+ chunks, ok := ref["chunks"].([]map[string]interface{})
+ if !ok {
+ 	t.Fatalf("ref[\"chunks\"] type = %T, want []map[string]interface{}", ref["chunks"])
+ }
+ if len(chunks) != 0 {
+ 	t.Errorf("scalar branch chunks = %v, want empty", chunks)
+ }
+ total, ok := ref["total"].(int)
+ if !ok {
+ 	t.Fatalf("ref[\"total\"] type = %T, want int", ref["total"])
+ }
+ if total != 1 {
+ 	t.Errorf("scalar branch total = %d, want 1", total)
+ }

Also applies to: 559-561, 1287-1289, 1312-1319, 1383-1390

🤖 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/chat_pipeline_test.go` around lines 535 - 540, The type
assertions for ref["chunks"], ref["total"], and ref["doc_aggs"] are ignoring the
ok boolean return value by using underscore, which means if the type drifts, the
variables will be assigned zero-values and tests can pass incorrectly. Capture
the ok return value from each type assertion (for
ref["chunks"].([]map[string]interface{}), ref["total"].(int), and
ref["doc_aggs"]), and add explicit checks that fail fast with t.Errorf or
t.Fatalf if ok is false before proceeding with the semantic value checks. Apply
this pattern to all instances in the file where type assertions from ref are
performed.
internal/engine/elasticsearch/sql.go-90-92 (1)

90-92: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Trim SQL before empty-check.

Line 90 only checks raw empty string. Inputs like " " pass validation and fail later with noisier backend errors.

💡 Proposed fix
-	if sqlText == "" {
+	sqlText = strings.TrimSpace(sqlText)
+	if sqlText == "" {
 		return nil, fmt.Errorf("Elasticsearch RunSQL: empty SQL")
 	}
🤖 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/engine/elasticsearch/sql.go` around lines 90 - 92, The empty SQL
validation in the RunSQL function only checks for an exactly empty string but
does not account for strings containing only whitespace like "   ". Trim the
sqlText variable before performing the empty-check comparison to ensure that
whitespace-only SQL inputs are properly rejected with a clear validation error
instead of failing later with backend errors.
internal/engine/infinity/sql.go-134-137 (1)

134-137: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Indentation error in rewriteFieldAliases.

Line 135 is indented incorrectly, breaking the visual structure of the for loop. While Go does not enforce indentation semantically, this harms readability and will likely fail gofmt checks.

🧹 Proposed fix
 	for alias, actual := range aliasToActual {
-	pat := regexp.MustCompile(`(^|[,\s])` + regexp.QuoteMeta(alias) + `($|[,\s])`)
+		pat := regexp.MustCompile(`(^|[,\s])` + regexp.QuoteMeta(alias) + `($|[,\s])`)
 		cols = pat.ReplaceAllString(cols, "${1}"+actual+"${2}")
 	}
🤖 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/engine/infinity/sql.go` around lines 134 - 137, In the
`rewriteFieldAliases` function, the line containing the `regexp.MustCompile`
call (where the `pat` variable is assigned) has incorrect indentation that
breaks consistency with the rest of the for loop body. Fix the indentation of
this line to align properly with the subsequent `cols = pat.ReplaceAllString`
statement, ensuring all statements within the for loop are at the same
indentation level to comply with Go formatting standards.
internal/service/toc_enhancer.go-89-94 (1)

89-94: ⚠️ Potential issue | 🟡 Minor

Remove Go function code from prompt string constant.

Lines 89-94 embed the asMap function definition inside the tocRelevanceSystemPrompt string literal, appearing in the middle of the JSON example section. This appears to be an unintended copy-paste artifact. The function has no relevance to TOC scoring and would confuse the LLM by including irrelevant Go syntax in the prompt's demonstration. Remove lines 89-94 from the string; the actual asMap function is properly defined at lines 600-605.

🤖 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/toc_enhancer.go` around lines 89 - 94, Locate the
`tocRelevanceSystemPrompt` string constant and remove the embedded `asMap`
function definition (the function that takes interface{} parameter and returns
map[string]interface{}) from within it. This function code is a copy-paste
artifact appearing in the middle of the JSON example section and should not be
part of the prompt string as it confuses the LLM with irrelevant Go syntax. The
actual `asMap` function is properly defined separately elsewhere in the file, so
removing it from the string literal will not affect functionality.
internal/tokenizer/tokenizer.go-41-43 (1)

41-43: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Guard RegisterEngineType against nil callbacks to prevent panics.

Line 42 assigns get directly; if RegisterEngineType(nil) is called, later engineTypeProvider() calls panic in Tokenize/FineGrainedTokenize.

💡 Proposed fix
 func RegisterEngineType(get func() string) {
-	engineTypeProvider = get
+	if get == nil {
+		engineTypeProvider = func() string { return "" }
+		return
+	}
+	engineTypeProvider = get
 }
🤖 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/tokenizer/tokenizer.go` around lines 41 - 43, The RegisterEngineType
function directly assigns the provided callback function to engineTypeProvider
without validating that it is not nil, which causes a panic when
engineTypeProvider is later invoked in functions like Tokenize or
FineGrainedTokenize if RegisterEngineType was called with a nil argument. Add a
nil check in RegisterEngineType to validate the get parameter before assignment,
and either reject the nil value with an error or provide appropriate error
handling to prevent the function from being called with an invalid state.
internal/tokenizer/tokenizer_test.go-94-101 (1)

94-101: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Assert the whitespace-token expectation instead of only logging it.

Lines 97-100 currently allow a zero-token regression to pass silently even though the test comment says whitespace should still tokenize.

💡 Proposed fix
 func TestNumTokensFromString_WhitespaceOnly(t *testing.T) {
 	for _, s := range []string{" ", "\t", "\n", "   "} {
 		got := NumTokensFromString(s)
 		// Whitespace strings should still produce tokens in BPE encoding
 		if got == 0 {
-			t.Logf("NumTokensFromString(%q) = %d", s, got)
+			t.Errorf("NumTokensFromString(%q) = %d, want >0", s, got)
 		}
 	}
 }
🤖 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/tokenizer/tokenizer_test.go` around lines 94 - 101, The
TestNumTokensFromString_WhitespaceOnly test currently only logs when
NumTokensFromString returns zero tokens, but does not actually assert that this
is a failure. Since the test comment indicates that whitespace strings should
still produce tokens in BPE encoding, replace the t.Logf logging statement with
a proper assertion using t.Errorf that fails the test when got equals zero. This
ensures that any regression where whitespace-only strings incorrectly produce
zero tokens will cause the test to fail rather than pass silently.
🧹 Nitpick comments (6)
internal/service/langfuse.go (1)

219-241: 💤 Low value

Consider adding debug logging for silent failures.

The post method silently discards all errors (JSON unmarshal, HTTP request creation, network errors, non-2xx responses). While this is appropriate for non-blocking observability, it makes diagnosing Langfuse integration issues difficult.

💡 Optional: Add debug-level logging
+import "ragflow/internal/common"
+
 func (c *LangfuseClient) post(ctx context.Context, envelope []byte) {
 	var env struct {
 		Kind string          `json:"kind"`
 		Body json.RawMessage `json:"body"`
 	}
 	if err := json.Unmarshal(envelope, &env); err != nil {
+		common.Debug("langfuse: failed to unmarshal envelope", zap.Error(err))
 		return
 	}
 	url := c.Host + "/api/public/" + env.Kind
 	auth := basicAuth(c.PublicKey, c.SecretKey)
 	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(env.Body))
 	if err != nil {
+		common.Debug("langfuse: failed to create request", zap.Error(err))
 		return
 	}
 	req.Header.Set("Content-Type", "application/json")
 	req.Header.Set("Authorization", auth)
 	res, err := c.HTTP.Do(req)
 	if err != nil {
+		common.Debug("langfuse: request failed", zap.Error(err))
 		return
 	}
 	defer res.Body.Close()
+	if res.StatusCode >= 400 {
+		common.Debug("langfuse: non-2xx response", zap.Int("status", res.StatusCode))
+	}
 	io.Copy(io.Discard, res.Body)
 }
🤖 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/langfuse.go` around lines 219 - 241, The post method in
LangfuseClient silently returns on all error conditions without logging, making
it difficult to diagnose Langfuse integration problems. Add debug-level logging
to each of the four error return points in the post method: after the
json.Unmarshal call, after the http.NewRequestWithContext call, after the
c.HTTP.Do call, and after checking the response status code. Each log statement
should include a descriptive message and the actual error details to help with
troubleshooting while keeping the method non-blocking.
internal/service/chat_session_test.go (2)

64-74: ⚡ Quick win

Make the update fake apply stored updates.

The service reads the session after UpdateByID, but this fake only records the call. Mutating f.sessions[id] and failing missing IDs makes the test double catch read-after-update regressions.

♻️ Proposed fix
 func (f *fakeSessionStore) UpdateByID(id string, updates map[string]interface{}) error {
 	f.mu.Lock()
 	defer f.mu.Unlock()
 	if f.updateByIDErr != nil {
 		return f.updateByIDErr
 	}
+	session, ok := f.sessions[id]
+	if !ok {
+		return errors.New("record not found")
+	}
+	if name, ok := updates["name"].(string); ok {
+		session.Name = &name
+	}
+	if userID, ok := updates["user_id"].(string); ok {
+		session.UserID = &userID
+	}
 	f.updateCalled = append(f.updateCalled, struct {
 		id      string
 		updates map[string]interface{}
 	}{id, updates})
🤖 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/chat_session_test.go` around lines 64 - 74, The UpdateByID
method in the fakeSessionStore only records the call but does not actually apply
the updates to the stored sessions. Modify the UpdateByID method to apply the
updates from the updates map to f.sessions[id] by iterating through the updates
and setting each key-value pair on the stored session, and return an error if
the ID does not exist in f.sessions. This ensures the fake store properly
simulates real store behavior and catches regressions when the service reads the
session after updating it.

574-609: ⚡ Quick win

Cover the terminal streaming result contract.

Production AsyncChat sends delta frames and then a Final=true frame containing the full answer/reference. This test only emits deltas, so it misses duplicate-final-answer and dropped-reference regressions in CompletionStream.

🧪 Proposed test strengthening
 	pipeline := &fakePipeline{
 		resultChan: makeResultChan(
 			AsyncChatResult{Answer: "stream", Reference: map[string]interface{}{"chunks": []interface{}{}}},
 			AsyncChatResult{Answer: " answer", Reference: map[string]interface{}{"chunks": []interface{}{}}},
+			AsyncChatResult{
+				Answer:    "stream answer",
+				Final:     true,
+				Reference: map[string]interface{}{"chunks": []map[string]interface{}{{"chunk_id": "chunk-1"}}},
+			},
 		),
 	}

Also assert the final streamed payload contains chunk-1 and does not contain a duplicated stream answerstream answer payload after fixing CompletionStream.

🤖 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/chat_session_test.go` around lines 574 - 609, The test's
fakePipeline is only emitting delta AsyncChatResult objects and missing the
final frame that production AsyncChat sends. Modify the makeResultChan call in
the test to emit a third AsyncChatResult item that represents the final frame
with Final=true set and contains the complete accumulated answer ("stream
answer") and the full reference with chunks. Additionally, update the test
assertions after reading from streamChan to verify that the final streamed
payload contains the expected chunk data and does not have duplicated answer
content to catch regressions in CompletionStream's handling of the terminal
signal.
rag/prompts/generator.py (1)

207-207: ⚡ Quick win

Add logging for this new prompt-output behavior.

Line 207 introduces a new instruction path but emits no log signal for observability/debugging.

💡 Proposed refactor
+import logging
+
+logger = logging.getLogger(__name__)
@@
 def citation_prompt(user_defined_prompts: dict = {}) -> str:
     template = PROMPT_JINJA_ENV.from_string(user_defined_prompts.get("citation_guidelines", CITATION_PROMPT_TEMPLATE))
-    return template.render() + "\n\nIMPORTANT: The example IDs above (45, 46, 78, etc.) are illustrative only. Use the actual chunk IDs from the provided knowledge blocks."
+    rendered = template.render() + "\n\nIMPORTANT: The example IDs above (45, 46, 78, etc.) are illustrative only. Use the actual chunk IDs from the provided knowledge blocks."
+    logger.debug("citation_prompt: appended illustrative-ID guardrail")
+    return rendered

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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 `@rag/prompts/generator.py` at line 207, The return statement in the function
containing the template.render() call on line 207 adds a new instruction
appending the IMPORTANT note about illustrative example IDs, but lacks logging
to track this behavior for observability and debugging. Add a logging statement
before the return statement to log that this new prompt-output behavior is being
executed, ensuring it captures the flow for monitoring and troubleshooting
purposes. Check the existing logging patterns in the file to use the appropriate
logger instance and log level consistent with the codebase standards.

Source: Coding guidelines

internal/service/toc_enhancer.go (1)

315-320: 💤 Low value

Inconsistent indentation in chunk ID mapping loop.

Lines 317-319 have extra indentation that doesn't match the surrounding code structure.

🤖 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/toc_enhancer.go` around lines 315 - 320, The for loop that
iterates over chunksRaw and populates the id2idx map has inconsistent
indentation. The if statement checking for chunk_id and the id2idx assignment
inside the loop body have extra indentation that doesn't align with Go's
standard conventions. Remove the extra indentation from the if condition and the
id2idx[cid] = i assignment so they are properly aligned with a single level of
indentation inside the for loop.
internal/engine/infinity/sql.go (1)

130-149: 💤 Low value

Regex recompilation inside loop impacts performance.

rewriteFieldAliases compiles a new regex for each alias on every call. For large alias maps or frequent SQL rewrites, this adds unnecessary overhead.

Consider precompiling patterns when loading the mapping file, or caching them on first use.

🤖 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/engine/infinity/sql.go` around lines 130 - 149, The regex pattern is
being recompiled inside the loop over aliasToActual in rewriteFieldAliases,
which causes unnecessary overhead on every SQL rewrite call. Move the pattern
compilation outside of the loop by either precompiling the patterns when the
aliasToActual map is initially loaded, or by caching the compiled regex patterns
so they can be reused across multiple invocations of rewriteFieldAliases instead
of being recreated on every iteration.

Comment thread internal/entity/models/openai.go Resolved
Comment thread internal/service/chat_session.go Resolved
Comment thread internal/service/chat_session.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🧹 Nitpick comments (1)
internal/tokenizer/tokenizer.go (1)

523-526: ⚡ Quick win

Avoid silent tokenizer-init failures in NumTokensFromString.

For non-empty input, returning 0 on encoder init error hides operational failures and makes diagnostics difficult. At minimum, log the error path.

🔍 Suggested improvement
 	enc, err := getCL100KEncoder()
 	if err != nil {
+		zap.L().Warn("failed to initialize cl100k tokenizer", zap.Error(err))
 		return 0
 	}
🤖 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/tokenizer/tokenizer.go` around lines 523 - 526, The error handling
in the NumTokensFromString function silently returns 0 when getCL100KEncoder()
fails, hiding operational failures. Modify the error handling block to log the
error returned from getCL100KEncoder() before returning 0, ensuring the actual
error is captured and visible for diagnostics rather than silently failing.
🤖 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/development.md`:
- Around line 163-205: All bare fenced code blocks (those starting with triple
backticks without a language identifier) need to have a language identifier
added to comply with markdownlint rule MD040. For each code block that shows
RAGFlow command examples and their output (including the examples starting at
line 163, 169, 175, 179, 184, 189, 194, 200, and 205, plus those at lines 380,
411, and 506), replace the opening triple backticks with triple backticks
followed by the language identifier `text` to properly mark them as text/command
output blocks rather than bare code blocks.
- Line 417: The section title "Audio to Speech" at line 417 in the
development.md file is incorrectly named. Since the asr command performs
Automatic Speech Recognition which converts audio to text (not text to speech),
rename the section title from "### 6.25. Audio to Speech" to "### 6.25. Audio to
Text (ASR)" to accurately reflect the functionality and avoid confusion.

In `@internal/service/chat_session.go`:
- Around line 591-602: The chunksFormat method has a type assertion that fails
for JSON-unmarshaled data. When reference originates from JSON unmarshaling,
reference["chunks"] is of type []interface{} rather than
[]map[string]interface{}, causing the assertion to return nil and silently drop
all chunks. Fix this by updating the type assertion logic to first check if
chunks is of type []interface{}, and if so, iterate through each element and
assert each one to map[string]interface{} individually before appending to the
formatted slice. This handles both the direct []map[string]interface{} case and
the JSON-unmarshaled []interface{} case.

In `@internal/service/nlp/retrieval.go`:
- Around line 1090-1096: Add an early validation check in the FetchChunkVectors
function to ensure the dim parameter is positive before it is used. At the
beginning of the function, after checking if chunkIDs is empty, add a guard
condition that checks if dim is less than or equal to 0 and returns an
appropriate error message. This prevents a panic that would occur later when dim
is used in slice allocation operations like make([]float64, dim) at line 1114
and ensures the caller receives a clear error instead of a panic.
- Around line 1145-1148: The issue is that the same `zero` slice is being
assigned to multiple chunk IDs in the out map, creating shared backing array
references that can cause unintended mutations. Instead of assigning `vec =
zero` directly when the vector length doesn't match the expected dimension,
allocate a fresh zero vector for each assignment by creating a new slice with
the correct dimension (e.g., make([]float32, dim)) and assign that new slice to
out[cid].
- Around line 1113-1151: The output map `out` currently only contains entries
for chunks found in the search results, but the code should ensure all requested
chunk IDs are present in the output with zero vectors for missing ones. Before
the loop that processes result.Chunks, prefill the `out` map by iterating
through all chunkIDs and initializing each one with the zero vector that is
already created. Then, as the loop processes result.Chunks and extracts valid
vectors, these will overwrite the zero-filled entries for chunks that were
actually found in the search results.

In `@internal/tokenizer/tokenizer.go`:
- Around line 41-43: The RegisterEngineType function accepts a callback
parameter `get` but does not validate whether it is nil before assigning it to
the `engineTypeProvider` variable, which causes a runtime panic when the
provider is invoked later. Add a nil guard at the beginning of the
RegisterEngineType function to check if the `get` parameter is nil, and either
return an error, panic with a descriptive message, or skip the assignment to
fail fast during registration instead of allowing a nil callback to be stored.

---

Nitpick comments:
In `@internal/tokenizer/tokenizer.go`:
- Around line 523-526: The error handling in the NumTokensFromString function
silently returns 0 when getCL100KEncoder() fails, hiding operational failures.
Modify the error handling block to log the error returned from
getCL100KEncoder() before returning 0, ensuring the actual error is captured and
visible for diagnostics rather than silently failing.
🪄 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: 91fbcdb3-9c1f-4f04-b446-c1bd16bb5f75

📥 Commits

Reviewing files that changed from the base of the PR and between 071e91e and 075c25c.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (60)
  • api/db/services/dialog_service.py
  • cmd/server_main.go
  • go.mod
  • internal/cli/cli.go
  • internal/cli/cli_http.go
  • internal/cli/http_client.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/response.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/common/metadata_utils.go
  • internal/common/multimodal.go
  • internal/common/timer.go
  • internal/common/timer_test.go
  • internal/development.md
  • internal/engine/elasticsearch/sql.go
  • internal/engine/elasticsearch/sql_test.go
  • internal/engine/engine.go
  • internal/engine/global.go
  • internal/engine/infinity/chunk.go
  • internal/engine/infinity/client.go
  • internal/engine/infinity/metadata.go
  • internal/engine/infinity/sql.go
  • internal/engine/infinity/sql_test.go
  • internal/entity/models/chat_tools.go
  • internal/entity/models/openai.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/handler/openai_chat.go
  • internal/handler/openai_chat_test.go
  • internal/router/router.go
  • internal/service/ask_service.go
  • internal/service/chat.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_pipeline_test.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/citation.go
  • internal/service/deep_researcher.go
  • internal/service/file.go
  • internal/service/generator.go
  • internal/service/kb_prompt.go
  • internal/service/kb_prompt_test.go
  • internal/service/kg/scoring.go
  • internal/service/langfuse.go
  • internal/service/metadata.go
  • internal/service/metadata_filter.go
  • internal/service/model_service.go
  • internal/service/nlp/retrieval.go
  • internal/service/openai_chat.go
  • internal/service/openai_chat_test.go
  • internal/service/tag.go
  • internal/service/tenant.go
  • internal/service/toc_enhancer.go
  • internal/service/toc_enhancer_test.go
  • internal/tokenizer/tokenizer.go
  • internal/tokenizer/tokenizer_test.go
  • rag/prompts/generator.py
🚧 Files skipped from review as they are similar to previous changes (54)
  • internal/cli/lexer.go
  • rag/prompts/generator.py
  • internal/cli/types.go
  • internal/engine/infinity/chunk.go
  • internal/cli/http_client.go
  • internal/engine/infinity/client.go
  • internal/cli/cli_http.go
  • internal/cli/parser.go
  • internal/engine/engine.go
  • internal/cli/cli.go
  • internal/service/kg/scoring.go
  • internal/service/ask_service.go
  • internal/common/metadata_utils.go
  • internal/service/tag.go
  • internal/service/kb_prompt_test.go
  • internal/service/kb_prompt.go
  • go.mod
  • cmd/server_main.go
  • internal/service/generator.go
  • internal/entity/models/siliconflow.go
  • internal/handler/openai_chat.go
  • api/db/services/dialog_service.py
  • internal/service/model_service.go
  • internal/service/tenant.go
  • internal/engine/global.go
  • internal/handler/openai_chat_test.go
  • internal/router/router.go
  • internal/common/timer_test.go
  • internal/service/citation.go
  • internal/tokenizer/tokenizer_test.go
  • internal/service/toc_enhancer_test.go
  • internal/service/metadata.go
  • internal/cli/user_command.go
  • internal/service/toc_enhancer.go
  • internal/entity/models/chat_tools.go
  • internal/entity/models/openai.go
  • internal/engine/infinity/sql_test.go
  • internal/service/metadata_filter.go
  • internal/engine/infinity/metadata.go
  • internal/engine/elasticsearch/sql.go
  • internal/service/file.go
  • internal/service/langfuse.go
  • internal/entity/models/types.go
  • internal/common/multimodal.go
  • internal/cli/user_parser.go
  • internal/service/chat_session_test.go
  • internal/cli/response.go
  • internal/service/chat.go
  • internal/service/deep_researcher.go
  • internal/service/openai_chat_test.go
  • internal/engine/elasticsearch/sql_test.go
  • internal/service/openai_chat.go
  • internal/engine/infinity/sql.go
  • internal/service/chat_pipeline_test.go

Comment thread internal/development.md
Comment on lines +163 to 205
```
RAGFlow(user)> openai_chat '<chat_id>' 'Hello, how are you?';
Answer: Hello! I'm just a virtual assistant, so I don't have feelings, but I'm here and ready to help you with anything you need. How can I assist you today? 😊
Time: 8.487349
```

```
RAGFlow(user)> openai_chat '<chat_id>' 'Great, now what about x^3?' \
system 'You are a math tutor. Always explain step by step.' \
history 'user:What is the derivative of x^2?;assistant:The derivative of x^2 is 2x.';
```

```
RAGFlow(user)> openai_chat '<chat_id>' 'Hello, how are you?' temperature 0.7 max_tokens 100;
```

```
RAGFlow(user)> openai_chat '<chat_id>' "what's in the doc?" stream true \
extra_body '{"reference":true,"reference_metadata":{"include":true,"fields":["author","title"]}}';
```

```
RAGFlow(user)> openai_chat '7b1d58f263ca11f18121ab54cc8673a7' 'Hello' \
extra_body '{"metadata_condition":{"logic":"and","conditions":[{"key":"doc_type","operator":"is","value":"faq"}]}}';
```

```
RAGFlow(user)> openai_chat '<chat_id>' 'Hello, how are you?' temp 100;
CLI error: OPENAI_CHAT: unknown option "temp" (valid: model, system, history, delimiter, temperature, max_tokens, stream, top_p, frequency_penalty, presence_penalty, extra_body)
```

```
RAGFlow(user)> openai_chat '<chat_id>' 'Hello, how are you?' extra_body '{"ref":true}';
CLI error: OPENAI_CHAT extra_body: unknown field "ref" (valid: reference, reference_metadata, metadata_condition)
```

### 6.9. Generate Embeddings
```
RAGFlow(api/default)> embed text 'what is rag' 'who are you' with 'embedding-3@test@zhipu-ai' dimension 16;
```
### 6.9. Document Reranking

### 6.10. Document Reranking
```

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add language identifiers to fenced code blocks flagged by markdownlint (MD040).

These blocks use bare triple backticks, which triggers lint warnings on Line 163, Line 169, Line 175, Line 179, Line 184, Line 189, Line 194, Line 200, Line 205, Line 380, Line 411, and Line 506. Use bash or text consistently.

🛠️ Minimal fix pattern
-```
+```text
 RAGFlow(user)> openai_chat '<chat_id>' 'Hello, how are you?';
 Answer: ...
 Time: 8.487349

</details>

   


Also applies to: 380-411, 506-506

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 markdownlint-cli2 (0.22.1)</summary>

[warning] 163-163: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

[warning] 169-169: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

[warning] 175-175: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

[warning] 179-179: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

[warning] 184-184: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

[warning] 189-189: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

[warning] 194-194: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

[warning] 200-200: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

---

[warning] 205-205: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

</details>

</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

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/development.md around lines 163 - 205, All bare fenced code blocks
(those starting with triple backticks without a language identifier) need to
have a language identifier added to comply with markdownlint rule MD040. For
each code block that shows RAGFlow command examples and their output (including
the examples starting at line 163, 169, 175, 179, 184, 189, 194, 200, and 205,
plus those at lines 380, 411, and 506), replace the opening triple backticks
with triple backticks followed by the language identifier text to properly
mark them as text/command output blocks rather than bare code blocks.


</details>

<!-- fingerprinting:phantom:poseidon:hawk -->

<!-- cr-comment:v1:8a421ba67691c0d1a10f989b -->

_Source: Linters/SAST tools_

<!-- This is an auto-generated comment by CodeRabbit -->

Comment thread internal/development.md
```

### 6.24 Audio to Speech
### 6.25. Audio to Speech

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Rename the ASR section title for correctness.

Line 417 says “Audio to Speech”, but the command is asr and the output is transcribed text. Rename to “Audio to Text (ASR)” to avoid confusion.

✏️ Suggested doc fix
-### 6.25. Audio to Speech
+### 6.25. Audio to Text (ASR)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
### 6.25. Audio to Speech
### 6.25. Audio to Text (ASR)
🤖 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/development.md` at line 417, The section title "Audio to Speech" at
line 417 in the development.md file is incorrectly named. Since the asr command
performs Automatic Speech Recognition which converts audio to text (not text to
speech), rename the section title from "### 6.25. Audio to Speech" to "### 6.25.
Audio to Text (ASR)" to accurately reflect the functionality and avoid
confusion.

Comment thread internal/service/chat_session.go Resolved
Comment thread internal/service/nlp/retrieval.go Resolved
Comment thread internal/service/nlp/retrieval.go Resolved
Comment thread internal/service/nlp/retrieval.go Resolved
Comment thread internal/tokenizer/tokenizer.go Resolved
@qinling0210
qinling0210 marked this pull request as draft June 18, 2026 07:30
@qinling0210
qinling0210 marked this pull request as ready for review June 18, 2026 07:30
@dosubot dosubot Bot added the ☯️ refactor Pull request that refactor/refine code label Jun 18, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🤖 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/chat_tools.go`:
- Around line 71-72: The totalTokens variable in the runToolLoop function is
initialized but never populated, causing it to always return 0. You need to
update the function to actually track token usage by either having
appendToolResults write to the totalTokens pointer when processing tool results,
or extracting the token count from the ChatWithMessages response and
accumulating it in totalTokens throughout the tool loop iterations. If token
counting is not actually needed for this functionality, you should consider
removing the totalTokens return value from the runToolLoop function signature to
avoid confusing callers.
- Line 32: The ctx parameter is accepted but never utilized in both
ChatWithTools and ChatStreamlyWithTools methods, preventing callers from
canceling or timing out these operations. Pass the ctx parameter through to the
underlying ModelDriver.ChatWithMessages and ChatStreamlyWithSender method calls
if those methods accept a context parameter, or alternatively check ctx.Done()
between operation rounds to respect cancellation signals from the caller.
- Line 267: Add a nil check for the `session` variable before it is used in the
`appendToolResults` function. Specifically, before calling
`session.ToolCall(name, args)`, verify that `session` is not nil to prevent a
potential panic. If `session` is nil, handle this case appropriately (either
skip the tool call, log a warning, or return early from the goroutine).
- Around line 59-68: The for loop in the ChatWithTools function using the
condition `attempt <= maxRetries` causes an off-by-one error, resulting in
maxRetries + 1 total attempts instead of maxRetries attempts. Fix this by
changing the loop condition from `attempt <= maxRetries` to `attempt <
maxRetries` so the loop runs exactly maxRetries times, which will then align
with the error message that states "failed after %d retries" using maxRetries.
- Around line 168-202: After the ChatStreamlyWithSender callback completes and
returns (after the err assignment), add a post-stream check to verify if
pendingThinkClose is still true, which indicates the stream ended while
reasoning content was being sent. If pendingThinkClose is true, emit the closing
</think> tag using the sender function to properly close the think block before
the function returns. This prevents leaving unclosed XML tags that would corrupt
downstream parsing.

In `@internal/tokenizer/tokenizer.go`:
- Around line 523-530: The NumTokensFromString function returns 0 when the
getCL100KEncoder call fails, which silently undercounts tokens and allows
oversized prompts to pass budget checks. Instead of returning 0 on error,
implement a conservative fallback calculation (such as estimating tokens based
on string length with a safe multiplier like dividing by 4 or similar
conservative estimate) to ensure token counts are never underestimated and
budget checks remain effective.
🪄 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: 1933238d-c376-405e-b1d4-66e9207200de

📥 Commits

Reviewing files that changed from the base of the PR and between 075c25c and 193d807.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (60)
  • api/db/services/dialog_service.py
  • cmd/server_main.go
  • go.mod
  • internal/cli/cli.go
  • internal/cli/cli_http.go
  • internal/cli/http_client.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/response.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/common/metadata_utils.go
  • internal/common/multimodal.go
  • internal/common/timer.go
  • internal/common/timer_test.go
  • internal/development.md
  • internal/engine/elasticsearch/sql.go
  • internal/engine/elasticsearch/sql_test.go
  • internal/engine/engine.go
  • internal/engine/global.go
  • internal/engine/infinity/chunk.go
  • internal/engine/infinity/client.go
  • internal/engine/infinity/metadata.go
  • internal/engine/infinity/sql.go
  • internal/engine/infinity/sql_test.go
  • internal/entity/models/chat_tools.go
  • internal/entity/models/openai.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/handler/openai_chat.go
  • internal/handler/openai_chat_test.go
  • internal/router/router.go
  • internal/service/ask_service.go
  • internal/service/chat.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_pipeline_test.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/citation.go
  • internal/service/deep_researcher.go
  • internal/service/file.go
  • internal/service/generator.go
  • internal/service/kb_prompt.go
  • internal/service/kb_prompt_test.go
  • internal/service/kg/scoring.go
  • internal/service/langfuse.go
  • internal/service/metadata.go
  • internal/service/metadata_filter.go
  • internal/service/model_service.go
  • internal/service/nlp/retrieval.go
  • internal/service/openai_chat.go
  • internal/service/openai_chat_test.go
  • internal/service/tag.go
  • internal/service/tenant.go
  • internal/service/toc_enhancer.go
  • internal/service/toc_enhancer_test.go
  • internal/tokenizer/tokenizer.go
  • internal/tokenizer/tokenizer_test.go
  • rag/prompts/generator.py
✅ Files skipped from review due to trivial changes (1)
  • internal/engine/infinity/chunk.go
🚧 Files skipped from review as they are similar to previous changes (54)
  • internal/cli/lexer.go
  • internal/cli/cli_http.go
  • cmd/server_main.go
  • rag/prompts/generator.py
  • internal/engine/engine.go
  • internal/common/metadata_utils.go
  • internal/cli/parser.go
  • internal/service/kg/scoring.go
  • internal/engine/global.go
  • internal/cli/http_client.go
  • internal/engine/infinity/client.go
  • internal/cli/cli.go
  • internal/service/kb_prompt_test.go
  • internal/service/tag.go
  • internal/service/kb_prompt.go
  • internal/router/router.go
  • internal/service/ask_service.go
  • internal/service/nlp/retrieval.go
  • internal/service/generator.go
  • go.mod
  • internal/service/metadata.go
  • internal/service/model_service.go
  • api/db/services/dialog_service.py
  • internal/service/tenant.go
  • internal/service/metadata_filter.go
  • internal/tokenizer/tokenizer_test.go
  • internal/common/timer_test.go
  • internal/engine/elasticsearch/sql.go
  • internal/common/timer.go
  • internal/service/chat_session_test.go
  • internal/service/toc_enhancer_test.go
  • internal/entity/models/types.go
  • internal/engine/infinity/metadata.go
  • internal/cli/user_parser.go
  • internal/service/file.go
  • internal/handler/openai_chat.go
  • internal/entity/models/siliconflow.go
  • internal/service/deep_researcher.go
  • internal/common/multimodal.go
  • internal/engine/infinity/sql_test.go
  • internal/service/chat.go
  • internal/cli/user_command.go
  • internal/engine/infinity/sql.go
  • internal/service/langfuse.go
  • internal/handler/openai_chat_test.go
  • internal/entity/models/openai.go
  • internal/engine/elasticsearch/sql_test.go
  • internal/service/openai_chat.go
  • internal/cli/response.go
  • internal/service/chat_pipeline_test.go
  • internal/service/chat_session.go
  • internal/service/toc_enhancer.go
  • internal/service/citation.go
  • internal/service/openai_chat_test.go

Comment thread internal/entity/models/chat_tools.go Resolved
Comment thread internal/entity/models/chat_tools.go Resolved
Comment thread internal/entity/models/chat_tools.go Resolved
Comment thread internal/entity/models/chat_tools.go Resolved
Comment thread internal/entity/models/chat_tools.go Resolved
Comment thread internal/tokenizer/tokenizer.go Resolved
@qinling0210
qinling0210 force-pushed the openai_chat_go branch 2 times, most recently from 78ee0f9 to 1b3a05b Compare June 18, 2026 08:50

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/tokenizer/tokenizer.go (1)

35-47: 💤 Low value

Consider synchronization for engineTypeProvider to eliminate theoretical data race.

The engineTypeProvider function pointer is written by RegisterEngineType (Line 46) and read by Tokenize/FineGrainedTokenize (Lines 434, 471) without synchronization. While the current usage pattern (set once during engine.Init before request processing) is safe in practice, the Go memory model requires synchronization for concurrent access.

If RegisterEngineType is ever called after tokenization begins, or if initialization order changes, this becomes a data race.

🔒 Suggested fix using sync/atomic
-// engineTypeProvider is injected at startup by engine.RegisterEngineType
-// to break the tokenizer → engine import cycle.
-var engineTypeProvider = func() string { return "" }
+import "sync/atomic"
+
+// engineTypeProvider is injected at startup by engine.RegisterEngineType
+// to break the tokenizer → engine import cycle.
+var engineTypeProvider atomic.Value // stores func() string

+func init() {
+	engineTypeProvider.Store(func() string { return "" })
+}

-// RegisterEngineType wires the engine package's GetEngineType into the
-// tokenizer, breaking the circular import (engine/elasticsearch → tokenizer → engine).
+// RegisterEngineType wires the engine package's GetEngineType into the tokenizer.
+// Must be called during initialization, before any tokenization requests.
 func RegisterEngineType(get func() string) {
 	if get == nil {
-		engineTypeProvider = func() string { return "" }
+		engineTypeProvider.Store(func() string { return "" })
 		return
 	}
-	engineTypeProvider = get
+	engineTypeProvider.Store(get)
 }

// In Tokenize and FineGrainedTokenize:
-	if engineTypeProvider() == "infinity" {
+	if engineTypeProvider.Load().(func() string)() == "infinity" {

Alternatively, document that RegisterEngineType must complete before any tokenization calls.

🤖 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/tokenizer/tokenizer.go` around lines 35 - 47, The engineTypeProvider
function pointer is accessed without synchronization, creating a potential data
race between the RegisterEngineType function (which writes the pointer) and the
Tokenize and FineGrainedTokenize functions (which read it). To fix this, wrap
the engineTypeProvider variable with synchronization using either sync.RWMutex
(protecting reads and writes with lock/unlock calls) or sync/atomic (using
atomic.StorePointer and atomic.LoadPointer for thread-safe access). Update
RegisterEngineType to acquire write locks or use atomic store operations when
modifying engineTypeProvider, and update all read locations in Tokenize and
FineGrainedTokenize to acquire read locks or use atomic load operations when
accessing the function pointer.
🤖 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/tokenizer/tokenizer.go`:
- Line 32: The import statement `rag "ragflow/internal/binding"` in the
tokenizer.go file requires CGO and C++ dependencies that may not be available in
all build environments. To fix this, add build tags at the top of the file using
`//go:build cgo` to conditionally compile the file only when CGO is enabled, or
alternatively document the required build environment dependencies (C/C++
compiler, libpcre2-8 library, CMake build artifacts) in the project README or
build documentation so users understand these requirements before attempting to
build.

---

Nitpick comments:
In `@internal/tokenizer/tokenizer.go`:
- Around line 35-47: The engineTypeProvider function pointer is accessed without
synchronization, creating a potential data race between the RegisterEngineType
function (which writes the pointer) and the Tokenize and FineGrainedTokenize
functions (which read it). To fix this, wrap the engineTypeProvider variable
with synchronization using either sync.RWMutex (protecting reads and writes with
lock/unlock calls) or sync/atomic (using atomic.StorePointer and
atomic.LoadPointer for thread-safe access). Update RegisterEngineType to acquire
write locks or use atomic store operations when modifying engineTypeProvider,
and update all read locations in Tokenize and FineGrainedTokenize to acquire
read locks or use atomic load operations when accessing the function pointer.
🪄 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: dfb1ec59-4134-4366-9b02-c235e717ac6c

📥 Commits

Reviewing files that changed from the base of the PR and between 193d807 and 1b3a05b.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (60)
  • api/db/services/dialog_service.py
  • cmd/server_main.go
  • go.mod
  • internal/cli/cli.go
  • internal/cli/cli_http.go
  • internal/cli/http_client.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/response.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/common/metadata_utils.go
  • internal/common/multimodal.go
  • internal/common/timer.go
  • internal/common/timer_test.go
  • internal/development.md
  • internal/engine/elasticsearch/sql.go
  • internal/engine/elasticsearch/sql_test.go
  • internal/engine/engine.go
  • internal/engine/global.go
  • internal/engine/infinity/chunk.go
  • internal/engine/infinity/client.go
  • internal/engine/infinity/metadata.go
  • internal/engine/infinity/sql.go
  • internal/engine/infinity/sql_test.go
  • internal/entity/models/chat_tools.go
  • internal/entity/models/openai.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/handler/openai_chat.go
  • internal/handler/openai_chat_test.go
  • internal/router/router.go
  • internal/service/ask_service.go
  • internal/service/chat.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_pipeline_test.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/citation.go
  • internal/service/deep_researcher.go
  • internal/service/file.go
  • internal/service/generator.go
  • internal/service/kb_prompt.go
  • internal/service/kb_prompt_test.go
  • internal/service/kg/scoring.go
  • internal/service/langfuse.go
  • internal/service/metadata.go
  • internal/service/metadata_filter.go
  • internal/service/model_service.go
  • internal/service/nlp/retrieval.go
  • internal/service/openai_chat.go
  • internal/service/openai_chat_test.go
  • internal/service/tag.go
  • internal/service/tenant.go
  • internal/service/toc_enhancer.go
  • internal/service/toc_enhancer_test.go
  • internal/tokenizer/tokenizer.go
  • internal/tokenizer/tokenizer_test.go
  • rag/prompts/generator.py
✅ Files skipped from review due to trivial changes (2)
  • internal/engine/infinity/client.go
  • internal/cli/cli.go
🚧 Files skipped from review as they are similar to previous changes (53)
  • internal/cli/cli_http.go
  • internal/cli/types.go
  • rag/prompts/generator.py
  • internal/service/kg/scoring.go
  • internal/engine/global.go
  • internal/service/tag.go
  • internal/engine/infinity/chunk.go
  • internal/common/metadata_utils.go
  • internal/cli/parser.go
  • internal/cli/lexer.go
  • internal/engine/engine.go
  • internal/service/kb_prompt.go
  • internal/service/kb_prompt_test.go
  • internal/cli/http_client.go
  • internal/service/ask_service.go
  • internal/service/citation.go
  • internal/router/router.go
  • cmd/server_main.go
  • go.mod
  • internal/tokenizer/tokenizer_test.go
  • internal/entity/models/siliconflow.go
  • internal/service/metadata.go
  • internal/service/generator.go
  • internal/service/model_service.go
  • internal/common/timer_test.go
  • internal/engine/elasticsearch/sql.go
  • internal/service/nlp/retrieval.go
  • internal/entity/models/types.go
  • internal/common/timer.go
  • internal/engine/infinity/metadata.go
  • internal/service/file.go
  • internal/service/chat.go
  • internal/cli/user_parser.go
  • api/db/services/dialog_service.py
  • internal/service/metadata_filter.go
  • internal/engine/elasticsearch/sql_test.go
  • internal/entity/models/openai.go
  • internal/service/tenant.go
  • internal/common/multimodal.go
  • internal/cli/user_command.go
  • internal/service/deep_researcher.go
  • internal/service/chat_session_test.go
  • internal/handler/openai_chat.go
  • internal/service/toc_enhancer_test.go
  • internal/service/chat_session.go
  • internal/engine/infinity/sql_test.go
  • internal/service/openai_chat_test.go
  • internal/engine/infinity/sql.go
  • internal/service/langfuse.go
  • internal/handler/openai_chat_test.go
  • internal/service/toc_enhancer.go
  • internal/service/openai_chat.go
  • internal/service/chat_pipeline_test.go

"github.com/pkoukk/tiktoken-go"
"go.uber.org/zap"

rag "ragflow/internal/binding"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check for build constraints in internal/binding package

echo "=== Checking for build tags in internal/binding ==="
fd -e go . internal/binding -x head -20 {} \; | rg '//\s*\+build|//go:build'

echo -e "\n=== Checking if package builds successfully ==="
go list -f '{{.Name}}: {{.GoFiles}}' ragflow/internal/binding 2>&1

Repository: infiniflow/ragflow

Length of output: 275


🏁 Script executed:

#!/bin/bash
# List all files in internal/binding directory to see what exists
echo "=== Files in internal/binding ==="
find internal/binding -type f | head -20

echo -e "\n=== Go files specifically ==="
find internal/binding -name "*.go" | head -20

echo -e "\n=== Directory structure ==="
tree -L 3 internal/binding 2>/dev/null || find internal/binding -type d | head -20

echo -e "\n=== Check file contents for build tags ==="
find internal/binding -name "*.go" -exec head -10 {} \; 2>/dev/null | head -50

Repository: infiniflow/ragflow

Length of output: 704


🏁 Script executed:

#!/bin/bash
# Read the full rag_analyzer.go file to see the build constraints
cat internal/binding/rag_analyzer.go | head -50

Repository: infiniflow/ragflow

Length of output: 1693


The ragflow/internal/binding import requires CGO and C++ dependencies.

The package cannot be imported in environments where:

  • CGO is disabled (e.g., CGO_ENABLED=0)
  • A C/C++ compiler is unavailable
  • The libpcre2-8 library is not installed
  • The C++ build artifacts in cmake-build-release/ are missing

This is not a false positive. The rag_analyzer.go file uses CGO with C++ interop (import "C" + #cgo directives), which requires a complete C++ build environment. The static analysis warning is valid for any build configuration that lacks these dependencies.

Consider documenting the build environment requirements or using conditional compilation if this package should be optional.

🧰 Tools
🪛 golangci-lint (2.12.2)

[error] 32-32: could not import ragflow/internal/binding (-: build constraints exclude all Go files in internal/binding)

(typecheck)

🤖 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/tokenizer/tokenizer.go` at line 32, The import statement `rag
"ragflow/internal/binding"` in the tokenizer.go file requires CGO and C++
dependencies that may not be available in all build environments. To fix this,
add build tags at the top of the file using `//go:build cgo` to conditionally
compile the file only when CGO is enabled, or alternatively document the
required build environment dependencies (C/C++ compiler, libpcre2-8 library,
CMake build artifacts) in the project README or build documentation so users
understand these requirements before attempting to build.

Source: Linters/SAST tools

@qinling0210
qinling0210 marked this pull request as draft June 18, 2026 09:08
@qinling0210 qinling0210 added the ci Continue Integration label Jun 18, 2026
@qinling0210
qinling0210 marked this pull request as ready for review June 18, 2026 09:10

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
internal/engine/infinity/sql.go (2)

315-318: ⚖️ Poor tradeoff

Field mapping loaded from disk on every SQL execution.

loadFieldMapping reads and parses the JSON file for each RunSQL call. If this method is invoked frequently, consider caching the mapping at engine initialization or with a TTL-based refresh.

🤖 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/engine/infinity/sql.go` around lines 315 - 318, The
`loadFieldMapping` function is being called on every `RunSQL` method invocation,
which causes repeated disk reads and JSON parsing of the same file. Instead of
loading the mapping every time from disk via `e.client.mappingFileName`, cache
the field mapping (aliasMap) in the engine struct during initialization or
implement a TTL-based caching mechanism that loads the file once and reuses it
across multiple SQL executions. Update the code to check for a cached mapping
first before calling `loadFieldMapping`, only refreshing when necessary.

130-139: ⚡ Quick win

Regex compiled repeatedly in hot path.

selectRe (line 130) is compiled on every call, and pat (line 135) is compiled inside a loop for each alias. With a typical alias map of 10+ entries, this creates significant overhead per SQL execution.

Consider pre-compiling selectRe at package level and caching alias patterns.

♻️ Suggested optimization
+var selectRe = regexp.MustCompile(`(?si)(select\s+)(.+?)(\s+from\b)`)
+
 func rewriteFieldAliases(sql string, aliasToActual map[string]string) string {
 	if len(aliasToActual) == 0 {
 		return sql
 	}
-	selectRe := regexp.MustCompile(`(?si)(select\s+)(.+?)(\s+from\b)`)
 	sql = selectRe.ReplaceAllStringFunc(sql, func(m string) string {

For the inner loop pattern, consider building a single combined regex or pre-compiling patterns once when the alias map is loaded.

🤖 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/engine/infinity/sql.go` around lines 130 - 139, The regex patterns
in this function are being compiled repeatedly in a hot path, causing
performance overhead. Move the selectRe regex compilation to package level so it
is only compiled once instead of on every function call. For the inner loop
where pat is compiled for each alias in the aliasToActual map, pre-compile these
patterns once when the alias map is initialized or loaded, and store them in a
cache map keyed by alias, then retrieve them in the loop instead of recompiling.
This eliminates the repeated regex compilations and significantly reduces
overhead, especially with large alias maps.
🤖 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.

Nitpick comments:
In `@internal/engine/infinity/sql.go`:
- Around line 315-318: The `loadFieldMapping` function is being called on every
`RunSQL` method invocation, which causes repeated disk reads and JSON parsing of
the same file. Instead of loading the mapping every time from disk via
`e.client.mappingFileName`, cache the field mapping (aliasMap) in the engine
struct during initialization or implement a TTL-based caching mechanism that
loads the file once and reuses it across multiple SQL executions. Update the
code to check for a cached mapping first before calling `loadFieldMapping`, only
refreshing when necessary.
- Around line 130-139: The regex patterns in this function are being compiled
repeatedly in a hot path, causing performance overhead. Move the selectRe regex
compilation to package level so it is only compiled once instead of on every
function call. For the inner loop where pat is compiled for each alias in the
aliasToActual map, pre-compile these patterns once when the alias map is
initialized or loaded, and store them in a cache map keyed by alias, then
retrieve them in the loop instead of recompiling. This eliminates the repeated
regex compilations and significantly reduces overhead, especially with large
alias maps.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7d49ec09-ad4d-44e3-99fe-92cfad332a4b

📥 Commits

Reviewing files that changed from the base of the PR and between 1b3a05b and b430bc7.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (60)
  • api/db/services/dialog_service.py
  • cmd/server_main.go
  • go.mod
  • internal/cli/cli.go
  • internal/cli/cli_http.go
  • internal/cli/http_client.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/response.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/common/metadata_utils.go
  • internal/common/multimodal.go
  • internal/common/timer.go
  • internal/common/timer_test.go
  • internal/development.md
  • internal/engine/elasticsearch/sql.go
  • internal/engine/elasticsearch/sql_test.go
  • internal/engine/engine.go
  • internal/engine/global.go
  • internal/engine/infinity/chunk.go
  • internal/engine/infinity/client.go
  • internal/engine/infinity/metadata.go
  • internal/engine/infinity/sql.go
  • internal/engine/infinity/sql_test.go
  • internal/entity/models/chat_tools.go
  • internal/entity/models/openai.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/handler/openai_chat.go
  • internal/handler/openai_chat_test.go
  • internal/router/router.go
  • internal/service/ask_service.go
  • internal/service/chat.go
  • internal/service/chat_pipeline.go
  • internal/service/chat_pipeline_test.go
  • internal/service/chat_session.go
  • internal/service/chat_session_test.go
  • internal/service/citation.go
  • internal/service/deep_researcher.go
  • internal/service/file.go
  • internal/service/generator.go
  • internal/service/kb_prompt.go
  • internal/service/kb_prompt_test.go
  • internal/service/kg/scoring.go
  • internal/service/langfuse.go
  • internal/service/metadata.go
  • internal/service/metadata_filter.go
  • internal/service/model_service.go
  • internal/service/nlp/retrieval.go
  • internal/service/openai_chat.go
  • internal/service/openai_chat_test.go
  • internal/service/tag.go
  • internal/service/tenant.go
  • internal/service/toc_enhancer.go
  • internal/service/toc_enhancer_test.go
  • internal/tokenizer/tokenizer.go
  • internal/tokenizer/tokenizer_test.go
  • rag/prompts/generator.py
✅ Files skipped from review due to trivial changes (1)
  • internal/cli/cli.go
🚧 Files skipped from review as they are similar to previous changes (53)
  • internal/engine/infinity/chunk.go
  • internal/cli/lexer.go
  • internal/engine/global.go
  • internal/engine/engine.go
  • internal/common/metadata_utils.go
  • rag/prompts/generator.py
  • internal/service/tag.go
  • internal/cli/cli_http.go
  • internal/cli/parser.go
  • internal/cli/http_client.go
  • internal/service/kb_prompt.go
  • internal/engine/infinity/client.go
  • internal/service/citation.go
  • internal/service/kb_prompt_test.go
  • internal/service/ask_service.go
  • cmd/server_main.go
  • internal/entity/models/siliconflow.go
  • go.mod
  • internal/common/timer_test.go
  • internal/engine/infinity/metadata.go
  • internal/engine/elasticsearch/sql.go
  • api/db/services/dialog_service.py
  • internal/service/toc_enhancer_test.go
  • internal/service/metadata.go
  • internal/entity/models/types.go
  • internal/handler/openai_chat.go
  • internal/tokenizer/tokenizer_test.go
  • internal/service/file.go
  • internal/service/model_service.go
  • internal/service/tenant.go
  • internal/common/multimodal.go
  • internal/service/metadata_filter.go
  • internal/cli/user_command.go
  • internal/engine/infinity/sql_test.go
  • internal/service/chat_session_test.go
  • internal/engine/elasticsearch/sql_test.go
  • internal/service/generator.go
  • internal/handler/openai_chat_test.go
  • internal/cli/user_parser.go
  • internal/common/timer.go
  • internal/service/nlp/retrieval.go
  • internal/cli/types.go
  • internal/service/deep_researcher.go
  • internal/entity/models/openai.go
  • internal/service/chat.go
  • internal/entity/models/chat_tools.go
  • internal/service/openai_chat_test.go
  • internal/cli/response.go
  • internal/service/langfuse.go
  • internal/service/openai_chat.go
  • internal/service/chat_pipeline_test.go
  • internal/service/toc_enhancer.go
  • internal/service/chat_session.go

@codecov

codecov Bot commented Jun 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (5eedd13) to head (0832b6c).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16177   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

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

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

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

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants