Repository navigation
Fix: search bot and verify model instance - #15588
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:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughProvider instance creation and API-key verification now accept optional per-instance ChangesChat endpoint tenant LLM resolution
Provider instance creation with model provisioning
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
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: 2
🧹 Nitpick comments (2)
api/apps/restful_apis/provider_api.py (1)
344-347: ⚡ Quick winValidate
model_infoat the request boundary.Both endpoints now accept an untyped object and forward it directly. That lets
{}or malformedmodel_infopayloads fail deep in the service layer instead of returning a clear 4xx here; please add a request model that validatesmodel_info.model_nameandmodel_info.model_typebefore dispatch.As per coding guidelines
api/apps/restful_apis/**/*.py:Use Pydantic request validation with service layer pattern in newer RESTful APIs under api/apps/restful_apis/.Also applies to: 412-415
🤖 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 344 - 347, Add a Pydantic request model for the incoming payload that enforces model_info is an object with required fields model_name (str) and model_type (str) and use it in the endpoint handler(s) before calling provider_api_service; specifically, replace the loose data.get("model_info", {}) usage around the call sites that invoke provider_api_service.create_provider_instance (and the similar call at the other site) with validated request data so the handler returns a 4xx for missing/invalid model_info rather than letting the service layer fail. Ensure the handler extracts validated_model.model_info and passes its values into create_provider_instance unchanged.api/apps/services/provider_api_service.py (1)
270-282: ⚡ Quick winAdd structured logs for the new verify/provision flow.
This path now has two distinct failure points—API-key verification and post-create model provisioning—but neither emits provider/instance/model context. A small log at each branch would make supportable failures much easier to trace.
As per coding guidelines
**/*.py: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 270 - 282, Add structured logging around the verify/provision flow: when calling verify_api_key(provider_name, api_key, base_url, region, model_info) log an error with provider_name and instance_name on failure before returning; after TenantModelInstanceService.create_instance(...) log an info/debug with provider_id, provider_name and instance_name and include extra_fields; when add_model_to_instance(tenant_id, provider_name, instance_name, **model_info) fails log an error containing provider_name, instance_name and model_info (or model identifier) before returning. Use the existing logger used by this module and the symbols verify_api_key, TenantModelInstanceService.create_instance and add_model_to_instance to locate where to add the logs.
🤖 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 354-359: Normalize and validate model_info before building
factory_llms: ensure model_info is a dict, coerce model_types =
model_info.get("model_type") into a list (if it's a str wrap it in [str], if
missing/None use []), filter out non-string/empty entries from that list, and
when constructing factory_llms use a safe model_name =
model_info.get("model_name") or _type (so you don't produce empty names); update
the comprehension that creates factory_llms to iterate the normalized
model_types and only include entries with a valid non-empty model_type,
referencing model_info, factory_llms and provider_name in your changes.
- Around line 274-282: The code always calls add_model_to_instance(...) after
creating the instance, which fails when model_info is empty and can leave an
orphaned instance; change TenantModelInstanceService.create_instance(...) to
capture the created instance (e.g., instance =
TenantModelInstanceService.create_instance(...)) and only call
add_model_to_instance(...) if model_info is non-empty/Truthy; additionally make
the create+provision steps atomic by wrapping them in a DB transaction or, if a
transaction context is not available, catch failures from add_model_to_instance
and delete/rollback the created instance (use the created instance identifier or
TenantModelInstanceService delete method) so a failed provisioning does not
leave an orphan record.
---
Nitpick comments:
In `@api/apps/restful_apis/provider_api.py`:
- Around line 344-347: Add a Pydantic request model for the incoming payload
that enforces model_info is an object with required fields model_name (str) and
model_type (str) and use it in the endpoint handler(s) before calling
provider_api_service; specifically, replace the loose data.get("model_info", {})
usage around the call sites that invoke
provider_api_service.create_provider_instance (and the similar call at the other
site) with validated request data so the handler returns a 4xx for
missing/invalid model_info rather than letting the service layer fail. Ensure
the handler extracts validated_model.model_info and passes its values into
create_provider_instance unchanged.
In `@api/apps/services/provider_api_service.py`:
- Around line 270-282: Add structured logging around the verify/provision flow:
when calling verify_api_key(provider_name, api_key, base_url, region,
model_info) log an error with provider_name and instance_name on failure before
returning; after TenantModelInstanceService.create_instance(...) log an
info/debug with provider_id, provider_name and instance_name and include
extra_fields; when add_model_to_instance(tenant_id, provider_name,
instance_name, **model_info) fails log an error containing provider_name,
instance_name and model_info (or model identifier) before returning. Use the
existing logger used by this module and the symbols verify_api_key,
TenantModelInstanceService.create_instance and add_model_to_instance to locate
where to add the logs.
🪄 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: a16a1855-5fd1-438c-925e-14bb99672eda
📒 Files selected for processing (3)
api/apps/restful_apis/bot_api.pyapi/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.py
| extra_fields = {} | ||
| if base_url: | ||
| extra_fields["base_url"] = base_url | ||
| if region: | ||
| extra_fields["region"] = region | ||
| TenantModelInstanceService.create_instance(provider_id=provider_obj.id,instance_name=instance_name,api_key=api_key, extra=json.dumps(extra_fields)) | ||
| success, msg = add_model_to_instance(tenant_id, provider_name, instance_name, **model_info) | ||
| if not success: | ||
| return False, msg |
There was a problem hiding this comment.
Make model provisioning optional and keep this write path atomic.
model_info is documented as optional, but this branch always expands it into add_model_to_instance(...) after the instance row is inserted. When the request omits model_info (the API layer currently sends {}), this will raise at runtime and can leave an orphaned instance behind.
Possible fix
- TenantModelInstanceService.create_instance(provider_id=provider_obj.id,instance_name=instance_name,api_key=api_key, extra=json.dumps(extra_fields))
- success, msg = add_model_to_instance(tenant_id, provider_name, instance_name, **model_info)
- if not success:
- return False, msg
+ TenantModelInstanceService.create_instance(
+ provider_id=provider_obj.id,
+ instance_name=instance_name,
+ api_key=api_key,
+ extra=json.dumps(extra_fields),
+ )
+ if model_info:
+ success, msg = add_model_to_instance(
+ tenant_id, provider_name, instance_name, **model_info
+ )
+ if not success:
+ return False, msgIf provisioning is meant to be all-or-nothing, this should also be wrapped in a transaction or explicitly roll back the created instance on failure.
🤖 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 274 - 282, The code
always calls add_model_to_instance(...) after creating the instance, which fails
when model_info is empty and can leave an orphaned instance; change
TenantModelInstanceService.create_instance(...) to capture the created instance
(e.g., instance = TenantModelInstanceService.create_instance(...)) and only call
add_model_to_instance(...) if model_info is non-empty/Truthy; additionally make
the create+provision steps atomic by wrapping them in a DB transaction or, if a
transaction context is not available, catch failures from add_model_to_instance
and delete/rollback the created instance (use the created instance identifier or
TenantModelInstanceService delete method) so a failed provisioning does not
leave an orphan record.
| if not model_info: | ||
| return False, f"No models found for provider '{provider_name}'" | ||
| v1_index = url.find("/v1") | ||
| if v1_index >= 0: | ||
| models_url = url[: v1_index + 3] + "/models" | ||
| else: | ||
| models_url = url.rstrip("/") + "/v1/models" | ||
| try: | ||
| async with aiohttp.ClientSession() as session: | ||
| async with session.get(models_url, headers={"Authorization": f"Bearer {api_key}"}) as resp: | ||
| if resp.status == 200: | ||
| return True, "success" | ||
| else: | ||
| return False, f"Fail to access {models_url} using this api key." | ||
| except Exception as e: | ||
| logging.error(f"Fail to access {models_url} using this api key.", exc_info=e) | ||
| return False, f"Fail to access {models_url} using this api key." | ||
| factory_llms = [{ | ||
| "model_type": _type, | ||
| "llm_name": model_info.get("model_name", ""), | ||
| } for _type in model_info.get("model_type", [])] |
There was a problem hiding this comment.
Normalize and validate model_info before synthesizing factory_llms.
This branch assumes model_info["model_type"] is already a list and that model_info["model_name"] is present. If a client sends "chat" or omits model_name, the new empty-llm verification path either iterates characters or probes a blank model name and fails ambiguously.
Suggested guard
- factory_llms = [{
- "model_type": _type,
- "llm_name": model_info.get("model_name", ""),
- } for _type in model_info.get("model_type", [])]
+ model_types = model_info.get("model_type", [])
+ if isinstance(model_types, str):
+ model_types = [model_types]
+ model_name = model_info.get("model_name")
+ if not model_name or not model_types:
+ return False, "model_info.model_name and model_info.model_type are required"
+ factory_llms = [
+ {"model_type": _type, "llm_name": model_name}
+ for _type in model_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/apps/services/provider_api_service.py` around lines 354 - 359, Normalize
and validate model_info before building factory_llms: ensure model_info is a
dict, coerce model_types = model_info.get("model_type") into a list (if it's a
str wrap it in [str], if missing/None use []), filter out non-string/empty
entries from that list, and when constructing factory_llms use a safe model_name
= model_info.get("model_name") or _type (so you don't produce empty names);
update the comprehension that creates factory_llms to iterate the normalized
model_types and only include entries with a valid non-empty model_type,
referencing model_info, factory_llms and provider_name in your changes.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
api/apps/restful_apis/bot_api.py (1)
266-269:⚠️ Potential issue | 🟠 Major | ⚡ Quick winGuard against a missing tenant before dereferencing
llm_id.
TenantService.get_by_idreturns(False, None)when no record is found (seeCommonService.get_by_idinapi/db/services/common_service.py). The success flag is discarded here, so ifuiddoes not resolve to a tenant,tenant_infoisNoneandtenant_info.llm_idraisesAttributeError. This code path runs synchronously in the handler with no surroundingtry/except, so it surfaces as an unhandled 500.🛡️ Proposed fix with guard and logging
chat_llm_name = "" if not search_config or not search_config.get("chat_id"): - _, tenant_info = TenantService.get_by_id(uid) - chat_llm_name = tenant_info.llm_id + ok, tenant_info = TenantService.get_by_id(uid) + if not ok or not tenant_info: + logger.warning("searchbots/ask: tenant not found for default chat LLM resolution, tenant_id=%s", uid) + return get_error_data_result(message="Tenant not found.") + chat_llm_name = tenant_info.llm_id + logger.info("searchbots/ask: using tenant default chat LLM '%s' for tenant_id=%s", chat_llm_name, uid)Note: the added logging also addresses the "Add logging for new flows" guideline for this new fallback path. As per coding guidelines,
**/*.py: "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/bot_api.py` around lines 266 - 269, Guard the TenantService.get_by_id call return before accessing tenant_info.llm_id: capture both return values from TenantService.get_by_id(uid) and check the success flag or that tenant_info is not None before assigning chat_llm_name; if tenant_info is missing, set a safe default for chat_llm_name (e.g., empty string) and emit a warning/error log mentioning uid and that tenant was not found. Update the block that currently reads TenantService.get_by_id(uid) / tenant_info.llm_id to validate the result and log the condition so the handler no longer raises an AttributeError when tenant_info is None.
🧹 Nitpick comments (1)
api/apps/restful_apis/bot_api.py (1)
268-268: ⚡ Quick winBlocking DB call on the async event loop.
TenantService.get_by_id(uid)is a synchronous database call invoked directly in this async handler, unlike every other DB access in this file (e.g., Line 263, Line 328) which is offloaded viaawait thread_pool_exec(...). Running it inline blocks the event loop.♻️ Offload to the thread pool
- _, tenant_info = TenantService.get_by_id(uid) + _, tenant_info = await thread_pool_exec(TenantService.get_by_id, uid)🤖 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/bot_api.py` at line 268, The call to TenantService.get_by_id(uid) is a synchronous DB call made on the async event loop; offload it to the thread pool like other DB calls by invoking it via await thread_pool_exec(TenantService.get_by_id, uid) (or the local thread_pool_exec wrapper used elsewhere) and assign the returned tuple to _, tenant_info. Update the occurrence of TenantService.get_by_id to use thread_pool_exec to avoid blocking the event loop.
🤖 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.
Outside diff comments:
In `@api/apps/restful_apis/bot_api.py`:
- Around line 266-269: Guard the TenantService.get_by_id call return before
accessing tenant_info.llm_id: capture both return values from
TenantService.get_by_id(uid) and check the success flag or that tenant_info is
not None before assigning chat_llm_name; if tenant_info is missing, set a safe
default for chat_llm_name (e.g., empty string) and emit a warning/error log
mentioning uid and that tenant was not found. Update the block that currently
reads TenantService.get_by_id(uid) / tenant_info.llm_id to validate the result
and log the condition so the handler no longer raises an AttributeError when
tenant_info is None.
---
Nitpick comments:
In `@api/apps/restful_apis/bot_api.py`:
- Line 268: The call to TenantService.get_by_id(uid) is a synchronous DB call
made on the async event loop; offload it to the thread pool like other DB calls
by invoking it via await thread_pool_exec(TenantService.get_by_id, uid) (or the
local thread_pool_exec wrapper used elsewhere) and assign the returned tuple to
_, tenant_info. Update the occurrence of TenantService.get_by_id to use
thread_pool_exec to avoid blocking the event loop.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e7e977eb-6393-4b1b-9453-1f94388abe40
📒 Files selected for processing (1)
api/apps/restful_apis/bot_api.py
…into fix/model-provider-001
There was a problem hiding this comment.
🧹 Nitpick comments (1)
test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py (1)
145-149: ⚡ Quick winMake the
rag.nlp.searchstub optional (likely redundant) to reduce duplication
api/apps/restful_apis/document_api.pydoesn’t directly importrag.nlp.searchor referencerag.nlp.search.*—it relies onfrom rag.nlp import search—so the extra_stub(monkeypatch, "rag.nlp.search", ...)at lines 145-149 is probably unnecessary for this test’s import path (remove unless other code exercised by the test suite requires it).🤖 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 `@test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py` around lines 145 - 149, The test duplicates stubbing of rag.nlp.search; remove the redundant _stub(monkeypatch, "rag.nlp.search", index_name=...) call so only the initial _stub(monkeypatch, "rag.nlp", search=SimpleNamespace(index_name=...)) remains; update the test in test_document_preview_accessible.py to delete the second _stub line referencing "rag.nlp.search" (keep the monkeypatch usage and SimpleNamespace stub for rag.nlp) unless another test path relies on the direct "rag.nlp.search" attribute.
🤖 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.
Nitpick comments:
In `@test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py`:
- Around line 145-149: The test duplicates stubbing of rag.nlp.search; remove
the redundant _stub(monkeypatch, "rag.nlp.search", index_name=...) call so only
the initial _stub(monkeypatch, "rag.nlp",
search=SimpleNamespace(index_name=...)) remains; update the test in
test_document_preview_accessible.py to delete the second _stub line referencing
"rag.nlp.search" (keep the monkeypatch usage and SimpleNamespace stub for
rag.nlp) unless another test path relies on the direct "rag.nlp.search"
attribute.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 13ff8ea4-0c3e-41e8-8ced-e9fa7169f36b
📒 Files selected for processing (1)
test/unit_test/api/apps/restful_apis/test_document_preview_accessible.py
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15588 +/- ##
=======================================
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. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
Fix:
Type of change