Repository navigation
Feat: tenant llm provider - #14595
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds tenant/provider model DB schema and services, migration updates, provider/model business services (including chat streaming), new REST endpoints for models/providers, and small infra/integration tweaks. ChangesProvider and Tenant Model Management System
Sequence Diagram(s)sequenceDiagram
participant Client
participant API as Rest API
participant Service as Service Layer
participant LLM as LLM Factory/Bundle
participant DB as Database
rect rgba(100, 150, 200, 0.5)
Note over Client,DB: List Providers / Provider Models
Client->>API: GET /providers
API->>Service: list_providers(tenant_id)
Service->>DB: query TenantModelProvider
DB-->>Service: provider rows
Service->>LLM: inspect factory model info (if needed)
Service-->>API: providers JSON
API-->>Client: HTTP 200
end
rect rgba(150, 100, 200, 0.5)
Note over Client,DB: Set Tenant Default Model
Client->>API: PATCH /models (model_type, composite id)
API->>Service: set_tenant_default_models(...)
Service->>LLM: resolve composite model -> provider/instance/model
Service->>DB: verify/create TenantModel / update Tenant.ocr_id
DB-->>Service: commit
Service-->>API: result JSON
API-->>Client: HTTP 200/400
end
rect rgba(200, 100, 150, 0.5)
Note over Client,LLM: Chat to Model (streaming)
Client->>API: POST /providers/{p}/instances/{i}/models/{m}/chat (stream=true)
API->>Service: chat_to_model(...)
Service->>LLM: initialize LLMBundle and chat(stream=true)
LLM-->>API: SSE stream chunks
API-->>Client: SSE response
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
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: 15
🧹 Nitpick comments (8)
common/constants.py (1)
69-72: 💤 Low valueTwo
Active*enums with overlapping semantics — clarify intent or rename.
ActiveStatusEnum.ACTIVE = "active"now coexists withActiveEnum.ACTIVE = "1"(lines 74-76). They model the same concept (active/inactive) with different stored values, and both are exported under similar names. A future caller comparingobj.status == ActiveEnum.ACTIVE.valueagainst a record written withActiveStatusEnum.ACTIVE.valuewill silently mis-evaluate.Suggest either renaming (e.g.,
TenantModelStatusEnum) to make scope explicit, or adding a docstring on each enum stating the tables/columns it applies to.🤖 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 `@common/constants.py` around lines 69 - 72, Two enums with overlapping semantics (ActiveStatusEnum and ActiveEnum) can cause silent mismatches; update to make intent explicit by renaming one enum (e.g., ActiveStatusEnum -> TenantModelStatusEnum or ActiveEnum -> DBFlagActiveEnum) or add clear docstrings on ActiveStatusEnum and ActiveEnum describing exactly which table/column/serialization each applies to, then update all imports/usages to the new name or ensure callers use the correct enum; verify any exported names are adjusted to avoid ambiguity (references: ActiveStatusEnum, ActiveEnum).api/apps/restful_apis/models_api.py (2)
78-80: 💤 Low valueUse a descriptive message with
logging.exception.
logging.exception(e)works, butlogging.exceptionalready captures the current exception viaexc_info=True; passing the exception as the message produces logs like"<ValueError object at 0x...>". Pass a description of the operation instead.🪵 Suggested change
except Exception as e: - logging.exception(e) + logging.exception("get_models failed for tenant=%s", tenant_id) return get_error_data_result(message="Internal server error")except Exception as e: - logging.exception(e) + logging.exception("set_models failed for tenant=%s", tenant_id) return get_error_data_result(message="Internal server error")Also applies to: 141-147
🤖 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/models_api.py` around lines 78 - 80, Replace the calls that pass the exception object to logging.exception (the handlers that currently call logging.exception(e) and then return get_error_data_result) with a descriptive message about the operation that failed (for example "Error fetching model list" or "Error creating model") so the log shows context while logging.exception will still record the traceback; update both occurrences (the one around the handler that returns get_error_data_result at ~78-80 and the one at ~141-147) to use logging.exception("Descriptive operation message") instead of logging.exception(e).
30-33: 💤 Low valueSync GET handler blocks executor thread during database calls—consider async if scaling.
get_modelsis synchronous whileset_modelsis async. Quart runs sync handlers in a thread pool, so they won't block the event loop, butlist_tenant_default_modelsalready performs blocking I/O (database queries viaTenantService.get_by_idand_get_model_info). This is acceptable for sync database access, but if request concurrency becomes a bottleneck, converting to async would allow the event loop to handle other requests while awaiting database operations.🤖 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/models_api.py` around lines 30 - 33, The GET handler get_models is currently synchronous and calls blocking DB helpers (list_tenant_default_models -> TenantService.get_by_id and _get_model_info); change get_models to an async def and await the blocking work by either converting list_tenant_default_models/_get_model_info to async (and await TenantService.get_by_id if an async client exists) or wrap the blocking calls with asyncio.to_thread / loop.run_in_executor so the event loop isn't blocked; ensure decorators (`@login_required`, `@add_tenant_id_to_kwargs`) are compatible with async handlers and update any call sites accordingly.api/apps/restful_apis/provider_api.py (3)
30-198: ⚡ Quick winAdd logging for tenant-mutating flows.
Per coding guidelines, new flows should add logging. Endpoints that mutate state (
add_provider,delete_provider,create_provider_instance,drop_provider_instances,enable_or_disable_model) currently log only on exception. Addlogging.info(or equivalent) at the success path with tenant/provider/instance/model identifiers so audit and operational tracing is possible — this is especially important for delete/drop flows which are destructive.For example in
delete_provider:if success: logging.info("Provider deleted: tenant_id=%s provider_name=%s", tenant_id, provider_name) return get_result(message=msg)As per coding guidelines: "Add logging for new flows".
🤖 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 30 - 198, The mutating endpoints lack success-path audit logs; add logging.info calls on successful operations to record tenant and resource identifiers for auditing. For add_provider and delete_provider, insert logging.info(...) in the success branch including tenant_id and provider_name; for create_provider_instance and drop_provider_instances log tenant_id, provider_name and instance identifiers on success; for enable_or_disable_model log tenant_id, provider_name, model_id and the new state. Use structured messages and format placeholders (e.g., "Provider deleted: tenant_id=%s provider_name=%s") and keep logs adjacent to the existing return get_result(...) in each success path.
697-697: 💤 Low valueMove
from quart import Responseto module-level imports.Importing inside the request handler is repeated work on every streaming call and obscures the dependency graph. Hoist this to the top of the file alongside
from quart import request.♻️ Proposed fix
-from quart import request +from quart import Response, requestif stream and isinstance(result, dict) and result.get("type") == "stream": # Streaming response using SSE - from quart import Response llm = result["llm"]🤖 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` at line 697, The local import "from quart import Response" inside the request handler should be hoisted to the module-level imports alongside the existing "from quart import request"; move the Response import to the top of the file, update the module import block to include Response, and remove the in-function import at its current location so the handler uses the module-level Response symbol (no runtime change to behavior, just avoid repeated imports and clarify dependencies).
30-30: 💤 Low value
managersymbol relies on implicit module injection.The route decorator uses
manager.route(...) # noqa: F821becausemanageris injected by the parent module loader. New contributors will struggle to locate wheremanageris defined. Consider documenting this convention at the top of the file with a brief comment, or importing it explicitly if the framework allows.🤖 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` at line 30, The route decorator uses an implicitly injected symbol "manager" (seen on the `@manager.route`(...) line) which is confusing to new contributors; either add a short explanatory comment at the top of provider_api.py stating that "manager" is supplied by the parent module loader and where to find that loader, or—if allowed by the framework—replace the implicit usage by explicitly importing or referencing the manager object so the origin is clear; update any module docstring or top-of-file comment to mention "manager" and its source (or add the explicit import) so future readers can locate its definition.api/db/services/tenant_model_instance_service.py (2)
25-26: 💤 Low valueConsider an index on
provider_id.
get_all_by_provider_idfilters onprovider_id, butprovider_idis declaredindex=FalseonTenantModelInstance. If this method is called on hot paths (e.g., listing instances per provider), expect full scans.🤖 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_instance_service.py` around lines 25 - 26, get_all_by_provider_id runs WHERE cls.model.provider_id == provider_id on TenantModelInstance but provider_id is defined index=False; add an index to avoid full-table scans by changing the TenantModelInstance model field provider_id to index=True and generate a DB migration that creates the corresponding index (or ALTER TABLE/CREATE INDEX) for the existing table; update any model imports referencing provider_id if needed and run migrations/CI to validate the schema change and tests.
30-42: ⚡ Quick winAdd an index/unique constraint on
(provider_id, instance_name).Both
get_by_provider_id_and_instance_nameanddelete_by_provider_id_and_instance_namefilter on(provider_id, instance_name), but perapi/db/db_models.py:1349-1362,TenantModelInstanceonly has a composite unique index on(api_key, provider_id), and bothprovider_idandinstance_nameare declared withindex=False. As the table grows these lookups will full-scan. Additionally,get_or_nonehere implicitly assumes uniqueness on(provider_id, instance_name); without a DB-level unique constraint, duplicates are possible and the method's contract is ambiguous.Consider adding a composite unique index on
(provider_id, instance_name)in the modelMeta.indexes, mirroring the existing composite indexes pattern.🤖 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_instance_service.py` around lines 30 - 42, The TenantModelInstance lookups (get_by_provider_id_and_instance_name and delete_by_provider_id_and_instance_name) will full-scan because provider_id and instance_name are not indexed and there is no uniqueness enforced; update the TenantModelInstance model (class TenantModelInstance in api/db/db_models.py) Meta.indexes to add a composite index and unique constraint on (provider_id, instance_name) mirroring the existing composite index pattern (e.g., add a tuple specifying fields ['provider_id', 'instance_name'] with unique=True), and ensure both provider_id and instance_name are not declared index=False so the DB enforces fast lookups and uniqueness for those methods.
🤖 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 680-708: The handler currently ignores the request's thinking flag
and hardcodes temperature to 0.9; update the handler to read temperature from
the request (e.g., temperature = data.get("temperature", 0.9)) and forward the
thinking and temperature values to the LLM call path: include thinking (and
temperature) in the call to provider_api_service.chat_to_model(tenant_id,
provider_name, model_name, message, stream, thinking, temperature) or, if the
provider_api_service already resolves parameters, at minimum forward thinking
and temperature into llm.async_chat_streamly by calling
llm.async_chat_streamly(None, [{"role":"user","content":message}],
{"temperature": temperature, "thinking": thinking}) so the documented thinking
flag and temperature are honored (adjust param names to match the provider API
signatures such as provider_api_service.chat_to_model and
llm.async_chat_streamly).
- Around line 700-713: The generator generate() currently swallows LLM errors by
filtering chunks with "**ERROR**" and lets exceptions close the SSE stream
silently; update generate() to (1) stop filtering out error-marked chunks and
instead detect when a chunk contains "**ERROR**" and yield a structured SSE
error event (e.g., "data: [ERROR]{...}\n\n") so clients can handle failures, (2)
wrap the async for loop in try/except to catch exceptions from
llm.async_chat_streamly, log the exception (use the existing logger) and yield a
final SSE error event before returning, and (3) ensure the final "data: [DONE]"
is only sent on successful completion so Response(generate(),
mimetype="text/event-stream", ...) reflects real success/failure.
In `@api/apps/services/models_api_service.py`:
- Around line 182-218: The function set_tenant_default_models mutates tenant
defaults without any audit log; add an INFO log after a successful update
(before returning True) that records tenant_id, model_type, and the new value
(use the composite string like f"{model_name}@{model_instance}@{model_provider}"
or the literal "cleared" when default_model == ""), using the module logger
(logger.info(...)); place the log right after TenantService.update_by_id(...) in
set_tenant_default_models so every successful change is traceable.
In `@api/apps/services/provider_api_service.py`:
- Around line 84-119: The functions add_provider and delete_provider (and
similarly create_provider_instance, drop_provider_instances,
update_model_status) perform tenant-scoped mutations but lack logging; add
structured logs using the module logger (or existing logger instance): emit an
INFO log on successful operations including tenant_id, provider_name (and any
created instance id or model status), and emit a WARNING or ERROR/EXCEPTION log
on validation failures or exceptions (e.g., when FACTORY_LLM_INFOS is empty,
provider_name not allowed, or provider already exists) referencing
TenantModelProviderService calls so operators can audit provider/instance churn
per tenant and capture the failure reason.
- Around line 250-265: The code in provider_api_service.py currently treats an
empty result from TenantModelInstanceService.get_all_by_provider_id(provider_id)
as an error (returning False and a message); change this so an empty list is a
valid successful result: when instance_objs is falsy, return True and an empty
list (e.g., True, []) instead of False and the error string, preserving the same
return shape used when instances exist (True, instances); update the branch that
references provider_id/provider_name and ensure callers still receive a boolean
success flag plus a list.
- Around line 142-194: In list_provider_models and show_provider_model update
all accesses of llm["name"] to llm["llm_name"] to match the FACTORY_LLM_INFOS
schema; locate the loops building models in list_provider_models (function
list_provider_models) and the target selection/return in show_provider_model
(function show_provider_model) and replace the key used for model names and any
places that construct the returned dicts (e.g., where "name": llm["name"] and
"name": llm_info["name"] are set) so they use llm["llm_name"] /
llm_info["llm_name"] instead, keeping other fields (max_tokens, model_type)
unchanged and mirroring the usage in models_api_service.py and
tenant_llm_service.py.
- Around line 197-233: create_provider_instance currently allows empty api_key,
doesn't check for existing instances by (api_key, provider_id) or instance_name,
and will raise an uncaught IntegrityError on duplicates; fix by validating
api_key is non-empty and meets any basic format rules, query TenantModelInstance
(or use TenantModelInstanceService) for existing records with the same
provider_id and either the same api_key or the same instance_name and return
friendly errors like "API key already in use" or "Instance name already exists",
and wrap the TenantModelInstanceService.insert call in a try/except that catches
peewee.IntegrityError (or the app's DB integrity exception) to return a clear
failure tuple instead of letting a 500 bubble up; reference the
functions/classes TenantModelProviderService.get_by_tenant_id_and_provider_name,
TenantModelInstanceService.insert, and the TenantModelInstance unique index on
(api_key, provider_id).
In `@api/db/db_models.py`:
- Line 752: The Tenant.ocr_id CharField declaration (Tenant.ocr_id) and the
migration addition in migrate_db are inconsistent (model uses max_length=256
while the migration uses max_length=128); update the migration and any
create_table logic so both use the same max_length (choose 256 or 128) to avoid
schema/runtime mismatches—modify the migration entry in migrate_db that adds
ocr_id to use max_length=256 (or change the model to 128 if you prefer smaller)
and ensure create_table uses the identical value so Tenant.ocr_id, the migration
that adds ocr_id, and any table-creation code are consistent.
- Around line 1364-1374: TenantModel lacks a uniqueness constraint on
(provider_id, instance_id, model_name), which allows race-condition inserts;
update the TenantModel class (Meta) to declare a unique constraint/index on
provider_id, instance_id and model_name (e.g. unique_together or a unique Index)
and generate/apply the corresponding DB migration so the DB enforces uniqueness;
reference the TenantModel class and its Meta to make this change so
get_by_provider_id_and_instance_id_and_model_name in provider_api_service.py
cannot produce duplicate rows.
- Around line 1349-1361: The unique index on TenantModelInstance is wrong:
change the Meta.indexes tuple in class TenantModelInstance so the unique
constraint is on ("provider_id", "instance_name") instead of ("api_key",
"provider_id"); if you still want to deduplicate api_key per provider, add a
separate unique tuple for ("api_key", "provider_id") instead of replacing it,
and create a corresponding migration in mysql_migration.py to drop the old index
and create the new one so existing installs are rebuilt; verify service lookups
such as get_by_provider_id_and_instance_name() continue to work with the updated
unique constraint.
In `@api/db/services/tenant_model_provider_service.py`:
- Around line 33-42: The delete_by_tenant_id_and_provider_name method currently
only deletes the provider row and leaves orphaned TenantModelInstance,
TenantModel, and TenantModelGroupMapping rows; update
delete_by_tenant_id_and_provider_name to perform a transaction-wrapped cascade
cleanup that removes rows from TenantModelInstance (by provider_id), TenantModel
(add and use a new delete_by_provider_id method on TenantModelService), and
TenantModelGroupMapping (add and use a delete_by_provider_id method on
TenantModelGroupMappingService) before deleting the provider, and add
processLogger.info/error calls around each delete and on transaction
commit/rollback to follow logging guidelines. Ensure the new
TenantModelService.delete_by_provider_id and
TenantModelGroupMappingService.delete_by_provider_id accept provider_id and
tenant_id so bulk deletes can be performed atomically inside the
DB.connection_context() used by delete_by_tenant_id_and_provider_name.
In `@api/db/services/tenant_model_service.py`:
- Around line 25-30: The TenantModel Peewee model lacks the composite unique
index that the migration creates, causing
get_by_provider_id_and_instance_id_and_model_name to assume uniqueness that the
ORM won't enforce; update TenantModel.Meta.indexes to include a unique composite
index on (provider_id, model_name, instance_id) (matching the migration's
idx_provider_model_instance order) so the ORM-created table enforces the same
uniqueness constraint as the migration.
In `@docker/entrypoint.sh`:
- Line 283: The entrypoint calls wait_for_server with a non-existent endpoint
"/api/v1/system/healthz", which causes 90s timeouts; update the call in
docker/entrypoint.sh to target an existing server health endpoint (e.g.,
"/health", "/v1/system/ping", or "/v1/system/version") or add a handler
registering "/api/v1/system/healthz" in the Go system routes; specifically
change the wait_for_server invocation (symbol: wait_for_server) to use one of
the existing endpoints ("/health" or "/v1/system/ping" or "/v1/system/version")
or implement the new route in the system handler so the path matches.
In `@tools/scripts/mysql_migration.py`:
- Line 521: The migration only adds "extra VARCHAR(512) DEFAULT '{}'" (and the
matching "extra VARCHAR(1024) ..." entry) inside CREATE TABLE IF NOT EXISTS
blocks, so existing tables won't receive the new extra column; update the
migration to detect and alter existing tables by adding an ALTER TABLE ... ADD
COLUMN extra ... (or a conditional column-existence check then ALTER) for each
affected table after or before the CREATE TABLE IF NOT EXISTS step, ensuring the
"extra" column name and types match the CREATE definitions and guarding against
duplicate-add errors.
- Around line 333-335: The INSERT construction in
TenantModelProviderStage.execute currently interpolates llm_factory and
tenant_id directly into the SQL string causing SQL errors when values contain
apostrophes; update the code to either use parameterized execution via
db.execute_sql(sql, params) for this insert or at minimum escape single quotes
the same way TenantModelInstanceStage does (use .replace("'", "''") on
llm_factory and tenant_id) before appending to values, ensuring you reference
the same record_id/current_ts logic already present in this method.
---
Nitpick comments:
In `@api/apps/restful_apis/models_api.py`:
- Around line 78-80: Replace the calls that pass the exception object to
logging.exception (the handlers that currently call logging.exception(e) and
then return get_error_data_result) with a descriptive message about the
operation that failed (for example "Error fetching model list" or "Error
creating model") so the log shows context while logging.exception will still
record the traceback; update both occurrences (the one around the handler that
returns get_error_data_result at ~78-80 and the one at ~141-147) to use
logging.exception("Descriptive operation message") instead of
logging.exception(e).
- Around line 30-33: The GET handler get_models is currently synchronous and
calls blocking DB helpers (list_tenant_default_models -> TenantService.get_by_id
and _get_model_info); change get_models to an async def and await the blocking
work by either converting list_tenant_default_models/_get_model_info to async
(and await TenantService.get_by_id if an async client exists) or wrap the
blocking calls with asyncio.to_thread / loop.run_in_executor so the event loop
isn't blocked; ensure decorators (`@login_required`, `@add_tenant_id_to_kwargs`) are
compatible with async handlers and update any call sites accordingly.
In `@api/apps/restful_apis/provider_api.py`:
- Around line 30-198: The mutating endpoints lack success-path audit logs; add
logging.info calls on successful operations to record tenant and resource
identifiers for auditing. For add_provider and delete_provider, insert
logging.info(...) in the success branch including tenant_id and provider_name;
for create_provider_instance and drop_provider_instances log tenant_id,
provider_name and instance identifiers on success; for enable_or_disable_model
log tenant_id, provider_name, model_id and the new state. Use structured
messages and format placeholders (e.g., "Provider deleted: tenant_id=%s
provider_name=%s") and keep logs adjacent to the existing return get_result(...)
in each success path.
- Line 697: The local import "from quart import Response" inside the request
handler should be hoisted to the module-level imports alongside the existing
"from quart import request"; move the Response import to the top of the file,
update the module import block to include Response, and remove the in-function
import at its current location so the handler uses the module-level Response
symbol (no runtime change to behavior, just avoid repeated imports and clarify
dependencies).
- Line 30: The route decorator uses an implicitly injected symbol "manager"
(seen on the `@manager.route`(...) line) which is confusing to new contributors;
either add a short explanatory comment at the top of provider_api.py stating
that "manager" is supplied by the parent module loader and where to find that
loader, or—if allowed by the framework—replace the implicit usage by explicitly
importing or referencing the manager object so the origin is clear; update any
module docstring or top-of-file comment to mention "manager" and its source (or
add the explicit import) so future readers can locate its definition.
In `@api/db/services/tenant_model_instance_service.py`:
- Around line 25-26: get_all_by_provider_id runs WHERE cls.model.provider_id ==
provider_id on TenantModelInstance but provider_id is defined index=False; add
an index to avoid full-table scans by changing the TenantModelInstance model
field provider_id to index=True and generate a DB migration that creates the
corresponding index (or ALTER TABLE/CREATE INDEX) for the existing table; update
any model imports referencing provider_id if needed and run migrations/CI to
validate the schema change and tests.
- Around line 30-42: The TenantModelInstance lookups
(get_by_provider_id_and_instance_name and
delete_by_provider_id_and_instance_name) will full-scan because provider_id and
instance_name are not indexed and there is no uniqueness enforced; update the
TenantModelInstance model (class TenantModelInstance in api/db/db_models.py)
Meta.indexes to add a composite index and unique constraint on (provider_id,
instance_name) mirroring the existing composite index pattern (e.g., add a tuple
specifying fields ['provider_id', 'instance_name'] with unique=True), and ensure
both provider_id and instance_name are not declared index=False so the DB
enforces fast lookups and uniqueness for those methods.
In `@common/constants.py`:
- Around line 69-72: Two enums with overlapping semantics (ActiveStatusEnum and
ActiveEnum) can cause silent mismatches; update to make intent explicit by
renaming one enum (e.g., ActiveStatusEnum -> TenantModelStatusEnum or ActiveEnum
-> DBFlagActiveEnum) or add clear docstrings on ActiveStatusEnum and ActiveEnum
describing exactly which table/column/serialization each applies to, then update
all imports/usages to the new name or ensure callers use the correct enum;
verify any exported names are adjusted to avoid ambiguity (references:
ActiveStatusEnum, ActiveEnum).
🪄 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: 7b84d066-08b1-417f-987f-1f5129e0b802
📒 Files selected for processing (15)
api/apps/restful_apis/models_api.pyapi/apps/restful_apis/provider_api.pyapi/apps/services/models_api_service.pyapi/apps/services/provider_api_service.pyapi/db/db_models.pyapi/db/services/tenant_model_group_mapping_service.pyapi/db/services/tenant_model_group_service.pyapi/db/services/tenant_model_instance_service.pyapi/db/services/tenant_model_provider_service.pyapi/db/services/tenant_model_service.pyapi/db/services/user_service.pycommon/constants.pydocker/entrypoint.shinternal/service/model_service.gotools/scripts/mysql_migration.py
| async def generate(): | ||
| async for chunk in llm.async_chat_streamly( | ||
| None, | ||
| [{"role": "user", "content": message}], | ||
| {"temperature": 0.9}, | ||
| ): | ||
| if chunk and isinstance(chunk, str) and chunk.find("**ERROR**") < 0: | ||
| yield f"data: [MESSAGE]{chunk}\n\n" | ||
| yield "data: [DONE]\n\n" | ||
|
|
||
| return Response(generate(), mimetype="text/event-stream", headers={ | ||
| "Cache-Control": "no-cache", | ||
| "Connection": "keep-alive", | ||
| }) |
There was a problem hiding this comment.
Silent error suppression in streaming chat response.
The streaming generator at line 706 filters out any chunk containing "**ERROR**":
if chunk and isinstance(chunk, str) and chunk.find("**ERROR**") < 0:
yield f"data: [MESSAGE]{chunk}\n\n"
Errors from the underlying LLM are dropped silently — the client receives a normal [DONE] and has no way to know the request actually failed mid-stream. Additionally, exceptions raised inside generate() will abruptly close the SSE stream without an error event reaching the client.
Forward a structured error event to the client and log the error so the failure is observable:
🛡️ Proposed fix
async def generate():
- async for chunk in llm.async_chat_streamly(
- None,
- [{"role": "user", "content": message}],
- {"temperature": 0.9},
- ):
- if chunk and isinstance(chunk, str) and chunk.find("**ERROR**") < 0:
- yield f"data: [MESSAGE]{chunk}\n\n"
- yield "data: [DONE]\n\n"
+ try:
+ async for chunk in llm.async_chat_streamly(
+ None,
+ [{"role": "user", "content": message}],
+ {"temperature": 0.9},
+ ):
+ if not chunk or not isinstance(chunk, str):
+ continue
+ if chunk.find("**ERROR**") >= 0:
+ logging.error("LLM stream error: %s", chunk)
+ yield f"data: [ERROR]{chunk}\n\n"
+ return
+ yield f"data: [MESSAGE]{chunk}\n\n"
+ except Exception as ex:
+ logging.exception(ex)
+ yield f"data: [ERROR]{ex}\n\n"
+ finally:
+ yield "data: [DONE]\n\n"🤖 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 700 - 713, The generator
generate() currently swallows LLM errors by filtering chunks with "**ERROR**"
and lets exceptions close the SSE stream silently; update generate() to (1) stop
filtering out error-marked chunks and instead detect when a chunk contains
"**ERROR**" and yield a structured SSE error event (e.g., "data:
[ERROR]{...}\n\n") so clients can handle failures, (2) wrap the async for loop
in try/except to catch exceptions from llm.async_chat_streamly, log the
exception (use the existing logger) and yield a final SSE error event before
returning, and (3) ensure the final "data: [DONE]" is only sent on successful
completion so Response(generate(), mimetype="text/event-stream", ...) reflects
real success/failure.
| def set_tenant_default_models(tenant_id: str, model_provider: str, model_instance: str, model_name: str, model_type: str): | ||
| """ | ||
| Set or clear a tenant default model. | ||
|
|
||
| If model_provider, model_instance, and model_name are all provided, | ||
| validates the model and sets it as the default. | ||
| If all three are empty, clears the default for the given model type. | ||
|
|
||
| :param tenant_id: tenant ID | ||
| :param model_provider: provider name | ||
| :param model_instance: instance name | ||
| :param model_name: model name | ||
| :param model_type: model type (chat, embedding, rerank, asr, vision, tts, ocr) | ||
| :return: (success, result_or_error_message) | ||
| """ | ||
| field_name = MODEL_TYPE_TO_FIELD.get(model_type) | ||
| if not field_name: | ||
| return False, f"model type '{model_type}' is invalid" | ||
|
|
||
| e, tenant = TenantService.get_by_id(tenant_id) | ||
| if not e: | ||
| return False, "Tenant not found" | ||
|
|
||
| if not model_provider and not model_instance and not model_name: | ||
| # Clear the default model | ||
| default_model = "" | ||
| elif model_provider and model_instance and model_name: | ||
| # Validate and set the default model | ||
| success, msg = _check_model_available(tenant_id, model_provider, model_instance, model_name, model_type) | ||
| if not success: | ||
| return False, msg | ||
| default_model = f"{model_name}@{model_instance}@{model_provider}" | ||
| else: | ||
| return False, "model_provider, model_instance and model_name must be specified together" | ||
|
|
||
| TenantService.update_by_id(tenant_id, {field_name: default_model}) | ||
| return True, "success" |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Add an INFO log on default-model change (per coding guidelines).
set_tenant_default_models mutates a tenant-scoped default with no log entry. This is exactly the kind of cross-tenant configuration change that ops/audit usually wants traceable. Recommend logging tenant_id, model_type, and the new composite value (or "cleared") on success.
As per coding guidelines: "Add logging for new flows".
📝 Suggested addition
TenantService.update_by_id(tenant_id, {field_name: default_model})
+ logging.info(
+ "Tenant default model updated: tenant=%s type=%s value=%r",
+ tenant_id, model_type, default_model or "<cleared>",
+ )
return True, "success"🤖 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/models_api_service.py` around lines 182 - 218, The function
set_tenant_default_models mutates tenant defaults without any audit log; add an
INFO log after a successful update (before returning True) that records
tenant_id, model_type, and the new value (use the composite string like
f"{model_name}@{model_instance}@{model_provider}" or the literal "cleared" when
default_model == ""), using the module logger (logger.info(...)); place the log
right after TenantService.update_by_id(...) in set_tenant_default_models so
every successful change is traceable.
| def add_provider(tenant_id: str, provider_name: str): | ||
| """ | ||
| Add a provider (factory) for a tenant by creating TenantLLM entries | ||
|
|
||
| :param tenant_id: tenant ID | ||
| :param provider_name: provider/factory name | ||
| :return: (success, result_or_error_message) | ||
| """ | ||
| if not FACTORY_LLM_INFOS: | ||
| return False, "No providers found" | ||
| # Check if factory is allowed | ||
| allowed_factories = [f["name"] for f in FACTORY_LLM_INFOS] | ||
| if provider_name not in allowed_factories: | ||
| return False, f"Provider '{provider_name}' is not allowed" | ||
|
|
||
| existing = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name) | ||
| if existing: | ||
| return False, f"Provider {provider_name} already exists" | ||
|
|
||
| TenantModelProviderService.insert( | ||
| tenant_id=tenant_id, | ||
| provider_name=provider_name | ||
| ) | ||
| return True, "success" | ||
|
|
||
|
|
||
| def delete_provider(tenant_id: str, provider_name: str): | ||
| """ | ||
| Delete all TenantLLM entries for a provider. | ||
|
|
||
| :param tenant_id: tenant ID | ||
| :param provider_name: provider/factory name | ||
| :return: (success, result_or_error_message) | ||
| """ | ||
| TenantModelProviderService.delete_by_tenant_id_and_provider_name(tenant_id, provider_name) | ||
| return True, "success" |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Missing logging across new mutating flows (per coding guidelines).
add_provider, delete_provider, create_provider_instance (above), drop_provider_instances, and update_model_status perform tenant-scoped mutations with no log line on success or failure. Recommend at least an INFO log on the successful path and a WARNING/EXCEPTION log on validation failures so operators can audit provider/instance churn per tenant.
As per coding guidelines: "Add logging for new flows".
🤖 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 84 - 119, The
functions add_provider and delete_provider (and similarly
create_provider_instance, drop_provider_instances, update_model_status) perform
tenant-scoped mutations but lack logging; add structured logs using the module
logger (or existing logger instance): emit an INFO log on successful operations
including tenant_id, provider_name (and any created instance id or model
status), and emit a WARNING or ERROR/EXCEPTION log on validation failures or
exceptions (e.g., when FACTORY_LLM_INFOS is empty, provider_name not allowed, or
provider already exists) referencing TenantModelProviderService calls so
operators can audit provider/instance churn per tenant and capture the failure
reason.
| values.append(f"('{record_id}', '{llm_factory}', '{tenant_id}', " | ||
| f"{current_ts}, FROM_UNIXTIME({current_ts}), " | ||
| f"{current_ts}, FROM_UNIXTIME({current_ts}))") | ||
| f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}), " | ||
| f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}))") |
There was a problem hiding this comment.
Unescaped string interpolation for llm_factory and tenant_id.
In TenantModelProviderStage.execute, llm_factory and tenant_id are interpolated directly into the SQL via f-string without replace("'", "''") escaping (contrast with TenantModelInstanceStage lines 493-494 which do escape). If any source llm_factory contains an apostrophe, the migration will fail or behave unexpectedly. Apply the same escaping pattern as the other stages, or — preferably — use parameterized inserts via db.execute_sql(sql, params) everywhere in this script.
🛡️ Proposed fix
for tenant_id, llm_factory in batch:
record_id = self.generate_uuid()
- values.append(f"('{record_id}', '{llm_factory}', '{tenant_id}', "
+ llm_factory_escaped = llm_factory.replace("'", "''") if llm_factory else ""
+ tenant_id_escaped = tenant_id.replace("'", "''") if tenant_id else ""
+ values.append(f"('{record_id}', '{llm_factory_escaped}', '{tenant_id_escaped}', "
f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}), "
f"{current_ts * 1000}, FROM_UNIXTIME({current_ts}))")🤖 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 `@tools/scripts/mysql_migration.py` around lines 333 - 335, The INSERT
construction in TenantModelProviderStage.execute currently interpolates
llm_factory and tenant_id directly into the SQL string causing SQL errors when
values contain apostrophes; update the code to either use parameterized
execution via db.execute_sql(sql, params) for this insert or at minimum escape
single quotes the same way TenantModelInstanceStage does (use .replace("'",
"''") on llm_factory and tenant_id) before appending to values, ensuring you
reference the same record_id/current_ts logic already present in this method.
| provider_id VARCHAR(32) NOT NULL, | ||
| api_key VARCHAR(512) NOT NULL, | ||
| status VARCHAR(32) DEFAULT 'active', | ||
| extra VARCHAR(512) DEFAULT '{}', |
There was a problem hiding this comment.
Confirm new extra column is added to existing tables on migration.
extra VARCHAR(512) DEFAULT '{}' (and the matching VARCHAR(1024) at line 708) appears only inside CREATE TABLE IF NOT EXISTS. For environments where these tables already exist from a prior run, the IF NOT EXISTS makes the CREATE a no-op and the new extra column will not be added. Code that reads/writes extra will then fail with "unknown column".
Please ensure either an ALTER TABLE ... ADD COLUMN extra ... step is performed for upgrades, or document that this migration script is only for fresh installs.
🤖 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 `@tools/scripts/mysql_migration.py` at line 521, The migration only adds "extra
VARCHAR(512) DEFAULT '{}'" (and the matching "extra VARCHAR(1024) ..." entry)
inside CREATE TABLE IF NOT EXISTS blocks, so existing tables won't receive the
new extra column; update the migration to detect and alter existing tables by
adding an ALTER TABLE ... ADD COLUMN extra ... (or a conditional
column-existence check then ALTER) for each affected table after or before the
CREATE TABLE IF NOT EXISTS step, ensuring the "extra" column name and types
match the CREATE definitions and guarding against duplicate-add errors.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (6)
api/apps/services/provider_api_service.py (6)
154-162:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winSchema mismatch:
llm["name"]isKeyErroragainstFACTORY_LLM_INFOS.Already raised on the previous revision —
FACTORY_LLM_INFOS(sourced fromconf/llm_factories.json) uses"llm_name", not"name". Line 157 still readsllm["name"]and will raise at runtime.🤖 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 154 - 162, The loop building models uses the wrong key name for factory entries: FACTORY_LLM_INFOS (and the llms items) use "llm_name" not "name", so change references in the models construction inside the function that iterates over llms to read llm["llm_name"] (leave llm["max_tokens"] and llm["model_type"] as-is) and return the corrected dict keys; update the models.append block that currently references llm["name"] to use llm["llm_name"] so no KeyError is raised at runtime.
173-192:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winSame
llm["name"]schema mismatch inshow_provider_model.Lines 179 and 185 still use
llm["name"]/llm_info["name"]; should be"llm_name". Already flagged on the prior revision.🤖 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 173 - 192, In show_provider_model, the code incorrectly accesses llm["name"] and llm_info["name"]; change these to llm["llm_name"] and llm_info["llm_name"] respectively so the returned payload uses the correct schema key, and ensure any other uses in that function (e.g., the target_llm filter and the returned "name" field) are updated to reference "llm_name" instead of "name".
322-381:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winSame
llm["name"]schema mismatch inlist_instance_models.Lines 347, 368, and 375 still use
llm["name"]to look up the model identifier — should bellm["llm_name"]. Same root cause as already flagged.🤖 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 322 - 381, In list_instance_models, replace all uses of llm["name"] with llm["llm_name"] (the llm identifier key) so lookups and returned model names match the tenant_model model_name; specifically update the supported_only branch where models = [{"name": llm["name"]}] and the loop where you read record_status = model_status_map.get(llm["name"]) and set "name": llm["name"] to use llm["llm_name"] instead, leaving model_type and max_tokens as-is so model_status_map (TenantModelService) keys align with the llm entries.
209-231:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
create_provider_instancestill missing api_key/instance_name validation and integrity-error handling.Already raised on the previous revision: empty
api_keywill be persisted, blank/emptyinstance_nameis not validated, and the unique index on(api_key, provider_id)(and any(provider_id, instance_name)constraint) will surfaceIntegrityErroras a 500. None of these are addressed in the current code.🤖 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 209 - 231, The create_provider_instance flow currently allows blank api_key and instance_name and does not handle DB uniqueness IntegrityError; update the validation and error handling in provider_api_service.py: ensure provider_name, instance_name and api_key are trimmed and non-empty (reject whitespace-only instance_name and api_key), keep the existing check that instance_name != "default", and before or when calling TenantModelInstanceService.insert (referenced by TenantModelInstanceService.insert and provider lookup via TenantModelProviderService.get_by_tenant_id_and_provider_name) either perform an existence check for (provider_id, instance_name) and (provider_id, api_key) or wrap the insert in a try/except catching IntegrityError and return a user-friendly (False, "... already exists" or validation) message instead of raising a 500; preserve use of FACTORY_LLM_INFOS and get_uuid.
97-104:⚠️ Potential issue | 🟠 Major | ⚡ Quick winTOCTOU race when inserting a new provider.
The check at line 97-99 followed by an unguarded
insertat line 101 lets two concurrent requests for the same tenant/provider both pass the existence check and then attempt to insert. If the underlying table has a uniqueness constraint, the second call surfaces an uncaughtIntegrityErroras a 500; otherwise duplicate rows are persisted. Wrap the insert in atry/exceptfor the DB integrity exception (and add anINFO/EXCEPTIONlog per the missing-logging note already raised for this function).🛡️ Suggested fix
- existing = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name) - if existing: - return False, f"Provider {provider_name} already exists" - - TenantModelProviderService.insert( - tenant_id=tenant_id, - provider_name=provider_name - ) - return True, "success" + existing = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name) + if existing: + return False, f"Provider {provider_name} already exists" + + try: + TenantModelProviderService.insert( + tenant_id=tenant_id, + provider_name=provider_name, + ) + except Exception as e: + logging.exception("add_provider failed") + return False, f"Failed to add provider: {e}" + + logging.info("Added provider: tenant=%s provider=%s", tenant_id, provider_name) + return True, "success"As per coding guidelines: "Add logging for new flows".
🤖 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 97 - 104, The current existence check (TenantModelProviderService.get_by_tenant_id_and_provider_name) followed by an unguarded TenantModelProviderService.insert is vulnerable to TOCTOU races; wrap the insert in a try/except that catches the DB integrity exception (e.g., IntegrityError from your DB layer) and handle duplicate-key errors by logging an INFO/EXCEPTION and returning (False, f"Provider {provider_name} already exists") instead of letting the exception bubble; ensure you log both the attempted insert (INFO) and the caught IntegrityError with context (EXCEPTION) referencing tenant_id and provider_name and leave other unexpected DB errors to propagate or re-raise after logging.
414-443:⚠️ Potential issue | 🟠 Major | ⚡ Quick winTOCTOU +
llm["name"]mismatch inupdate_model_status.
- Line 432 still uses
llm["name"]; same schema mismatch as already flagged.- The check at lines 414-418 followed by
insert/update_by_idis racy: two concurrent disable requests for the same(provider, instance, model)will both miss the existing record and both attemptinsert, producing either duplicates or an uncaughtIntegrityError. Wrap the insert intry/exceptfor the DB integrity exception (and prefer an upsert if the service layer offers one).🤖 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 414 - 443, In update_model_status, fix the schema mismatch and TOCTOU race: replace the incorrect llm["name"] lookup with the correct key used in FACTORY_LLM_INFOS entries (use the same field name used elsewhere in your codebase) when locating target_llm, and wrap the TenantModelService.insert call in a try/except that catches the DB integrity exception (e.g., IntegrityError) to handle concurrent inserts by either performing TenantModelService.update_by_id(model_id, {"status": status}) on conflict or returning success; if TenantModelService supports an upsert/merge API prefer using that instead of plain insert to atomically create-or-update the status.
🤖 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/services/provider_api_service.py`:
- Around line 108-117: The delete_provider implementation must check the result
of TenantModelProviderService.delete_by_tenant_id_and_provider_name and fail if
no rows were deleted (mirror show_provider behavior: return False, "Provider not
found"); before removing the provider row, explicitly delete dependent records
in TenantModelInstanceService, TenantModelService and
TenantModelGroupMappingService (or call appropriate methods on those services)
to avoid orphaned rows, and perform all deletions inside a transaction so either
all dependent rows and the provider are removed or none are; update
delete_provider to return (True, "success") only after dependent deletions and
the provider deletion succeed, and (False, "Provider not found") when the
initial provider delete indicates no matching provider.
- Around line 460-498: The chat_to_model flow currently does two DB lookups,
returns internal LLMBundle/model_config to the REST layer for streaming, lacks a
success audit log, and imports LLMBundle inline; fix by (1) collapsing DB calls
into a single service call (e.g., add/use a
TenantLLMService.get_model_with_status or similar that returns both model_config
and the TenantLLM object) and update chat_to_model to use that single call
instead of TenantLLMService.get_model_config followed by
TenantLLMService.get_or_none, (2) add an INFO log on successful non-stream and
stream starts including tenant_id, provider_name, model_name, and stream flag,
(3) change the streaming contract so the service exposes an async
generator/stream iterator (e.g., a new method on LLMBundle or TenantLLMService
like async_stream_chat) and have chat_to_model return that iterator rather than
LLMBundle and model_config, and (4) move the "from api.db.services.llm_service
import LLMBundle" import to the module-level imports.
---
Duplicate comments:
In `@api/apps/services/provider_api_service.py`:
- Around line 154-162: The loop building models uses the wrong key name for
factory entries: FACTORY_LLM_INFOS (and the llms items) use "llm_name" not
"name", so change references in the models construction inside the function that
iterates over llms to read llm["llm_name"] (leave llm["max_tokens"] and
llm["model_type"] as-is) and return the corrected dict keys; update the
models.append block that currently references llm["name"] to use llm["llm_name"]
so no KeyError is raised at runtime.
- Around line 173-192: In show_provider_model, the code incorrectly accesses
llm["name"] and llm_info["name"]; change these to llm["llm_name"] and
llm_info["llm_name"] respectively so the returned payload uses the correct
schema key, and ensure any other uses in that function (e.g., the target_llm
filter and the returned "name" field) are updated to reference "llm_name"
instead of "name".
- Around line 322-381: In list_instance_models, replace all uses of llm["name"]
with llm["llm_name"] (the llm identifier key) so lookups and returned model
names match the tenant_model model_name; specifically update the supported_only
branch where models = [{"name": llm["name"]}] and the loop where you read
record_status = model_status_map.get(llm["name"]) and set "name": llm["name"] to
use llm["llm_name"] instead, leaving model_type and max_tokens as-is so
model_status_map (TenantModelService) keys align with the llm entries.
- Around line 209-231: The create_provider_instance flow currently allows blank
api_key and instance_name and does not handle DB uniqueness IntegrityError;
update the validation and error handling in provider_api_service.py: ensure
provider_name, instance_name and api_key are trimmed and non-empty (reject
whitespace-only instance_name and api_key), keep the existing check that
instance_name != "default", and before or when calling
TenantModelInstanceService.insert (referenced by
TenantModelInstanceService.insert and provider lookup via
TenantModelProviderService.get_by_tenant_id_and_provider_name) either perform an
existence check for (provider_id, instance_name) and (provider_id, api_key) or
wrap the insert in a try/except catching IntegrityError and return a
user-friendly (False, "... already exists" or validation) message instead of
raising a 500; preserve use of FACTORY_LLM_INFOS and get_uuid.
- Around line 97-104: The current existence check
(TenantModelProviderService.get_by_tenant_id_and_provider_name) followed by an
unguarded TenantModelProviderService.insert is vulnerable to TOCTOU races; wrap
the insert in a try/except that catches the DB integrity exception (e.g.,
IntegrityError from your DB layer) and handle duplicate-key errors by logging an
INFO/EXCEPTION and returning (False, f"Provider {provider_name} already exists")
instead of letting the exception bubble; ensure you log both the attempted
insert (INFO) and the caught IntegrityError with context (EXCEPTION) referencing
tenant_id and provider_name and leave other unexpected DB errors to propagate or
re-raise after logging.
- Around line 414-443: In update_model_status, fix the schema mismatch and
TOCTOU race: replace the incorrect llm["name"] lookup with the correct key used
in FACTORY_LLM_INFOS entries (use the same field name used elsewhere in your
codebase) when locating target_llm, and wrap the TenantModelService.insert call
in a try/except that catches the DB integrity exception (e.g., IntegrityError)
to handle concurrent inserts by either performing
TenantModelService.update_by_id(model_id, {"status": status}) on conflict or
returning success; if TenantModelService supports an upsert/merge API prefer
using that instead of plain insert to atomically create-or-update the status.
🪄 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: 43e1a595-531c-445b-915a-e307e38c59f2
📒 Files selected for processing (1)
api/apps/services/provider_api_service.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14595 +/- ##
=======================================
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 Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
api/db/services/__init__.py (1)
76-77: ⚡ Quick winNo logging on new error and retry-exhaustion paths.
The
KeyError(line 77) andRuntimeError(line 100) are raised silently. Callers relying on these paths will have no trace in application logs.📋 Proposed fix
import re +import logging from pathlib import PurePath +logger = logging.getLogger(__name__) ... if name_field not in kwargs: + logger.error("duplicate_name called without required field '%s' in kwargs", name_field) raise KeyError(f"Arguments must contain '{name_field}' key") ... + logger.warning( + "duplicate_name exhausted %d retries for original name '%s' (field='%s')", + MAX_RETRIES, original_name, name_field, + ) raise RuntimeError(f"Failed to generate unique name within {MAX_RETRIES} attempts. Original: {original_name}")As per coding guidelines, new flows must include logging.
Also applies to: 100-100
🤖 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/__init__.py` around lines 76 - 77, The code raises KeyError (when name_field not in kwargs) and RuntimeError (when retry exhaustion occurs) without logging; add logging calls before each raise: obtain a module logger (e.g. logger = logging.getLogger(__name__) if none exists), then call logger.error with a clear, contextual message including name_field and kwargs for the KeyError path and include retry attempt/count and any error details for the RuntimeError path, then raise the same KeyError / RuntimeError so behavior is unchanged but the failure is recorded.
🤖 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/db/services/__init__.py`:
- Around line 57-58: The docstring still refers to a hard-coded "'name' key"
even though the function now accepts a name_field parameter; update the
docstring in api/db/services/__init__.py to state that kwargs must contain a key
matching the name_field parameter (or explicitly mention name_field defaults to
'name'), replacing both occurrences that mention the "'name' key" so the
documentation reflects the new name_field behavior and uses the actual parameter
name_field to describe which key will be read from kwargs.
- Line 45: The function signature for duplicate_name uses an annotated default
without surrounding whitespace ("name_field: str="name""), which violates ruff
E252; update the signature in the duplicate_name definition to add spaces around
the '=' in the annotation (change name_field: str="name" to name_field: str =
"name") so the function signature conforms to PEP 8 and ruff linting.
---
Nitpick comments:
In `@api/db/services/__init__.py`:
- Around line 76-77: The code raises KeyError (when name_field not in kwargs)
and RuntimeError (when retry exhaustion occurs) without logging; add logging
calls before each raise: obtain a module logger (e.g. logger =
logging.getLogger(__name__) if none exists), then call logger.error with a
clear, contextual message including name_field and kwargs for the KeyError path
and include retry attempt/count and any error details for the RuntimeError path,
then raise the same KeyError / RuntimeError so behavior is unchanged but the
failure is recorded.
🪄 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: 41d147c7-c530-4890-a8d9-2f2f8b20183a
📒 Files selected for processing (3)
api/apps/services/provider_api_service.pyapi/db/services/__init__.pyapi/db/services/tenant_model_instance_service.py
🚧 Files skipped from review as they are similar to previous changes (2)
- api/db/services/tenant_model_instance_service.py
- api/apps/services/provider_api_service.py
|
|
||
|
|
||
| def duplicate_name(query_func, **kwargs) -> str: | ||
| def duplicate_name(query_func, name_field: str="name", **kwargs) -> str: |
There was a problem hiding this comment.
Ruff E252: missing whitespace around annotated default.
name_field: str="name" should be name_field: str = "name" per PEP 8 and ruff's E252 rule.
🔧 Proposed fix
-def duplicate_name(query_func, name_field: str="name", **kwargs) -> str:
+def duplicate_name(query_func, name_field: str = "name", **kwargs) -> str:As per coding guidelines, Python code must pass ruff linting.
📝 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.
| def duplicate_name(query_func, name_field: str="name", **kwargs) -> str: | |
| def duplicate_name(query_func, name_field: str = "name", **kwargs) -> str: |
🤖 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/__init__.py` at line 45, The function signature for
duplicate_name uses an annotated default without surrounding whitespace
("name_field: str="name""), which violates ruff E252; update the signature in
the duplicate_name definition to add spaces around the '=' in the annotation
(change name_field: str="name" to name_field: str = "name") so the function
signature conforms to PEP 8 and ruff linting.
| name_field: the field name of name in db. default to 'name' | ||
| **kwargs: Must contain 'name' key with original filename to check |
There was a problem hiding this comment.
Stale docstring still references the hard-coded "name" key.
Lines 58 and 66 still say 'name' key rather than reflecting the new name_field parameter.
📝 Proposed fix
- **kwargs: Must contain 'name' key with original filename to check
+ **kwargs: Must contain the key specified by `name_field` with the original name to check
...
Raises:
- KeyError: If 'name' key not provided in kwargs
+ KeyError: If the key specified by `name_field` is not present in kwargsAlso applies to: 66-66
🤖 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/__init__.py` around lines 57 - 58, The docstring still refers
to a hard-coded "'name' key" even though the function now accepts a name_field
parameter; update the docstring in api/db/services/__init__.py to state that
kwargs must contain a key matching the name_field parameter (or explicitly
mention name_field defaults to 'name'), replacing both occurrences that mention
the "'name' key" so the documentation reflects the new name_field behavior and
uses the actual parameter name_field to describe which key will be read from
kwargs.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
api/apps/restful_apis/provider_api.py (1)
686-715:⚠️ Potential issue | 🟠 Major | ⚡ Quick winStreaming chat path:
thinkingignored,temperaturehardcoded, and LLM errors silently dropped.These were already raised on the prior revision and are still present in the current code:
thinking(line 688) is read but never passed tollm.async_chat_streamly;temperatureis hardcoded to0.9(line 706) with no override path.- The generator at lines 702-710 filters chunks containing
**ERROR**and never surfaces them to the client; exceptions insidegenerate()will close the SSE stream without any error event.Please consolidate the fix here — forward
thinking(and an optional request-suppliedtemperature) into the streaming options, emit a structured[ERROR]SSE event when an error chunk or exception occurs, and only emit[DONE]on clean completion. See the proposed diff in the prior comment thread for a concrete shape.🤖 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 686 - 715, The streaming branch ignores the incoming thinking flag and hardcodes temperature while silently dropping errors; fix provider_api_service.chat_to_model handling by passing the request's thinking and an optional temperature (read from data.get("temperature")) into llm.async_chat_streamly instead of the fixed 0.9, update the async generator function generate to detect error chunks and yield a structured SSE error event (e.g. "data: [ERROR]...\\n\\n") when chunk contains error markers, and wrap the async iteration in try/except to yield a single error SSE on exception and re-raise/close so that "data: [DONE]\\n\\n" is only emitted on successful completion; references: provider_api_service.chat_to_model, llm.async_chat_streamly, generate, stream, thinking, temperature, Response.
🧹 Nitpick comments (2)
api/apps/restful_apis/provider_api.py (2)
71-71: 💤 Low valueUse
POST(notPUT) for creating a tenant-scoped provider.
PUT /providersis unusual for a create-collection action —PUTis typically used to upsert a known resource at a specific URI (e.g.,PUT /providers/<provider_name>). Since this endpoint creates a new tenant-scoped provider keyed byprovider_namein the body,POST /providers(orPUT /providers/<provider_name>with the name in the path) would be more idiomatic and consistent withPOST /providers/<provider_name>/instances(line 286) elsewhere in this module.🤖 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` at line 71, The route decorator for the provider creation endpoint is using PUT but should use POST; update the manager.route decorator for the tenant-scoped provider creation (the line with manager.route("/providers", methods=["PUT"])) to use methods=["POST"] instead, and ensure any related tests or documentation referencing this endpoint are updated to POST to /providers to match the existing pattern (e.g., POST /providers/<provider_name>/instances).
697-715: 💤 Low valueHoist
from quart import Responseto module top-level.The local import inside the streaming branch runs on every streaming request and obscures the module's dependencies. Moving it next to the existing
from quart import requestat line 18 is cleaner and lets static tooling see the dependency.♻️ Proposed change
-from quart import request +from quart import Response, request- if stream and isinstance(result, dict) and result.get("type") == "stream": - # Streaming response using SSE - from quart import Response - llm = result["llm"] + if stream and isinstance(result, dict) and result.get("type") == "stream": + # Streaming response using SSE + llm = result["llm"]🤖 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 697 - 715, Move the local import "from quart import Response" out of the streaming branch and hoist it to the module top-level alongside the existing "from quart import request" import; update the imports at the top of the file so Response is imported once, leaving the streaming code (the block that returns Response(generate(), mimetype="text/event-stream", ...), the async generator function generate, and use of llm.async_chat_streamly) unchanged other than removing the in-function import.
🤖 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 60-68: Add info-level logging for new flows by creating a small
helper/decorator (e.g., log_operation or log_request) that emits an info log
with the operation name, tenant_id and any relevant key identifiers
(provider_name, instance_name, model_name) before calling the handler; then
apply it to each route handler in provider_api.py (including the list_providers
call path that invokes provider_api_service.list_providers) so that successful
paths and entry into create/delete/drop/enable-disable/chat handlers are logged,
while leaving existing logging.exception(e) for error stacks intact.
- Around line 689-693: The route handler captures instance_name but does not
forward it to the service; update the call to provider_api_service.chat_to_model
to include the instance_name argument and then modify
provider_api_service.chat_to_model signature to accept instance_name and perform
the instance resolution using
TenantModelInstanceService.get_by_provider_id_and_instance_name(provider_id,
instance_name) (same pattern used in
create_provider_instance/show_provider_instance/list_instance_models/update_model_status)
so the resolved instance credentials/config are used for model lookup and the
chat operation.
---
Duplicate comments:
In `@api/apps/restful_apis/provider_api.py`:
- Around line 686-715: The streaming branch ignores the incoming thinking flag
and hardcodes temperature while silently dropping errors; fix
provider_api_service.chat_to_model handling by passing the request's thinking
and an optional temperature (read from data.get("temperature")) into
llm.async_chat_streamly instead of the fixed 0.9, update the async generator
function generate to detect error chunks and yield a structured SSE error event
(e.g. "data: [ERROR]...\\n\\n") when chunk contains error markers, and wrap the
async iteration in try/except to yield a single error SSE on exception and
re-raise/close so that "data: [DONE]\\n\\n" is only emitted on successful
completion; references: provider_api_service.chat_to_model,
llm.async_chat_streamly, generate, stream, thinking, temperature, Response.
---
Nitpick comments:
In `@api/apps/restful_apis/provider_api.py`:
- Line 71: The route decorator for the provider creation endpoint is using PUT
but should use POST; update the manager.route decorator for the tenant-scoped
provider creation (the line with manager.route("/providers", methods=["PUT"]))
to use methods=["POST"] instead, and ensure any related tests or documentation
referencing this endpoint are updated to POST to /providers to match the
existing pattern (e.g., POST /providers/<provider_name>/instances).
- Around line 697-715: Move the local import "from quart import Response" out of
the streaming branch and hoist it to the module top-level alongside the existing
"from quart import request" import; update the imports at the top of the file so
Response is imported once, leaving the streaming code (the block that returns
Response(generate(), mimetype="text/event-stream", ...), the async generator
function generate, and use of llm.async_chat_streamly) unchanged other than
removing the in-function import.
🪄 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: 0e229108-df5f-4aa8-86f0-d5abec9e5b1b
📒 Files selected for processing (2)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.py
🚧 Files skipped from review as they are similar to previous changes (1)
- api/apps/services/provider_api_service.py
| try: | ||
| success, result = provider_api_service.list_providers(tenant_id, available_only) | ||
| if success: | ||
| return get_result(data=result) | ||
| else: | ||
| return get_error_data_result(message=result) | ||
| except Exception as e: | ||
| logging.exception(e) | ||
| return get_error_data_result(message="Internal server error") |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Add info-level logging for these new flows (per coding guidelines).
Across all 11 handlers in this module, logging is limited to logging.exception(e) on the failure path. Per the project's coding guidelines, new flows should have logging — at minimum an info-level entry recording the operation, tenant_id, and the key path/body identifiers (provider_name, instance_name, model_name) for create/delete/drop/enable-disable/chat. This is also valuable for auditing tenant-scoped credential and model lifecycle changes.
A small helper or a single decorator on the route handlers can centralize this without polluting each function.
As per coding guidelines: "Add logging for new flows".
🤖 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 60 - 68, Add info-level
logging for new flows by creating a small helper/decorator (e.g., log_operation
or log_request) that emits an info log with the operation name, tenant_id and
any relevant key identifiers (provider_name, instance_name, model_name) before
calling the handler; then apply it to each route handler in provider_api.py
(including the list_providers call path that invokes
provider_api_service.list_providers) so that successful paths and entry into
create/delete/drop/enable-disable/chat handlers are logged, while leaving
existing logging.exception(e) for error stacks intact.
Sync API layer toward upstream v0.26 (architecture is shared: fork's restful_apis+services was an early snapshot of upstream's REST migration). Added (exact v0.26 copies, deps verified present in fork): _generation_params, agent_api, bot_api, chunk_api, connector_api, dify_retrieval_api, file2document_api, langfuse_api, mcp_api, openai_api, plugin_api, stats_api, task_api, tenant_api, user_api Deferred to batch D (need model-provider tables/services from infiniflow#14595): models_api, provider_api Deleted residual sdk/ (agents, doc, session, dify_retrieval) — migrated to restful_apis; were duplicate routes via auto-discovery. __init__.py: dropped sdk from blueprint discovery (cleaner than upstream which left the dead glob). Verified: all 15 py_compile; infra deps (connector_service, mcp_server_service, agent.plugin) import OK; _generation_params has no module-level manager ref (safe under auto-registration). Live blueprint registration deferred to batch F (needs Redis).
Combined model+executor batch, step 1 (DB foundation; coupling: v0.26 shared files reflect both infiniflow#15154 and infiniflow#14595, so done together). - db_models: 5 model-provider tables (TenantModelProvider/Instance/Model/Group/ GroupMapping) grafted after SystemSettings + Tenant.ocr_id field + migrate_db ocr_id registration (tables auto-create via init_database_tables reflection; fork's content_hash etc. customs untouched) - common/constants: added ActiveStatusEnum + OPENDATALOADER_DEFAULT_CONFIG/ ENV_KEYS (imported by the services; fork was missing them) - new services: tenant_model_provider/instance/model/group/group_mapping_service - adopted upstream joint_services/tenant_model_service.py + tools/scripts/ mysql_migration.py (fork had half-baked older versions referencing services it lacked; upstream versions are authoritative) Verified: all 6 services + joint import clean in 3.13 venv (no Redis needed; dep closure resolved); db_models + constants py_compile. Tables empty on create; zero impact on existing chunk/document data. Migration run + live verify -> batch F.
… (option-1 #9) Deploy-readiness for AWS: - command += --init-model-provider-tables (v0.26 main compose has it; fork's AWS compose lacked it — needed to backfill the 5 model-provider tables from tenant_llm on first boot, per infiniflow#14595) - TE_RUN_MODE=2 (original task executor) as safe first-deploy default; flip to 0 (refactored) after a TE_RUN_MODE=1 dry-run confirms equivalence (infiniflow#15154) Entrypoint/task_executor argparse already aligned (v0.26 base).
What problem does this PR solve?
Python implementation of the Go-based model_provider API suite.
Type of change