Repository navigation
Go: add LLM usage - #17049
Go: add LLM usage#17049
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThe 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 ChangesTyped chat usage flow
Connection setup
Chat application metadata
TOC parsing error handling
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
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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 liftFix
sync.Onceerror suppression on subsequent calls.Because
erris a local variable (declared on line 45), ifInitis called again after an initial failure,once.Dowill skip the closure, and the function will silently returnnildespite the driver failing to initialize.If
Initis meant to be retryable (e.g., waiting for the database to start),sync.Onceshould be replaced with async.Mutexso 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'ssync.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.Oncewith amu sync.Mutexat the package level, and updateInit: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
📒 Files selected for processing (7)
internal/cli/response.gointernal/engine/clickhouse/clickhouse.gointernal/entity/models/base_model.gointernal/entity/models/types.gointernal/entity/models/zhipu-ai.gointernal/handler/providers.gointernal/service/toc_enhancer.go
| 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 |
There was a problem hiding this comment.
🩺 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.
| 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.
Summary