Skip to content

feat[Go]: implement add multi_models - #15563

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
Haruko386:main
Jun 3, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

@Haruko386 Haruko386 commented Jun 3, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

Verified from Postman

image
image

Type of change

  • New Feature (non-breaking change which adds functionality)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 3, 2026
@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5eebc7e9-fc47-4815-a31d-5f457c8c64c6

📥 Commits

Reviewing files that changed from the base of the PR and between 5f3c840 and f75e5bd.

📒 Files selected for processing (1)
  • internal/service/model_service.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/service/model_service.go

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Batch Model Creation with Thinking Support

Layer / File(s) Summary
DAO transactional batch creation
internal/dao/tenant_model.go
TenantModelDAO.CreateBatch() uses GORM transactions to atomically insert multiple TenantModel records, returning early for empty slices and propagating the first error.
Service API for batch model addition
internal/service/model_service.go
ModelProviderService.AddModel() and types AddModelRequest/ModelRequest validate requests, resolve tenant/provider/instance, dedupe names case-insensitively, check for existing models (treating gorm.ErrRecordNotFound as absent), build per-model Extra (including max_tokens and optional thinking), and call CreateBatch.
Handler validation and router integration
internal/handler/providers.go, internal/router/router.go
Adds prepareProviderInstance, introduces prepareAddModelRequest, updates AddModel to call the service and return its code, and registers PUT /:provider_name/instances/:instance_name/models routed to providerHandler.AddModel.
Moonshot reasoning extraction for thinking
internal/entity/models/moonshot.go
When chatModelConfig.Thinking is enabled, reasoning_content extraction uses an unchecked type assertion (ignoring the assertion result) instead of returning an error on mismatch.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

💞 feature

Poem

🐰 I hopped through code to stitch a batch,
Transactions safe, no partial catch,
Dedupes trimmed and extras set,
Route switched to PUT — all wired up yet,
A rabbit cheers — the models matched!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat[Go]: implement add multi_models' directly describes the main feature addition: implementing batch model creation functionality.
Description check ✅ Passed The description includes the required 'What problem does this PR solve?' section with context and verification screenshots, and the 'Type of change' section with 'New Feature' selected.
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.

@Haruko386 Haruko386 added the ci Continue Integration label Jun 3, 2026
@Haruko386
Haruko386 marked this pull request as draft June 3, 2026 05:22
@Haruko386
Haruko386 marked this pull request as ready for review June 3, 2026 05:22

@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: 3

🧹 Nitpick comments (2)
internal/dao/tenant_model.go (1)

37-50: ⚡ Quick win

Consider using GORM's CreateInBatches for better performance.

The current implementation loops through models and calls tx.Create individually. GORM provides tx.CreateInBatches which 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 value

Consider logging when reasoning_content type mismatch occurs.

The unchecked type assertion at line 187 silently ignores any reasoning_content field 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 when reasoning_content is 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

📥 Commits

Reviewing files that changed from the base of the PR and between c41855d and dba0067.

📒 Files selected for processing (5)
  • internal/dao/tenant_model.go
  • internal/entity/models/moonshot.go
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/service/model_service.go

Comment thread internal/router/router.go Resolved
Comment thread internal/service/model_service.go Resolved
Comment thread internal/service/model_service.go Resolved
@codecov

codecov Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (9799f33) to head (f75e5bd).
⚠️ Report is 8 commits behind head on main.

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.
📢 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.

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 047a385 and 5f3c840.

📒 Files selected for processing (3)
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/service/model_service.go
💤 Files with no reviewable changes (1)
  • internal/handler/providers.go

Comment thread internal/router/router.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)

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 | 🟠 Major | 🏗️ Heavy lift

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.

@JinHai-CN
JinHai-CN merged commit 473d06d into infiniflow:main Jun 3, 2026
1 check 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.

2 participants