Repository navigation
Go: implement Bedrock embeddings - #15543
Conversation
📝 WalkthroughWalkthroughAdds 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. ChangesBedrock Embedding Support
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/bedrock.go (1)
966-1002: 💤 Low valueConsider making Cohere
input_typeconfigurable.The
input_typeis 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
EmbeddingConfigin 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
📒 Files selected for processing (3)
conf/models/bedrock.jsoninternal/entity/models/bedrock.gointernal/entity/models/bedrock_test.go
|
@Haruko386 |
|
@tmimmanuel before I review your code, could you provide |
|
Bedrock does not have a separate universal “Embeddings API.” Embeddings are invoked through |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
@tmimmanuel please refer #15627 for model provider refactor |
# Conflicts: # internal/entity/models/bedrock.go
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/entity/models/bedrock.go (1)
892-901:⚠️ Potential issue | 🟠 Major | ⚡ Quick winUse 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 consumenonStreamCallTimeoutand later items start failing withcontext deadline exceededeven 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.Timeoutis intentionally unset,context.WithTimeoutshould 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
📒 Files selected for processing (1)
internal/entity/models/bedrock.go
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 theno such methodsentinel. This PR implements Bedrock text embeddings under the umbrella provider tracker #14736.What this PR includes
internal/entity/models/bedrock.go: implementBedrockModel.Embed(...)through Bedrock RuntimeInvokeModelwith existing SigV4 auth, region resolution, and runtime URL helpers.amazon.titan-embed-text-v1andamazon.titan-embed-text-v2:0; v2 forwardsEmbeddingConfig.Dimensionasdimensionswhen provided, while v1 keeps the payload minimal.cohere.embed-english-v3,cohere.embed-multilingual-v3, andcohere.embed-v4:0; batches input texts and maps returned vectors to RAGFlowEmbeddingDatain input order.conf/models/bedrock.json: adds theembeddingURL 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
How was this tested?
jq empty conf/models/bedrock.jsongit diff --checkgo test ./internal/entity/models/... -run Bedrock -count=1go test ./internal/entity/models/... -run '^$' -count=1go test ./internal/entity/models/... -run Bedrock -race -count=1Note:
go test ./internal/entity/models/... -count=1currently fails in unrelated existing Astraflow coverage (TestAstraflowEmbedReturnsNoSuchMethodpanics ininternal/entity/models/astraflow.go). The Bedrock-specific tests and compile-only package check pass.