Repository navigation
feat[Go]: implement add multi_models - #15563
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds DAO transactional CreateBatch, service AddModel API with validation/deduplication and Extra construction, handler helpers and PUT route for batch adds, and a Moonshot change to unchecked reasoning_content extraction when thinking is enabled. ChangesBatch Model Creation with Thinking Support
Sequence DiagramsequenceDiagram
participant Client
participant Router
participant ProviderHandler
participant ModelProviderService
participant TenantModelDAO
Client->>Router: PUT /:provider_name/instances/:instance_name/models (AddModelRequest)
Router->>ProviderHandler: providerHandler.AddModel
ProviderHandler->>ProviderHandler: prepareAddModelRequest (validate path/body)
ProviderHandler->>ModelProviderService: AddModel(request, userID)
ModelProviderService->>TenantModelDAO: CreateBatch(models)
TenantModelDAO->>TenantModelDAO: Transaction + tx.Create per model
TenantModelDAO->>ModelProviderService: result
ModelProviderService->>ProviderHandler: code, err
ProviderHandler->>Client: HTTP response with code
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
internal/dao/tenant_model.go (1)
37-50: ⚡ Quick winConsider using GORM's
CreateInBatchesfor better performance.The current implementation loops through models and calls
tx.Createindividually. GORM providestx.CreateInBatcheswhich can insert multiple records in a single batch operation, reducing database round trips and improving performance for large model sets.♻️ Suggested optimization
func (dao *TenantModelDAO) CreateBatch(models []*entity.TenantModel) error { if len(models) == 0 { return nil } - return DB.Transaction(func(tx *gorm.DB) error { - for _, model := range models { - if err := tx.Create(model).Error; err != nil { - return err - } - } - return nil - }) + return DB.CreateInBatches(models, 100).Error }Note: Adjust batch size (100) based on your typical use case and database constraints.
🤖 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/dao/tenant_model.go` around lines 37 - 50, The CreateBatch method currently inserts each TenantModel inside a loop using tx.Create, causing many DB round-trips; update TenantModelDAO.CreateBatch to use GORM's tx.CreateInBatches to insert the slice in batches (e.g., batch size 100) inside the existing DB.Transaction call and return any error from CreateInBatches instead of the per-item loop; keep the early len(models)==0 check and ensure you reference tx.CreateInBatches when replacing the loop.internal/entity/models/moonshot.go (1)
186-192: 💤 Low valueConsider logging when
reasoning_contenttype mismatch occurs.The unchecked type assertion at line 187 silently ignores any
reasoning_contentfield that isn't a string. While this provides flexibility for models that omit or format this field differently, it could mask unexpected API responses. Consider logging a debug message whenreasoning_contentis present but not a string type.📊 Proposed logging enhancement
var reasonContent string if chatModelConfig != nil && chatModelConfig.Thinking != nil && *chatModelConfig.Thinking { - reasonContent, _ = messageMap["reasoning_content"].(string) + var ok bool + reasonContent, ok = messageMap["reasoning_content"].(string) + if !ok && messageMap["reasoning_content"] != nil { + common.Debug("reasoning_content present but not string type: %T", messageMap["reasoning_content"]) + } // if first char of reasonContent is \n remove the \n if reasonContent != "" && reasonContent[0] == '\n' { reasonContent = reasonContent[1:] } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/moonshot.go` around lines 186 - 192, The code silently ignores non-string reasoning_content when extracting reasonContent from messageMap; update the block that checks chatModelConfig (the if using chatModelConfig.Thinking) to detect when messageMap["reasoning_content"] exists but is not a string and emit a debug log (via the existing logger) noting the unexpected type and contents, while preserving the current behavior of assigning reasonContent when it is a string and trimming a leading '\n'. Use symbol names messageMap, reasonContent and chatModelConfig to locate and modify the code.
🤖 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/router/router.go`:
- Around line 331-332: Remove the test-only
"/:provider_name/instances/:instance_name/modelss" route registration from the
router: the duplicate-‘s’ endpoint is only for tests and should not be in
production code. Locate the provider.POST call that registers
"/:provider_name/instances/:instance_name/modelss" (handler
r.providerHandler.AddModel) and delete that line; if batch model creation is
required, re-register it under the canonical
"/:provider_name/instances/:instance_name/models" path and update the AddModel
handler to detect/process batch payloads or gate the test route behind build
tags or a test-only router.
In `@internal/service/model_service.go`:
- Around line 2066-2072: The tenant authorization is using
m.userTenantDAO.GetByUserID(userID) which differs from other methods that
enforce owner role; replace the call with
m.userTenantDAO.GetByUserIDAndRole(userID, "owner") in the method containing
this snippet, and update the subsequent checks (len(tenants) == 0) to return the
same CodeNotFound / error message when no owner-tenants are found so only owners
can create models (ensure references to tenants variable and error handling
remain consistent).
- Around line 2089-2098: The loop over request.Models accesses
model.ModelTypes[0] without checking length; update the code in the method
iterating request.Models to defensively validate that len(model.ModelTypes) > 0
before reading index 0 (e.g., check len(model.ModelTypes) == 0 and return
common.CodeBadRequest with an appropriate error), and keep the existing
trim/empty checks for modelName and modelType; reference the local variable
model and the field ModelTypes to locate and modify the logic.
---
Nitpick comments:
In `@internal/dao/tenant_model.go`:
- Around line 37-50: The CreateBatch method currently inserts each TenantModel
inside a loop using tx.Create, causing many DB round-trips; update
TenantModelDAO.CreateBatch to use GORM's tx.CreateInBatches to insert the slice
in batches (e.g., batch size 100) inside the existing DB.Transaction call and
return any error from CreateInBatches instead of the per-item loop; keep the
early len(models)==0 check and ensure you reference tx.CreateInBatches when
replacing the loop.
In `@internal/entity/models/moonshot.go`:
- Around line 186-192: The code silently ignores non-string reasoning_content
when extracting reasonContent from messageMap; update the block that checks
chatModelConfig (the if using chatModelConfig.Thinking) to detect when
messageMap["reasoning_content"] exists but is not a string and emit a debug log
(via the existing logger) noting the unexpected type and contents, while
preserving the current behavior of assigning reasonContent when it is a string
and trimming a leading '\n'. Use symbol names messageMap, reasonContent and
chatModelConfig to locate and modify the code.
🪄 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: 0a5388c0-a658-4047-a80e-0b2bf8d161b1
📒 Files selected for processing (5)
internal/dao/tenant_model.gointernal/entity/models/moonshot.gointernal/handler/providers.gointernal/router/router.gointernal/service/model_service.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15563 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/router/router.go`:
- Line 330: The POST route was repointed to the batch-only handler causing
legacy flat requests to be rejected; restore backward compatibility by either
updating ProviderHandler.AddModel to accept the legacy single-model shape (bind
the legacy fields or detect and translate a flat {model_name, model_types,
max_tokens} payload into the current service.AddModelRequest) or by creating a
new batch-specific handler (e.g., ProviderHandler.AddModelsBatch) and route POST
"/:provider_name/instances/:instance_name/models" to the original single-model
handler while registering the new batch handler at a distinct path; examine
prepareAddModelRequest and service.AddModelRequest to implement the
translation/acceptance logic or to split handlers accordingly so existing
callers keep working.
🪄 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: c3bdaf9a-ef3c-4129-8a6d-53f7b03b39d4
📒 Files selected for processing (3)
internal/handler/providers.gointernal/router/router.gointernal/service/model_service.go
💤 Files with no reviewable changes (1)
- internal/handler/providers.go
| provider.GET("/:provider_name/instances/:instance_name/models", r.providerHandler.ListInstanceModels) | ||
| provider.PATCH("/:provider_name/instances/:instance_name/models/*model_name", r.providerHandler.EnableOrDisableModel) | ||
| provider.POST("/:provider_name/instances/:instance_name/models", r.providerHandler.AddCustomModel) | ||
| provider.POST("/:provider_name/instances/:instance_name/models", r.providerHandler.AddModel) |
There was a problem hiding this comment.
Don’t repoint the legacy POST /models contract to the batch-only handler.
internal/cli/user_command.go:2665-2720 still sends a flat {model_name, model_types, max_tokens} body to this exact POST endpoint. ProviderHandler.AddModel now binds service.AddModelRequest, and prepareAddModelRequest rejects requests without models, so existing callers will start failing with 400 Models are required. Preserve the old POST shape or move batch creation to a new method/path.
🤖 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/router/router.go` at line 330, The POST route was repointed to the
batch-only handler causing legacy flat requests to be rejected; restore backward
compatibility by either updating ProviderHandler.AddModel to accept the legacy
single-model shape (bind the legacy fields or detect and translate a flat
{model_name, model_types, max_tokens} payload into the current
service.AddModelRequest) or by creating a new batch-specific handler (e.g.,
ProviderHandler.AddModelsBatch) and route POST
"/:provider_name/instances/:instance_name/models" to the original single-model
handler while registering the new batch handler at a distinct path; examine
prepareAddModelRequest and service.AddModelRequest to implement the
translation/acceptance logic or to split handlers accordingly so existing
callers keep working.
What problem does this PR solve?
Verified from Postman
Type of change