Skip to content

Go: add LLM usage - #17049

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix559
Jul 17, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix559

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

Summary

RAGFlow(api/default)> CHAT WITH 'glm-4-flash@new_test@zhipu-ai' MESSAGE '30 words describes LLM';
Answer: Hello! I'm ChatGLM, an AI assistant. Feel free to ask me any questions or request help with any tasks.
Input tokens: 5
Output tokens: 28
Time: 12.748241

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 17, 2026
@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds typed Zhipu response parsing and propagates token usage through non-stream responses to CLI output. It also updates ClickHouse initialization, adds a TLS timeout, introduces ChatAppConfig, and preserves TOC parsing errors during retries.

Changes

Typed chat usage flow

Layer / File(s) Summary
Typed response and usage propagation
internal/entity/models/zhipu-ai.go, internal/handler/providers.go, internal/cli/response.go
Zhipu responses use typed answer, reasoning, and usage fields; non-stream JSON includes usage, and CLI output displays input and output token counts.

Connection setup

Layer / File(s) Summary
Explicit connection and TLS settings
internal/engine/clickhouse/clickhouse.go, internal/entity/models/base_model.go
ClickHouse initialization accepts explicit connection parameters, and driver HTTP transports set a 30-second TLS handshake timeout.

Chat application metadata

Layer / File(s) Summary
Chat application configuration model
internal/entity/models/types.go
Adds JSON-tagged ChatAppConfig fields for application, session, provider, timing, token, and error metadata.

TOC parsing error handling

Layer / File(s) Summary
Retry error capture
internal/service/toc_enhancer.go
Preserves the JSON unmarshal error in the surrounding retry logic.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Zhipu
  participant ChatWithMessages
  participant ChatToModel
  participant CLI
  Zhipu->>ChatWithMessages: typed response with answer and usage
  ChatWithMessages->>ChatToModel: ChatResponse with ChatUsage
  ChatToModel->>CLI: non-stream JSON including usage
  CLI->>CLI: print input and output token counts
Loading

Suggested labels: 💞 feature, go

Suggested reviewers: qinling0210, haruko386

Poem

I’m a rabbit with tokens to spare,
Typed answers hop through the air.
ClickHouse doors open, TLS waits,
Errors remember their retrying fates.
Usage counts shine in the CLI bright—
Hop, hop, review, and goodnight! 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: adding LLM usage reporting to the Go code.
Description check ✅ Passed The description includes the required Summary section and explains the usage output change, though it is terse.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

@JinHai-CN
JinHai-CN marked this pull request as ready for review July 17, 2026 09:35
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 17, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft July 17, 2026 09:35
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 17, 2026 09:35
@JinHai-CN
JinHai-CN marked this pull request as draft July 17, 2026 09:35
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 17, 2026 09:35

@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

Caution

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

⚠️ Outside diff range comments (1)
internal/engine/clickhouse/clickhouse.go (1)

44-72: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Fix sync.Once error suppression on subsequent calls.

Because err is a local variable (declared on line 45), if Init is called again after an initial failure, once.Do will skip the closure, and the function will silently return nil despite the driver failing to initialize.

If Init is meant to be retryable (e.g., waiting for the database to start), sync.Once should be replaced with a sync.Mutex so it can be retried upon failure. If it's strictly a run-once function, you should cache the error globally (or use Go 1.21's sync.OnceValues) so subsequent calls return the initialization error rather than a false success.

🛠️ Proposed fix using a Mutex (allows retries on failure)

Replace once sync.Once with a mu sync.Mutex at the package level, and update Init:

var mu sync.Mutex

func Init(ctx context.Context, host string, port int, user, password, database string) error {
	mu.Lock()
	defer mu.Unlock()

	// If already initialized and ping succeeds, return nil
	if globalDriver != nil && globalDriver.conn != nil {
		if err := globalDriver.conn.Ping(ctx); err == nil {
			return nil
		}
	}

	address := fmt.Sprintf("%s:%d", host, port)

	globalDriver = &Driver{}
	globalDriver.config = &clickhouse.Options{
		Addr: []string{address},
		Auth: clickhouse.Auth{
			Database: database,
			Username: user,
			Password: password,
		},
		DialTimeout:     5 * time.Second,
		MaxOpenConns:    10,
		MaxIdleConns:    5,
		ConnMaxLifetime: time.Hour,
	}

	conn, err := clickhouse.Open(globalDriver.config)
	if err != nil {
		return err
	}

	if err = conn.Ping(ctx); err != nil {
		return err
	}

	globalDriver.conn = conn
	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/engine/clickhouse/clickhouse.go` around lines 44 - 72, Replace the
package-level sync.Once used by Init with mutex-protected initialization so
failed attempts can be retried. Update Init to lock around driver setup,
preserve an already healthy connection when available, return Open or Ping
errors directly, and only assign the successfully connected client to
globalDriver.conn after Ping succeeds.
🤖 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/zhipu-ai.go`:
- Around line 183-188: In the response parsing flow after json.Unmarshal,
validate that result.Choices contains at least one element before accessing
result.Choices[0]. Return an appropriate error when it is empty, while
preserving the existing content extraction for non-empty responses.

---

Outside diff comments:
In `@internal/engine/clickhouse/clickhouse.go`:
- Around line 44-72: Replace the package-level sync.Once used by Init with
mutex-protected initialization so failed attempts can be retried. Update Init to
lock around driver setup, preserve an already healthy connection when available,
return Open or Ping errors directly, and only assign the successfully connected
client to globalDriver.conn after Ping succeeds.
🪄 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: f26719be-1fdf-4cf7-af3c-c9d5d5d470c7

📥 Commits

Reviewing files that changed from the base of the PR and between 6da5085 and 47e9918.

📒 Files selected for processing (7)
  • internal/cli/response.go
  • internal/engine/clickhouse/clickhouse.go
  • internal/entity/models/base_model.go
  • internal/entity/models/types.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/providers.go
  • internal/service/toc_enhancer.go

Comment on lines +183 to +188
var result ZhipuChatResponse
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}

choices, ok := result["choices"].([]interface{})
if !ok || len(choices) == 0 {
return nil, fmt.Errorf("no choices in response")
}

firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("invalid choice format")
}

messageMap, ok := firstChoice["message"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("invalid message format")
}
content := &result.Choices[0].Message.Content

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Prevent panic from out-of-bounds access if Choices is empty.

If the API returns a response with an empty Choices array, accessing result.Choices[0] will cause a runtime panic. Add a length check before accessing the array elements.

🛡️ Proposed fix to check array length
 	var result ZhipuChatResponse
 	if err = json.Unmarshal(body, &result); err != nil {
 		return nil, fmt.Errorf("failed to parse response: %w", err)
 	}
 
+	if len(result.Choices) == 0 {
+		return nil, fmt.Errorf("API response returned empty choices")
+	}
+
 	content := &result.Choices[0].Message.Content
📝 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
var result ZhipuChatResponse
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
choices, ok := result["choices"].([]interface{})
if !ok || len(choices) == 0 {
return nil, fmt.Errorf("no choices in response")
}
firstChoice, ok := choices[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("invalid choice format")
}
messageMap, ok := firstChoice["message"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("invalid message format")
}
content := &result.Choices[0].Message.Content
var result ZhipuChatResponse
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
if len(result.Choices) == 0 {
return nil, fmt.Errorf("API response returned empty choices")
}
content := &result.Choices[0].Message.Content
🤖 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/zhipu-ai.go` around lines 183 - 188, In the response
parsing flow after json.Unmarshal, validate that result.Choices contains at
least one element before accessing result.Choices[0]. Return an appropriate
error when it is empty, while preserving the existing content extraction for
non-empty responses.

@JinHai-CN
JinHai-CN merged commit 8ebdc02 into infiniflow:main Jul 17, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant