Skip to content

Feat: model provider - #16028

Merged
wangq8 merged 6 commits into
infiniflow:mainfrom
Lynn-Inf:feat/v0.26.1-model-provider
Jun 15, 2026
Merged

wangq8 merged 6 commits into
infiniflow:mainfrom
Lynn-Inf:feat/v0.26.1-model-provider

Conversation

@Lynn-Inf

@Lynn-Inf Lynn-Inf commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Feat:

  • Allow upsert model_type for instance model

Fix:

  • Allow create instance with duplicate api_key

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • 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 15, 2026
@dosubot dosubot Bot added 🐞 bug Something isn't working, pull request that fix bug. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 15, 2026
@Lynn-Inf Lynn-Inf added ci Continue Integration and removed 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 15, 2026
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds ActiveStatusEnum.UNSUPPORTED to the status enum and propagates it through DB queries, service logic, and API endpoints. A new TenantModelService.upsert_model_type classmethod reconciles add/delete model-type operations. A _hybrid_get_instance_models helper merges factory and tenant model records. A new PUT /providers/<provider_name>/instances/<instance_name>/models endpoint enables batch model-type updates.

Changes

UNSUPPORTED model status and batch model-type update

Layer / File(s) Summary
UNSUPPORTED enum, upsert_model_type, and joint service filtering
common/constants.py, api/db/services/tenant_model_service.py, api/db/joint_services/tenant_model_service.py
ActiveStatusEnum.UNSUPPORTED is added; TenantModelService.upsert_model_type is introduced to reconcile add/delete type sets by updating or inserting records with appropriate statuses; joint service functions get_model_config_from_provider_instance, get_model_type_by_name, and get_models_by_tenant_and_provider_and_model_type are updated to guard against and exclude UNSUPPORTED entries.
_hybrid_get_instance_models and provider service changes
api/apps/services/provider_api_service.py
_hybrid_get_instance_models is added to merge factory LLM definitions with tenant model records while filtering out unsupported types; list_instance_models delegates to this helper; update_instance_models is rewired to compute add/delete diffs and persist via upsert_model_type; the duplicate-instance early-return in create_provider_instance is removed; update_model_status excludes UNSUPPORTED records from bulk status updates.
models_api_service UNSUPPORTED checks and PUT endpoint
api/apps/services/models_api_service.py, api/apps/restful_apis/provider_api.py
_get_model_info and _check_model_available are updated to require exactly ACTIVE status; list_tenant_added_models subtracts UNSUPPORTED model types from the computed set; the new PUT /providers/<provider_name>/instances/<instance_name>/models route handler validates model_name/model_type fields and delegates to provider_api_service.update_instance_models.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐇 Hippity-hop through the model maze,
Some types are UNSUPPORTED — that's the new phase!
Upsert and merge, add and delete,
The hybrid list makes factory and tenant meet.
No "inactive" guesses — ACTIVE is the gate,
A PUT endpoint seals each model's fate! 🌟

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.63% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Feat: model provider' is vague and overly broad, failing to clearly describe the specific changes (upsert capability for model_type, duplicate api_key support). Use a more descriptive title like 'Feat: Add model type upsert and allow duplicate api_key instances' to clearly indicate the main changes.
Description check ❓ Inconclusive The PR description addresses the main objectives but lacks depth and proper section formatting compared to the template requirements. Expand the description with more background context. Under 'What problem does this PR solve?', explain why upsert capability and duplicate api_key support are needed and what issues they resolve. Add more specific details about the use cases and impacts.
✅ Passed checks (2 passed)
Check name Status Explanation
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.

@Lynn-Inf Lynn-Inf added the 💞 feature Feature request, pull request that fullfill a new feature. label Jun 15, 2026
@Lynn-Inf
Lynn-Inf marked this pull request as draft June 15, 2026 09:21
@Lynn-Inf
Lynn-Inf marked this pull request as ready for review June 15, 2026 09:21

@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

🧹 Nitpick comments (2)
api/apps/restful_apis/provider_api.py (1)

670-675: 💤 Low value

Invalid OpenAPI type syntax in docstring.

type: list of string is not valid OpenAPI schema syntax. Should use type: array with items.

📝 Proposed fix
           properties:
             model_name:
-              type: list of string
+              type: array
+              items:
+                type: string
               description: Model name.
             model_type:
-              type: list of string
+              type: array
+              items:
+                type: string
               description: Model type.
🤖 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/apps/restful_apis/provider_api.py` around lines 670 - 675, The OpenAPI
schema syntax in the docstring for model_name and model_type parameters uses
invalid syntax with `type: list of string`. Replace this with valid OpenAPI
schema syntax by changing `type: list of string` to `type: array` with an
`items` property that specifies `type: string`. Apply this correction to both
the model_name and model_type field descriptions in the docstring.
api/db/joint_services/tenant_model_service.py (1)

301-301: 💤 Low value

Consider breaking up this complex line for readability.

The set operation is correct but hard to parse at a glance. Extracting intermediate variables would improve maintainability.

♻️ Suggested refactor
-    return list(set(types_in_json + [model_obj.model_type for model_obj in model_objs if model_obj.status != ActiveStatusEnum.UNSUPPORTED.value]) - {model_obj.model_type for model_obj in model_objs if model_obj.status == ActiveStatusEnum.UNSUPPORTED.value})
+    supported_db_types = {m.model_type for m in model_objs if m.status != ActiveStatusEnum.UNSUPPORTED.value}
+    unsupported_db_types = {m.model_type for m in model_objs if m.status == ActiveStatusEnum.UNSUPPORTED.value}
+    return list((set(types_in_json) | supported_db_types) - unsupported_db_types)
🤖 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/joint_services/tenant_model_service.py` at line 301, The return
statement in the method contains a complex nested set operation with multiple
list comprehensions that is difficult to read. Extract intermediate variables to
break this down: first create a variable for the list of supported model types
(combining types_in_json with model types where status is not UNSUPPORTED), then
create a variable for the set of unsupported model types, then perform the set
difference operation between these two variables, and finally convert the result
to a list and return it. This will improve code clarity and maintainability
without changing the logic.
🤖 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 `@api/apps/restful_apis/provider_api.py`:
- Around line 677-681: The endpoint validates the presence of model_name and
model_type in the request data but does not validate their types, which could
allow unexpected input types to reach the service layer. After extracting
model_name and model_type from the data dictionary, add type validation to
ensure both fields are strings before proceeding. This can be done by adding
isinstance() checks for each field and returning an appropriate error response
(using get_error_argument_result) if either field has an incorrect type.

In `@api/apps/services/provider_api_service.py`:
- Around line 636-641: The model_type field in the models.append block is being
assigned a set (result of set difference operation), but other code paths return
a list for model_type, creating type inconsistency for API consumers. Convert
the set result to a list by wrapping the set difference operation with the
list() constructor to ensure consistent return types across all code paths in
the function.

In `@api/db/joint_services/tenant_model_service.py`:
- Around line 334-337: The method
`TenantModelService.get_by_provider_id_and_instance_id_and_model_type` returns a
single TenantModel object or None, not a list, but the code at line 335 attempts
to iterate over it with a list comprehension. Fix this by first checking if the
returned `models` object is not None, then either wrap it in a list before
iterating (e.g., `[models]`) or conditionally check the single object's status
and add it to results if it meets the criteria (status is not UNSUPPORTED). This
ensures you handle the single object correctly rather than iterating over its
attributes or raising a TypeError.

In `@api/db/services/tenant_model_service.py`:
- Around line 82-88: The issue is that enum objects (like
ActiveStatusEnum.UNSUPPORTED) are being compared against string values from the
database, which will never match. In api/db/services/tenant_model_service.py
lines 82-88, change two comparisons: the status assignment at line 82 should use
ActiveStatusEnum.UNSUPPORTED.value instead of ActiveStatusEnum.UNSUPPORTED, and
the filter condition at line 86 checking model_record.status should compare
against ActiveStatusEnum.UNSUPPORTED.value instead of the enum object.
Additionally, in api/apps/services/provider_api_service.py lines 606-611, change
the comparison at line 606 to use ActiveStatusEnum.UNSUPPORTED.value instead of
the enum object. These changes ensure that string values from the database are
properly compared against string enum values using .value.

---

Nitpick comments:
In `@api/apps/restful_apis/provider_api.py`:
- Around line 670-675: The OpenAPI schema syntax in the docstring for model_name
and model_type parameters uses invalid syntax with `type: list of string`.
Replace this with valid OpenAPI schema syntax by changing `type: list of string`
to `type: array` with an `items` property that specifies `type: string`. Apply
this correction to both the model_name and model_type field descriptions in the
docstring.

In `@api/db/joint_services/tenant_model_service.py`:
- Line 301: The return statement in the method contains a complex nested set
operation with multiple list comprehensions that is difficult to read. Extract
intermediate variables to break this down: first create a variable for the list
of supported model types (combining types_in_json with model types where status
is not UNSUPPORTED), then create a variable for the set of unsupported model
types, then perform the set difference operation between these two variables,
and finally convert the result to a list and return it. This will improve code
clarity and maintainability without changing the logic.
🪄 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: ea19cc05-829c-4327-8499-a342e2549df2

📥 Commits

Reviewing files that changed from the base of the PR and between f6a2075 and c247e81.

📒 Files selected for processing (6)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/models_api_service.py
  • api/apps/services/provider_api_service.py
  • api/db/joint_services/tenant_model_service.py
  • api/db/services/tenant_model_service.py
  • common/constants.py

Comment on lines +677 to +681
data = await request.get_json()
if not data or "model_name" not in data or "model_type" not in data:
return get_error_argument_result(message="model_name and model_type are required")
model_name = data["model_name"]
model_type = data["model_type"]

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

Missing type validation for model_name and model_type inputs.

The endpoint validates presence but not types. If a client sends non-list values (e.g., strings), the service layer may behave unexpectedly or produce unclear errors.

🛡️ Proposed fix
     data = await request.get_json()
     if not data or "model_name" not in data or "model_type" not in data:
         return get_error_argument_result(message="model_name and model_type are required")
     model_name = data["model_name"]
     model_type = data["model_type"]
+    if not isinstance(model_name, list) or not isinstance(model_type, list):
+        return get_error_argument_result(message="model_name and model_type must be arrays")
     try:

As per coding guidelines, newer RESTful APIs under api/apps/restful_apis/ should use Pydantic request validation with service layer pattern. While other endpoints in this file also use manual validation, consider adopting Pydantic for consistency with the guideline.

📝 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
data = await request.get_json()
if not data or "model_name" not in data or "model_type" not in data:
return get_error_argument_result(message="model_name and model_type are required")
model_name = data["model_name"]
model_type = data["model_type"]
data = await request.get_json()
if not data or "model_name" not in data or "model_type" not in data:
return get_error_argument_result(message="model_name and model_type are required")
model_name = data["model_name"]
model_type = data["model_type"]
if not isinstance(model_name, list) or not isinstance(model_type, list):
return get_error_argument_result(message="model_name and model_type must be arrays")
🤖 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/apps/restful_apis/provider_api.py` around lines 677 - 681, The endpoint
validates the presence of model_name and model_type in the request data but does
not validate their types, which could allow unexpected input types to reach the
service layer. After extracting model_name and model_type from the data
dictionary, add type validation to ensure both fields are strings before
proceeding. This can be done by adding isinstance() checks for each field and
returning an appropriate error response (using get_error_argument_result) if
either field has an incorrect type.

Source: Coding guidelines

Comment on lines +636 to +641
models.append({
"name": model_name,
"model_type": set(model_info_dict["model_type"]) - set(model_unsupported_type_map.get(model_name, [])),
"max_tokens": extra_fields.get("max_tokens", 8192),
"status": model_info_dict["status"],
})

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

Inconsistent model_type return type: set vs list.

Line 638 assigns a set to model_type, but lines 626-628 return a list. API consumers may encounter type inconsistencies when processing the returned models.

🐛 Proposed fix
             models.append({
                 "name": model_name,
-                "model_type": set(model_info_dict["model_type"]) - set(model_unsupported_type_map.get(model_name, [])),
+                "model_type": list(set(model_info_dict["model_type"]) - set(model_unsupported_type_map.get(model_name, []))),
                 "max_tokens": extra_fields.get("max_tokens", 8192),
                 "status": model_info_dict["status"],
             })
📝 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
models.append({
"name": model_name,
"model_type": set(model_info_dict["model_type"]) - set(model_unsupported_type_map.get(model_name, [])),
"max_tokens": extra_fields.get("max_tokens", 8192),
"status": model_info_dict["status"],
})
models.append({
"name": model_name,
"model_type": list(set(model_info_dict["model_type"]) - set(model_unsupported_type_map.get(model_name, []))),
"max_tokens": extra_fields.get("max_tokens", 8192),
"status": model_info_dict["status"],
})
🤖 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/apps/services/provider_api_service.py` around lines 636 - 641, The
model_type field in the models.append block is being assigned a set (result of
set difference operation), but other code paths return a list for model_type,
creating type inconsistency for API consumers. Convert the set result to a list
by wrapping the set difference operation with the list() constructor to ensure
consistent return types across all code paths in the function.

Comment on lines 334 to +337
models = TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id, inst.id, model_type)
if models:
results.extend(models)
supported = [model for model in models if model.status != ActiveStatusEnum.UNSUPPORTED.value]
if supported:
results.extend(supported)

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 | ⚡ Quick win

Type mismatch: iterating over a single object or None.

TenantModelService.get_by_provider_id_and_instance_id_and_model_type returns a single TenantModel object (via get_or_none), not a list. Iterating over models at line 335 will either:

  • Iterate over the object's attributes if a model is found (incorrect behavior)
  • Raise TypeError if None is returned
🐛 Proposed fix
     for inst in instances:
         models = TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id, inst.id, model_type)
-        supported = [model for model in models if model.status != ActiveStatusEnum.UNSUPPORTED.value]
-        if supported:
-            results.extend(supported)
+        if models and models.status != ActiveStatusEnum.UNSUPPORTED.value:
+            results.append(models)
     return results
📝 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
models = TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id, inst.id, model_type)
if models:
results.extend(models)
supported = [model for model in models if model.status != ActiveStatusEnum.UNSUPPORTED.value]
if supported:
results.extend(supported)
for inst in instances:
models = TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id, inst.id, model_type)
if models and models.status != ActiveStatusEnum.UNSUPPORTED.value:
results.append(models)
return results
🤖 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/joint_services/tenant_model_service.py` around lines 334 - 337, The
method `TenantModelService.get_by_provider_id_and_instance_id_and_model_type`
returns a single TenantModel object or None, not a list, but the code at line
335 attempts to iterate over it with a list comprehension. Fix this by first
checking if the returned `models` object is not None, then either wrap it in a
list before iterating (e.g., `[models]`) or conditionally check the single
object's status and add it to results if it meets the criteria (status is not
UNSUPPORTED). This ensures you handle the single object correctly rather than
iterating over its attributes or raising a TypeError.

Comment on lines +82 to +88
status=ActiveStatusEnum.UNSUPPORTED,
extra="{}"
)
return len(operation.get("add", [])) + len(operation.get("delete", []))
model_record_example = [model_record for model_record in model_type_records if model_record.status != ActiveStatusEnum.UNSUPPORTED]
extra_fields = model_record_example[0].extra if model_record_example else "{}"
model_status = model_record_example[0].status if model_record_example else ActiveStatusEnum.ACTIVE.value

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 | ⚡ Quick win

Enum object vs. string comparison will never match. Both locations compare model_record.status (a string from the database like "unsupported") against ActiveStatusEnum.UNSUPPORTED (the enum object), which will never be equal. This prevents UNSUPPORTED records from being correctly identified and filtered.

  • api/db/services/tenant_model_service.py#L82-L88: Change status=ActiveStatusEnum.UNSUPPORTED to status=ActiveStatusEnum.UNSUPPORTED.value at line 82, and change != ActiveStatusEnum.UNSUPPORTED to != ActiveStatusEnum.UNSUPPORTED.value at line 86.
  • api/apps/services/provider_api_service.py#L606-L611: Change == ActiveStatusEnum.UNSUPPORTED to == ActiveStatusEnum.UNSUPPORTED.value at line 606.
📍 Affects 2 files
  • api/db/services/tenant_model_service.py#L82-L88 (this comment)
  • api/apps/services/provider_api_service.py#L606-L611
🤖 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/tenant_model_service.py` around lines 82 - 88, The issue is
that enum objects (like ActiveStatusEnum.UNSUPPORTED) are being compared against
string values from the database, which will never match. In
api/db/services/tenant_model_service.py lines 82-88, change two comparisons: the
status assignment at line 82 should use ActiveStatusEnum.UNSUPPORTED.value
instead of ActiveStatusEnum.UNSUPPORTED, and the filter condition at line 86
checking model_record.status should compare against
ActiveStatusEnum.UNSUPPORTED.value instead of the enum object. Additionally, in
api/apps/services/provider_api_service.py lines 606-611, change the comparison
at line 606 to use ActiveStatusEnum.UNSUPPORTED.value instead of the enum
object. These changes ensure that string values from the database are properly
compared against string enum values using .value.

@codecov

codecov Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16028   +/-   ##
=======================================
  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.

@wangq8
wangq8 merged commit 47495c1 into infiniflow:main Jun 15, 2026
2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 25, 2026
1 task done
This was referenced Jul 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. 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