Repository navigation
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:
📝 WalkthroughWalkthroughBedrock API-key support adds endpoint validation, request-scoped authorization, Runtime and Mantle model discovery, provider verification, POST model-list requests, transactional persistence, frontend configuration, deferred model mutations, and localized settings fields. ChangesBedrock API-Key Authentication
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant BedrockSettings
participant ProviderModelsAPI
participant ProviderAPIService
participant BedrockEndpoint
participant BedrockDiscovery
BedrockSettings->>ProviderModelsAPI: POST credentials, region, endpoint, and extensions
ProviderModelsAPI->>ProviderAPIService: list provider models
ProviderAPIService->>BedrockEndpoint: validate credentials and endpoint
ProviderAPIService->>BedrockDiscovery: discover compatible models
BedrockDiscovery-->>ProviderAPIService: return filtered models or error
ProviderAPIService-->>BedrockSettings: return normalized model catalog
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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: 4
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/service/model_service.go (1)
1018-1028: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winThe
"default"region placeholder shadowsbedrock_region.Line 1001 replaces an empty
regionwith"default", and Line 1020 puts that placeholder intoapiConfig.Region.resolveBedrockRegionininternal/entity/models/bedrock.goprefersapiConfig.Regionwhenever it is non-empty, so it returns"default"and never readsbedrock_regionfrom the key JSON. The driver then builds the hostbedrock.default.amazonaws.com, which passes the hostname allowlist and fails later with a DNS error instead of a clear region error.If the provider is Bedrock, leave
Regionempty so the driver falls back tobedrock_region.🐛 Proposed fix
apiConfig := &modelModule.APIConfig{ ApiKey: &apiKey, Region: ®ion, BaseURL: &baseURL, } if shouldVerifyBedrockAPIKeyWithoutModels(providerName, apiKey, modelInfo) { + // Bedrock carries its own region in the key JSON. Do not pass the + // "default" placeholder, which resolveBedrockRegion would treat as + // a real region. + emptyRegion := "" + apiConfig.Region = &emptyRegion if err := driver.CheckConnection(ctx, apiConfig); err != nil { return common.CodeServerError, err } return common.CodeSuccess, nil }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/model_service.go` around lines 1018 - 1028, Update the APIConfig construction in the Bedrock verification path to leave Region empty when region contains the "default" placeholder, allowing resolveBedrockRegion to fall back to bedrock_region from the key JSON. Preserve the existing region value for non-Bedrock providers and keep the surrounding CheckConnection flow unchanged.
🟡 Minor comments (18)
web/src/locales/ar.ts-853-864 (1)
853-864: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTranslate the new Bedrock strings in the Arabic locale.
These labels, prompts, and descriptions are English, so Arabic users will see untranslated text. Translate the user-facing text in
web/src/locales/ar.ts. Keep product names such asBedrock,Mantle,OpenAI, andAnthropicunchanged where appropriate.🤖 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 `@web/src/locales/ar.ts` around lines 853 - 864, Translate the user-facing Bedrock strings in the Arabic locale entries around awsAuthModeBedrockAPIKey through bedrockDiscoveryEndpointURLMessage, preserving product names such as Bedrock, Mantle, OpenAI, and Anthropic. Keep the existing keys and message meanings unchanged while replacing the English labels, prompts, and descriptions with natural Arabic.web/src/locales/bg.ts-922-933 (1)
922-933: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTranslate the new strings in the Bulgarian locale.
Lines 922-933 add English labels and validation messages to
web/src/locales/bg.ts. Bulgarian users will see English text for the new Bedrock fields. Translate the UI text while preserving product names and identifiers such asBedrock,Mantle,OpenAI,Anthropic, andHTTPS.Proposed direction
- bedrockEndpointType: 'Endpoint type', - bedrockEndpointURLMessage: 'Enter a trusted Bedrock HTTPS endpoint', + bedrockEndpointType: 'Тип на крайната точка', + bedrockEndpointURLMessage: 'Въведете надеждна Bedrock HTTPS крайна точка',Apply the same localization to the remaining added values.
🤖 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 `@web/src/locales/bg.ts` around lines 922 - 933, Translate the newly added Bedrock locale values in the Bulgarian translations, including labels and validation messages such as bedrockAPIKey through bedrockDiscoveryEndpointURLMessage. Preserve product names and identifiers including Bedrock, Mantle, OpenAI, Anthropic, and HTTPS.web/src/locales/de.ts-937-948 (1)
937-948: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTranslate the new German locale values before merging.
Lines [937]-[948] contain English labels and validation messages in
web/src/locales/de.ts. German users will see English text for the new Bedrock configuration fields.Suggested translation
- awsAuthModeBedrockAPIKey: 'Bedrock API Key', - bedrockAPIKey: 'Bedrock API Key', - bedrockAPIKeyMessage: 'Enter your Bedrock API Key', - bedrockEndpointType: 'Endpoint type', + awsAuthModeBedrockAPIKey: 'Bedrock-API-Schlüssel', + bedrockAPIKey: 'Bedrock-API-Schlüssel', + bedrockAPIKeyMessage: 'Geben Sie Ihren Bedrock-API-Schlüssel ein', + bedrockEndpointType: 'Endpunkttyp', bedrockEndpointRuntime: 'Bedrock Runtime', - bedrockEndpointMantleOpenAI: 'Mantle (OpenAI-compatible)', - bedrockEndpointMantleAnthropic: 'Mantle (Anthropic-compatible)', - bedrockEndpointURL: 'Endpoint URL', - bedrockEndpointURLMessage: 'Enter a trusted Bedrock HTTPS endpoint', - bedrockDiscoveryEndpointURL: 'Model discovery endpoint URL', + bedrockEndpointMantleOpenAI: 'Mantle (OpenAI-kompatibel)', + bedrockEndpointMantleAnthropic: 'Mantle (Anthropic-kompatibel)', + bedrockEndpointURL: 'Endpunkt-URL', + bedrockEndpointURLMessage: + 'Geben Sie eine vertrauenswürdige Bedrock-HTTPS-Endpunkt-URL ein', + bedrockDiscoveryEndpointURL: 'URL des Endpunkts für die Modellerkennung', bedrockDiscoveryEndpointURLMessage: - 'Optional Bedrock control-plane endpoint for listing models', + 'Optionaler Bedrock-Endpunkt der Steuerungsebene zum Auflisten von Modellen',🤖 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 `@web/src/locales/de.ts` around lines 937 - 948, Translate the newly added Bedrock locale values in the German translation object, including labels and messages for API keys, endpoint types, URLs, and model discovery, while preserving the existing locale keys and structure.web/src/locales/en.ts-1301-1303 (1)
1301-1303: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUse sentence case for the Bedrock API-key labels.
Keyis a common noun, not a proper noun. Change these strings toBedrock API keyandPlease enter your Bedrock API key.As per coding guidelines, English locale strings must use sentence case while preserving proper nouns.
Proposed wording
- awsAuthModeBedrockAPIKey: 'Bedrock API Key', - bedrockAPIKey: 'Bedrock API Key', - bedrockAPIKeyMessage: 'Please enter your Bedrock API Key', + awsAuthModeBedrockAPIKey: 'Bedrock API key', + bedrockAPIKey: 'Bedrock API key', + bedrockAPIKeyMessage: 'Please enter your Bedrock API key',🤖 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 `@web/src/locales/en.ts` around lines 1301 - 1303, Update the English locale entries awsAuthModeBedrockAPIKey, bedrockAPIKey, and bedrockAPIKeyMessage to use sentence case, changing “Bedrock API Key” to “Bedrock API key” while preserving the existing wording and proper noun “Bedrock API.”Source: Coding guidelines
web/src/locales/fr.ts-1404-1415 (1)
1404-1415: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTranslate the new Bedrock strings into French.
Lines [1404-1415] currently display English text in the French locale. Translate the labels, placeholders, and validation messages. Keep product names such as Bedrock, Mantle, OpenAI, and Anthropic unchanged.
Proposed translations
- awsAuthModeBedrockAPIKey: 'Bedrock API Key', - bedrockAPIKey: 'Bedrock API Key', - bedrockAPIKeyMessage: 'Enter your Bedrock API Key', - bedrockEndpointType: 'Endpoint type', - bedrockEndpointRuntime: 'Bedrock Runtime', - bedrockEndpointMantleOpenAI: 'Mantle (OpenAI-compatible)', - bedrockEndpointMantleAnthropic: 'Mantle (Anthropic-compatible)', - bedrockEndpointURL: 'Endpoint URL', - bedrockEndpointURLMessage: 'Enter a trusted Bedrock HTTPS endpoint', - bedrockDiscoveryEndpointURL: 'Model discovery endpoint URL', - bedrockDiscoveryEndpointURLMessage: - 'Optional Bedrock control-plane endpoint for listing models', + awsAuthModeBedrockAPIKey: 'Clé API Bedrock', + bedrockAPIKey: 'Clé API Bedrock', + bedrockAPIKeyMessage: 'Saisissez votre clé API Bedrock', + bedrockEndpointType: 'Type de point de terminaison', + bedrockEndpointRuntime: 'Bedrock Runtime', + bedrockEndpointMantleOpenAI: 'Mantle (compatible OpenAI)', + bedrockEndpointMantleAnthropic: 'Mantle (compatible Anthropic)', + bedrockEndpointURL: 'URL du point de terminaison', + bedrockEndpointURLMessage: + 'Saisissez un point de terminaison HTTPS Bedrock de confiance', + bedrockDiscoveryEndpointURL: + 'URL du point de terminaison de découverte des modèles', + bedrockDiscoveryEndpointURLMessage: + 'Point de terminaison facultatif du plan de contrôle Bedrock pour lister les modèles',🤖 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 `@web/src/locales/fr.ts` around lines 1404 - 1415, Translate the newly added Bedrock strings in the French locale, including labels, placeholders, and validation messages: awsAuthModeBedrockAPIKey, bedrockAPIKey, bedrockAPIKeyMessage, bedrockEndpointType, bedrockEndpointRuntime, bedrockEndpointMantleOpenAI, bedrockEndpointMantleAnthropic, bedrockEndpointURL, bedrockEndpointURLMessage, bedrockDiscoveryEndpointURL, and bedrockDiscoveryEndpointURLMessage. Preserve product names such as Bedrock, Mantle, OpenAI, and Anthropic unchanged.web/src/locales/it.ts-1186-1197 (1)
1186-1197: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTranslate the new Bedrock UI text into Italian.
Lines 1188-1197 contain English labels and validation messages in the Italian locale. Translate the descriptive text while preserving official names such as
Bedrock Runtime,Mantle,OpenAI, andAnthropic.Proposed translation
- bedrockAPIKeyMessage: 'Enter your Bedrock API Key', - bedrockEndpointType: 'Endpoint type', + bedrockAPIKeyMessage: 'Inserisci la tua chiave API Bedrock', + bedrockEndpointType: 'Tipo di endpoint', bedrockEndpointRuntime: 'Bedrock Runtime', - bedrockEndpointMantleOpenAI: 'Mantle (OpenAI-compatible)', - bedrockEndpointMantleAnthropic: 'Mantle (Anthropic-compatible)', - bedrockEndpointURL: 'Endpoint URL', - bedrockEndpointURLMessage: 'Enter a trusted Bedrock HTTPS endpoint', - bedrockDiscoveryEndpointURL: 'Model discovery endpoint URL', + bedrockEndpointMantleOpenAI: 'Mantle (compatibile con OpenAI)', + bedrockEndpointMantleAnthropic: 'Mantle (compatibile con Anthropic)', + bedrockEndpointURL: "URL dell'endpoint", + bedrockEndpointURLMessage: 'Inserisci un endpoint HTTPS Bedrock attendibile', + bedrockDiscoveryEndpointURL: + "URL dell'endpoint per la scoperta dei modelli", bedrockDiscoveryEndpointURLMessage: - 'Optional Bedrock control-plane endpoint for listing models', + 'Endpoint Bedrock facoltativo del control plane per elencare i modelli',🤖 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 `@web/src/locales/it.ts` around lines 1186 - 1197, Translate the newly added Bedrock labels and messages in the Italian locale around the awsAuthModeBedrockAPIKey and bedrockDiscoveryEndpointURL entries. Preserve official names and product terms including Bedrock, Runtime, Mantle, OpenAI, and Anthropic, while translating the surrounding descriptive text into natural Italian.web/src/locales/ja.ts-1279-1290 (1)
1279-1290: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winTranslate the new Bedrock strings for the Japanese locale.
Lines 1281-1290 contain English user-facing labels and validation messages. Japanese users will see untranslated text in the Bedrock form. Keep product names unchanged, but translate the surrounding text before merge.
Proposed fix
- awsAuthModeBedrockAPIKey: 'Bedrock API Key', - bedrockAPIKey: 'Bedrock API Key', - bedrockAPIKeyMessage: 'Enter your Bedrock API Key', - bedrockEndpointType: 'Endpoint type', + awsAuthModeBedrockAPIKey: 'Bedrock APIキー', + bedrockAPIKey: 'Bedrock APIキー', + bedrockAPIKeyMessage: 'Bedrock APIキーを入力してください', + bedrockEndpointType: 'エンドポイントタイプ', bedrockEndpointRuntime: 'Bedrock Runtime', - bedrockEndpointMantleOpenAI: 'Mantle (OpenAI-compatible)', - bedrockEndpointMantleAnthropic: 'Mantle (Anthropic-compatible)', - bedrockEndpointURL: 'Endpoint URL', - bedrockEndpointURLMessage: 'Enter a trusted Bedrock HTTPS endpoint', - bedrockDiscoveryEndpointURL: 'Model discovery endpoint URL', + bedrockEndpointMantleOpenAI: 'Mantle(OpenAI互換)', + bedrockEndpointMantleAnthropic: 'Mantle(Anthropic互換)', + bedrockEndpointURL: 'エンドポイントURL', + bedrockEndpointURLMessage: + '信頼できるBedrock HTTPSエンドポイントを入力してください', + bedrockDiscoveryEndpointURL: 'モデル一覧取得エンドポイントURL', bedrockDiscoveryEndpointURLMessage: - 'Optional Bedrock control-plane endpoint for listing models', + 'モデル一覧取得用のBedrockコントロールプレーンエンドポイント(任意)',🤖 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 `@web/src/locales/ja.ts` around lines 1279 - 1290, Translate the new Bedrock labels and messages in the Japanese locale object, including endpoint types, URL labels, and validation text, while preserving product names such as Bedrock, Runtime, Mantle, OpenAI, and Anthropic. Keep the existing locale keys and structure unchanged.web/src/locales/ko.ts-1162-1173 (1)
1162-1173: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTranslate the new Bedrock settings text into Korean.
The newly added labels, validation messages, and help text remain in English. Translate the surrounding text while preserving product and protocol names such as
Bedrock,Mantle,OpenAI,Anthropic, andHTTPS.🤖 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 `@web/src/locales/ko.ts` around lines 1162 - 1173, Translate the newly added Bedrock settings values in the locale section around awsAuthModeBedrockAPIKey through bedrockDiscoveryEndpointURLMessage into Korean, including labels, validation messages, and help text. Preserve product and protocol names such as Bedrock, Mantle, OpenAI, Anthropic, and HTTPS.web/src/locales/ru.ts-982-993 (1)
982-993: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winTranslate the new Bedrock strings into Russian.
Lines 982-993 contain English labels and validation messages in
web/src/locales/ru.ts. Russian users will see mixed-language Bedrock settings. Translate these values while preserving product names such asBedrock,Mantle,OpenAI,Anthropic, andHTTPS.Proposed translation
- awsAuthModeBedrockAPIKey: 'Bedrock API Key', - bedrockAPIKey: 'Bedrock API Key', - bedrockAPIKeyMessage: 'Enter your Bedrock API Key', - bedrockEndpointType: 'Endpoint type', + awsAuthModeBedrockAPIKey: 'API-ключ Bedrock', + bedrockAPIKey: 'API-ключ Bedrock', + bedrockAPIKeyMessage: 'Введите API-ключ Bedrock', + bedrockEndpointType: 'Тип конечной точки', bedrockEndpointRuntime: 'Bedrock Runtime', - bedrockEndpointMantleOpenAI: 'Mantle (OpenAI-compatible)', - bedrockEndpointMantleAnthropic: 'Mantle (Anthropic-compatible)', - bedrockEndpointURL: 'Endpoint URL', - bedrockEndpointURLMessage: 'Enter a trusted Bedrock HTTPS endpoint', - bedrockDiscoveryEndpointURL: 'Model discovery endpoint URL', + bedrockEndpointMantleOpenAI: 'Mantle (совместимый с OpenAI)', + bedrockEndpointMantleAnthropic: 'Mantle (совместимый с Anthropic)', + bedrockEndpointURL: 'URL конечной точки', + bedrockEndpointURLMessage: + 'Введите доверенную конечную точку Bedrock по протоколу HTTPS', + bedrockDiscoveryEndpointURL: 'URL конечной точки обнаружения моделей', bedrockDiscoveryEndpointURLMessage: - 'Optional Bedrock control-plane endpoint for listing models', + 'Необязательная конечная точка плоскости управления Bedrock для получения списка моделей',🤖 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 `@web/src/locales/ru.ts` around lines 982 - 993, Translate the Bedrock locale values in the `ru.ts` entries `awsAuthModeBedrockAPIKey`, `bedrockAPIKey`, `bedrockAPIKeyMessage`, `bedrockEndpointType`, `bedrockEndpointRuntime`, `bedrockEndpointMantleOpenAI`, `bedrockEndpointMantleAnthropic`, `bedrockEndpointURL`, `bedrockEndpointURLMessage`, `bedrockDiscoveryEndpointURL`, and `bedrockDiscoveryEndpointURLMessage` into natural Russian while preserving the product names `Bedrock`, `Mantle`, `OpenAI`, `Anthropic`, and `HTTPS`.web/src/locales/tr.ts-1145-1156 (1)
1145-1156: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winTranslate the new Turkish strings before merge.
Lines [1145-1156] add English labels and validation messages to
web/src/locales/tr.ts. This leaves the Bedrock settings partly untranslated for Turkish users. Translate the user-facing text and keep product names unchanged.Suggested translation
- awsAuthModeBedrockAPIKey: 'Bedrock API Key', - bedrockAPIKey: 'Bedrock API Key', - bedrockAPIKeyMessage: 'Enter your Bedrock API Key', - bedrockEndpointType: 'Endpoint type', + awsAuthModeBedrockAPIKey: 'Bedrock API anahtarı', + bedrockAPIKey: 'Bedrock API anahtarı', + bedrockAPIKeyMessage: 'Bedrock API anahtarınızı girin', + bedrockEndpointType: 'Uç nokta türü', bedrockEndpointRuntime: 'Bedrock Runtime', - bedrockEndpointMantleOpenAI: 'Mantle (OpenAI-compatible)', - bedrockEndpointMantleAnthropic: 'Mantle (Anthropic-compatible)', - bedrockEndpointURL: 'Endpoint URL', - bedrockEndpointURLMessage: 'Enter a trusted Bedrock HTTPS endpoint', - bedrockDiscoveryEndpointURL: 'Model discovery endpoint URL', + bedrockEndpointMantleOpenAI: 'Mantle (OpenAI uyumlu)', + bedrockEndpointMantleAnthropic: 'Mantle (Anthropic uyumlu)', + bedrockEndpointURL: "Uç nokta URL'si", + bedrockEndpointURLMessage: 'Güvenilir bir Bedrock HTTPS uç noktası girin', + bedrockDiscoveryEndpointURL: "Model keşif uç noktası URL'si", bedrockDiscoveryEndpointURLMessage: - 'Optional Bedrock control-plane endpoint for listing models', + 'Model listelemek için isteğe bağlı Bedrock kontrol düzlemi uç noktası',🤖 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 `@web/src/locales/tr.ts` around lines 1145 - 1156, Translate the newly added Bedrock strings in the Turkish locale, including labels, endpoint descriptions, and validation messages such as awsAuthModeBedrockAPIKey, bedrockAPIKey, bedrockAPIKeyMessage, bedrockEndpointType, bedrockEndpointRuntime, bedrockEndpointMantleOpenAI, bedrockEndpointMantleAnthropic, bedrockEndpointURL, bedrockEndpointURLMessage, bedrockDiscoveryEndpointURL, and bedrockDiscoveryEndpointURLMessage. Keep product and compatibility names such as Bedrock, Mantle, OpenAI, and Anthropic unchanged.web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts-165-204 (1)
165-204: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winThe test name claims coverage the hook cannot provide.
useModelsDerivedreceives onlyisDraftInstance. It never seesdeferModelMutations. This test passesisDraftInstance: true, so it verifies the draft path, not the deferred-saved-instance path. The deferred seeding logic lives inindex.tsx(lines 126-131) and stays untested.Rename the case to describe what it checks, and state the deferred path in the description only if a test covers it.
💚 Proposed rename
- it('keeps a deferred saved instance selection instead of selecting the full catalog', () => { + it('keeps the local model selection instead of selecting the full catalog', () => {🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts` around lines 165 - 204, Rename the useModelsDerived test case to describe the draft-instance behavior it actually exercises with isDraftInstance: true, rather than claiming coverage of deferred saved-instance selection. Do not mention the deferred path unless adding coverage that invokes the deferModelMutations logic in index.tsx.rag/llm/model_meta.py-71-77 (1)
71-77: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winReject non-object JSON before calling
config.get.
json.loadsreturns a non-dict for scalar input. Anapi_keyvalue such as12345parses to anint, andconfig.get("auth_mode")then raisesAttributeErrorinstead of the intendedValueError. Add anisinstancecheck.The change summary states that the code raises
ValueErrorwhen the value is not a JSON object. The code does not implement that check.🛡️ Proposed fix
try: config = json.loads(self.api_key) except (JSONDecodeError, TypeError) as error: raise ValueError("Bedrock API key must be a JSON object") from error + if not isinstance(config, dict): + raise ValueError("Bedrock API key must be a JSON object") if config.get("auth_mode") != "bedrock_api_key":🤖 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 `@rag/llm/model_meta.py` around lines 71 - 77, Validate that the result of json.loads assigned to config is a dictionary before calling config.get, and raise the existing ValueError for any non-object JSON value. Update the exception/validation flow in the surrounding model discovery method while preserving the auth_mode check and discover_bedrock_models call for valid objects.rag/llm/bedrock_model_discovery.py-60-81 (1)
60-81: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick winReject control characters in
api_keybefore setting the header.
add_bearer_tokenwrites the tenant-suppliedapi_keydirectly into theAuthorizationheader. A key that contains CR or LF characters produces an invalid header value. Depending on the HTTP stack, the request either fails with an obscure error or carries injected header lines. Strip surrounding whitespace and reject control characters when the key is read.🛡️ Proposed fix
def create_bedrock_bearer_client(service_name: str, api_key: str, region_name: str, endpoint_url: str = "") -> BaseClient: import boto3 + api_key = api_key.strip() + if any(character in api_key for character in "\r\n") or not api_key.isprintable(): + raise ValueError("Bedrock API key must not contain control characters") + client_args: dict[str, object] = {🤖 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 `@rag/llm/bedrock_model_discovery.py` around lines 60 - 81, Update create_bedrock_bearer_client to normalize api_key by stripping surrounding whitespace and reject it if it contains carriage-return or newline characters before registering add_bearer_token. Ensure invalid keys fail during client setup, while the validated key is the only value used for the Authorization header.Source: Linters/SAST tools
rag/llm/model_meta.py-68-77 (1)
68-77: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winCatch Bedrock model-discovery exceptions and return API errors.
Bedrock.get_model_list()can raiseValueErrorandBedrockModelDiscoveryError. The provider call site only catchesTimeoutError, and the update path uses the generic_run_verification(), which only logs timeout/cancel errors and converts all other exceptions into generic verification failures. Handle Bedrock discovery failures explicitly so invalid JSON and discovery errors are returned as API errors instead of generic verification results.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rag/llm/model_meta.py` around lines 68 - 77, The Bedrock model-list flow in Bedrock.get_model_list must explicitly handle JSON ValueError and BedrockModelDiscoveryError at the provider/update call site, converting them into API errors rather than allowing _run_verification to produce generic verification failures. Preserve the existing TimeoutError handling and ensure both direct discovery and update paths use the explicit error response behavior.test/unit_test/rag/llm/conftest.py-63-68 (1)
63-68: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAlign the LiteLLM mock with the production provider map.
The mock
SupportedLiteLLMProvidervalues match the production enum, butconftest.pykeepsLITELLM_PROVIDER_PREFIXlimited toBedrock. Use the production entries for the added providers (Nvidia,Ollama,OpenRouter,MiniMax,GPUStack, plusMoonshot/ZHIPU_AIwhere covered by the mock) to avoid tests masking provider-prefix routing behavior.🤖 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/rag/llm/conftest.py` around lines 63 - 68, Update the LITELLM_PROVIDER_PREFIX mapping in conftest.py to include provider-prefix entries matching the production map for Nvidia, Ollama, OpenRouter, MiniMax, GPUStack, and the mock-covered Moonshot and ZHIPU_AI providers, while preserving the existing Bedrock entry. Use the corresponding production prefix values so tests exercise provider-prefix routing accurately.api/apps/services/provider_api_service.py-261-268 (1)
261-268: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winThe new Bedrock model-listing path has no logging. The request-handling layer and the discovery layer both add new flows without log records, so a failed or timed-out Bedrock discovery leaves no server-side trace.
api/apps/services/provider_api_service.py#L261-L268: log the remote-discovery attempt and log a warning before returning the timeout message.api/apps/restful_apis/provider_api.py#L248-L263: log the provider name and request method when the POST credential path is used.Based on the coding guidelines for
**/*.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 261 - 268, In api/apps/services/provider_api_service.py lines 261-268, update the Bedrock branch around ModelMeta.get_model_list() to log the remote-discovery attempt and emit a warning before returning the timeout response. In api/apps/restful_apis/provider_api.py lines 248-263, add logging to the POST credential path that records the provider name and request method.Source: Coding guidelines
rag/llm/embedding_model.py-716-719 (1)
716-719: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUpdate the stale key-protocol comment.
The comment block at Lines 670-676 still states that unknown modes are "treated as assume_role" and omits
bedrock_api_key. Lines 693-719 now supportbedrock_api_keyand raiseValueErrorfor unknown modes. Update the comment so it matches the current runtime path.Based on learnings from the coding guidelines: "Remove dead tests, commented-out code, stale documentation, and 'move later' notes."
🤖 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 `@rag/llm/embedding_model.py` around lines 716 - 719, Update the key-protocol comment near the authentication mode handling to document the supported bedrock_api_key and assume_role modes, and state that unsupported modes raise ValueError. Remove the outdated claim that unknown modes are treated as assume_role, keeping the comment aligned with the branching logic in the surrounding authentication setup.Source: Coding guidelines
test/unit_test/rag/llm/test_bedrock_api_key.py-83-105 (1)
83-105: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winIsolate the timeout assertion from the ambient environment.
Line 84 asserts
kwargs["timeout"] == 10.list_provider_modelsderives that value fromos.environ.get("LLM_TIMEOUT_SECONDS")with a fallback of10(api/apps/services/provider_api_service.py Line 264). IfLLM_TIMEOUT_SECONDSis set in the test environment, this test fails for an unrelated reason. Clear the variable inside the test.💚 Proposed fix to pin the environment
-def test_list_bedrock_models_times_out_remote_discovery(): +def test_list_bedrock_models_times_out_remote_discovery(monkeypatch): + monkeypatch.delenv("LLM_TIMEOUT_SECONDS", raising=False) + class SlowDiscovery:🤖 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/rag/llm/test_bedrock_api_key.py` around lines 83 - 105, Update the timeout test around raise_timeout and list_provider_models to clear or override the LLM_TIMEOUT_SECONDS environment variable within the test, ensuring the production fallback remains 10 regardless of ambient environment settings. Keep the existing timeout assertion and result checks unchanged.
🧹 Nitpick comments (17)
web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.ts (1)
33-43: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a test for the nullish branch.
serializeProviderAPIKeymapsnullandundefinedto''. Callers rely on that branch when the form holds no API key. The branch is untested.💚 Proposed test
it('serializes a provider-specific API key object', () => { expect(serializeProviderAPIKey({ yiyan_ak: 'ak', yiyan_sk: 'sk' })).toBe( '{"yiyan_ak":"ak","yiyan_sk":"sk"}', ); }); + + it('maps missing API keys to an empty string', () => { + expect(serializeProviderAPIKey(undefined)).toBe(''); + expect(serializeProviderAPIKey(null)).toBe(''); + }); });🤖 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 `@web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.ts` around lines 33 - 43, Add a test case in the serializeProviderAPIKey suite that passes nullish input, covering both null and undefined, and verifies each returns an empty string as required by the function’s nullish branch.web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx (2)
644-644: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the inline JSX event handlers.
Line 644 uses
onSubmit={(e) => e.preventDefault()}. Line 835 usesonChange={(e) => field.onChange(Number(e.target.value))}. Both create a new function on every render.♻️ Proposed refactor
+ const handleFormSubmit = useCallback((e: React.FormEvent) => { + e.preventDefault(); + }, []);- <form className="space-y-6" onSubmit={(e) => e.preventDefault()}> + <form className="space-y-6" onSubmit={handleFormSubmit}>For the numeric input, extract a handler factory or a small
NumberInputwrapper so the field callback is referenced by name rather than built inline.As per coding guidelines: "Avoid inline JSX event handlers such as onClick={() => ...} and onChange={(e) => ...}; extract named handlers and reference them by name."
Also applies to: 830-837
🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx` at line 644, Extract the inline form submit and numeric input change callbacks into named handlers or reusable handler helpers within the component. Update the form around the submit handler and the numeric field near `field.onChange` to reference those handlers directly, preserving `preventDefault()` and numeric conversion behavior.Source: Coding guidelines
445-461: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMake the injected-key contract explicit and align the
api_keyguard.Two points.
First,
transformModelVerifydeletesapi_keyandextensionsbecausegetModelsSectionValuesinjects them. It does not deleteregion, whichgetBedrockModelListRequestalso injects.buildPayloadcurrently survives that because itsflatobject setsregion: values.bedrock_regionafter spreadingcleaned. The correctness depends on key ordering insidebuildPayload. IfgetBedrockModelListRequestgains another key that collides with a form field, this transform mis-builds the payload with no error.Second, line 479 uses
JSON.stringify(payload.api_key)while line 455 usesJSON.stringify(payload.api_key ?? '').JSON.stringify(undefined)returnsundefined, not a string, so the two paths send different shapes whenapi_keyis absent.♻️ Proposed refactor
+const MODEL_LIST_INJECTED_KEYS = ['api_key', 'region', 'extensions'] as const;const transformModelVerify = useCallback( (values: Record<string, any>) => { const formValues = { ...values }; - delete formValues.api_key; - delete formValues.extensions; + MODEL_LIST_INJECTED_KEYS.forEach((key) => { + delete formValues[key]; + });const ret = await verifyProviderConnection({ provider_name: providerName, - api_key: JSON.stringify(payload.api_key), + api_key: JSON.stringify(payload.api_key ?? ''),Also applies to: 477-482
🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx` around lines 445 - 461, Make the injected-key contract explicit across transformModelVerify and buildPayload: remove every key supplied by getModelsSectionValues or getBedrockModelListRequest, including region, before building the payload, and enforce injected-value precedence explicitly rather than relying on spread order. Align the api_key handling in both verification paths, including the code around line 479, so missing keys are serialized as an empty string instead of producing undefined.web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts (1)
292-297: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueName the Bedrock auto-fetch delay and document its purpose.
500is a bare magic number. The comment block above (lines 261-276) explains the readiness gate but not the delay. The delay debounces catalog requests while the user types the Bedrock API key; each keystroke changesapiKeyValueand re-runs this effect.♻️ Proposed refactor
+/** Debounce window for the Bedrock catalog auto-fetch. The API key is + * typed character by character, and each keystroke re-runs the effect; + * the delay avoids firing a discovery request per keystroke. */ +const BEDROCK_AUTO_FETCH_DELAY_MS = 500;- const delay = providerName === LLMFactory.Bedrock ? 500 : 0; + const delay = + providerName === LLMFactory.Bedrock ? BEDROCK_AUTO_FETCH_DELAY_MS : 0;🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts` around lines 292 - 297, Replace the bare 500ms value in the auto-fetch effect with a clearly named Bedrock delay constant, and add a concise comment documenting that it debounces catalog requests while the user types the API key. Use the constant in the existing setTimeout logic without changing behavior for other providers.web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx (1)
126-131: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winNormalize the seeded instance models instead of double-casting.
instanceModelsentries carrymodel_type, whileIProviderModelItemdeclaresmodel_types. Theas unknown ascast hides that mismatch.useModelsDerivedcurrently normalizes both spellings, so the mixed shapes work today, butdraftModelsthen holds two different item shapes and any future direct reader ofdraftModelsbreaks.The file already imports
normalizeModelTypes-shaped logic inhooks.ts; reuse it here.♻️ Proposed refactor
- hasSeededDeferredModelsRef.current = true; - setDraftModels(instanceModels as unknown as IProviderModelItem[]); + hasSeededDeferredModelsRef.current = true; + setDraftModels( + instanceModels.map((im: any) => ({ + name: im.name, + max_tokens: im.max_tokens ?? 0, + model_types: normalizeModelTypes(im.model_types ?? im.model_type), + features: im.features ?? null, + extra: im.extra, + })), + );Add
normalizeModelTypesto the existing./hooksimport.🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx` around lines 126 - 131, Update the deferred-model seeding effect to normalize instanceModels with normalizeModelTypes before passing them to setDraftModels, and add that helper to the existing ./hooks import. Remove the as unknown as cast so draftModels consistently uses IProviderModelItem shapes.web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts (1)
64-75: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd the
undefinedbase URL case.
isCatalogBaseURLReadytreatsundefinedas "the provider form has nobase_urlfield" and returnstrue. That branch distinguishes a missing field from an empty field, and it drives the auto-fetch gate for providers such as VolcEngine and Google Cloud. It is untested.💚 Proposed test
it('still requires configured base URLs for generic providers', () => { expect(isCatalogBaseURLReady(LLMFactory.Ollama, '')).toBe(false); expect( isCatalogBaseURLReady(LLMFactory.Ollama, 'http://localhost:11434'), ).toBe(true); }); + + it('treats a provider without a base URL field as ready', () => { + expect(isCatalogBaseURLReady(LLMFactory.VolcEngine, undefined)).toBe(true); + }); });🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts` around lines 64 - 75, Add a test in the isCatalogBaseURLReady suite covering an undefined base URL, asserting it returns true for a provider whose form omits the base_url field, such as VolcEngine or Google Cloud. Keep the existing empty-string and configured-URL cases unchanged.rag/llm/bedrock_model_discovery.py (2)
130-134: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueMatch the Anthropic prefix case-insensitively.
_is_mantle_chat_modellowercases the model ID before the prefix comparison, but theanthropic.check uses the rawmodel.id. The Go implementation ininternal/entity/models/bedrock.golowercases the name before both checks. A catalog that returnsAnthropic.claude-...is then filtered out in Python but kept in Go.♻️ Proposed fix
return [ {"name": model.id, "model_types": [LLMType.CHAT.value], "max_tokens": DEFAULT_BEDROCK_MAX_TOKENS, "features": []} for model in response.data - if _is_mantle_chat_model(model.id) and (not anthropic_only or model.id.startswith("anthropic.")) + if _is_mantle_chat_model(model.id) and (not anthropic_only or model.id.lower().startswith("anthropic.")) ]🤖 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 `@rag/llm/bedrock_model_discovery.py` around lines 130 - 134, Update the anthropic_only filter in the model discovery comprehension to compare a lowercased model.id against the “anthropic.” prefix, matching _is_mantle_chat_model and the Go implementation while preserving existing filtering behavior.
137-155: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd logging to the discovery flow.
discover_bedrock_modelsis a new remote flow with several rejection paths and two backends. It emits no log records, so an operator cannot tell which endpoint was queried, how many models were returned, or why the catalog was empty. Log the resolved endpoint type, the model count, and the failure cases. Do not log the API key.Based on learnings from the 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 `@rag/llm/bedrock_model_discovery.py` around lines 137 - 155, Update discover_bedrock_models to use the module’s established logger, recording the resolved endpoint type and discovered model count without exposing api_key or other secrets. Add logs before raising for validation/rejection failures and the empty catalog case, while preserving the existing runtime and Mantle backend behavior and return values.Source: Coding guidelines
internal/entity/models/bedrock.go (2)
209-226: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueAlign suffix stripping with the Python implementation.
The loop applies
strings.TrimSuffixfor every suffix in sequence. The Python helper_mantle_root_urlinrag/utils/bedrock_endpoint.pyreturns after the first matching suffix. For an input such ashttps://host/anthropic/v1/models, Go strips/v1/modelsand then/anthropic, while Python strips only/v1/models. The two runtimes then derive different Mantle base URLs from the same saved configuration.Stop after the first match to keep both implementations equivalent.
♻️ Proposed fix
for _, suffix := range []string{"/anthropic/v1/messages", "/v1/models", "/anthropic", "/v1"} { - endpointURL = strings.TrimSuffix(endpointURL, suffix) + if trimmed := strings.TrimSuffix(endpointURL, suffix); trimmed != endpointURL { + endpointURL = trimmed + break + } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/bedrock.go` around lines 209 - 226, Update normalizeBedrockEndpoint so suffix removal stops immediately after the first matching suffix, matching the ordered behavior of the Python _mantle_root_url helper. Preserve the existing suffix order and endpoint-type handling, ensuring inputs such as paths ending in /anthropic/v1/models are not stripped again by later suffixes.
1120-1141: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
slices.Containsinstead of the local closure.The file already imports
slicesand usesslices.Containsat Line 1090. The localcontainsclosure duplicates that behavior.♻️ Proposed fix
func bedrockModelTypes(modelID string, inputModalities, outputModalities []string) []string { - contains := func(values []string, target string) bool { - for _, value := range values { - if value == target { - return true - } - } - return false - } - if !contains(inputModalities, "TEXT") || strings.Contains(strings.ToLower(modelID), "rerank") { + if !slices.Contains(inputModalities, "TEXT") || strings.Contains(strings.ToLower(modelID), "rerank") { return nil } - if contains(outputModalities, "EMBEDDING") && (strings.HasPrefix(modelID, "amazon.titan-embed-text") || strings.HasPrefix(modelID, "cohere.embed-")) { + if slices.Contains(outputModalities, "EMBEDDING") && (strings.HasPrefix(modelID, "amazon.titan-embed-text") || strings.HasPrefix(modelID, "cohere.embed-")) { return []string{"embedding"} } - if contains(outputModalities, "TEXT") { + if slices.Contains(outputModalities, "TEXT") {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/bedrock.go` around lines 1120 - 1141, The bedrockModelTypes function defines a redundant local contains closure despite the file already using slices.Contains. Remove the closure and replace its inputModalities and outputModalities checks with slices.Contains, preserving the existing modality and model-ID behavior.internal/handler/providers.go (1)
318-328: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winEmit an empty array when
ModelTypesis nil.A nil
model.ModelTypesserializes as"model_types": null. The Python listing path always emits a list formodel_types, and the frontend consumes the field as an array. Normalize the nil case so both backends produce the same shape.♻️ Proposed change
func providerListModelItem(model models.ListModelResponse) map[string]interface{} { maxTokens := 8192 if model.MaxOutput != nil { maxTokens = *model.MaxOutput } + modelTypes := model.ModelTypes + if modelTypes == nil { + modelTypes = []string{} + } return map[string]interface{}{ "name": model.Name, - "model_types": model.ModelTypes, + "model_types": modelTypes, "max_tokens": maxTokens, } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/providers.go` around lines 318 - 328, Update providerListModelItem to normalize a nil model.ModelTypes value to an empty array before constructing the response map, while preserving existing non-nil model types. Ensure the serialized model_types field is always an array.test/unit_test/rag/llm/test_bedrock_api_key.py (2)
108-115: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAssert against the imported constant.
The file already imports
BEDROCK_DISCOVERY_TIMEOUT_SECONDSat Line 19 and uses it at Line 318. Lines 113-114 hardcode10instead. Use the constant so the assertion tracks the production value.♻️ Proposed change
- assert config.connect_timeout == 10 - assert config.read_timeout == 10 + assert config.connect_timeout == BEDROCK_DISCOVERY_TIMEOUT_SECONDS + assert config.read_timeout == BEDROCK_DISCOVERY_TIMEOUT_SECONDS🤖 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/rag/llm/test_bedrock_api_key.py` around lines 108 - 115, Update test_runtime_discovery_client_has_bounded_network_timeouts to compare connect_timeout and read_timeout against the imported BEDROCK_DISCOVERY_TIMEOUT_SECONDS constant instead of hardcoding 10; leave the retries assertion unchanged.
349-354: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMake the
matchpattern a raw string.Ruff reports RUF043 for Line 350. The pattern uses regex metacharacters. Mark it as a raw string to state the regex intent and clear the lint warning.
♻️ Proposed change
- with pytest.raises(ValueError, match="do not support.*rerank"): + with pytest.raises(ValueError, match=r"do not support.*rerank"):🤖 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/rag/llm/test_bedrock_api_key.py` around lines 349 - 354, Update the pytest.raises match argument in test_rerank_rejects_bedrock_api_key to use a raw string literal, preserving the existing regex pattern and expected ValueError behavior while clearing Ruff RUF043.Source: Linters/SAST tools
api/apps/services/provider_api_service.py (2)
216-216: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAnnotate the optional parameters explicitly.
Ruff reports RUF013 on this signature. Implicit Optional is prohibited by PEP 484; for Python 3.10 and later you can use
T | None. The newly addedregionparameter follows the same implicit pattern asapi_keyandbase_url. The backend targets Python 3.13+, so the union syntax is available.♻️ Proposed change
-async def list_provider_models(provider_id_or_name: str, api_key: str = None, base_url: str = None, region: str = None, extensions: dict[str, object] | None = None): +async def list_provider_models(provider_id_or_name: str, api_key: str | None = None, base_url: str | None = None, region: str | None = None, extensions: dict[str, object] | None = None):🤖 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` at line 216, Update the list_provider_models signature to explicitly annotate api_key, base_url, and region as str | None, preserving their existing defaults and behavior. Keep extensions unchanged unless needed for consistent optional typing.Source: Linters/SAST tools
238-243: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse one Bedrock auth-mode parser.
Lines 238-243 duplicate the
auth_modedetection already implemented in_should_verify_bedrock_api_key_without_modelsat Lines 82-89. Extract a single private helper, for example_is_bedrock_api_key_config(api_key), and call it from both sites. One parser prevents the two checks from diverging.♻️ Proposed refactor
+def _is_bedrock_api_key_config(api_key: str | dict | None) -> bool: + if not api_key: + return False + if isinstance(api_key, dict): + key_config = api_key + else: + try: + key_config = json.loads(api_key) + except (json.JSONDecodeError, TypeError): + return False + return isinstance(key_config, dict) and key_config.get("auth_mode") == "bedrock_api_key"Then in
list_provider_models:- bedrock_remote_only = False - if provider_name == "Bedrock" and api_key: - try: - parsed_bedrock_key = json.loads(api_key) if isinstance(api_key, str) else api_key - bedrock_remote_only = parsed_bedrock_key.get("auth_mode") == "bedrock_api_key" - except (json.JSONDecodeError, TypeError, AttributeError): - pass + bedrock_remote_only = provider_name == "Bedrock" and _is_bedrock_api_key_config(api_key)🤖 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 238 - 243, Extract the duplicated Bedrock auth-mode parsing into a private helper such as _is_bedrock_api_key_config(api_key), preserving the existing JSON, mapping, and exception behavior. Replace the inline parsing in list_provider_models and the equivalent logic in _should_verify_bedrock_api_key_without_models with calls to this helper so both checks share one implementation.rag/llm/cv_model.py (2)
1379-1380: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAlign the region requirement with the other Bedrock drivers.
BedrockCVdefaultsbedrock_regionto"us-east-1".LiteLLMBase._construct_completion_args(rag/llm/chat_model.py, Line 2385) andBedrockEmbed.__init__(rag/llm/embedding_model.py, Line 684) now reject a missing region. A vision request therefore silently targetsus-east-1when the provider instance omits the region, and the resulting API-key failure is hard to attribute.♻️ Proposed change to require the region
- self.aws_region = bedrock_key.get("bedrock_region", "us-east-1") - validate_bedrock_region(self.aws_region) + self.aws_region = bedrock_key.get("bedrock_region") + if not self.aws_region: + raise ValueError("Bedrock region must be provided in the key") + validate_bedrock_region(self.aws_region)🤖 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 `@rag/llm/cv_model.py` around lines 1379 - 1380, Update BedrockCV initialization around the bedrock_region assignment and validate_bedrock_region call to require an explicitly provided bedrock_region instead of defaulting to "us-east-1". Preserve the existing region validation while ensuring omitted configuration is rejected consistently with LiteLLMBase._construct_completion_args and BedrockEmbed.__init__.
1396-1410: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting the shared Bedrock API-key argument builder.
Lines 1400-1410 duplicate the runtime and Mantle credential wiring in
rag/llm/chat_model.pyLines 2398-2417, including the inert access-key placeholders and the bearer header. Two copies of credential construction can drift. A private helper next toresolve_bedrock_endpointinrag/utils/bedrock_endpoint.pywould let both call sites share one implementation.🤖 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 `@rag/llm/cv_model.py` around lines 1396 - 1410, Extract the shared Bedrock API-key credential construction from _get_aws_creds and the corresponding chat-model flow into a private helper near resolve_bedrock_endpoint in bedrock_endpoint.py. Have both call sites use this helper so runtime and Mantle wiring consistently preserve the access-key placeholders, bearer header, endpoint handling, and API-key validation.
feat: - Add POST provider model discovery with string API keys and extensions - Support Bedrock API key authentication for Runtime and Mantle endpoints - Discover active on-demand Bedrock models - Add Bedrock authentication and endpoint configuration UI fix: - Preserve object-based provider credentials when listing models - Keep Go Bedrock model capabilities aligned with its text-only runtime
fix: - Reject empty discovery results and invalid credential payloads - Keep model catalogs synchronized across credential and reset changes - Align Python and Go discovery validation and response normalization test: - Cover empty discovery, credential scope, and provider edge cases
|
Prepared the review fixes in final local SHA Implemented the correctness, validation, localization, response-normalization, logging, and focused regression-test findings, including the Go Bedrock region fallback and the Python/Go discovery parity fixes. I did not apply five refactor-only suggestions where the existing local code has no observed defect: extracting the JSX handler, introducing constants for the injected key and debounce delay, replacing the small local modality helper with resolve-review-comments:v1 {"platform":"github","item_kind":"review-summary","item_id":"PRR_kwDOK4sStM8AAAABIo-tHg","body_sha256":"sha256:bb7cf64c184b850f57cc7dd7570329f4227e0d51bbcb140170e4e608b7a405b6","disposition":"Mixed","final_sha":"3665c0588c221c7706a751ed8816f0eebdc12a59","supersedes_reply_id":null} |
332b421 to
3665c05
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
api/apps/services/provider_api_service.py (1)
726-726: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReuse
_to_intfor the timeout parse.Line 270 parses the same environment variable with
max(1, _to_int(os.environ.get("LLM_TIMEOUT_SECONDS"), 10)). Line 726 usesint(...), which raisesValueErrorif the operator sets a non-numeric value. Use the existing helper so both Bedrock paths behave the same.♻️ Proposed change
- timeout_seconds = int(os.environ.get("LLM_TIMEOUT_SECONDS", 10)) + timeout_seconds = max(1, _to_int(os.environ.get("LLM_TIMEOUT_SECONDS"), 10))🤖 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` at line 726, Update the timeout parsing at the Bedrock path around timeout_seconds to reuse the existing _to_int helper instead of int, matching the established LLM_TIMEOUT_SECONDS handling and preserving the default timeout for non-numeric values.web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx (1)
17-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename the top-level fixture to PascalCase.
Rename
valuestoValuesand update its references. The TSX naming rule requires PascalCase for top-level constants.🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx` around lines 17 - 30, Rename the top-level BedrockFormValues fixture constant from values to Values and update every reference to use the new PascalCase identifier.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/bedrock.go`:
- Around line 231-255: Update validateBedrockEndpointTarget to reject endpoint
URLs with an explicit non-443 port before hostname allowlist matching, while
continuing to accept URLs without a port and those explicitly using port 443.
Preserve the existing HTTPS, credential, query, fragment, and hostname
validation behavior.
- Around line 676-688: The mantleOpenAI and mantleAnthropic constructors
currently create drivers without reusing a shared HTTP client, while Bedrock
request cleanup can close active transport resources. Update the BedrockModel
client construction and lifecycle so both Mantle drivers reuse a shared HTTP
client and only the owning caller manages its cleanup; avoid closing resources
still needed by active requests.
---
Nitpick comments:
In `@api/apps/services/provider_api_service.py`:
- Line 726: Update the timeout parsing at the Bedrock path around
timeout_seconds to reuse the existing _to_int helper instead of int, matching
the established LLM_TIMEOUT_SECONDS handling and preserving the default timeout
for non-numeric values.
In
`@web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx`:
- Around line 17-30: Rename the top-level BedrockFormValues fixture constant
from values to Values and update every reference to use the new PascalCase
identifier.
🪄 Autofix
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 Plus
Run ID: d63ab826-d371-4b8b-a282-0131f773fa9d
📒 Files selected for processing (44)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.pyinternal/entity/models/bedrock.gointernal/entity/models/bedrock_test.gointernal/handler/providers.gointernal/handler/providers_test.gointernal/router/router.gointernal/service/model_service.gointernal/service/model_service_test.gorag/llm/bedrock_model_discovery.pyrag/llm/chat_model.pyrag/llm/cv_model.pyrag/llm/embedding_model.pyrag/llm/model_meta.pyrag/llm/rerank_model.pyrag/utils/bedrock_endpoint.pytest/unit_test/rag/llm/conftest.pytest/unit_test/rag/llm/test_bedrock_api_key.pyweb/src/hooks/use-llm-request.tsxweb/src/interfaces/request/llm.tsweb/src/locales/ar.tsweb/src/locales/bg.tsweb/src/locales/de.tsweb/src/locales/en.tsweb/src/locales/fr.tsweb/src/locales/it.tsweb/src/locales/ja.tsweb/src/locales/ko.tsweb/src/locales/ru.tsweb/src/locales/tr.tsweb/src/locales/zh-traditional.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.tsweb/src/pages/user-setting/setting-model/instance-card/interface.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/index.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/interface.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.tsweb/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.tsweb/src/services/llm-service.ts
🚧 Files skipped from review as they are similar to previous changes (35)
- web/src/locales/it.ts
- web/src/locales/zh-traditional.ts
- web/src/locales/bg.ts
- internal/router/router.go
- web/src/locales/ar.ts
- web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts
- web/src/locales/en.ts
- web/src/services/llm-service.ts
- web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.ts
- web/src/interfaces/request/llm.ts
- web/src/pages/user-setting/setting-model/instance-card/interface.ts
- rag/llm/rerank_model.py
- rag/llm/model_meta.py
- test/unit_test/rag/llm/conftest.py
- web/src/locales/zh.ts
- web/src/hooks/use-llm-request.tsx
- web/src/locales/fr.ts
- web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
- web/src/locales/ru.ts
- rag/llm/chat_model.py
- rag/llm/cv_model.py
- api/apps/restful_apis/provider_api.py
- web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx
- internal/handler/providers_test.go
- web/src/locales/de.ts
- web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts
- web/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.ts
- web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
- rag/utils/bedrock_endpoint.py
- rag/llm/embedding_model.py
- web/src/locales/ko.ts
- web/src/locales/ja.ts
- web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
- internal/service/model_service.go
- web/src/locales/tr.ts
fix: - Reject unsafe endpoint ports and normalize API keys and timeouts - Reuse Mantle clients and preserve credential-owned regions - Reject instance writes when connection validation fails - Wait for persisted models before seeding deferred selections test: - Cover endpoint validation, client reuse, region fallback, and async model loading
fix: - Verify selected models without requiring catalog access - Preserve unknown status for skipped same-type models - Allow custom proxy ports only through exact allowlist entries test: - Cover selected-model verification and proxy port trust
|
@coderabbitai pause |
✅ Action performedReviews paused. |
|
Implemented and published in final SHA
The final review pass also aligned selected-model verification with the Python/Go model-level contract and added exact resolve-review-comments:v1 {"platform":"github","item_kind":"review-summary","item_id":"PRR_kwDOK4sStM8AAAABIu-cvQ","body_sha256":"sha256:ab6d8dad894b7c9d675ea4fdf1b20e901547b9874bc678a059518b8dd1d0708c","disposition":"Implement","final_sha":"341aa8d7f5544ebf5f1d499efcb7ccd8afcd6995","supersedes_reply_id":null} |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/llm/chat_model.py (1)
2378-2382: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winBedrock credential parsing raises a raw
JSONDecodeErrorin three drivers. Each Bedrock driver callsjson.loadson the stored credential without converting the failure to a domain error, unlikerag/llm/model_meta.pyLines 71-74. A malformed stored credential surfaces as a parser traceback instead of a clear configuration error.
rag/llm/chat_model.py#L2378-L2382: wrapjson.loads(self.api_key)intry/except (JSONDecodeError, TypeError), raiseValueError("Bedrock API key must be a JSON object") from error, and reject non-dict values.rag/llm/cv_model.py#L1377-L1377: wrapjson.loads(key)inBedrockCV._parse_credentialswith the same conversion and chaining.rag/llm/embedding_model.py#L678-L678: wrapjson.loads(key)inBedrockEmbed.__init__with the same conversion and chaining.Based on learnings: "when catching a JSON parsing (or other) exception and re-raising a domain-specific error (e.g.,
ModelException), use Python exception chaining:raise ModelException(...) from exc".🤖 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 `@rag/llm/chat_model.py` around lines 2378 - 2382, Convert malformed or non-object Bedrock credentials into the domain-specific ValueError instead of exposing raw JSON parsing failures. In rag/llm/chat_model.py lines 2378-2382, wrap credential parsing in the Bedrock driver with JSONDecodeError/TypeError handling, reject non-dict results, and chain ValueError("Bedrock API key must be a JSON object") from the original error; apply the same conversion in BedrockCV._parse_credentials at rag/llm/cv_model.py lines 1377-1377 and BedrockEmbed.__init__ at rag/llm/embedding_model.py lines 678-678.Source: Learnings
🧹 Nitpick comments (5)
internal/handler/providers.go (1)
221-231: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueLog the discovery error for non-Bedrock providers.
If
driver.ListModelsfails for a non-Bedrock provider, the handler discardslistErrand returns only the static catalog. The user sees a partial list with no signal, and operators get no record of the failure. Add a warning log before falling back.♻️ Proposed refactor
liveModels, listErr := driver.ListModels(c.Request.Context(), apiConfig) if listErr != nil { if isBedrockAPIKey { common.ErrorWithCode(c, common.CodeConnectionError, listErr.Error()) return } + common.Logger.Warn("failed to list remote models", + zap.String("provider", providerName), zap.Error(listErr)) } else {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/providers.go` around lines 221 - 231, Update the ListModels error branch in the handler around driver.ListModels so non-Bedrock failures emit a warning containing listErr before continuing with the static catalog fallback. Preserve the existing Bedrock ErrorWithCode response and return behavior, and keep successful liveModels appending unchanged.internal/entity/models/bedrock.go (3)
228-231: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueSimplify
mantleCatalogURL.The function assigns
rootand returns it immediately. Return the call result directly.♻️ Proposed refactor
func mantleCatalogURL(endpointURL string) string { - root := normalizeBedrockEndpoint(bedrockEndpointMantleOpenAI, endpointURL) - return root + return normalizeBedrockEndpoint(bedrockEndpointMantleOpenAI, endpointURL) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/bedrock.go` around lines 228 - 231, Simplify mantleCatalogURL by returning normalizeBedrockEndpoint(bedrockEndpointMantleOpenAI, endpointURL) directly, removing the unnecessary root local variable.
1150-1158: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
slices.Containsinstead of the localcontainsclosure.The file already imports
slicesand usesslices.Containsat Line 1120. The local closure duplicates that behavior.♻️ Proposed refactor
func bedrockModelTypes(modelID string, inputModalities, outputModalities []string) []string { - contains := func(values []string, target string) bool { - for _, value := range values { - if value == target { - return true - } - } - return false - } - if !contains(inputModalities, "TEXT") || strings.Contains(strings.ToLower(modelID), "rerank") { + if !slices.Contains(inputModalities, "TEXT") || strings.Contains(strings.ToLower(modelID), "rerank") { return nil } - if contains(outputModalities, "EMBEDDING") && (strings.HasPrefix(modelID, "amazon.titan-embed-text") || strings.HasPrefix(modelID, "cohere.embed-")) { + if slices.Contains(outputModalities, "EMBEDDING") && (strings.HasPrefix(modelID, "amazon.titan-embed-text") || strings.HasPrefix(modelID, "cohere.embed-")) { return []string{"embedding"} } - if contains(outputModalities, "TEXT") { + if slices.Contains(outputModalities, "TEXT") {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/bedrock.go` around lines 1150 - 1158, Remove the local contains closure from bedrockModelTypes and replace its modality membership checks with the existing slices.Contains helper, preserving the current matching behavior.
1135-1148: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
slices.ContainsFuncfor the prefix scan.
isMantleNonChatModelcan use the importedslicespackage and remove the manual loop.♻️ Proposed refactor
func isMantleNonChatModel(modelID string) bool { - for _, prefix := range mantleNonChatPrefixes { - if strings.HasPrefix(modelID, prefix) { - return true - } - } - return false + return slices.ContainsFunc(mantleNonChatPrefixes, func(prefix string) bool { + return strings.HasPrefix(modelID, prefix) + }) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/bedrock.go` around lines 1135 - 1148, Refactor isMantleNonChatModel to use slices.ContainsFunc over mantleNonChatPrefixes, with the predicate checking strings.HasPrefix(modelID, prefix). Remove the manual loop while preserving the existing boolean result.rag/llm/model_meta.py (1)
77-79: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLog the unsupported-auth-mode early return.
get_model_listreturns an empty list without any log record whenauth_modeis notbedrock_api_key. The caller cannot distinguish "no discovery support" from "no models". Add one log line for this branch.♻️ Proposed change
if config.get("auth_mode") != "bedrock_api_key": + logging.info("Bedrock model discovery skipped: auth_mode %s does not support discovery", config.get("auth_mode")) return [] return await asyncio.to_thread(discover_bedrock_models, config)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 `@rag/llm/model_meta.py` around lines 77 - 79, Update get_model_list’s unsupported-auth-mode branch to emit a log record before returning the empty list when config["auth_mode"] is not "bedrock_api_key". Keep the existing discovery behavior unchanged for the supported mode and use the module’s established logger.Source: Coding guidelines
🤖 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 271-278: Update api/apps/services/provider_api_service.py lines
271-278 to catch asyncio.TimeoutError in the remote model listing handler,
matching the exception used by asyncio.wait_for and the existing handler near
line 674. Update test/unit_test/rag/llm/test_bedrock_api_key.py lines 76-108 so
raise_timeout raises asyncio.TimeoutError, ensuring the test exercises the same
exception class.
In `@rag/llm/bedrock_model_discovery.py`:
- Around line 105-113: Align the Bedrock model classification in the discovery
logic around the output-modality branch with the Go bedrockModelTypes behavior:
do not advertise LLMType.VISION for IMAGE input unless the driver supports it,
or explicitly document and apply the same capability distinction in both paths.
Ensure model_types consistently reflects supported Bedrock completion behavior
across discovery implementations.
In `@rag/llm/rerank_model.py`:
- Around line 337-341: Update the BedrockRerank initialization around model_arn
construction to require a non-empty bedrock_region and invoke the existing
validate_bedrock_region helper, matching BedrockEmbed, BedrockCV, and the
LiteLLM chat path before constructing the ARN.
In `@rag/utils/bedrock_endpoint.py`:
- Around line 52-56: Update normalize_bedrock_endpoint to trim surrounding
whitespace from endpoint_url before removing trailing slashes or performing any
endpoint-type and URL validation, matching the Go normalization behavior while
preserving the existing runtime and root URL handling.
In `@test/unit_test/rag/llm/test_bedrock_api_key.py`:
- Around line 76-108: Update test_list_bedrock_models_times_out_remote_discovery
so its mocked asyncio.wait_for raises asyncio.TimeoutError, matching the
exception produced by the real timeout path and exercising the handler in
list_provider_models. Keep the existing timeout assertion and expected failure
message unchanged.
In `@web/src/locales/ar.ts`:
- Around line 852-863: Add the missing selectModelBeforeVerify translation entry
near the Bedrock locale keys in web/src/locales/ar.ts lines 852-863,
web/src/locales/tr.ts lines 1145-1156, and web/src/locales/zh-traditional.ts
lines 594-605, using accurate Arabic, Turkish, and Traditional Chinese text
respectively so BedrockInstanceCard displays localized validation feedback.
---
Outside diff comments:
In `@rag/llm/chat_model.py`:
- Around line 2378-2382: Convert malformed or non-object Bedrock credentials
into the domain-specific ValueError instead of exposing raw JSON parsing
failures. In rag/llm/chat_model.py lines 2378-2382, wrap credential parsing in
the Bedrock driver with JSONDecodeError/TypeError handling, reject non-dict
results, and chain ValueError("Bedrock API key must be a JSON object") from the
original error; apply the same conversion in BedrockCV._parse_credentials at
rag/llm/cv_model.py lines 1377-1377 and BedrockEmbed.__init__ at
rag/llm/embedding_model.py lines 678-678.
---
Nitpick comments:
In `@internal/entity/models/bedrock.go`:
- Around line 228-231: Simplify mantleCatalogURL by returning
normalizeBedrockEndpoint(bedrockEndpointMantleOpenAI, endpointURL) directly,
removing the unnecessary root local variable.
- Around line 1150-1158: Remove the local contains closure from
bedrockModelTypes and replace its modality membership checks with the existing
slices.Contains helper, preserving the current matching behavior.
- Around line 1135-1148: Refactor isMantleNonChatModel to use
slices.ContainsFunc over mantleNonChatPrefixes, with the predicate checking
strings.HasPrefix(modelID, prefix). Remove the manual loop while preserving the
existing boolean result.
In `@internal/handler/providers.go`:
- Around line 221-231: Update the ListModels error branch in the handler around
driver.ListModels so non-Bedrock failures emit a warning containing listErr
before continuing with the static catalog fallback. Preserve the existing
Bedrock ErrorWithCode response and return behavior, and keep successful
liveModels appending unchanged.
In `@rag/llm/model_meta.py`:
- Around line 77-79: Update get_model_list’s unsupported-auth-mode branch to
emit a log record before returning the empty list when config["auth_mode"] is
not "bedrock_api_key". Keep the existing discovery behavior unchanged for the
supported mode and use the module’s established logger.
🪄 Autofix
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 Plus
Run ID: 5707453a-c431-4c59-959f-477d2e11ae9b
📒 Files selected for processing (47)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.pyinternal/entity/models/anthropic.gointernal/entity/models/bedrock.gointernal/entity/models/bedrock_test.gointernal/entity/models/openai.gointernal/handler/providers.gointernal/handler/providers_test.gointernal/router/router.gointernal/service/model_service.gointernal/service/model_service_test.gorag/llm/bedrock_model_discovery.pyrag/llm/chat_model.pyrag/llm/cv_model.pyrag/llm/embedding_model.pyrag/llm/model_meta.pyrag/llm/rerank_model.pyrag/utils/bedrock_endpoint.pytest/unit_test/rag/llm/conftest.pytest/unit_test/rag/llm/test_bedrock_api_key.pyweb/src/hooks/__tests__/use-fetch-instance-models.test.tsxweb/src/hooks/use-llm-request.tsxweb/src/interfaces/request/llm.tsweb/src/locales/ar.tsweb/src/locales/bg.tsweb/src/locales/de.tsweb/src/locales/en.tsweb/src/locales/fr.tsweb/src/locales/it.tsweb/src/locales/ja.tsweb/src/locales/ko.tsweb/src/locales/ru.tsweb/src/locales/tr.tsweb/src/locales/zh-traditional.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.tsweb/src/pages/user-setting/setting-model/instance-card/interface.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/index.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/interface.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.tsweb/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.tsweb/src/services/llm-service.ts
Normalize runtime and discovery endpoints before validation and use. Return domain errors for malformed credentials and validate rerank regions before creating AWS clients.
|
Reviewed every finding and published the valid fixes in final SHA Implemented:
Not changed after independent verification:
Validation: fresh-context final diff review is CLEAN; Ruff format/check, resolve-review-comments:v1 {"platform":"github","item_kind":"review-summary","item_id":"PRR_kwDOK4sStM8AAAABI7TdYg","body_sha256":"sha256:7be9dda77d6f47d51992935df6af868c00c41296d4b704f73af7d088f3c65221","disposition":"Mixed","final_sha":"074fd5f375b74a598cd1da6b4df7cf838ec259a3","supersedes_reply_id":null} |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (5)
internal/service/model_service.go (2)
1008-1027: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider inlining
buildCheckConnectionAPIConfig.The function only forwards to
buildProviderAPIConfigandshouldVerifyBedrockAPIKeyWithoutModels. The single call site at Line 1056 can call both directly, which removes one indirection and makes the two independent decisions visible.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/model_service.go` around lines 1008 - 1027, Remove buildCheckConnectionAPIConfig and update its sole call site to invoke buildProviderAPIConfig and shouldVerifyBedrockAPIKeyWithoutModels directly, preserving their existing arguments and returned values.
759-762: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the dead loop over
modelInfo.Line 741 returns when
len(modelInfo) > 0. Execution reaches Line 760 only whenmodelInfois empty, so the loop never assigns a status andresultstays empty.♻️ Proposed cleanup
verifyErr := driver.CheckConnection(ctx, apiConfig) - verifyStatus := entity.ModelVerifySuccess - if verifyErr != nil { - verifyStatus = entity.ModelVerifyFail - } - - for _, model := range modelInfo { - result[model.ModelName] = verifyStatus - } if verifyErr != nil { return result, fmt.Errorf("provider %s connection verification failed: %w", providerName, verifyErr) } return result, nilAs per coding guidelines,
**/*.{go,py,ts,tsx,js,jsx,md}: "Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/model_service.go` around lines 759 - 762, Remove the unreachable loop over modelInfo in the surrounding model-status logic; because the earlier return handles non-empty modelInfo, execution here only occurs when it is empty. Preserve the existing result behavior without retaining the dead assignment to result[model.ModelName].Source: Coding guidelines
internal/service/model_service_test.go (2)
209-223: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd a lowercase provider-name case.
shouldVerifyBedrockAPIKeyWithoutModelscompares the provider name exactly, whilebuildProviderAPIConfigusesstrings.EqualFold. A case for"bedrock"locks the comparison once the mismatch ininternal/service/model_service.goLines 1084-1092 is fixed.💚 Proposed test addition
if shouldVerifyBedrockAPIKeyWithoutModels("Bedrock", `{"auth_mode":"access_key_secret"}`, nil) { t.Fatal("SigV4 credentials used the Bedrock API key connection check") } + if !shouldVerifyBedrockAPIKeyWithoutModels("bedrock", apiKey, nil) { + t.Fatal("lowercase provider name did not use the connection check") + } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/model_service_test.go` around lines 209 - 223, Add a lowercase provider-name assertion to TestShouldVerifyBedrockAPIKeyWithoutModels, verifying that "bedrock" with Bedrock API-key credentials and no selected models returns true. This should cover the case-insensitive provider comparison used by shouldVerifyBedrockAPIKeyWithoutModels.
265-270: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the provider driver swap into a test helper.
Lines 265-270 and Lines 347-352 repeat the same lookup, save, and
t.Cleanuprestore ofprovider.ModelDriver. One helper removes the duplication and guarantees identical restore behavior.♻️ Proposed helper
func useBedrockTestDriver(t *testing.T, driver modelModule.ModelDriver) { t.Helper() provider := dao.GetModelProviderManager().FindProvider("Bedrock") if provider == nil { t.Fatal("Bedrock provider is not registered") } original := provider.ModelDriver t.Cleanup(func() { provider.ModelDriver = original }) provider.ModelDriver = driver }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/model_service_test.go` around lines 265 - 270, Extract the repeated Bedrock provider driver lookup, preservation, cleanup, and replacement from the affected tests into a useBedrockTestDriver helper. Make the helper accept *testing.T and modelModule.ModelDriver, mark itself with t.Helper(), retain the missing-provider failure, and update both call sites to use it while preserving identical restoration behavior.api/apps/services/provider_api_service.py (1)
270-270: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the repeated timeout expression into one helper.
max(1, _to_int(os.environ.get("LLM_TIMEOUT_SECONDS"), 10))now appears at Line 270, Line 726, and Line 773. A single helper keeps the clamp and the default in one place.♻️ Proposed refactor
+def _llm_timeout_seconds(default: int = 10) -> int: + return max(1, _to_int(os.environ.get("LLM_TIMEOUT_SECONDS"), default))Then replace each occurrence:
- timeout_seconds = max(1, _to_int(os.environ.get("LLM_TIMEOUT_SECONDS"), 10)) + timeout_seconds = _llm_timeout_seconds()Also applies to: 773-773
🤖 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` at line 270, Extract the repeated LLM timeout calculation into a shared helper near the existing utility functions, preserving the minimum value of 1 and default of 10. Update the timeout assignments at the locations corresponding to lines 270, 726, and 773 to call this helper instead of duplicating the max/_to_int/os.environ expression.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/bedrock.go`:
- Around line 179-181: Normalize key.DiscoveryEndpointURL with
normalizeBedrockEndpoint before passing it to validateBedrockEndpointTarget and
before the subsequent joinBedrockPath flow in resolveBedrockEndpoint, preserving
the normalized value for both validation and path construction.
In `@internal/service/model_service.go`:
- Around line 1084-1092: The Bedrock provider check is case-sensitive while
provider resolution is case-insensitive. In
shouldVerifyBedrockAPIKeyWithoutModels, use strings.EqualFold for the Bedrock
comparison, and in internal/service/model_service_test.go lines 209-223 add
coverage asserting shouldVerifyBedrockAPIKeyWithoutModels("bedrock", apiKey,
nil) returns true.
In `@rag/llm/embedding_model.py`:
- Around line 694-700: Add a timeout parameter to create_bedrock_bearer_client
and use it for the bearer client's connect and read timeouts, while preserving
the discovery profile as its default for existing callers. Update the
bedrock_api_key embedding branch in the embedding model to pass a
runtime-appropriate timeout so encode and encode_queries are not constrained by
discovery settings; retain the existing retry behavior unless required by the
new parameter.
In `@test/unit_test/rag/llm/test_bedrock_api_key.py`:
- Around line 148-173: Update
test_verify_bedrock_api_key_without_models_uses_default_for_invalid_timeout to
observe the timeout passed into the verification flow, matching
test_verify_selected_bedrock_model_uses_default_for_invalid_timeout. Patch or
instrument the relevant verification helper and assert it receives the default
timeout value of 10 when LLM_TIMEOUT_SECONDS is invalid, while preserving the
existing success and empty-results assertions.
In
`@web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx`:
- Around line 60-98: Scope bedrock_discovery_endpoint_url to Bedrock Runtime
mode only: update getBedrockModelListRequest and buildPayload so it is included
or retained only when bedrock_endpoint_type is runtime, and removed for Mantle
types. Apply the same request/response mapping and cleanup across the provider
API service, provider handler, and Bedrock model mappings so stale Runtime
discovery URLs are neither sent nor persisted for Mantle configurations.
In
`@web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx`:
- Around line 131-138: Update the draftModels mapping in setDraftModels to
normalize model.model_types when present, falling back to model.model_type for
the alternate API response shape. Preserve the existing normalizeModelTypes
behavior and add coverage verifying both persisted response shapes retain their
model capabilities.
- Around line 180-182: Update the props passed to the model-derived state around
onInstanceModelsEdited so deferred model mutations do not invoke the
persisted-edit callback. When deferModelMutations is true, pass undefined (or
the existing explicit persisted-state flag) to useModelsDerived; preserve
onInstanceModelsEdited for immediate-persistence mode so deferred edits remain
unsaved until credential submission.
- Around line 121-140: Prevent deferred mode from publishing an empty model
snapshot while instanceModels is still pending. Update useModelsDerived or its
onInstanceModelsChange flow to retain persisted models, or suppress propagation
until hasSeededDeferredModelsRef confirms the seeding effect completed; preserve
normal behavior after seeding. Add a regression test covering saving credentials
before the pending instanceModels query resolves and verify model_info is not
empty.
---
Nitpick comments:
In `@api/apps/services/provider_api_service.py`:
- Line 270: Extract the repeated LLM timeout calculation into a shared helper
near the existing utility functions, preserving the minimum value of 1 and
default of 10. Update the timeout assignments at the locations corresponding to
lines 270, 726, and 773 to call this helper instead of duplicating the
max/_to_int/os.environ expression.
In `@internal/service/model_service_test.go`:
- Around line 209-223: Add a lowercase provider-name assertion to
TestShouldVerifyBedrockAPIKeyWithoutModels, verifying that "bedrock" with
Bedrock API-key credentials and no selected models returns true. This should
cover the case-insensitive provider comparison used by
shouldVerifyBedrockAPIKeyWithoutModels.
- Around line 265-270: Extract the repeated Bedrock provider driver lookup,
preservation, cleanup, and replacement from the affected tests into a
useBedrockTestDriver helper. Make the helper accept *testing.T and
modelModule.ModelDriver, mark itself with t.Helper(), retain the
missing-provider failure, and update both call sites to use it while preserving
identical restoration behavior.
In `@internal/service/model_service.go`:
- Around line 1008-1027: Remove buildCheckConnectionAPIConfig and update its
sole call site to invoke buildProviderAPIConfig and
shouldVerifyBedrockAPIKeyWithoutModels directly, preserving their existing
arguments and returned values.
- Around line 759-762: Remove the unreachable loop over modelInfo in the
surrounding model-status logic; because the earlier return handles non-empty
modelInfo, execution here only occurs when it is empty. Preserve the existing
result behavior without retaining the dead assignment to
result[model.ModelName].
🪄 Autofix
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 Plus
Run ID: 39eee3b3-a767-429d-8fe1-32ad399441da
📒 Files selected for processing (48)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.pyinternal/entity/models/anthropic.gointernal/entity/models/bedrock.gointernal/entity/models/bedrock_test.gointernal/entity/models/openai.gointernal/handler/providers.gointernal/handler/providers_test.gointernal/router/router.gointernal/service/model_service.gointernal/service/model_service_test.gorag/llm/bedrock_model_discovery.pyrag/llm/chat_model.pyrag/llm/cv_model.pyrag/llm/embedding_model.pyrag/llm/model_meta.pyrag/llm/rerank_model.pyrag/utils/bedrock_endpoint.pytest/unit_test/rag/llm/conftest.pytest/unit_test/rag/llm/test_bedrock_api_key.pytest/unit_test/rag/llm/test_bedrock_rerank.pyweb/src/hooks/__tests__/use-fetch-instance-models.test.tsxweb/src/hooks/use-llm-request.tsxweb/src/interfaces/request/llm.tsweb/src/locales/ar.tsweb/src/locales/bg.tsweb/src/locales/de.tsweb/src/locales/en.tsweb/src/locales/fr.tsweb/src/locales/it.tsweb/src/locales/ja.tsweb/src/locales/ko.tsweb/src/locales/ru.tsweb/src/locales/tr.tsweb/src/locales/zh-traditional.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.tsweb/src/pages/user-setting/setting-model/instance-card/interface.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/index.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/interface.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.tsweb/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.tsweb/src/services/llm-service.ts
| Follow-up review handled in commit `221d3f6ba`. Implemented: Go discovery endpoint normalization, case-insensitive Bedrock provider detection, runtime-specific bearer embedding transport policy, discriminating timeout coverage, and Runtime-only discovery endpoint persistence with Mantle stale-value compatibility. The remaining three inline suggestions were verified against the current contracts/state flow and do not represent production failures; detailed replies are attached to those threads. The review-body refactor nits were also evaluated and intentionally left unchanged because they do not affect behavior. |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/handler/providers.go`:
- Around line 274-316: Update buildModelListAPIKey and isBedrockAPIKeyConfig to
compare providerName with “Bedrock” case-insensitively, reusing the existing
strings.EqualFold convention. Preserve all current Bedrock extension
translation, API-key detection, and non-Bedrock behavior so lowercase provider
identifiers follow the same Bedrock paths.
In `@rag/llm/chat_model.py`:
- Around line 2394-2418: Add debug-level, non-secret logging for the new Bedrock
API-key authentication paths: in rag/llm/chat_model.py lines 2394-2418, log the
auth mode, endpoint type, and service before updating completion arguments; in
rag/llm/embedding_model.py lines 694-715, log the Bedrock Runtime bearer-client
path before client creation; and in rag/llm/cv_model.py lines 1400-1414, log the
Runtime or Mantle vision credential path before returning credentials. Do not
include API keys or AWS credentials in any log.
In
`@web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts`:
- Around line 285-290: Update the Bedrock readiness check in the hook’s
`areCatalogCredentialsReady` call to pass `authMode ??
creds.extensions.auth_mode` as the auth mode, preserving the existing fallback
when authMode is unset. Add a hook-level regression test covering an externally
provided authMode with an empty API key so invalid discovery is not started.
🪄 Autofix
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 Plus
Run ID: 949664cb-8996-457a-aa6c-cc3149c37481
📒 Files selected for processing (48)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.pyinternal/entity/models/anthropic.gointernal/entity/models/bedrock.gointernal/entity/models/bedrock_test.gointernal/entity/models/openai.gointernal/handler/providers.gointernal/handler/providers_test.gointernal/router/router.gointernal/service/model_service.gointernal/service/model_service_test.gorag/llm/bedrock_model_discovery.pyrag/llm/chat_model.pyrag/llm/cv_model.pyrag/llm/embedding_model.pyrag/llm/model_meta.pyrag/llm/rerank_model.pyrag/utils/bedrock_endpoint.pytest/unit_test/rag/llm/conftest.pytest/unit_test/rag/llm/test_bedrock_api_key.pytest/unit_test/rag/llm/test_bedrock_rerank.pyweb/src/hooks/__tests__/use-fetch-instance-models.test.tsxweb/src/hooks/use-llm-request.tsxweb/src/interfaces/request/llm.tsweb/src/locales/ar.tsweb/src/locales/bg.tsweb/src/locales/de.tsweb/src/locales/en.tsweb/src/locales/fr.tsweb/src/locales/it.tsweb/src/locales/ja.tsweb/src/locales/ko.tsweb/src/locales/ru.tsweb/src/locales/tr.tsweb/src/locales/zh-traditional.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.tsweb/src/pages/user-setting/setting-model/instance-card/interface.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/index.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/interface.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.tsweb/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.tsweb/src/services/llm-service.ts
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
internal/service/model_service.go (1)
1047-1062: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReuse
validateLocalProviderBaseURLinCheckConnection.
CheckConnectionkeeps an inlinebaseURL == ""check.validateLocalProviderBaseURLtrims whitespace before the check. A whitespace-onlybase_urltherefore passesCheckConnectionbut failsCreateProviderInstanceandAlterProviderInstance. Note thatbaseURLis trimmed at Line 1045, so the two paths agree today; the divergence appears if that trim is removed later. Reusing the helper keeps one validation rule.♻️ Proposed refactor
driver := providerInfo.ModelDriver if strings.EqualFold(providerInfo.Class, "local") { - if baseURL == "" { - return common.CodeDataError, fmt.Errorf("base_url is required for local provider %s", providerName) + if err := validateLocalProviderBaseURL(providerInfo, providerName, baseURL); err != nil { + return common.CodeDataError, err } var err error🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/model_service.go` around lines 1047 - 1062, Update CheckConnection’s local-provider validation to call validateLocalProviderBaseURL instead of performing its inline baseURL check. Preserve the existing CodeDataError response and provider-specific error context, and keep the validation consistent with CreateProviderInstance and AlterProviderInstance.web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx (2)
669-669: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the submit handler.
The form uses an inline arrow handler. Define a named handler and reference it.
As per coding guidelines, "Avoid inline JSX event handlers such as onClick={() => ...} and onChange={(e) => ...}; extract named handlers and reference them by name."
♻️ Proposed refactor
+ const handleFormSubmit = useCallback((event: React.FormEvent) => { + event.preventDefault(); + }, []); + const renderFields = () => ( <Form {...form}> - <form className="space-y-6" onSubmit={(e) => e.preventDefault()}> + <form className="space-y-6" onSubmit={handleFormSubmit}>🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx` at line 669, Extract the inline form submit callback into a named handler within the Bedrock instance card component, then pass that handler by reference to the form’s onSubmit prop. Preserve the existing preventDefault behavior.Source: Coding guidelines
427-443: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse
serializeProviderAPIKeyfor the verify credentials.Line 437 uses
JSON.stringify(payload.api_key ?? '')and Line 461 usesJSON.stringify(payload.api_key). This PR addsserializeProviderAPIKeyinweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.tsfor exactly this normalization, anduse-list-models-picker.tsalready uses it. Use the shared helper in both places so the serialization stays identical.As per coding guidelines, "When old and new implementations coexist, converge on one implementation path unless an external contract requires compatibility."
♻️ Proposed refactor
- apiKey: JSON.stringify(payload.api_key ?? ''), + apiKey: serializeProviderAPIKey(payload.api_key),Update the import at Line 60:
-import { parseApiKeyAsObject } from '../provider-schema/field-config/utils'; +import { + parseApiKeyAsObject, + serializeProviderAPIKey, +} from '../provider-schema/field-config/utils';Apply the same change at Line 461.
🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx` around lines 427 - 443, Update the verify-credentials serialization in transformModelVerify and the corresponding line around the second payload.api_key usage to call the shared serializeProviderAPIKey helper instead of JSON.stringify. Add the helper import from the existing field-config utilities and use it consistently in both locations.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/bedrock_test.go`:
- Around line 253-266: Add wildcard allowlist tests alongside
TestValidateBedrockEndpointAllowsExplicitProxyPort and
TestValidateBedrockEndpointRequiresExactProxyPort: verify a *.-prefixed entry
accepts a matching subdomain, and verify it rejects the bare apex domain. Keep
assertions focused on validateBedrockEndpointTarget success and failure.
In
`@web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx`:
- Around line 274-355: Update the initialValues reset effect around
shouldResetBedrockForm so that after computing nextScope and assigning
pendingCatalogResetRef, it immediately clears the pending reset when nextScope
already matches the current catalogCredentialScopeRef. Preserve the existing
pending-reset flow for scopes that differ, allowing the scope effect to process
those changes.
---
Nitpick comments:
In `@internal/service/model_service.go`:
- Around line 1047-1062: Update CheckConnection’s local-provider validation to
call validateLocalProviderBaseURL instead of performing its inline baseURL
check. Preserve the existing CodeDataError response and provider-specific error
context, and keep the validation consistent with CreateProviderInstance and
AlterProviderInstance.
In
`@web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx`:
- Line 669: Extract the inline form submit callback into a named handler within
the Bedrock instance card component, then pass that handler by reference to the
form’s onSubmit prop. Preserve the existing preventDefault behavior.
- Around line 427-443: Update the verify-credentials serialization in
transformModelVerify and the corresponding line around the second
payload.api_key usage to call the shared serializeProviderAPIKey helper instead
of JSON.stringify. Add the helper import from the existing field-config
utilities and use it consistently in both locations.
🪄 Autofix
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 Plus
Run ID: 0a507f41-a406-4e3f-b97f-19f367390507
📒 Files selected for processing (48)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.pyinternal/entity/models/anthropic.gointernal/entity/models/bedrock.gointernal/entity/models/bedrock_test.gointernal/entity/models/openai.gointernal/handler/providers.gointernal/handler/providers_test.gointernal/router/router.gointernal/service/model_service.gointernal/service/model_service_test.gorag/llm/bedrock_model_discovery.pyrag/llm/chat_model.pyrag/llm/cv_model.pyrag/llm/embedding_model.pyrag/llm/model_meta.pyrag/llm/rerank_model.pyrag/utils/bedrock_endpoint.pytest/unit_test/rag/llm/conftest.pytest/unit_test/rag/llm/test_bedrock_api_key.pytest/unit_test/rag/llm/test_bedrock_rerank.pyweb/src/hooks/__tests__/use-fetch-instance-models.test.tsxweb/src/hooks/use-llm-request.tsxweb/src/interfaces/request/llm.tsweb/src/locales/ar.tsweb/src/locales/bg.tsweb/src/locales/de.tsweb/src/locales/en.tsweb/src/locales/fr.tsweb/src/locales/it.tsweb/src/locales/ja.tsweb/src/locales/ko.tsweb/src/locales/ru.tsweb/src/locales/tr.tsweb/src/locales/zh-traditional.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.tsweb/src/pages/user-setting/setting-model/instance-card/interface.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/index.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/interface.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.tsweb/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.tsweb/src/services/llm-service.ts
|
Round 11 follow-up is complete in aaa0b6e:\n\n- Fix the saved-card catalog reset state so an equal-scope refetch cannot leave a permanent pending reset.\n- Add focused transition tests for no-op, immediate, and deferred catalog invalidation.\n- Add wildcard allowlist coverage for subdomain, apex, and lookalike boundaries.\n- Reuse the shared provider API-key serializer and local-provider base-URL validator.\n- Extract the named form submit handler.\n- Resolve both inline threads (CodeRabbit auto-resolved them after the evidence replies).\n\nValidation: frontend focused Jest 2 suites / 14 tests passed; Oxfmt and Oxlint passed; Go internal/entity/models passed; git diff checks passed. Full frontend type-check remains blocked by unrelated pre-existing errors with none in the touched files. Go internal/service remains blocked on macOS by Pdeathsig and existing native duplicate-symbol link failures. |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
rag/llm/model_meta.py (1)
72-75: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueLog the non-API-key early return.
Line 74 returns an empty list without any signal. The discovery path logs at
rag/llm/bedrock_model_discovery.pyLines 168 and 181, but this branch does not. If a caller ever reaches this branch, the empty catalog is indistinguishable from a discovery that found nothing.Add a debug log with the auth mode only. Do not log the credential payload.
As per coding guidelines,
**/*.py: Add logging for new flows.♻️ Proposed change
config = parse_bedrock_credentials(self.api_key) if config.get("auth_mode") != "bedrock_api_key": + logging.debug("Skipping Bedrock model discovery for auth_mode=%s", config.get("auth_mode")) return [] return await asyncio.to_thread(discover_bedrock_models, config)🤖 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 `@rag/llm/model_meta.py` around lines 72 - 75, Add a debug log immediately before the non-API-key early return in the model discovery flow, using the auth mode from config and excluding all credential payload fields. Keep the existing empty-list return and Bedrock API-key discovery behavior unchanged.Source: Coding guidelines
web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts (1)
277-297: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDocument and cover the Bedrock auto-fetch delay.
The
500value has no named constant and no comment explaining why Bedrock needs a delay while other providers use0. Extract it into a named constant (e.g.BEDROCK_DISCOVERY_DELAY_MS) with a short comment on the rationale (e.g., debounce endpoint/region typing before firing discovery).Add a hook-level test with fake timers that verifies the Bedrock branch waits before calling
handleListModels, and that a dependency change before the timer fires cancels the pending call. Without this, a future edit could remove or shorten the delay and cause premature invalid discovery requests, with no test to catch 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 `@web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts` around lines 277 - 297, In the auto-fetch effect around hasAutoFetchedRef, replace the inline Bedrock delay value with a named BEDROCK_DISCOVERY_DELAY_MS constant and briefly document that it debounces endpoint/region input before discovery. Add a hook-level fake-timer test covering that Bedrock waits before handleListModels runs and that changing dependencies before the timer fires cancels the pending call.
🤖 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 `@rag/llm/chat_model.py`:
- Around line 2427-2439: Update the iam_role handling in
_construct_completion_args to cache assumed Bedrock credentials together with
their expiration, reuse them for unexpired completions, and refresh them only
after expiry. Move the synchronous boto3 STS assume_role call to an
off-event-loop execution path while preserving existing error handling and
credential fields passed to litellm.
In `@test/unit_test/rag/llm/test_bedrock_api_key.py`:
- Around line 615-631: Update test_embedding_uses_request_scoped_bearer_client
to accept the monkeypatch fixture and remove LLM_TIMEOUT_SECONDS and
LLM_MAX_RETRIES from the environment before constructing BedrockEmbed, matching
the isolation used by test_list_bedrock_models_times_out_remote_discovery. Keep
the existing client and assert_called_once_with expectations unchanged.
---
Nitpick comments:
In `@rag/llm/model_meta.py`:
- Around line 72-75: Add a debug log immediately before the non-API-key early
return in the model discovery flow, using the auth mode from config and
excluding all credential payload fields. Keep the existing empty-list return and
Bedrock API-key discovery behavior unchanged.
In
`@web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts`:
- Around line 277-297: In the auto-fetch effect around hasAutoFetchedRef,
replace the inline Bedrock delay value with a named BEDROCK_DISCOVERY_DELAY_MS
constant and briefly document that it debounces endpoint/region input before
discovery. Add a hook-level fake-timer test covering that Bedrock waits before
handleListModels runs and that changing dependencies before the timer fires
cancels the pending call.
🪄 Autofix
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 Plus
Run ID: 6704406f-1224-4489-845e-9866b419f93e
📒 Files selected for processing (48)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.pyinternal/entity/models/anthropic.gointernal/entity/models/bedrock.gointernal/entity/models/bedrock_test.gointernal/entity/models/openai.gointernal/handler/providers.gointernal/handler/providers_test.gointernal/router/router.gointernal/service/model_service.gointernal/service/model_service_test.gorag/llm/bedrock_model_discovery.pyrag/llm/chat_model.pyrag/llm/cv_model.pyrag/llm/embedding_model.pyrag/llm/model_meta.pyrag/llm/rerank_model.pyrag/utils/bedrock_endpoint.pytest/unit_test/rag/llm/conftest.pytest/unit_test/rag/llm/test_bedrock_api_key.pytest/unit_test/rag/llm/test_bedrock_rerank.pyweb/src/hooks/__tests__/use-fetch-instance-models.test.tsxweb/src/hooks/use-llm-request.tsxweb/src/interfaces/request/llm.tsweb/src/locales/ar.tsweb/src/locales/bg.tsweb/src/locales/de.tsweb/src/locales/en.tsweb/src/locales/fr.tsweb/src/locales/it.tsweb/src/locales/ja.tsweb/src/locales/ko.tsweb/src/locales/ru.tsweb/src/locales/tr.tsweb/src/locales/zh-traditional.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.tsweb/src/pages/user-setting/setting-model/instance-card/interface.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/index.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/interface.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.tsweb/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.tsweb/src/services/llm-service.ts
|
Round 12 follow-up is complete in a34711c:\n\n- Move Bedrock IAM-role STS calls off the event loop.\n- Cache credentials per LiteLLM instance and (role ARN, region), refresh before Expiration, and single-flight concurrent refreshes.\n- Cover reuse/off-loop execution, expiry refresh, concurrent refresh, and failure retry.\n- Isolate the embedding default transport test from ambient environment variables.\n- Add the non-API-key discovery debug signal.\n- Name and document the Bedrock catalog debounce, with a fake-timer cancellation regression test.\n- Resolve both inline threads.\n\nValidation: Ruff check/format, py_compile, Oxfmt/Oxlint, frontend focused Jest 1 suite / 11 tests, and git diff checks passed. Python pytest remains unavailable in this local environment because its runtime dependencies (including nltk/litellm) are not installed. |
|
@coderabbitai full review |
✅ Action performedFull review finished. |
|
@coderabbitai resume |
|
Addressed the latest save-state review findings in
Local validation: 4 focused Jest suites / 33 tests passed; touched files pass Oxfmt, Oxlint, and @coderabbitai full review |
|
If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! ✅ Action performedFull review finished. |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/llm/embedding_model.py (1)
722-741: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winForward
endpoint_urlinto SigV4 Bedrock runtime clients.
resolve_bedrock_endpointreturns a runtime endpoint URL foraccess_key_secret,iam_role, andassume_role, but those branches buildboto3.client("bedrock-runtime", ...)withoutendpoint_url. Configure the runtime client with the returned URL in each SigV4 branch, or reject a non-emptyendpoint_urlfor those modes. Also passregion_name=self.bedrock_regionwhen creating theiam_roleBedrock runtime client.🤖 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 `@rag/llm/embedding_model.py` around lines 722 - 741, Update the Bedrock runtime client creation in the access_key_secret, iam_role, and assume_role branches to pass the endpoint URL returned by resolve_bedrock_endpoint, and ensure the iam_role client also receives region_name=self.bedrock_region. Keep all SigV4 authentication credentials and existing mode handling unchanged.
🧹 Nitpick comments (6)
rag/llm/chat_model.py (1)
2352-2380: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd non-secret logging for the role-refresh flow.
_assume_bedrock_roleperforms an STS call and caches the result. It emits no log for a cache miss, a refresh, or a failure. Log the region and a role identifier at debug level before the STS call. Do not log the access key, secret key, or session token.As per coding guidelines,
**/*.py: Add logging for new flows.📝 Proposed logging
import boto3 from botocore.exceptions import BotoCoreError, ClientError + logging.debug("Refreshing Bedrock IAM-role credentials: region=%s cached=%s", region_name, cached is not None) try: response = boto3.client("sts", region_name=region_name).assume_role(RoleArn=role_arn, RoleSessionName="BedrockSession") except (BotoCoreError, ClientError) as error: + logging.warning("Failed to assume Bedrock AWS role in region %s", region_name) raise ValueError("Failed to assume Bedrock AWS role") from error🤖 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 `@rag/llm/chat_model.py` around lines 2352 - 2380, Update _assume_bedrock_role to emit a debug log immediately before the STS assume_role call, including region_name and a non-secret role identifier derived from role_arn. Ensure the message covers the role-refresh/cache-miss flow without logging credentials or tokens, and use the module’s existing logger.Source: Coding guidelines
internal/entity/models/bedrock.go (1)
1163-1174: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReplace the local
containsclosure withslices.Contains.
slicesis already imported and used at Line 1133. The local closure duplicates that behavior.♻️ Proposed refactor
func bedrockModelTypes(modelID string, inputModalities, outputModalities []string) []string { - contains := func(values []string, target string) bool { - for _, value := range values { - if value == target { - return true - } - } - return false - } - if !contains(inputModalities, "TEXT") || strings.Contains(strings.ToLower(modelID), "rerank") { + if !slices.Contains(inputModalities, "TEXT") || strings.Contains(strings.ToLower(modelID), "rerank") { return nil } - if contains(outputModalities, "EMBEDDING") && (strings.HasPrefix(modelID, "amazon.titan-embed-text") || strings.HasPrefix(modelID, "cohere.embed-")) { + if slices.Contains(outputModalities, "EMBEDDING") && (strings.HasPrefix(modelID, "amazon.titan-embed-text") || strings.HasPrefix(modelID, "cohere.embed-")) { return []string{"embedding"} } - if contains(outputModalities, "TEXT") { + if slices.Contains(outputModalities, "TEXT") {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/bedrock.go` around lines 1163 - 1174, In bedrockModelTypes, remove the local contains closure and use the existing slices.Contains helper for the inputModalities check, preserving the current TEXT presence and rerank conditions.api/apps/services/provider_api_service.py (1)
268-278: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the repeated Bedrock timeout computation into one helper.
max(1, _to_int(os.environ.get("LLM_TIMEOUT_SECONDS"), 10))appears at Line 270, Line 726, and Line 773. A future change to the default or the floor must touch three sites. Extract a single module-level helper and call it from all three locations.♻️ Proposed helper
+def _verification_timeout_seconds() -> int: + return max(1, _to_int(os.environ.get("LLM_TIMEOUT_SECONDS"), 10))Then replace each inline expression with
_verification_timeout_seconds().Also applies to: 724-736, 773-773
🤖 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 268 - 278, Extract the repeated timeout expression into a module-level helper named _verification_timeout_seconds(), preserving the existing environment key, default, and minimum floor. Replace the inline computation at the Bedrock model-listing flow and the corresponding locations around the other two occurrences with calls to this helper.web/src/pages/user-setting/setting-model/index.test.tsx (1)
132-138: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the global
Reactassignment if the mocks no longer need it.Lines 133 and 137 write
ReactontoglobalThis. Each mock factory already callsjest.requireActual('react')and holds its own reference. A global shim hides the real dependency and can mask a missing import in a future mock. Delete thebeforeAll/afterAllpair and confirm the suite still passes.🤖 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 `@web/src/pages/user-setting/setting-model/index.test.tsx` around lines 132 - 138, Remove the beforeAll and afterAll hooks that assign or delete globalThis.React in the test setup, since the mock factories already obtain React through jest.requireActual('react'). Keep the existing mock references unchanged and verify the test suite still passes without the global shim.api/apps/restful_apis/provider_api.py (1)
248-267: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueMerge the API key assignment with the query fallback.
get_data()preserves the request body for the following Quart 0.20.0get_json()call, so no change is needed there. Use one assignment forapi_keysuch asapi_key = body.get("api_key") or request.args.get("api_key").🤖 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 248 - 267, Update the provider model-listing handler to assign api_key only once, combining body.get("api_key") with request.args.get("api_key") as the fallback; remove the earlier standalone api_key assignment while preserving the existing base_url, region, extensions validation, and service call.web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts (1)
984-1017: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCompute
acknowledgedModelInfooutside thesetQueryDataupdater.The updater currently mutates
acknowledgedModelInfofrom insidesetQueryData. TanStack Query expects the updater to return new cache data immutably, so build the acknowledged list after writing to the cache instead.🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts` around lines 984 - 1017, Update the logic around setQueryData and acknowledgedModelInfo so the updater only computes and returns the immutable next model list, without mutating acknowledgedModelInfo. After setQueryData completes, derive acknowledgedModelInfo from the resulting cached instance models and then invoke onInstanceModelsEdited with that list when available.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/service/model_service.go`:
- Around line 573-575: Trim baseURL and region once at the start of both
CreateProviderInstance and AlterProviderInstance, before verifyProviderAPIKey or
validateLocalProviderBaseURL runs, then use those trimmed variables for
verification and persistence into extra. Ensure the stored values exactly match
the values used during provider verification.
---
Outside diff comments:
In `@rag/llm/embedding_model.py`:
- Around line 722-741: Update the Bedrock runtime client creation in the
access_key_secret, iam_role, and assume_role branches to pass the endpoint URL
returned by resolve_bedrock_endpoint, and ensure the iam_role client also
receives region_name=self.bedrock_region. Keep all SigV4 authentication
credentials and existing mode handling unchanged.
---
Nitpick comments:
In `@api/apps/restful_apis/provider_api.py`:
- Around line 248-267: Update the provider model-listing handler to assign
api_key only once, combining body.get("api_key") with
request.args.get("api_key") as the fallback; remove the earlier standalone
api_key assignment while preserving the existing base_url, region, extensions
validation, and service call.
In `@api/apps/services/provider_api_service.py`:
- Around line 268-278: Extract the repeated timeout expression into a
module-level helper named _verification_timeout_seconds(), preserving the
existing environment key, default, and minimum floor. Replace the inline
computation at the Bedrock model-listing flow and the corresponding locations
around the other two occurrences with calls to this helper.
In `@internal/entity/models/bedrock.go`:
- Around line 1163-1174: In bedrockModelTypes, remove the local contains closure
and use the existing slices.Contains helper for the inputModalities check,
preserving the current TEXT presence and rerank conditions.
In `@rag/llm/chat_model.py`:
- Around line 2352-2380: Update _assume_bedrock_role to emit a debug log
immediately before the STS assume_role call, including region_name and a
non-secret role identifier derived from role_arn. Ensure the message covers the
role-refresh/cache-miss flow without logging credentials or tokens, and use the
module’s existing logger.
In `@web/src/pages/user-setting/setting-model/index.test.tsx`:
- Around line 132-138: Remove the beforeAll and afterAll hooks that assign or
delete globalThis.React in the test setup, since the mock factories already
obtain React through jest.requireActual('react'). Keep the existing mock
references unchanged and verify the test suite still passes without the global
shim.
In
`@web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts`:
- Around line 984-1017: Update the logic around setQueryData and
acknowledgedModelInfo so the updater only computes and returns the immutable
next model list, without mutating acknowledgedModelInfo. After setQueryData
completes, derive acknowledgedModelInfo from the resulting cached instance
models and then invoke onInstanceModelsEdited with that list when available.
🪄 Autofix
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 Plus
Run ID: 663e8219-91b2-4d13-8082-a629b77db77b
📒 Files selected for processing (52)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.pyinternal/entity/models/anthropic.gointernal/entity/models/bedrock.gointernal/entity/models/bedrock_test.gointernal/entity/models/openai.gointernal/handler/providers.gointernal/handler/providers_test.gointernal/router/router.gointernal/service/model_service.gointernal/service/model_service_test.gorag/llm/bedrock_model_discovery.pyrag/llm/chat_model.pyrag/llm/cv_model.pyrag/llm/embedding_model.pyrag/llm/model_meta.pyrag/llm/rerank_model.pyrag/utils/bedrock_endpoint.pytest/unit_test/rag/llm/conftest.pytest/unit_test/rag/llm/test_bedrock_api_key.pytest/unit_test/rag/llm/test_bedrock_rerank.pyweb/src/hooks/__tests__/use-fetch-instance-models.test.tsxweb/src/hooks/use-llm-request.tsxweb/src/interfaces/request/llm.tsweb/src/locales/ar.tsweb/src/locales/bg.tsweb/src/locales/de.tsweb/src/locales/en.tsweb/src/locales/fr.tsweb/src/locales/it.tsweb/src/locales/ja.tsweb/src/locales/ko.tsweb/src/locales/ru.tsweb/src/locales/tr.tsweb/src/locales/zh-traditional.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/index.test.tsxweb/src/pages/user-setting/setting-model/index.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.tsweb/src/pages/user-setting/setting-model/instance-card/hooks.test.tsxweb/src/pages/user-setting/setting-model/instance-card/hooks.tsxweb/src/pages/user-setting/setting-model/instance-card/interface.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/index.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/interface.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.tsweb/src/pages/user-setting/setting-model/provider-schema/field-config/utils.tsweb/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.tsweb/src/services/llm-service.ts
✅ Action performedReviews resumed. |
fix: - align Bedrock discovery, endpoint, region, and credential semantics across Python, Go, and the web UI - make provider instance and model persistence atomic with strict request normalization - serialize settings saves with acknowledged model mutations and canonical provider payloads test: - cover malformed requests, rollback paths, capability candidates, cache acknowledgements, and settings races
|
Latest review follow-up is complete in b9cd2ac.
Validation: 8 focused frontend suites / 60 tests passed; changed frontend paths pass Oxlint and have no new type-check diagnostics; Ruff check/format, Python py_compile, Gofmt, and git diff --check passed. Go handler/service tests remain blocked by the existing macOS Pdeathsig build incompatibility and native duplicate-symbol link failures; focused Python pytest remains unavailable because this environment lacks nltk/quart. |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
web/src/pages/user-setting/setting-model/index.tsx (1)
229-266: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winInvalidate the instance query after partial batch success.
If one card save succeeds and a later card returns a nonzero code, the early return skips lines 264-266. The acknowledged draft is removed or the saved baseline is updated, but the instance cache stays stale. The newly persisted instance can disappear from the page until another refetch.
Track whether any request succeeded. Invalidate in
finallywhen that flag is set.Proposed fix
+ let acknowledged = false; try { // ... for (const { cardId, ref, payload } of validations) { if (!payload) continue; if (payload.apiKind === 'add') { const ret = await addProviderInstance(payload.payload as any); if (ret?.code !== 0) { return; } + acknowledged = true; // ... } else { const ret = await updateProviderInstance(payload.payload as any); if (ret?.code !== 0) { return; } + acknowledged = true; ref.markSaved(payload.payload); } } - queryClient.invalidateQueries({ - queryKey: LlmKeys.providerInstances(providerQueryName), - }); } finally { + if (acknowledged) { + queryClient.invalidateQueries({ + queryKey: LlmKeys.providerInstances(providerQueryName), + }); + } setSaving(false); }🤖 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 `@web/src/pages/user-setting/setting-model/index.tsx` around lines 229 - 266, Track whether any addProviderInstance or updateProviderInstance call succeeds in the validation loop, and set that flag before continuing to later cards. Move the providerInstances query invalidation into a finally block so it runs even when a later request returns a nonzero code, but only invalidate when at least one request was acknowledged.web/src/pages/user-setting/setting-model/instance-card/hooks.tsx (1)
572-583: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winOmit
model_infofrom saved-instance saves until the model list is authoritative.
modelInfoRef.currentstarts empty and the update API treats an explicit emptymodel_infoas “no selected models”, deleting existing models. IfbuildPayload()can run before the model selection query/user changes are settled, it sends a destructivemodel_info: []. Preserve a separate not-loaded state, clear it only when authority is established, and include a regression test for saving before model selection is loaded/dirty.🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/hooks.tsx` around lines 572 - 583, Update buildPayload and the surrounding model-selection state so an empty modelInfoRef.current remains distinguishable from an authoritative empty selection. Until the model list is loaded or user changes establish authority, buildPayload must omit model_info rather than pass an empty array to buildPayloadFromValues; once authoritative, preserve intentional empty selections. Add a regression test covering save before model selection is loaded or dirty.
🧹 Nitpick comments (15)
internal/handler/providers.go (2)
738-750: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
req.ModelInfois already checked fornilat Line 722.The guard at Line 747 cannot be false. Assign
modelInfodirectly.♻️ Proposed refactor
- var modelInfo []service.CreateInstanceModelInfo - if req.ModelInfo != nil { - modelInfo = *req.ModelInfo - } + modelInfo := *req.ModelInfo🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/providers.go` around lines 738 - 750, In the handler code before AlterProviderInstance, remove the redundant nil check around req.ModelInfo and assign modelInfo directly from req.ModelInfo, preserving the existing call arguments and behavior.
701-725: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low value
AlterProviderInstancevalidates request fields before it checksuser_id. The handler returns field-level validation errors to unauthenticated callers, and the new handler test depends on that ordering because it sets nouser_id.
internal/handler/providers.go#L701-L725: move theuser_idcheck above thehasFieldpresence checks and the null checks.internal/handler/providers_test.go#L87-L107: callctx.Set("user_id", "user-1")before invoking the handler so the assertion stays valid after the ordering change.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/providers.go` around lines 701 - 725, In internal/handler/providers.go lines 701-725, update AlterProviderInstance to perform the user_id authentication check before required-field presence and null validation, preventing unauthenticated callers from receiving field-level errors. In internal/handler/providers_test.go lines 87-107, set user_id to "user-1" on the context before invoking the handler so the existing validation assertion remains authenticated and valid.internal/service/model_service.go (3)
2193-2211: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDeclare the transaction-local errors inside the closure.
Line 2195 assigns the function-scope
errdeclared at Line 2140. Line 2206 then declares a newerrwith:=, and Line 2300 reuses that inner variable. The code compiles and behaves correctly because the closure returns before Line 2321 reads the transaction result. The mixed scopes make a future edit easy to break. Use distinct local variables inside the closure.Also applies to: 2300-2304
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/model_service.go` around lines 2193 - 2211, Declare transaction-local errors within the closure instead of assigning the function-scope err. Update the json.Unmarshal and subsequent transaction operations around existingExtra, extraBytes, and modelInstanceDAO.UpdateByID to use a consistently scoped local error variable, including the code around the referenced later error handling.
1251-1260: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winClient-supplied invalid
model_typevalues now produce a server error on theCheckConnectionpath.
verifyProviderModelreturns a validation error for a missing name or an unsupported type.CheckConnectionmaps anyverifyErrtocommon.CodeServerErrorat Line 1157.CreateProviderInstanceandAlterProviderInstancereject the same input earlier withcommon.CodeDataErrorthroughnormalizeCreateInstanceModelInfo. A/connection/verifyrequest with an unsupportedmodel_typetherefore returns a 500-class code for a client input error.Normalize the
CheckConnectionmodel list before verification and returncommon.CodeDataError.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/model_service.go` around lines 1251 - 1260, Update the CheckConnection flow to normalize its client-supplied model list with normalizeCreateInstanceModelInfo before calling verifyProviderModel, and map normalization failures to common.CodeDataError. Preserve verifyProviderModel for subsequent validation while ensuring unsupported model_type values follow the same client-error response as CreateProviderInstance and AlterProviderInstance.
3986-3989: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRefactor
addModelToInstanceDBto useentity.ModelTypeFromStrings.
entity.ModelTypeFromStringsalready exists and uses the same OR-basedModelTypeFromStringloop as the bitmask code atinternal/service/model_service.go:870-873; replace that duplicate loop with the helper for the model type input used there.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/model_service.go` around lines 3986 - 3989, Update addModelToInstanceDB to replace the normalizeModelTypes call with entity.ModelTypeFromStrings for request.ModelTypes, preserving the existing error return behavior and using the helper’s returned model-type value directly.api/apps/services/provider_api_service.py (3)
520-533: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRename the inner
update_dictand drop the always-true guard.Line 522 reuses the name
update_dictfrom Line 470. The instance update already ran at Line 488, so the behavior is correct, but the shadowing makes the transaction body hard to read. Line 531 always assigns"extra", so theif update_dict:check at Line 532 is always true.♻️ Proposed refactor
if model_name in existing_model_names: # Update existing model - update_dict = {} + model_update_dict = {} if isinstance(model.get("model_type"), (str, list)): target_model_type = calculate_model_type(model["model_type"]) if target_model_type != existing_model_names[model_name].model_type: - update_dict["model_type"] = target_model_type + model_update_dict["model_type"] = target_model_type merged_extra = json.loads(existing_model_names[model_name].extra) if existing_model_names[model_name].extra else {} merged_extra.update(model.get("extra") or {}) if "max_tokens" in model: merged_extra.update({"max_tokens": model["max_tokens"]}) - update_dict["extra"] = json.dumps(merged_extra) - if update_dict: - TenantModelService.update_model(existing_model_names[model_name].id, update_dict) + model_update_dict["extra"] = json.dumps(merged_extra) + TenantModelService.update_model(existing_model_names[model_name].id, model_update_dict)🤖 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 520 - 533, In the existing-model branch, rename the inner update_dict variable to a distinct name such as model_update_dict, and remove the redundant if update_dict guard because the "extra" field is always assigned. Call TenantModelService.update_model unconditionally with the renamed update payload while preserving the existing model_type and extra merge logic.
1323-1329: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
model_typeis always a list after normalization, so Line 1351 is dead.
_normalize_model_inforeturnsmodel_typeas a list at Line 1328. Theisinstance(model_type, str)branch at Line 1351 can no longer run. Remove it.♻️ Proposed refactor
- llms = factory_info[0].get("llm", []) - if isinstance(model_type, str): - model_type = [model_type] - + llms = factory_info[0].get("llm", []) model_type_bin = calculate_model_type(model_type)Also applies to: 1351-1352
🤖 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 1323 - 1329, In add_model_to_instance, remove the unreachable isinstance(model_type, str) branch and its associated handling because _normalize_model_info guarantees model_type is a list. Preserve the remaining list-based model type processing unchanged.
402-402: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse an explicit optional annotation for
model_info.Ruff reports RUF013 on this signature.
model_info: list[dict] = Noneis an implicitOptional. The function relies onmodel_info is Noneat Lines 501 and 539, so theNonedefault is intentional. Declare it explicitly.♻️ Proposed refactor
- model_info: list[dict] = None, + model_info: list[dict] | None = None,🤖 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` at line 402, Update the model_info parameter annotation in the affected function signature to explicitly allow None while retaining its existing default and the model_info is None behavior.Source: Linters/SAST tools
internal/dao/tenant_model_instance.go (1)
44-52: 🗄️ Data Integrity & Integration | 🔵 TrivialAdd a unique constraint to make the duplicate-instance check race-safe.
CreateInTransactionreads the existing row and then inserts. Two concurrent create requests can both pass the check under read-committed isolation and insert two instances with the sameprovider_idandinstance_name. Thetenant_model_instanceschema inapi/db/db_models.pyLines 1394-1403 declares no unique index for that pair, unliketenant_model_provider, which declares one. A unique index on(provider_id, instance_name)would let the database reject the duplicate, and the handler could map the constraint violation to the existing "already exists" error.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/dao/tenant_model_instance.go` around lines 44 - 52, Add a database-level unique constraint or unique index on the tenant_model_instance provider_id and instance_name columns in the schema definition, then update CreateInTransaction to translate the resulting duplicate-key constraint error into the existing “instance already exists” response while preserving other errors.internal/handler/providers_test.go (1)
87-107: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThis test depends on validation running before the
user_idcheck.The request context never sets
user_id. The test passes only becauseAlterProviderInstancevalidatesmodel_infobefore it readsuser_id. If the handler moves the authorization check earlier, this test returnsCodeUnauthorizedinstead. Setuser_idin the test context to make the assertion independent of that ordering.💚 Proposed change
ctx.Request.Header.Set("Content-Type", "application/json") + ctx.Set("user_id", "user-1") (&ProviderHandler{}).AlterProviderInstance(ctx)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/providers_test.go` around lines 87 - 107, Update TestAlterProviderInstanceRejectsNullModelInfo to set a valid user_id in the Gin test context before invoking AlterProviderInstance, so the test reaches model_info validation regardless of authorization-check ordering.web/src/pages/user-setting/setting-model/index.tsx (1)
64-64: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
useTranslationfor the new flow translation.Replace the new
useTranslate('flow')call withuseTranslation('flow'). This keeps new translation usage on the standard i18next hook.🤖 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 `@web/src/pages/user-setting/setting-model/index.tsx` at line 64, Replace the new useTranslate('flow') call with the standard useTranslation('flow') hook in the component, preserving the existing tFlow alias and translation behavior.Source: Coding guidelines
web/src/pages/user-setting/setting-model/instance-card/add-custom-model-dialog.tsx (1)
211-218: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the new JSX event handlers into named handlers.
web/src/pages/user-setting/setting-model/instance-card/add-custom-model-dialog.tsx#L211-L218: create a named switch-change handler that receiveschecked,fieldProps, and the option value.web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx#L513-L526: create a named model-selection handler or handler factory fortoggleModel(model.name).As per coding guidelines, avoid inline JSX event handlers such as
onClick={() => ...}andonChange={(event) => ...}.🤖 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 `@web/src/pages/user-setting/setting-model/instance-card/add-custom-model-dialog.tsx` around lines 211 - 218, Extract the inline switch handler in add-custom-model-dialog.tsx (lines 211-218) into a named handler accepting checked, fieldProps, and the option value, while preserving the loading/disabled guard and value update behavior. In models-section/index.tsx (lines 513-526), replace the inline model-selection callback with a named handler or handler factory that invokes toggleModel(model.name).Source: Coding guidelines
web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts (1)
128-128: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAlign the callback documentation with batch updates.
useModelMutationscallsonInstanceModelsEditedafter a successful batch instance update. Lines 110-126 state that the callback fires only for PATCH edits. Update this contract so host callers handle both acknowledged paths correctly.As per coding guidelines, remove stale documentation rather than preserving 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 `@web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts` at line 128, Update the documentation for onInstanceModelsEdited to describe invocation after successful batch instance updates, including both acknowledged update paths rather than only PATCH edits. Remove the stale PATCH-only wording while preserving the callback signature and behavior.Source: Coding guidelines
web/src/pages/user-setting/setting-model/index.test.tsx (2)
23-24: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse PascalCase for new top-level test constants.
Rename the new top-level constants to PascalCase.
web/src/pages/user-setting/setting-model/index.test.tsx#L23-L24: RenamemockGetSavePayloadto a PascalCase constant.web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts#L13-L15: Rename the new top-level mutation mock constants to PascalCase.web/src/pages/user-setting/setting-model/instance-card/models-section/index.test.tsx#L11-L17: Rename the new top-level test mock constants to PascalCase.As per coding guidelines, use PascalCase for top-level constants.
🤖 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 `@web/src/pages/user-setting/setting-model/index.test.tsx` around lines 23 - 24, Rename the top-level test constants to PascalCase and update all references: in web/src/pages/user-setting/setting-model/index.test.tsx lines 23-24, rename mockGetSavePayload and mockMutationCount; in web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts lines 13-15, rename the new mutation mock constants; and in web/src/pages/user-setting/setting-model/instance-card/models-section/index.test.tsx lines 11-17, rename the new test mock constants. No behavioral changes are needed.Source: Coding guidelines
81-116: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReplace inline test-double event handlers with named handlers.
Extract the inline click handlers into named functions before passing them to the test components.
web/src/pages/user-setting/setting-model/index.test.tsx#L81-L116: Replace the inlineonClickhandlers in the header and sidebar test doubles.web/src/pages/user-setting/setting-model/instance-card/models-section/index.test.tsx#L74-L132: Replace the inlineonClickhandlers in the dialog and model-row test doubles.As per coding guidelines, avoid inline JSX event handlers.
🤖 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 `@web/src/pages/user-setting/setting-model/index.test.tsx` around lines 81 - 116, Replace the inline onClick handlers in the ProviderHeaderBar and Sidebar test doubles in web/src/pages/user-setting/setting-model/index.test.tsx:81-116 with named handler functions defined before they are passed to the test elements. Apply the same change to the dialog and model-row test doubles in web/src/pages/user-setting/setting-model/instance-card/models-section/index.test.tsx:74-132, preserving each handler’s existing behavior.Source: Coding guidelines
🤖 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 508-533: Guard the extra-field merge in the existing-model update
path so missing model["extra"] does not raise when verify is false. Update the
logic around merged_extra and model["extra"] to merge only when the value is
present and a dict, while preserving max_tokens handling and existing model
updates.
In `@rag/llm/embedding_model.py`:
- Around line 734-744: Update BedrockEmbed.__init__ so iam_role credentials are
supplied through a refreshable, scope-cached role credential provider rather
than a one-time sts_client.assume_role result and static aws_* values. Reuse or
expose the chat model’s provider and _BEDROCK_ROLE_REFRESH_SKEW_SECONDS
behavior, ensuring credentials refresh before expiration while preserving the
existing Bedrock runtime client configuration.
---
Outside diff comments:
In `@web/src/pages/user-setting/setting-model/index.tsx`:
- Around line 229-266: Track whether any addProviderInstance or
updateProviderInstance call succeeds in the validation loop, and set that flag
before continuing to later cards. Move the providerInstances query invalidation
into a finally block so it runs even when a later request returns a nonzero
code, but only invalidate when at least one request was acknowledged.
In `@web/src/pages/user-setting/setting-model/instance-card/hooks.tsx`:
- Around line 572-583: Update buildPayload and the surrounding model-selection
state so an empty modelInfoRef.current remains distinguishable from an
authoritative empty selection. Until the model list is loaded or user changes
establish authority, buildPayload must omit model_info rather than pass an empty
array to buildPayloadFromValues; once authoritative, preserve intentional empty
selections. Add a regression test covering save before model selection is loaded
or dirty.
---
Nitpick comments:
In `@api/apps/services/provider_api_service.py`:
- Around line 520-533: In the existing-model branch, rename the inner
update_dict variable to a distinct name such as model_update_dict, and remove
the redundant if update_dict guard because the "extra" field is always assigned.
Call TenantModelService.update_model unconditionally with the renamed update
payload while preserving the existing model_type and extra merge logic.
- Around line 1323-1329: In add_model_to_instance, remove the unreachable
isinstance(model_type, str) branch and its associated handling because
_normalize_model_info guarantees model_type is a list. Preserve the remaining
list-based model type processing unchanged.
- Line 402: Update the model_info parameter annotation in the affected function
signature to explicitly allow None while retaining its existing default and the
model_info is None behavior.
In `@internal/dao/tenant_model_instance.go`:
- Around line 44-52: Add a database-level unique constraint or unique index on
the tenant_model_instance provider_id and instance_name columns in the schema
definition, then update CreateInTransaction to translate the resulting
duplicate-key constraint error into the existing “instance already exists”
response while preserving other errors.
In `@internal/handler/providers_test.go`:
- Around line 87-107: Update TestAlterProviderInstanceRejectsNullModelInfo to
set a valid user_id in the Gin test context before invoking
AlterProviderInstance, so the test reaches model_info validation regardless of
authorization-check ordering.
In `@internal/handler/providers.go`:
- Around line 738-750: In the handler code before AlterProviderInstance, remove
the redundant nil check around req.ModelInfo and assign modelInfo directly from
req.ModelInfo, preserving the existing call arguments and behavior.
- Around line 701-725: In internal/handler/providers.go lines 701-725, update
AlterProviderInstance to perform the user_id authentication check before
required-field presence and null validation, preventing unauthenticated callers
from receiving field-level errors. In internal/handler/providers_test.go lines
87-107, set user_id to "user-1" on the context before invoking the handler so
the existing validation assertion remains authenticated and valid.
In `@internal/service/model_service.go`:
- Around line 2193-2211: Declare transaction-local errors within the closure
instead of assigning the function-scope err. Update the json.Unmarshal and
subsequent transaction operations around existingExtra, extraBytes, and
modelInstanceDAO.UpdateByID to use a consistently scoped local error variable,
including the code around the referenced later error handling.
- Around line 1251-1260: Update the CheckConnection flow to normalize its
client-supplied model list with normalizeCreateInstanceModelInfo before calling
verifyProviderModel, and map normalization failures to common.CodeDataError.
Preserve verifyProviderModel for subsequent validation while ensuring
unsupported model_type values follow the same client-error response as
CreateProviderInstance and AlterProviderInstance.
- Around line 3986-3989: Update addModelToInstanceDB to replace the
normalizeModelTypes call with entity.ModelTypeFromStrings for
request.ModelTypes, preserving the existing error return behavior and using the
helper’s returned model-type value directly.
In `@web/src/pages/user-setting/setting-model/index.test.tsx`:
- Around line 23-24: Rename the top-level test constants to PascalCase and
update all references: in
web/src/pages/user-setting/setting-model/index.test.tsx lines 23-24, rename
mockGetSavePayload and mockMutationCount; in
web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
lines 13-15, rename the new mutation mock constants; and in
web/src/pages/user-setting/setting-model/instance-card/models-section/index.test.tsx
lines 11-17, rename the new test mock constants. No behavioral changes are
needed.
- Around line 81-116: Replace the inline onClick handlers in the
ProviderHeaderBar and Sidebar test doubles in
web/src/pages/user-setting/setting-model/index.test.tsx:81-116 with named
handler functions defined before they are passed to the test elements. Apply the
same change to the dialog and model-row test doubles in
web/src/pages/user-setting/setting-model/instance-card/models-section/index.test.tsx:74-132,
preserving each handler’s existing behavior.
In `@web/src/pages/user-setting/setting-model/index.tsx`:
- Line 64: Replace the new useTranslate('flow') call with the standard
useTranslation('flow') hook in the component, preserving the existing tFlow
alias and translation behavior.
In
`@web/src/pages/user-setting/setting-model/instance-card/add-custom-model-dialog.tsx`:
- Around line 211-218: Extract the inline switch handler in
add-custom-model-dialog.tsx (lines 211-218) into a named handler accepting
checked, fieldProps, and the option value, while preserving the loading/disabled
guard and value update behavior. In models-section/index.tsx (lines 513-526),
replace the inline model-selection callback with a named handler or handler
factory that invokes toggleModel(model.name).
In
`@web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts`:
- Line 128: Update the documentation for onInstanceModelsEdited to describe
invocation after successful batch instance updates, including both acknowledged
update paths rather than only PATCH edits. Remove the stale PATCH-only wording
while preserving the callback signature and behavior.
🪄 Autofix
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 Plus
Run ID: b1d3b566-7f04-44fd-b1a8-a970deef900a
📒 Files selected for processing (35)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.pyinternal/dao/tenant_model_instance.gointernal/entity/models/bedrock.gointernal/entity/models/bedrock_test.gointernal/handler/providers.gointernal/handler/providers_test.gointernal/service/model_service.gointernal/service/model_service_test.gorag/llm/bedrock_model_discovery.pyrag/llm/chat_model.pyrag/llm/cv_model.pyrag/llm/embedding_model.pytest/unit_test/rag/llm/test_bedrock_api_key.pyweb/src/hooks/__tests__/use-add-instance-model.test.tsxweb/src/hooks/use-llm-request.tsxweb/src/pages/user-setting/setting-model/index.test.tsxweb/src/pages/user-setting/setting-model/index.tsxweb/src/pages/user-setting/setting-model/instance-card/add-custom-model-dialog.tsxweb/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsxweb/src/pages/user-setting/setting-model/instance-card/components/draft-mode-card.tsxweb/src/pages/user-setting/setting-model/instance-card/components/saved-mode-card.tsxweb/src/pages/user-setting/setting-model/instance-card/hooks.test.tsxweb/src/pages/user-setting/setting-model/instance-card/hooks.tsxweb/src/pages/user-setting/setting-model/instance-card/interface.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/components/model-row.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/index.test.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/index.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/interface.tsweb/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsxweb/src/pages/user-setting/setting-model/instance-card/use-custom-model-fields.test.tsweb/src/pages/user-setting/setting-model/instance-card/use-custom-model-fields.tsxweb/src/pages/user-setting/setting-model/provider-schema/hooks/use-provider-modal-actions.ts
🚧 Files skipped from review as they are similar to previous changes (7)
- web/src/hooks/use-llm-request.tsx
- rag/llm/cv_model.py
- internal/entity/models/bedrock_test.go
- rag/llm/chat_model.py
- api/apps/restful_apis/provider_api.py
- internal/entity/models/bedrock.go
- web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
|
Follow-up review fixes are available in
Focused frontend suites pass (63 tests), along with touched-file Oxlint/Oxfmt, Ruff check/format, Python byte-compilation, Go formatting, and |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
api/apps/services/provider_api_service.py (1)
113-122: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLog malformed stored model metadata before returning the controlled error.
This new failure flow returns an error to the caller but creates no server-side diagnostic. Use the existing service logger before raising
_ModelPersistenceError. Log the model identifier only. Do not logmodel.extra.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 113 - 122, Update _load_model_extra to log malformed stored model metadata through the existing service logger immediately before each _ModelPersistenceError raise, including only the model identifier such as model.model_name and never model.extra. Cover both JSON parsing failures and non-dict metadata while preserving the current controlled error behavior.Source: Coding guidelines
🤖 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`:
- Line 562: Update the model-removal logic in the update flow so models are
deleted only when model_info is explicitly provided, or ensure factory model
names are established before calculating models_to_remove; preserve the
factory-default path’s ability to update existing models. Add a regression test
covering an update with model_info=None and verifying the factory models remain
available.
---
Nitpick comments:
In `@api/apps/services/provider_api_service.py`:
- Around line 113-122: Update _load_model_extra to log malformed stored model
metadata through the existing service logger immediately before each
_ModelPersistenceError raise, including only the model identifier such as
model.model_name and never model.extra. Cover both JSON parsing failures and
non-dict metadata while preserving the current controlled error behavior.
🪄 Autofix
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 Plus
Run ID: 863273ab-9b15-4952-89bc-88221c81c69c
📒 Files selected for processing (20)
api/apps/services/provider_api_service.pyinternal/service/model_service.gointernal/service/model_service_test.gotest/unit_test/rag/llm/test_bedrock_api_key.pyweb/src/hooks/__tests__/use-fetch-instance-models.test.tsxweb/src/hooks/use-llm-request.tsxweb/src/pages/user-setting/setting-model/index.test.tsxweb/src/pages/user-setting/setting-model/index.tsxweb/src/pages/user-setting/setting-model/instance-card/add-custom-model-dialog.tsxweb/src/pages/user-setting/setting-model/instance-card/components/draft-mode-card.tsxweb/src/pages/user-setting/setting-model/instance-card/components/saved-mode-card.tsxweb/src/pages/user-setting/setting-model/instance-card/hooks.test.tsxweb/src/pages/user-setting/setting-model/instance-card/hooks.tsxweb/src/pages/user-setting/setting-model/instance-card/interface.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/hooks.tsweb/src/pages/user-setting/setting-model/instance-card/models-section/index.test.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/index.tsxweb/src/pages/user-setting/setting-model/instance-card/models-section/interface.tsweb/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsx
🚧 Files skipped from review as they are similar to previous changes (14)
- web/src/pages/user-setting/setting-model/instance-card/add-custom-model-dialog.tsx
- web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
- web/src/pages/user-setting/setting-model/instance-card/hooks.test.tsx
- web/src/pages/user-setting/setting-model/index.test.tsx
- web/src/pages/user-setting/setting-model/index.tsx
- internal/service/model_service_test.go
- web/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsx
- web/src/pages/user-setting/setting-model/instance-card/interface.ts
- web/src/pages/user-setting/setting-model/instance-card/hooks.tsx
- web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
- web/src/hooks/use-llm-request.tsx
- internal/service/model_service.go
- web/src/pages/user-setting/setting-model/instance-card/models-section/index.test.tsx
- web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx
|
Follow-up
Ruff check/format, Python byte-compilation, and |
### Summary Closes #17848. This replaces #17958 with a smaller implementation focused on the original requirement. The previous PR gradually expanded beyond the necessary scope; the optional custom endpoint extension is intentionally excluded from this version. - Add request-scoped Bedrock API key authentication to the Python Bedrock adapters and Go chat runtime. - Discover and persist models available to API key instances, so users do not need to manually enter the model type, model name, or maximum token count. - Add API Key mode to the existing Bedrock settings UI and refresh the model and default-model lists after instance changes. - Preserve selected models during credential-only updates while keeping the existing SigV4 authentication modes unchanged. - Return a clear error for unsupported API-key reranking. - Document instance-scoped authentication and short-term API key guidance.
Summary
Closes #17848.
This PR adds API key authentication and dynamic model discovery to the existing Bedrock provider.
Public API impact
POST /api/v1/providers/{provider}/models, acceptingapi_key,base_url,region, and provider-specificextensionsin the request body.max_outputtomax_tokens, matching the existing provider-model contract.Backend implementations
Web interface
Local validation
Validated locally against Bedrock Runtime in the Asia Pacific (Tokyo) region: