Skip to content

Go: implement Bedrock embeddings - #15543

Merged
yingfeng merged 2 commits into
infiniflow:mainfrom
tmimmanuel:feat/bedrock-embedding
Jun 5, 2026
Merged

yingfeng merged 2 commits into
infiniflow:mainfrom
tmimmanuel:feat/bedrock-embedding

Conversation

@tmimmanuel

@tmimmanuel tmimmanuel commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

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:

Type of change

  • New Feature (non-breaking change which adds functionality)

How was this tested?

  • jq empty conf/models/bedrock.json
  • git diff --check
  • go test ./internal/entity/models/... -run Bedrock -count=1
  • go test ./internal/entity/models/... -run '^$' -count=1
  • 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.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 3, 2026
@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds Bedrock embedding support: updates bedrock.json with embedding model entries and URL suffixes, implements BedrockModel.Embed with SigV4-signed InvokeModel calls, routes to Titan or Cohere embedders, parses embeddings, and adds comprehensive unit tests.

Changes

Bedrock Embedding Support

Layer / File(s) Summary
Embedding model configuration
conf/models/bedrock.json
Bedrock configuration's url_suffix is extended with models ("foundation-models") and embedding ("invoke") endpoints. Embedding model entries are added for Amazon Titan Text Embed v2 and v1, and Cohere embed v3 and v4, each with max_tokens and model_types: ["embedding"].
Embedding endpoint infrastructure
internal/entity/models/bedrock.go
New default embedding URL suffix constant ("invoke") and embeddingSuffix() resolver to compute the InvokeModel path from config or defaults.
Embedding request/response types
internal/entity/models/bedrock.go
Adds Titan single-input and Cohere batched request/response struct types used by the embedding implementations.
Embed entry point and routing
internal/entity/models/bedrock.go
Embed() validates inputs and API key, parses Bedrock API key JSON, resolves region and credentials, and routes by model prefix to Titan or Cohere implementations. Returns empty slice for nil input and errors for unsupported models.
InvokeModel signer and executor
internal/entity/models/bedrock.go
invokeEmbeddingModel() marshals embedding requests, builds per-region Runtime URL using embeddingSuffix(), signs the request with SigV4, performs the HTTP request, enforces HTTP 200, and returns the JSON body.
Titan embedding implementation
internal/entity/models/bedrock.go
embedTitan() issues one request per input text to Titan, parses per-response embeddings, requires non-empty vectors, and constructs ordered []EmbeddingData.
Cohere embedding implementation
internal/entity/models/bedrock.go
embedCohere() sends a batched Cohere request. decodeCohereEmbeddingVectors() decodes vectors from either [][]float64 or typed maps with "float", validates counts and non-empty vectors, and returns ordered embeddings.
Comprehensive embedding test coverage
internal/entity/models/bedrock_test.go
Adds tests for Titan v2 (dimension forwarding and multi-input ordering) and v1 (omits dimensions), Cohere v3 (array responses) and v4 (typed responses and output dimension forwarding), input guards (nil texts), required validation (API key and non-blank model), unsupported model rejection, and HTTP error propagation including response body.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Embed
  participant Router
  participant invokeEmbeddingModel
  participant BedrockRuntime
  Client->>Embed: Embed(modelName, texts, apiConfig)
  Embed->>Embed: Validate inputs, parse API key, resolve region/creds
  Embed->>Router: route by modelName prefix
  alt Titan model
    Router->>invokeEmbeddingModel: POST /model/{id}/invoke (single text)
    invokeEmbeddingModel->>BedrockRuntime: Signed InvokeModel request
    BedrockRuntime-->>invokeEmbeddingModel: 200 + Titan embedding JSON
    invokeEmbeddingModel-->>Router: response body
    Router-->>Embed: EmbeddingData[] (one per input)
  else Cohere model
    Router->>invokeEmbeddingModel: POST /model/{id}/invoke (batched texts)
    invokeEmbeddingModel->>BedrockRuntime: Signed InvokeModel request
    BedrockRuntime-->>invokeEmbeddingModel: 200 + Cohere embeddings JSON
    invokeEmbeddingModel-->>Router: response body
    Router-->>Embed: EmbeddingData[] (ordered batch)
  end
  Embed-->>Client: []EmbeddingData, error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15166: Prior Bedrock driver merge that left Embed() as a "no such method" stub and provides surrounding Bedrock auth/region/runtime helpers.

Suggested labels

size:XL

Suggested reviewers

  • Haruko386

Poem

🐰 I hopped through JSON, code, and test,
Found Titan vectors, parsed the rest.
Cohere batched and signed with care,
Embeddings bloom from Bedrock's lair.
Hooray! — a rabbit's coding cheer.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 'Go: implement Bedrock embeddings' directly and concisely describes the main change—implementing AWS Bedrock embedding support in the Go model provider layer.
Linked Issues check ✅ Passed The implementation successfully addresses all coding objectives from #15542: implements BedrockModel.Embed() using InvokeModel, adds Titan and Cohere embedding support, updates conf/models/bedrock.json with embedding models and URL suffix, adds comprehensive unit tests, and reuses existing auth/region helpers.
Out of Scope Changes check ✅ Passed All changes are directly scoped to Bedrock embedding implementation: embedding method logic, model configuration, and corresponding tests. No rerank, TTS/STT, OCR, or other out-of-scope features are introduced.
Description check ✅ Passed The PR description comprehensively addresses the problem statement, lists all included changes with file references, specifies the type of change, and provides testing evidence with reference documentation.

✏️ 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.

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

🧹 Nitpick comments (1)
internal/entity/models/bedrock.go (1)

966-1002: 💤 Low value

Consider making Cohere input_type configurable.

The input_type is hardcoded to "search_document". Cohere recommends using "search_query" for query embeddings and "search_document" for document indexing to optimize asymmetric retrieval. If RAGFlow uses this for both indexing and querying, queries may benefit from the appropriate type.

This isn't blocking for initial implementation, but could be added to EmbeddingConfig in a follow-up.

🤖 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 966 - 1002, The embedCohere
method currently hardcodes the input type as "search_document", but this should
be configurable to support different embedding scenarios like "search_query" for
queries. To fix this, add an optional input_type field to the EmbeddingConfig
struct and use its value when set; otherwise, default to "search_document"
within the embedCohere function. This change allows the caller to specify the
input type to better optimize embedding for queries versus documents, improving
flexibility without breaking existing behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@internal/entity/models/bedrock.go`:
- Around line 966-1002: The embedCohere method currently hardcodes the input
type as "search_document", but this should be configurable to support different
embedding scenarios like "search_query" for queries. To fix this, add an
optional input_type field to the EmbeddingConfig struct and use its value when
set; otherwise, default to "search_document" within the embedCohere function.
This change allows the caller to specify the input type to better optimize
embedding for queries versus documents, improving flexibility without breaking
existing behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a2a8cd6a-0067-4c03-b569-3916bad03526

📥 Commits

Reviewing files that changed from the base of the PR and between 9799f33 and 453ccb8.

📒 Files selected for processing (3)
  • conf/models/bedrock.json
  • internal/entity/models/bedrock.go
  • internal/entity/models/bedrock_test.go

@tmimmanuel

Copy link
Copy Markdown
Contributor Author

@Haruko386
Please check.

@Haruko386

Copy link
Copy Markdown
Member

@tmimmanuel before I review your code, could you provide BedRock embeddings API docs?
I need docs to review your code

@tmimmanuel

Copy link
Copy Markdown
Contributor Author

Bedrock does not have a separate universal “Embeddings API.” Embeddings are invoked through bedrock-runtime:InvokeModel, and the request/response body depends on the selected embedding model.
What shall I do?

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

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jun 3, 2026
@Haruko386 Haruko386 added the ci Continue Integration label Jun 3, 2026
@Haruko386
Haruko386 marked this pull request as draft June 3, 2026 11:05
@Haruko386
Haruko386 marked this pull request as ready for review June 3, 2026 11:05
@codecov

codecov Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (98f2a2e) to head (ee2826e).
⚠️ Report is 19 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15543   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 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.

@Haruko386

Copy link
Copy Markdown
Member

@tmimmanuel please refer #15627 for model provider refactor

# Conflicts:
#	internal/entity/models/bedrock.go

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/entity/models/bedrock.go (1)

892-901: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use a request-scoped timeout for Titan instead of a batch-scoped one.

embedTitan() makes one InvokeModel call per input, but every call inherits the single deadline created here. On larger Titan batches, early requests consume nonStreamCallTimeout and later items start failing with context deadline exceeded even when each individual Bedrock call is healthy.

Suggested direction
-	ctx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
-	defer cancel()
-
-	creds, err := resolveBedrockCredentials(ctx, key, region)
+	credsCtx, cancel := context.WithTimeout(context.Background(), nonStreamCallTimeout)
+	defer cancel()
+
+	creds, err := resolveBedrockCredentials(credsCtx, key, region)
 	if err != nil {
 		return nil, err
 	}
 
 	if strings.HasPrefix(modelID, "amazon.titan-embed-text-") {
-		return b.embedTitan(ctx, modelID, texts, region, creds, embeddingConfig)
+		return b.embedTitan(context.Background(), modelID, texts, region, creds, embeddingConfig)
 	}
 func (b *BedrockModel) invokeEmbeddingModel(ctx context.Context, modelID string, body interface{}, region string, creds awssdk.Credentials) ([]byte, error) {
+	reqCtx, cancel := context.WithTimeout(ctx, nonStreamCallTimeout)
+	defer cancel()
+
 	raw, err := json.Marshal(body)
 	if err != nil {
 		return nil, fmt.Errorf("bedrock: marshal embedding request: %w", err)
 	}
 	url := b.bedrockRuntimeURL(region, modelID, b.embeddingSuffix())
-	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(raw))
+	req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, url, bytes.NewReader(raw))
 	if err != nil {
 		return nil, fmt.Errorf("bedrock: build embedding request: %w", err)
 	}
@@
-	if err := signBedrockRequest(ctx, req, raw, creds, bedrockRuntimeService, region); err != nil {
+	if err := signBedrockRequest(reqCtx, req, raw, creds, bedrockRuntimeService, region); err != nil {
 		return nil, err
 	}

Based on learnings: when httpClient.Timeout is intentionally unset, context.WithTimeout should be the per-request deadline rather than one shared deadline across multiple HTTP calls.

🤖 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 892 - 901, The shared
context.WithTimeout created here applies a single deadline to the whole batch
and causes later per-input InvokeModel calls to fail; for Titan embedding, stop
passing that batch-scoped timeout into embedTitan and instead enforce a
per-request timeout inside embedTitan (use context.WithTimeout for each
InvokeModel call using nonStreamCallTimeout), so locate embedTitan and wrap each
InvokeModel invocation with its own request-scoped context (and cancel) while
still using resolveBedrockCredentials/creds as before.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@internal/entity/models/bedrock.go`:
- Around line 892-901: The shared context.WithTimeout created here applies a
single deadline to the whole batch and causes later per-input InvokeModel calls
to fail; for Titan embedding, stop passing that batch-scoped timeout into
embedTitan and instead enforce a per-request timeout inside embedTitan (use
context.WithTimeout for each InvokeModel call using nonStreamCallTimeout), so
locate embedTitan and wrap each InvokeModel invocation with its own
request-scoped context (and cancel) while still using
resolveBedrockCredentials/creds as before.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 357b387d-1764-4c3c-b1da-7e13e47d550b

📥 Commits

Reviewing files that changed from the base of the PR and between 453ccb8 and ee2826e.

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

@yingfeng
yingfeng merged commit f78ef32 into infiniflow:main Jun 5, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants