Skip to content

feat(bedrock): support API key authentication and model discovery - #17958

Closed
whhe wants to merge 19 commits into
infiniflow:mainfrom
whhe:feat/bedrock-api-key-auth
Closed

whhe wants to merge 19 commits into
infiniflow:mainfrom
whhe:feat/bedrock-api-key-auth

Conversation

@whhe

@whhe whhe commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #17848.

This PR adds API key authentication and dynamic model discovery to the existing Bedrock provider.

Public API impact

  • Adds POST /api/v1/providers/{provider}/models, accepting api_key, base_url, region, and provider-specific extensions in the request body.
  • Updates the web client to use the POST endpoint so credentials are not included in URLs, browser history, or access logs.
  • Changes Bedrock API key connection validation without selected models to validate credentials through model discovery.
  • Normalizes dynamically discovered Go model descriptors from max_output to max_tokens, matching the existing provider-model contract.

Backend implementations

  • Updates the Python implementation with Bedrock Runtime and Mantle API key authentication, model discovery, connection validation, and endpoint security checks.
  • Updates the Go implementation with equivalent authentication, discovery, validation, and request-handling behavior.
  • Rejects untrusted endpoints and explicit non-default ports before transmitting Bedrock API keys.
  • Reuses the Bedrock-owned HTTP client for Mantle requests to preserve connection pooling.

Web interface

  • Adds API key, Runtime/Mantle endpoint, region, and model-discovery configuration to the existing Bedrock provider form.
  • Allows API key validation before models are refreshed or selected.
  • Prevents unsaved credentials from mutating the previously saved provider instance.
  • Avoids automatically selecting the complete discovered model catalog when credentials change.
  • Adds localized labels and validation messages.

Local validation

Validated locally against Bedrock Runtime in the Asia Pacific (Tokyo) region:

  • Bedrock API key validation completed successfully.
bedrock-config
  • Dynamic discovery returned 41 available models: 36 LLMs and 5 embedding models.
bedrock-models

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Aug 6, 2026
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

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

Changes

Bedrock API-Key Authentication

Layer / File(s) Summary
Endpoint validation and model discovery
rag/utils/bedrock_endpoint.py, rag/llm/bedrock_model_discovery.py, internal/entity/models/bedrock.go, rag/llm/*
Bedrock credentials, regions, endpoints, and trusted targets are validated. Runtime and Mantle discovery filters and classifies compatible models. Chat, vision, embedding, and rerank flows use shared authentication paths.
Provider APIs, verification, and persistence
api/apps/restful_apis/provider_api.py, api/apps/services/provider_api_service.py, internal/handler/providers.go, internal/router/router.go, internal/service/model_service.go, internal/dao/tenant_model_instance.go
Provider model listing accepts POST JSON with query fallbacks. Bedrock discovery and verification propagate region and extensions. Model definitions are normalized, provider updates are transactional, and verification errors prevent persistence.
Frontend catalog and settings
web/src/hooks/*, web/src/services/llm-service.ts, web/src/pages/user-setting/setting-model/*, web/src/interfaces/request/llm.ts, web/src/locales/*
The frontend sends POST catalog requests, serializes API keys, supports Bedrock endpoint fields, manages catalog resets and deferred model mutations, updates cached model metadata, and adds localized settings text.

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
Loading

Possibly related PRs

Suggested labels: 🧰 typescript, 🌈 python

Suggested reviewers: dcc123456, wangq8, lynn-inf

Poem

A rabbit checks each endpoint bright,
Bearer keys hop through the night.
Models gather, clean and true,
POST requests carry settings through.
The catalog blooms beneath the moon.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.18% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary changes: Bedrock API key authentication and model discovery.
Description check ✅ Passed The description includes the required Summary section and provides clear scope, implementation details, API impact, validation, and test context.
Linked Issues check ✅ Passed The implementation satisfies issue #17848 by adding scoped Bedrock API-key authentication, endpoint and region support, discovery, validation, and retained SigV4 modes.
Out of Scope Changes check ✅ Passed The changes support the linked feature through backend, frontend, security, persistence, discovery, and regression-test updates without evident unrelated scope.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

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 win

The "default" region placeholder shadows bedrock_region.

Line 1001 replaces an empty region with "default", and Line 1020 puts that placeholder into apiConfig.Region. resolveBedrockRegion in internal/entity/models/bedrock.go prefers apiConfig.Region whenever it is non-empty, so it returns "default" and never reads bedrock_region from the key JSON. The driver then builds the host bedrock.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 Region empty so the driver falls back to bedrock_region.

🐛 Proposed fix
 	apiConfig := &modelModule.APIConfig{
 		ApiKey:  &apiKey,
 		Region:  &region,
 		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 win

Translate 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 as Bedrock, Mantle, OpenAI, and Anthropic unchanged 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 win

Translate 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 as Bedrock, Mantle, OpenAI, Anthropic, and HTTPS.

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 win

Translate 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 win

Use sentence case for the Bedrock API-key labels.

Key is a common noun, not a proper noun. Change these strings to Bedrock API key and Please 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 win

Translate 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 win

Translate 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, and Anthropic.

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 win

Translate 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 win

Translate 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, and HTTPS.

🤖 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 win

Translate 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 as Bedrock, Mantle, OpenAI, Anthropic, and HTTPS.

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 win

Translate 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 win

The test name claims coverage the hook cannot provide.

useModelsDerived receives only isDraftInstance. It never sees deferModelMutations. This test passes isDraftInstance: true, so it verifies the draft path, not the deferred-saved-instance path. The deferred seeding logic lives in index.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 win

Reject non-object JSON before calling config.get.

json.loads returns a non-dict for scalar input. An api_key value such as 12345 parses to an int, and config.get("auth_mode") then raises AttributeError instead of the intended ValueError. Add an isinstance check.

The change summary states that the code raises ValueError when 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 win

Reject control characters in api_key before setting the header.

add_bearer_token writes the tenant-supplied api_key directly into the Authorization header. 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 win

Catch Bedrock model-discovery exceptions and return API errors.

Bedrock.get_model_list() can raise ValueError and BedrockModelDiscoveryError. The provider call site only catches TimeoutError, 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 win

Align the LiteLLM mock with the production provider map.

The mock SupportedLiteLLMProvider values match the production enum, but conftest.py keeps LITELLM_PROVIDER_PREFIX limited to Bedrock. Use the production entries for the added providers (Nvidia, Ollama, OpenRouter, MiniMax, GPUStack, plus Moonshot/ZHIPU_AI where 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 win

The 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 win

Update 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 support bedrock_api_key and raise ValueError for 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 win

Isolate the timeout assertion from the ambient environment.

Line 84 asserts kwargs["timeout"] == 10. list_provider_models derives that value from os.environ.get("LLM_TIMEOUT_SECONDS") with a fallback of 10 (api/apps/services/provider_api_service.py Line 264). If LLM_TIMEOUT_SECONDS is 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 win

Add a test for the nullish branch.

serializeProviderAPIKey maps null and undefined to ''. 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 value

Extract the inline JSX event handlers.

Line 644 uses onSubmit={(e) => e.preventDefault()}. Line 835 uses onChange={(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 NumberInput wrapper 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 win

Make the injected-key contract explicit and align the api_key guard.

Two points.

First, transformModelVerify deletes api_key and extensions because getModelsSectionValues injects them. It does not delete region, which getBedrockModelListRequest also injects. buildPayload currently survives that because its flat object sets region: values.bedrock_region after spreading cleaned. The correctness depends on key ordering inside buildPayload. If getBedrockModelListRequest gains 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 uses JSON.stringify(payload.api_key ?? ''). JSON.stringify(undefined) returns undefined, not a string, so the two paths send different shapes when api_key is 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 value

Name the Bedrock auto-fetch delay and document its purpose.

500 is 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 changes apiKeyValue and 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 win

Normalize the seeded instance models instead of double-casting.

instanceModels entries carry model_type, while IProviderModelItem declares model_types. The as unknown as cast hides that mismatch. useModelsDerived currently normalizes both spellings, so the mixed shapes work today, but draftModels then holds two different item shapes and any future direct reader of draftModels breaks.

The file already imports normalizeModelTypes-shaped logic in hooks.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 normalizeModelTypes to the existing ./hooks import.

🤖 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 win

Add the undefined base URL case.

isCatalogBaseURLReady treats undefined as "the provider form has no base_url field" and returns true. 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 value

Match the Anthropic prefix case-insensitively.

_is_mantle_chat_model lowercases the model ID before the prefix comparison, but the anthropic. check uses the raw model.id. The Go implementation in internal/entity/models/bedrock.go lowercases the name before both checks. A catalog that returns Anthropic.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 win

Add logging to the discovery flow.

discover_bedrock_models is 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 value

Align suffix stripping with the Python implementation.

The loop applies strings.TrimSuffix for every suffix in sequence. The Python helper _mantle_root_url in rag/utils/bedrock_endpoint.py returns after the first matching suffix. For an input such as https://host/anthropic/v1/models, Go strips /v1/models and 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 value

Use slices.Contains instead of the local closure.

The file already imports slices and uses slices.Contains at Line 1090. The local contains closure 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 win

Emit an empty array when ModelTypes is nil.

A nil model.ModelTypes serializes as "model_types": null. The Python listing path always emits a list for model_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 value

Assert against the imported constant.

The file already imports BEDROCK_DISCOVERY_TIMEOUT_SECONDS at Line 19 and uses it at Line 318. Lines 113-114 hardcode 10 instead. 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 value

Make the match pattern 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 value

Annotate 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 added region parameter follows the same implicit pattern as api_key and base_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 win

Reuse one Bedrock auth-mode parser.

Lines 238-243 duplicate the auth_mode detection already implemented in _should_verify_bedrock_api_key_without_models at 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 win

Align the region requirement with the other Bedrock drivers.

BedrockCV defaults bedrock_region to "us-east-1". LiteLLMBase._construct_completion_args (rag/llm/chat_model.py, Line 2385) and BedrockEmbed.__init__ (rag/llm/embedding_model.py, Line 684) now reject a missing region. A vision request therefore silently targets us-east-1 when 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 win

Consider extracting the shared Bedrock API-key argument builder.

Lines 1400-1410 duplicate the runtime and Mantle credential wiring in rag/llm/chat_model.py Lines 2398-2417, including the inert access-key placeholders and the bearer header. Two copies of credential construction can drift. A private helper next to resolve_bedrock_endpoint in rag/utils/bedrock_endpoint.py would 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.

Comment thread web/src/hooks/use-llm-request.tsx Resolved
whhe added 2 commits August 7, 2026 10:51
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
@whhe

whhe commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

Prepared the review fixes in final local SHA 3665c0588c221c7706a751ed8816f0eebdc12a59.

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 slices.Contains, and sharing the Chat/CV Bedrock argument builder. Remote publication will be verified separately.

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}

@whhe
whhe force-pushed the feat/bedrock-api-key-auth branch from 332b421 to 3665c05 Compare August 7, 2026 08:03
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
api/apps/services/provider_api_service.py (1)

726-726: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reuse _to_int for the timeout parse.

Line 270 parses the same environment variable with max(1, _to_int(os.environ.get("LLM_TIMEOUT_SECONDS"), 10)). Line 726 uses int(...), which raises ValueError if 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 value

Rename the top-level fixture to PascalCase.

Rename values to Values and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f78c15 and 3665c05.

📒 Files selected for processing (44)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py
  • internal/entity/models/bedrock.go
  • internal/entity/models/bedrock_test.go
  • internal/handler/providers.go
  • internal/handler/providers_test.go
  • internal/router/router.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • rag/llm/bedrock_model_discovery.py
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py
  • rag/llm/embedding_model.py
  • rag/llm/model_meta.py
  • rag/llm/rerank_model.py
  • rag/utils/bedrock_endpoint.py
  • test/unit_test/rag/llm/conftest.py
  • test/unit_test/rag/llm/test_bedrock_api_key.py
  • web/src/hooks/use-llm-request.tsx
  • web/src/interfaces/request/llm.ts
  • web/src/locales/ar.ts
  • web/src/locales/bg.ts
  • web/src/locales/de.ts
  • web/src/locales/en.ts
  • web/src/locales/fr.ts
  • web/src/locales/it.ts
  • web/src/locales/ja.ts
  • web/src/locales/ko.ts
  • web/src/locales/ru.ts
  • web/src/locales/tr.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.ts
  • web/src/pages/user-setting/setting-model/instance-card/interface.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts
  • web/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.ts
  • web/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

Comment thread internal/entity/models/bedrock.go Resolved
Comment thread internal/entity/models/bedrock.go Resolved
whhe added 2 commits August 7, 2026 18:05
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
@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai pause

@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews paused.

@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Implemented and published in final SHA 341aa8d7f5544ebf5f1d499efcb7ccd8afcd6995.

  • Provider verification now parses LLM_TIMEOUT_SECONDS through _to_int with the established minimum/default handling.
  • The Bedrock test fixture now uses PascalCase.
  • The non-default endpoint-port and Mantle HTTP-client findings are implemented and covered by focused Go tests.

The final review pass also aligned selected-model verification with the Python/Go model-level contract and added exact host:port allowlisting for trusted custom proxies while keeping AWS endpoints restricted to port 443.

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}

@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 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 win

Bedrock credential parsing raises a raw JSONDecodeError in three drivers. Each Bedrock driver calls json.loads on the stored credential without converting the failure to a domain error, unlike rag/llm/model_meta.py Lines 71-74. A malformed stored credential surfaces as a parser traceback instead of a clear configuration error.

  • rag/llm/chat_model.py#L2378-L2382: wrap json.loads(self.api_key) in try/except (JSONDecodeError, TypeError), raise ValueError("Bedrock API key must be a JSON object") from error, and reject non-dict values.
  • rag/llm/cv_model.py#L1377-L1377: wrap json.loads(key) in BedrockCV._parse_credentials with the same conversion and chaining.
  • rag/llm/embedding_model.py#L678-L678: wrap json.loads(key) in BedrockEmbed.__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 value

Log the discovery error for non-Bedrock providers.

If driver.ListModels fails for a non-Bedrock provider, the handler discards listErr and 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 value

Simplify mantleCatalogURL.

The function assigns root and 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 win

Use slices.Contains instead of the local contains closure.

The file already imports slices and uses slices.Contains at 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 value

Use slices.ContainsFunc for the prefix scan.

isMantleNonChatModel can use the imported slices package 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 win

Log the unsupported-auth-mode early return.

get_model_list returns an empty list without any log record when auth_mode is not bedrock_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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f78c15 and 341aa8d.

📒 Files selected for processing (47)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py
  • internal/entity/models/anthropic.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/bedrock_test.go
  • internal/entity/models/openai.go
  • internal/handler/providers.go
  • internal/handler/providers_test.go
  • internal/router/router.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • rag/llm/bedrock_model_discovery.py
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py
  • rag/llm/embedding_model.py
  • rag/llm/model_meta.py
  • rag/llm/rerank_model.py
  • rag/utils/bedrock_endpoint.py
  • test/unit_test/rag/llm/conftest.py
  • test/unit_test/rag/llm/test_bedrock_api_key.py
  • web/src/hooks/__tests__/use-fetch-instance-models.test.tsx
  • web/src/hooks/use-llm-request.tsx
  • web/src/interfaces/request/llm.ts
  • web/src/locales/ar.ts
  • web/src/locales/bg.ts
  • web/src/locales/de.ts
  • web/src/locales/en.ts
  • web/src/locales/fr.ts
  • web/src/locales/it.ts
  • web/src/locales/ja.ts
  • web/src/locales/ko.ts
  • web/src/locales/ru.ts
  • web/src/locales/tr.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.ts
  • web/src/pages/user-setting/setting-model/instance-card/interface.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts
  • web/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.ts
  • web/src/services/llm-service.ts

Comment thread rag/llm/bedrock_model_discovery.py Resolved
Comment thread rag/llm/rerank_model.py Resolved
Comment thread rag/utils/bedrock_endpoint.py Resolved
Comment thread web/src/locales/ar.ts Resolved
Normalize runtime and discovery endpoints before validation and use.

Return domain errors for malformed credentials and validate rerank regions before creating AWS clients.
@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Reviewed every finding and published the valid fixes in final SHA 074fd5f375b74a598cd1da6b4df7cf838ec259a3.

Implemented:

  • Added one shared Bedrock credential parser so malformed JSON and non-object values produce the domain ValueError across chat, vision, embedding, rerank, and model discovery.
  • Required and validated bedrock_region before BedrockRerank creates an AWS client or model ARN.
  • Normalized surrounding whitespace for both runtime/Mantle endpoints and the independent model-discovery endpoint, with call-chain regression coverage.

Not changed after independent verification:

  • This repository requires Python 3.13, where asyncio.TimeoutError is TimeoutError; the handler and test already exercise the same exception class.
  • Python retains the discovered vision capability because BedrockCV implements image requests; the Go driver intentionally advertises chat only because its runtime implementation is text-only.
  • The locale lookup has an English fallback, so missing per-locale copies do not expose raw keys or break validation.
  • The logging and Go collection-helper suggestions are non-functional refactors and do not address an observed defect.

Validation: fresh-context final diff review is CLEAN; Ruff format/check, py_compile, direct parser/endpoint assertions, Go entity-model tests, frontend focused tests, and git diff --check passed. Python pytest remains unavailable in the local environment because pytest/litellm are not installed.

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}

@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (5)
internal/service/model_service.go (2)

1008-1027: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider inlining buildCheckConnectionAPIConfig.

The function only forwards to buildProviderAPIConfig and shouldVerifyBedrockAPIKeyWithoutModels. 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 value

Remove the dead loop over modelInfo.

Line 741 returns when len(modelInfo) > 0. Execution reaches Line 760 only when modelInfo is empty, so the loop never assigns a status and result stays 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, nil

As 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 win

Add a lowercase provider-name case.

shouldVerifyBedrockAPIKeyWithoutModels compares the provider name exactly, while buildProviderAPIConfig uses strings.EqualFold. A case for "bedrock" locks the comparison once the mismatch in internal/service/model_service.go Lines 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 value

Extract the provider driver swap into a test helper.

Lines 265-270 and Lines 347-352 repeat the same lookup, save, and t.Cleanup restore of provider.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 value

Extract 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f78c15 and 074fd5f.

📒 Files selected for processing (48)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py
  • internal/entity/models/anthropic.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/bedrock_test.go
  • internal/entity/models/openai.go
  • internal/handler/providers.go
  • internal/handler/providers_test.go
  • internal/router/router.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • rag/llm/bedrock_model_discovery.py
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py
  • rag/llm/embedding_model.py
  • rag/llm/model_meta.py
  • rag/llm/rerank_model.py
  • rag/utils/bedrock_endpoint.py
  • test/unit_test/rag/llm/conftest.py
  • test/unit_test/rag/llm/test_bedrock_api_key.py
  • test/unit_test/rag/llm/test_bedrock_rerank.py
  • web/src/hooks/__tests__/use-fetch-instance-models.test.tsx
  • web/src/hooks/use-llm-request.tsx
  • web/src/interfaces/request/llm.ts
  • web/src/locales/ar.ts
  • web/src/locales/bg.ts
  • web/src/locales/de.ts
  • web/src/locales/en.ts
  • web/src/locales/fr.ts
  • web/src/locales/it.ts
  • web/src/locales/ja.ts
  • web/src/locales/ko.ts
  • web/src/locales/ru.ts
  • web/src/locales/tr.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.ts
  • web/src/pages/user-setting/setting-model/instance-card/interface.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts
  • web/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.ts
  • web/src/services/llm-service.ts

Comment thread internal/entity/models/bedrock.go Resolved
Comment thread internal/service/model_service.go Resolved
Comment thread rag/llm/embedding_model.py Resolved
@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author
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.

@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f78c15 and 221d3f6.

📒 Files selected for processing (48)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py
  • internal/entity/models/anthropic.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/bedrock_test.go
  • internal/entity/models/openai.go
  • internal/handler/providers.go
  • internal/handler/providers_test.go
  • internal/router/router.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • rag/llm/bedrock_model_discovery.py
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py
  • rag/llm/embedding_model.py
  • rag/llm/model_meta.py
  • rag/llm/rerank_model.py
  • rag/utils/bedrock_endpoint.py
  • test/unit_test/rag/llm/conftest.py
  • test/unit_test/rag/llm/test_bedrock_api_key.py
  • test/unit_test/rag/llm/test_bedrock_rerank.py
  • web/src/hooks/__tests__/use-fetch-instance-models.test.tsx
  • web/src/hooks/use-llm-request.tsx
  • web/src/interfaces/request/llm.ts
  • web/src/locales/ar.ts
  • web/src/locales/bg.ts
  • web/src/locales/de.ts
  • web/src/locales/en.ts
  • web/src/locales/fr.ts
  • web/src/locales/it.ts
  • web/src/locales/ja.ts
  • web/src/locales/ko.ts
  • web/src/locales/ru.ts
  • web/src/locales/tr.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.ts
  • web/src/pages/user-setting/setting-model/instance-card/interface.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts
  • web/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.ts
  • web/src/services/llm-service.ts

Comment thread internal/handler/providers.go Resolved
Comment thread rag/llm/chat_model.py Resolved
@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
internal/service/model_service.go (1)

1047-1062: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Reuse validateLocalProviderBaseURL in CheckConnection.

CheckConnection keeps an inline baseURL == "" check. validateLocalProviderBaseURL trims whitespace before the check. A whitespace-only base_url therefore passes CheckConnection but fails CreateProviderInstance and AlterProviderInstance. Note that baseURL is 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 value

Extract 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 win

Reuse serializeProviderAPIKey for the verify credentials.

Line 437 uses JSON.stringify(payload.api_key ?? '') and Line 461 uses JSON.stringify(payload.api_key). This PR adds serializeProviderAPIKey in web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts for exactly this normalization, and use-list-models-picker.ts already 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f78c15 and c7817dd.

📒 Files selected for processing (48)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py
  • internal/entity/models/anthropic.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/bedrock_test.go
  • internal/entity/models/openai.go
  • internal/handler/providers.go
  • internal/handler/providers_test.go
  • internal/router/router.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • rag/llm/bedrock_model_discovery.py
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py
  • rag/llm/embedding_model.py
  • rag/llm/model_meta.py
  • rag/llm/rerank_model.py
  • rag/utils/bedrock_endpoint.py
  • test/unit_test/rag/llm/conftest.py
  • test/unit_test/rag/llm/test_bedrock_api_key.py
  • test/unit_test/rag/llm/test_bedrock_rerank.py
  • web/src/hooks/__tests__/use-fetch-instance-models.test.tsx
  • web/src/hooks/use-llm-request.tsx
  • web/src/interfaces/request/llm.ts
  • web/src/locales/ar.ts
  • web/src/locales/bg.ts
  • web/src/locales/de.ts
  • web/src/locales/en.ts
  • web/src/locales/fr.ts
  • web/src/locales/it.ts
  • web/src/locales/ja.ts
  • web/src/locales/ko.ts
  • web/src/locales/ru.ts
  • web/src/locales/tr.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.ts
  • web/src/pages/user-setting/setting-model/instance-card/interface.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts
  • web/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.ts
  • web/src/services/llm-service.ts

Comment thread internal/entity/models/bedrock_test.go Resolved
@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

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.

@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
rag/llm/model_meta.py (1)

72-75: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Log 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.py Lines 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 win

Document and cover the Bedrock auto-fetch delay.

The 500 value has no named constant and no comment explaining why Bedrock needs a delay while other providers use 0. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f78c15 and aaa0b6e.

📒 Files selected for processing (48)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py
  • internal/entity/models/anthropic.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/bedrock_test.go
  • internal/entity/models/openai.go
  • internal/handler/providers.go
  • internal/handler/providers_test.go
  • internal/router/router.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • rag/llm/bedrock_model_discovery.py
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py
  • rag/llm/embedding_model.py
  • rag/llm/model_meta.py
  • rag/llm/rerank_model.py
  • rag/utils/bedrock_endpoint.py
  • test/unit_test/rag/llm/conftest.py
  • test/unit_test/rag/llm/test_bedrock_api_key.py
  • test/unit_test/rag/llm/test_bedrock_rerank.py
  • web/src/hooks/__tests__/use-fetch-instance-models.test.tsx
  • web/src/hooks/use-llm-request.tsx
  • web/src/interfaces/request/llm.ts
  • web/src/locales/ar.ts
  • web/src/locales/bg.ts
  • web/src/locales/de.ts
  • web/src/locales/en.ts
  • web/src/locales/fr.ts
  • web/src/locales/it.ts
  • web/src/locales/ja.ts
  • web/src/locales/ko.ts
  • web/src/locales/ru.ts
  • web/src/locales/tr.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.ts
  • web/src/pages/user-setting/setting-model/instance-card/interface.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts
  • web/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.ts
  • web/src/services/llm-service.ts

Comment thread rag/llm/chat_model.py Resolved
@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

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.

@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai resume

@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the latest save-state review findings in 1711d1a96:

  • provider baselines now advance only from exact acknowledged request/model snapshots;
  • model PATCH cache updates merge against the latest cache and only acknowledge successful writes;
  • Bedrock catalog/model state no longer treats derived or unsaved state as persisted;
  • batch saves freeze card/provider context across validation and requests, preserve failed/skipped drafts, and distinguish duplicate-name no-op results from real writes;
  • added focused regression coverage for request-in-flight edits, late refetches, provider transforms, partial batch failures, duplicate names, and validation/selection races.

Local validation: 4 focused Jest suites / 33 tests passed; touched files pass Oxfmt, Oxlint, and git diff --check. Full tsc --noEmit remains blocked by unrelated existing repository errors; no new errors were found in the touched paths.

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

@whhe The reported save-state fixes and focused validation are noted. I will perform a full review of the current PR state.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

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 win

Forward endpoint_url into SigV4 Bedrock runtime clients.

resolve_bedrock_endpoint returns a runtime endpoint URL for access_key_secret, iam_role, and assume_role, but those branches build boto3.client("bedrock-runtime", ...) without endpoint_url. Configure the runtime client with the returned URL in each SigV4 branch, or reject a non-empty endpoint_url for those modes. Also pass region_name=self.bedrock_region when creating the iam_role Bedrock 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 win

Add non-secret logging for the role-refresh flow.

_assume_bedrock_role performs 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 value

Replace the local contains closure with slices.Contains.

slices is 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 value

Extract 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 value

Remove the global React assignment if the mocks no longer need it.

Lines 133 and 137 write React onto globalThis. Each mock factory already calls jest.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 the beforeAll/afterAll pair 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 value

Merge the API key assignment with the query fallback.

get_data() preserves the request body for the following Quart 0.20.0 get_json() call, so no change is needed there. Use one assignment for api_key such as api_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 value

Compute acknowledgedModelInfo outside the setQueryData updater.

The updater currently mutates acknowledgedModelInfo from inside setQueryData. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f78c15 and 1711d1a.

📒 Files selected for processing (52)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py
  • internal/entity/models/anthropic.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/bedrock_test.go
  • internal/entity/models/openai.go
  • internal/handler/providers.go
  • internal/handler/providers_test.go
  • internal/router/router.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • rag/llm/bedrock_model_discovery.py
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py
  • rag/llm/embedding_model.py
  • rag/llm/model_meta.py
  • rag/llm/rerank_model.py
  • rag/utils/bedrock_endpoint.py
  • test/unit_test/rag/llm/conftest.py
  • test/unit_test/rag/llm/test_bedrock_api_key.py
  • test/unit_test/rag/llm/test_bedrock_rerank.py
  • web/src/hooks/__tests__/use-fetch-instance-models.test.tsx
  • web/src/hooks/use-llm-request.tsx
  • web/src/interfaces/request/llm.ts
  • web/src/locales/ar.ts
  • web/src/locales/bg.ts
  • web/src/locales/de.ts
  • web/src/locales/en.ts
  • web/src/locales/fr.ts
  • web/src/locales/it.ts
  • web/src/locales/ja.ts
  • web/src/locales/ko.ts
  • web/src/locales/ru.ts
  • web/src/locales/tr.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/setting-model/index.test.tsx
  • web/src/pages/user-setting/setting-model/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.test.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-utils.ts
  • web/src/pages/user-setting/setting-model/instance-card/hooks.test.tsx
  • web/src/pages/user-setting/setting-model/instance-card/hooks.tsx
  • web/src/pages/user-setting/setting-model/instance-card/interface.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.test.ts
  • web/src/pages/user-setting/setting-model/provider-schema/field-config/utils.ts
  • web/src/pages/user-setting/setting-model/provider-schema/hooks/use-list-models-picker.ts
  • web/src/services/llm-service.ts

Comment thread internal/service/model_service.go Resolved
@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Reviews 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
@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Latest review follow-up is complete in b9cd2ac.

  • Normalize and validate provider model metadata before verification or persistence, and keep Mantle discovery capability-neutral until a model type is explicitly selected and verified.
  • Make Python and Go provider-instance/model writes atomic, preserve request-field presence, and align canonical endpoint/region values across verification, persistence, and runtime fallback.
  • Propagate Bedrock SigV4 runtime endpoints consistently and keep the Go text-only vision boundary explicit.
  • Stabilize provider settings around acknowledged model cache updates, provider-specific payload transforms, input-select region mapping, model mutation/save serialization, and candidate-dialog transactions.
  • Add focused regression coverage for rollback, malformed inputs, multi-tenant verification persistence, discovery candidates, cache acknowledgements, and frontend races.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 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 win

Invalidate 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 finally when 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 win

Omit model_info from saved-instance saves until the model list is authoritative.

modelInfoRef.current starts empty and the update API treats an explicit empty model_info as “no selected models”, deleting existing models. If buildPayload() can run before the model selection query/user changes are settled, it sends a destructive model_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.ModelInfo is already checked for nil at Line 722.

The guard at Line 747 cannot be false. Assign modelInfo directly.

♻️ 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

AlterProviderInstance validates request fields before it checks user_id. The handler returns field-level validation errors to unauthenticated callers, and the new handler test depends on that ordering because it sets no user_id.

  • internal/handler/providers.go#L701-L725: move the user_id check above the hasField presence checks and the null checks.
  • internal/handler/providers_test.go#L87-L107: call ctx.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 value

Declare the transaction-local errors inside the closure.

Line 2195 assigns the function-scope err declared at Line 2140. Line 2206 then declares a new err with :=, 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 win

Client-supplied invalid model_type values now produce a server error on the CheckConnection path.

verifyProviderModel returns a validation error for a missing name or an unsupported type. CheckConnection maps any verifyErr to common.CodeServerError at Line 1157. CreateProviderInstance and AlterProviderInstance reject the same input earlier with common.CodeDataError through normalizeCreateInstanceModelInfo. A /connection/verify request with an unsupported model_type therefore returns a 500-class code for a client input error.

Normalize the CheckConnection model list before verification and return common.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 value

Refactor addModelToInstanceDB to use entity.ModelTypeFromStrings.

entity.ModelTypeFromStrings already exists and uses the same OR-based ModelTypeFromString loop as the bitmask code at internal/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 win

Rename the inner update_dict and drop the always-true guard.

Line 522 reuses the name update_dict from 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 the if 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_type is always a list after normalization, so Line 1351 is dead.

_normalize_model_info returns model_type as a list at Line 1328. The isinstance(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 value

Use an explicit optional annotation for model_info.

Ruff reports RUF013 on this signature. model_info: list[dict] = None is an implicit Optional. The function relies on model_info is None at Lines 501 and 539, so the None default 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 | 🔵 Trivial

Add a unique constraint to make the duplicate-instance check race-safe.

CreateInTransaction reads 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 same provider_id and instance_name. The tenant_model_instance schema in api/db/db_models.py Lines 1394-1403 declares no unique index for that pair, unlike tenant_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 win

This test depends on validation running before the user_id check.

The request context never sets user_id. The test passes only because AlterProviderInstance validates model_info before it reads user_id. If the handler moves the authorization check earlier, this test returns CodeUnauthorized instead. Set user_id in 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 win

Use useTranslation for the new flow translation.

Replace the new useTranslate('flow') call with useTranslation('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 win

Extract 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 receives checked, 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 for toggleModel(model.name).

As per coding guidelines, avoid inline JSX event handlers such as onClick={() => ...} and onChange={(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 win

Align the callback documentation with batch updates.

useModelMutations calls onInstanceModelsEdited after 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 value

Use 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: Rename mockGetSavePayload to 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 value

Replace 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 inline onClick handlers 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 inline onClick handlers 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1711d1a and b9cd2ac.

📒 Files selected for processing (35)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py
  • internal/dao/tenant_model_instance.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/bedrock_test.go
  • internal/handler/providers.go
  • internal/handler/providers_test.go
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • rag/llm/bedrock_model_discovery.py
  • rag/llm/chat_model.py
  • rag/llm/cv_model.py
  • rag/llm/embedding_model.py
  • test/unit_test/rag/llm/test_bedrock_api_key.py
  • web/src/hooks/__tests__/use-add-instance-model.test.tsx
  • web/src/hooks/use-llm-request.tsx
  • web/src/pages/user-setting/setting-model/index.test.tsx
  • web/src/pages/user-setting/setting-model/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/add-custom-model-dialog.tsx
  • web/src/pages/user-setting/setting-model/instance-card/bedrock-instance-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/components/draft-mode-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/components/saved-mode-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/hooks.test.tsx
  • web/src/pages/user-setting/setting-model/instance-card/hooks.tsx
  • web/src/pages/user-setting/setting-model/instance-card/interface.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/components/model-row.tsx
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
  • 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
  • web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts
  • web/src/pages/user-setting/setting-model/instance-card/provider-instance-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/use-custom-model-fields.test.ts
  • web/src/pages/user-setting/setting-model/instance-card/use-custom-model-fields.tsx
  • web/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

Comment thread rag/llm/embedding_model.py Resolved
@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up review fixes are available in 40ce1d049:

  • Fixed existing-model extra merging at the Python persistence boundary, including controlled handling of malformed stored JSON.
  • Made Go connection checks reject invalid model metadata as DataError before driver calls or persistence.
  • Added an explicit saved-model authority/readiness boundary in the generic provider card. Failed instance-model queries no longer become an authoritative empty list, and validation blocks saves until the authoritative model snapshot is loaded. Provider identity is now part of the saved-card key to prevent cross-provider state reuse.
  • Kept successful mutation invalidation with the mutation hooks that own it; adding a tail invalidation to the partial-batch loop would duplicate existing invalidation and does not address a missing update.
  • Did not add a one-off Bedrock embedding STS refresh implementation: that lifecycle issue predates this PR and is shared with rerank. It should be handled as a separate credential-owner design covering expiration, refresh single-flight, client rebuild, and failure semantics for both drivers.

Focused frontend suites pass (63 tests), along with touched-file Oxlint/Oxfmt, Ruff check/format, Python byte-compilation, Go formatting, and git diff --check. Full TypeScript checking remains blocked by unrelated repository baseline errors (none in touched files). Targeted Python tests cannot start because the local environment lacks pytest/dependencies, and the Go service package remains blocked on macOS by the existing SysProcAttr.Pdeathsig build issue.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
api/apps/services/provider_api_service.py (1)

113-122: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log 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 log model.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

📥 Commits

Reviewing files that changed from the base of the PR and between b9cd2ac and 40ce1d0.

📒 Files selected for processing (20)
  • api/apps/services/provider_api_service.py
  • internal/service/model_service.go
  • internal/service/model_service_test.go
  • test/unit_test/rag/llm/test_bedrock_api_key.py
  • web/src/hooks/__tests__/use-fetch-instance-models.test.tsx
  • web/src/hooks/use-llm-request.tsx
  • web/src/pages/user-setting/setting-model/index.test.tsx
  • web/src/pages/user-setting/setting-model/index.tsx
  • web/src/pages/user-setting/setting-model/instance-card/add-custom-model-dialog.tsx
  • web/src/pages/user-setting/setting-model/instance-card/components/draft-mode-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/components/saved-mode-card.tsx
  • web/src/pages/user-setting/setting-model/instance-card/hooks.test.tsx
  • web/src/pages/user-setting/setting-model/instance-card/hooks.tsx
  • web/src/pages/user-setting/setting-model/instance-card/interface.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.test.ts
  • web/src/pages/user-setting/setting-model/instance-card/models-section/hooks.ts
  • 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
  • web/src/pages/user-setting/setting-model/instance-card/models-section/interface.ts
  • web/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

@whhe

whhe commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up f0427a51f addresses the latest review:

  • Factory-default reconciliation now computes the target model set before deletion, so it updates existing defaults, adds missing defaults, and removes only non-factory models. Explicit model_info: [] still clears all models.
  • Python Alter rejects null/non-array model_info before verification or persistence, matching the Go and frontend external contract.
  • Malformed persisted model metadata now emits a safe diagnostic containing only the opaque model ID; raw metadata and credentials are never logged. Both malformed JSON and valid non-object JSON are covered.

Ruff check/format, Python byte-compilation, and git diff --check pass. Dynamic pytest remains unavailable because neither the repository virtualenv nor the host Python has pytest and the broader environment is missing test dependencies.

@whhe whhe closed this Aug 14, 2026
JinHai-CN pushed a commit that referenced this pull request Aug 25, 2026
### 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

💞 feature Feature request, pull request that fullfill a new feature. size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Add Bedrock API key authentication to the existing Bedrock provider

1 participant