Skip to content

feat(go-models): add AWS Bedrock provider driver - #15166

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
whitepicker:feat/go-bedrock-provider
May 26, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
whitepicker:feat/go-bedrock-provider

Conversation

@whitepicker

Copy link
Copy Markdown
Contributor

Summary

Closes #15165.

Implements the AWS Bedrock model provider for the Go API server, tracked under #14736. Adds Converse + Converse-Stream chat and foundation-model listing, with SigV4 signing over a hand-rolled net/http path that matches the established pattern in internal/entity/models/ (no new direct go.mod deps).

  • internal/entity/models/bedrock.go — driver: SigV4-signed Converse / Converse-Stream / ListModels, three auth modes, vnd.amazon.eventstream decoding, truncation detection.
  • internal/entity/models/bedrock_test.go — 33 unit tests against httptest.Server.
  • internal/entity/models/factory.go — case "bedrock": registration.
  • conf/models/bedrock.json — 15 chat-capable foundation models (Claude 3.x, Llama 3.1, Mistral, Nova, Cohere).

What's included

  • Auth (mirrors rag/llm/chat_model.py:1872): API key is a JSON blob carrying auth_mode:
    • access_key_secret — static bedrock_ak/bedrock_sk signed directly.
    • iam_role — STS AssumeRole against aws_role_arn using the default credential chain, then sign with the temporary credentials.
    • assume_role — default credential chain (IRSA, env, instance profile) used directly.
  • Endpoints (region-scoped):
    • POST https://bedrock-runtime.{region}.amazonaws.com/model/{modelId}/converse (sync chat)
    • POST https://bedrock-runtime.{region}.amazonaws.com/model/{modelId}/converse-stream (streaming chat, event-stream framing)
    • GET https://bedrock.{region}.amazonaws.com/foundation-models (catalog)
  • Streaming: contentBlockDelta text frames are forwarded as chunks; loop exits on messageStop and fails loudly if the stream ends before it. exception / error frames surface upstream messages verbatim.
  • Region resolution: APIConfig.Region wins; falls back to bedrock_region in the key blob. A misconfigured region fails fast with an explicit error.
  • URLSuffix override: chat, models (and optional async_chat) in conf/models/bedrock.json are honoured; sensible AWS defaults apply when omitted, so on-prem VPC-endpoint operators can re-route.

What's intentionally out of scope

Embedding, OCR (Textract), ASR (Transcribe), TTS (Polly), Image2Text, and balance return the documented "no such method" sentinel. Each is a separate AWS service and will land in follow-on PRs alongside the relevant conf/models/bedrock.json entries — matching how Novita, NVIDIA, TogetherAI, and Replicate were rolled out method-by-method.

Why hand-rolled SigV4 (no bedrockruntime / bedrock SDK clients)

  • Matches every existing provider in internal/entity/models/ which uses net/http directly.
  • Adds zero new direct go.mod entries — only sub-packages of already-pinned modules: aws/signer/v4 (sub-package of aws-sdk-go-v2), aws/protocol/eventstream (v1.7.6, transitively present), and service/sts (v1.41.8, transitively present). go mod tidy will promote the two indirects to direct on first build.

Test plan

  • go mod tidy — confirm only aws/protocol/eventstream and service/sts move from indirect → direct.
  • go build ./... — compiles cleanly.
  • go vet ./... — no warnings.
  • go test ./internal/entity/models/... -run Bedrock -race -count=1 — 33 unit tests pass:
    • key-parsing: empty, non-JSON, missing auth_mode, unknown mode, access_key_secret requires both AK and SK, iam_role requires ARN, assume_role accepts bare config.
    • region resolution prefers APIConfig.Region, falls back to key, fails when neither set.
    • buildConverseRequest: system extraction, interleaved-system rejection, unsupported-role rejection, empty messages, only-system messages, multimodal-content rejection.
    • URL builders: default AWS host, BaseURL override, control plane fallback, trailing-slash joining.
    • HTTP chat happy path, missing API key / model id, 401 propagation with body included.
    • ListModels filters empty modelId entries; CheckConnection surfaces a 403 from the catalog.
    • Streaming: content-delta concatenation, messageStop terminator with [DONE] sentinel emission, exception-frame surfacing, truncation detection (EOF before messageStop), explicit stream=false rejection, nil-sender rejection.
    • Every interface method has a no such method test.
  • Compile-time var _ ModelDriver = (*BedrockModel)(nil) pins interface satisfaction.
  • Live smoke (manual, against a real AWS account): build ragflow_cli, add provider 'bedrock', create provider 'bedrock' instance ... with each auth_mode, run the chat / stream-chat / list-models commands from [Feature] Implement model providers of RAGFlow API server in Go #14736.

Linked tracker

Tracked under #14736 (Implement model providers of RAGFlow API server in Go). Closes #15165.

Implements the AWS Bedrock model provider for the Go API server,
tracked under infiniflow#14736. Adds Converse and Converse-Stream chat plus
foundation-model listing, with SigV4-signed requests over a
hand-rolled net/http path that matches the existing provider
pattern in internal/entity/models/.

The API key is a JSON blob carrying auth_mode plus the
mode-specific credential material, mirroring the Python
LiteLLMBase dispatch at rag/llm/chat_model.py:1872. Three modes
are supported:

  - access_key_secret: static AK/SK signed directly.
  - iam_role: STS AssumeRole using the default credential chain,
    then sign with the temporary credentials.
  - assume_role: default credential chain (IRSA, env, instance
    profile) used directly.

Streaming uses the AWS vnd.amazon.eventstream binary framing
decoded via aws-sdk-go-v2/aws/protocol/eventstream. A
contentBlockDelta with text is forwarded as a chunk; the loop
returns on messageStop and fails loudly if the stream ends
before messageStop. Exception frames are surfaced verbatim so
partial completions cannot masquerade as success.

Wires the driver into internal/entity/models/factory.go and
ships conf/models/bedrock.json with 15 chat-capable foundation
models (Claude 3.x, Llama 3.1, Mistral, Nova, Cohere).

Embedding, OCR, ASR, TTS, and Image2Text are intentionally
out of scope for this PR and return the documented "no such
method" sentinel.

Tests cover key parsing (every auth_mode), region resolution,
Converse request shaping (system extraction, role validation,
multimodal rejection), URL building (default and override),
HTTP happy path / error propagation, event-stream decoding,
exception surfacing, truncation detection, and every
no-such-method sentinel. The httptest server accepts any SigV4
signature rather than re-verifying it; SigV4 correctness is
the SDK's responsibility.
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 22, 2026
@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e310693e-f96b-48a5-8ba3-654c6b586b8b

📥 Commits

Reviewing files that changed from the base of the PR and between 19884cb and dc69d83.

📒 Files selected for processing (1)
  • internal/entity/models/factory.go

📝 Walkthrough

Walkthrough

Adds an AWS Bedrock ModelDriver: new provider config, SigV4-signed Converse and Converse-Stream implementations with credential/region resolution (access-key, IAM-role, assume-role), model listing, unsupported capability stubs, factory wiring, and comprehensive unit tests.

Changes

Bedrock Chat Provider Implementation

Layer / File(s) Summary
Configuration and Constants
conf/models/bedrock.json, internal/entity/models/bedrock.go (lines 1–61)
Bedrock JSON provider config and Go constants for URL suffixes, hosts, and auth-mode strings.
Authentication and Credential Resolution
internal/entity/models/bedrock.go (lines 144–277), internal/entity/models/bedrock_test.go (lines 54–138)
Parses API key JSON (access_key_secret, iam_role, assume_role), resolves region precedence, retrieves AWS credentials (static, chain, STS AssumeRole), and validates required fields; tests cover parse and region logic.
Driver Instance Structure
internal/entity/models/bedrock.go (lines 95–137)
BedrockModel driver type, constructor, and NewInstance method with custom HTTP transport for streaming.
Request/Response Contracts and Helpers
internal/entity/models/bedrock.go (lines 279–511), internal/entity/models/bedrock_test.go (lines 198–306)
Converse request/response shapes, system-message extraction, ChatConfig→inference mapping, answer concatenation, SigV4 signing, runtime/control URL builders, safe path join, event-stream header/payload decoding, and related tests.
Non-Streaming Chat
internal/entity/models/bedrock.go (lines 513–585), internal/entity/models/bedrock_test.go (lines 307–409)
ChatWithMessages: builds & SigV4-signs Converse POST, executes request, parses JSON response, returns ChatResponse; tests cover happy path, missing API key/model, and HTTP error propagation.
Streaming Chat
internal/entity/models/bedrock.go (lines 587–714), internal/entity/models/bedrock_test.go (lines 461–648)
ChatStreamlyWithSender: SigV4-signed Converse-Stream POST with event-stream decoding, forwards contentBlockDelta deltas to sender, enforces terminal messageStop and stream config; tests include happy path, exceptions, truncation, and config guards.
Model Discovery and Capability Stubs
internal/entity/models/bedrock.go (lines 755–826, 828–834, 836–892), internal/entity/models/bedrock_test.go (lines 410–460, 649–694)
ListModels calls control-plane foundation-models endpoint and returns filtered model IDs; CheckConnection delegates to ListModels; unsupported methods return “no such method”; tests validate listing and stub behavior.
Factory Integration & Test Setup
internal/entity/models/factory.go (lines 138–139), internal/entity/models/bedrock_test.go (lines 1–30, 695–698)
CreateModelDriver recognizes "bedrock" and returns NewBedrockModel; test file includes imports and compile-time ModelDriver interface check.

Sequence Diagram

sequenceDiagram
  participant Client
  participant BedrockRuntime as Bedrock Runtime (converse/converse-stream)
  participant STS as AWS STS (AssumeRole)
  participant Control as Bedrock Control Plane (foundation-models)

  Client->>STS: AssumeRole (when auth_mode=assume_role)
  STS-->>Client: Temporary credentials
  Client->>BedrockRuntime: POST /model/{id}/converse (SigV4-signed)
  BedrockRuntime-->>Client: JSON response (content blocks)
  Client->>BedrockRuntime: POST /model/{id}/converse-stream (SigV4-signed, event-stream)
  BedrockRuntime-->>Client: Event-stream frames (contentBlockDelta / messageStop / exception)
  Client->>Control: GET /foundation-models (SigV4-signed) [ListModels]
  Control-->>Client: Catalog JSON (modelId list)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • infiniflow/ragflow#15010: Adds a provider driver and updates CreateModelDriver routing (similar factory integration pattern).
  • infiniflow/ragflow#15092: Registers a new provider in the model factory, matching the factory-change approach used here.
  • infiniflow/ragflow#15045: Adds another provider driver and factory branch; related at the provider-registration level.

Suggested reviewers

  • Haruko386

🐰 I hopped to add Bedrock cheer,
SigV4 signed and streaming near,
Regions found and models shown,
Tests assert the driver’s tone,
Hooray — the runtime answers clear!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.51% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The PR description is comprehensive but does not follow the provided template structure with required sections like 'What problem does this PR solve?' and 'Type of change' checkboxes. Restructure the description to match the template format with explicit sections for problem statement and type of change selection, while preserving the detailed technical content.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(go-models): add AWS Bedrock provider driver' accurately and concisely describes the main change—adding a new AWS Bedrock provider driver implementation.
Linked Issues check ✅ Passed All coding objectives from #15165 are met: BedrockModel driver with SigV4 auth (3 modes), chat/streaming endpoints, ListModels, region resolution, event-stream decoding, truncation detection, and 'no such method' sentinels for out-of-scope methods.
Out of Scope Changes check ✅ Passed All changes align with PR objectives: bedrock.go driver, bedrock_test.go tests, factory.go registration, and bedrock.json config are all within scope of implementing the Bedrock provider.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

❤️ Share

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

@whitepicker

Copy link
Copy Markdown
Contributor Author

Hi @Haruko386 how are you? Could you please review this PR?

@Haruko386

Haruko386 commented May 25, 2026 •

Copy link
Copy Markdown
Member

Hi @jakearmstrong59, I wil review your code soon.
But before it, would you mind giving me API reference Docs for BedRock
I can't find it : ( . I would be happy if you could point me where it.

@Haruko386 Haruko386 added the ci Continue Integration label May 25, 2026

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@jakearmstrong59 LGTM

@codecov

codecov Bot commented May 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (ed179ce) to head (dc69d83).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15166   +/-   ##
=======================================
  Coverage   93.12%   93.12%           
=======================================
  Files          10       10           
  Lines         713      713           
  Branches      116      116           
=======================================
  Hits          664      664           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit 0fb85a6 into infiniflow:main May 26, 2026
1 check passed
@tmimmanuel tmimmanuel mentioned this pull request Jun 3, 2026
6 tasks done
yingfeng pushed a commit that referenced this pull request Jun 5, 2026
### What problem does this PR solve?

Fixes #15542.

AWS Bedrock support for the Go model provider layer was added in #15166,
but embedding support was intentionally left out of scope and
`BedrockModel.Embed(...)` still returned the `no such method` sentinel.
This PR implements Bedrock text embeddings under the umbrella provider
tracker #14736.

### What this PR includes

- `internal/entity/models/bedrock.go`: implement
`BedrockModel.Embed(...)` through Bedrock Runtime `InvokeModel` with
existing SigV4 auth, region resolution, and runtime URL helpers.
- Titan embeddings: supports `amazon.titan-embed-text-v1` and
`amazon.titan-embed-text-v2:0`; v2 forwards `EmbeddingConfig.Dimension`
as `dimensions` when provided, while v1 keeps the payload minimal.
- Cohere embeddings: supports `cohere.embed-english-v3`,
`cohere.embed-multilingual-v3`, and `cohere.embed-v4:0`; batches input
texts and maps returned vectors to RAGFlow `EmbeddingData` in input
order.
- `conf/models/bedrock.json`: adds the `embedding` URL suffix (`invoke`)
and Bedrock embedding model entries.
- `internal/entity/models/bedrock_test.go`: adds unit tests for Titan,
Cohere, typed Cohere responses, validation, empty input, unsupported
models, and HTTP error propagation.

Reference docs:

- Bedrock InvokeModel API:
https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html
- Titan Text Embeddings:
https://docs.aws.amazon.com/bedrock/latest/userguide/titan-embedding-models.html
- Cohere Embed models on Bedrock:
https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-embed.html

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### How was this tested?

- [x] `jq empty conf/models/bedrock.json`
- [x] `git diff --check`
- [x] `go test ./internal/entity/models/... -run Bedrock -count=1`
- [x] `go test ./internal/entity/models/... -run '^$' -count=1`
- [x] `go test ./internal/entity/models/... -run Bedrock -race -count=1`

Note: `go test ./internal/entity/models/... -count=1` currently fails in
unrelated existing Astraflow coverage
(`TestAstraflowEmbedReturnsNoSuchMethod` panics in
`internal/entity/models/astraflow.go`). The Bedrock-specific tests and
compile-only package check pass.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Implement provider: AWS Bedrock in Go driver

3 participants