sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[FEATURE] Score threshold for BedrockKnowledgeBaseStore.search()

Open saime428 opened this issue 3 months ago • 1 comments

SDK Language

Both / Not language-specific

Problem Statement

BedrockKnowledgeBaseStore.search() returns every result the Retrieve API hands back. The relevance score is read off the response and stuffed into metadata as _relevance_score / _relevanceScore, and then nothing uses it. There is no way to say "drop anything below 0.5".

So the only lever a caller has over what lands in the agent's context is max_search_results, which is a count, not a quality bar. On a narrow query where the KB only holds one good chunk, asking for 5 results gets 1 good chunk and 4 pieces of noise, and all 5 go into the prompt.

There is a second half to this. Scores from a Bedrock KB are not always similarities. When the KB is backed by Aurora PostgreSQL with pgvector using the <=> operator, what comes back is cosine distance, where 0 is a perfect match and larger is worse. Any filter that assumes "higher is better" gets it exactly backwards on that setup and throws away the best results. That was reported against the retrieve tool in strands-agents/tools#417.

Some history so this doesn't look like it comes out of nowhere: I opened strands-agents/tools#535 to fix the direction problem in the retrieve tool. During review @lizradway pointed out that the memory manager is where this belongs going forward and suggested porting the capability here. I'm opening this per CONTRIBUTING before writing any code.

Proposed Solution

Two optional fields on BedrockKnowledgeBaseStoreConfig, next to the max_search_results that is already there:

  • score_threshold: float / scoreThreshold: number
  • score_metric: "similarity" | "distance" / scoreMetric, defaulting to "similarity"

Filtering happens in BedrockKnowledgeBaseStore.search(), where the score is already being pulled off each result:

  • threshold unset: no filtering, current behavior unchanged
  • similarity: keep score >= threshold
  • distance: keep score <= threshold
  • result with no score: kept either way, since there is nothing to compare

Two things I left out on purpose.

No per-call override in SearchOptions. A relevance floor is a deployment tuning decision, not something that should vary per query, and definitely not something the model should be picking through a memory search tool. Config-only also keeps the whole change inside the bedrock_knowledge_base package instead of touching the shared store contract. If per-call turns out to be wanted it can be added later without breaking anyone.

No auto-detection of the metric. The store cannot tell which vector backend sits behind the KB without extra API calls, Retrieve does not report it, and guessing wrong silently deletes exactly the results the caller wanted. Whoever configured the KB knows; let them say so. The value is validated at construction rather than left to the TypedDict, because a typo falling through to the similarity branch would reproduce the original bug.

Use Case

Concretely, what I'm doing: a support agent with a KB of product docs. Questions vary in how well they're covered. For a covered question there are two or three genuinely relevant chunks; for an uncovered one there are none, but the KB still returns 5 because that's what I asked for. Those 5 weak chunks then get treated as authoritative context and the agent confabulates around them. I want to set a floor and let a search legitimately come back with fewer results, or zero, so the agent can say it doesn't know.

Second case is the pgvector one from tools#417. Anyone on Aurora with <=> needs score_metric="distance" for a threshold to mean anything at all.

Third, smaller but real: fewer chunks in the prompt is fewer input tokens on every single turn.

Alternatives Solutions

Filter server side. Would be the clean answer, but the Bedrock Retrieve API has no minimum-score parameter. KnowledgeBaseVectorSearchConfiguration takes numberOfResults, overrideSearchType, filter, rerankingConfiguration, nothing about a score floor. Client side is the only place this can happen.

Let callers filter on _relevance_score themselves. This works today and is what I'm doing. The reasons I don't think it should stay that way: the metadata key is a reserved synthetic field that every caller now has to know about, the name differs between the two SDKs (_relevance_score vs _relevanceScore), and every caller reimplements the same comparison with the same chance of getting the direction wrong on a distance-based KB. That's the bug in tools#417, just relocated into user code. It's also awkward on the injection path: _provide_memory_context searches and renders internally, so the only place an application can drop a weak entry is inside the format callback, which is a rendering hook being used as a filter.

Put the filter in MemoryManager.search() instead of the store. Would cover every store at once rather than just this one. I don't think it's right, because scores from different backends aren't on a common scale and a single threshold across a multi-store search would mean different things in each store. But I'd rather be told than assume. See the open questions below.

Additional Context

Where this lands, against main at the time of writing:

  • strands-py/src/strands/vended_memory_stores/bedrock_knowledge_base/store.py:230-244 - the result loop, _relevance_score set at 239
  • strands-ts/src/vended-memory-stores/bedrock-knowledge-base/store.ts:343-361 - same loop, _relevanceScore at 354
  • strands-py/src/strands/vended_memory_stores/bedrock_knowledge_base/types.py:114 - BedrockKnowledgeBaseStoreConfig, where the two fields would go
  • site/src/content/docs/user-guide/concepts/memory/overview.mdx:124 - config table where max_search_results is documented

Two things I'd like a decision on:

  1. Store or manager. Above I argue for the store, on the grounds that scores from different backends aren't on a common scale so one manager-wide threshold would mean something different in each store. If you'd rather have it generic in MemoryManager.search() over _relevance_score, say so and I'll build that instead.

  2. Interaction with numberOfResults. Filtering runs after retrieval, so max_search_results=5 with a threshold can return fewer than 5. The alternative is over-fetching and trimming back to 5, which costs more per query and makes the result count depend on the threshold in a way that's hard to reason about. My preference is the simple one: retrieve the requested number, filter, return what survives, document it clearly. Happy to go the other way if you disagree.

I have the Python side written against main - the two config fields, the filter in search(), and 10 tests covering both metrics, the unscored-result case, and a no-threshold regression guard. ruff check, ruff format --check and mypy ./src are clean and the memory + vended-store suites pass (293 tests). I've held off opening the PR until the two questions above are settled, since both could change the shape of it. TypeScript parity and the docs row would follow in the same PR, or a second one if you'd rather review Python first.

Related: strands-agents/tools#417, strands-agents/tools#535

saime428 avatar Aug 06 '26 07:08 saime428

Shipped in #3726 (merged 2026-08-18). That PR did not carry a closing reference, so closing this by hand.

saime428 avatar Sep 01 '26 19:09 saime428