@aws-blocks/bb-knowledge-base

中文文档
0.3.0发布于 2026/11/02Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 6.3万

Semantic document retrieval backed by Amazon Bedrock Knowledge Bases.

原始使用文档
文档目录16 节
  1. Quick Start
  2. API
  3. Options
  4. Source Configuration
  5. Chunking Strategies
  6. Chunking Options
  7. Retrieve Options
  8. Retrieve Result
  9. Sync
  10. Metadata Filtering
  11. Trust Boundary
  12. Error Handling
  13. Deploy Behavior
  14. Scaling & Cost (AWS)
  15. Local Development
  16. See Also

@aws-blocks/bb-knowledge-base

Semantic document retrieval backed by Amazon Bedrock Knowledge Bases.

When to use: Search over your own documents — FAQs, product guides, support articles, internal wikis. Point it at a folder and query with natural language.

When NOT to use: If you need structured key-value lookups, use KVStore. If you need relational queries, use Database. If you need full-text keyword search only (no semantic understanding), roll your own with DistributedTable.

Design & mock parity details: DESIGN.md

Quick Start

import { Scope, ApiNamespace } from '@aws-blocks/core';
import { KnowledgeBase } from '@aws-blocks/bb-knowledge-base';

const scope = new Scope('my-app');

const kb = new KnowledgeBase(scope, 'docs', {
  source: './knowledge',
  description: 'Product documentation',
});

export const api = new ApiNamespace(scope, 'api', (context) => ({
  async search(query: string) {
    const results = await kb.retrieve(query, { maxResults: 5 });
    return { results };
  },
}));

API

const kb = new KnowledgeBase(scope, id, options)
MethodReturnsDescription
retrieve(query, options?)Promise<RetrieveResult[]>Search for relevant document chunks. Returns results ranked by relevance score.
isSynced()Promise<boolean>Whether the KB is synced with your latest data. true once the latest ingestion job is COMPLETE (or there is no BB-managed data source to track). Reports data freshness, not availability — retrieve() is always callable and serves the prior snapshot while a re-ingestion is in flight. Throws IngestionFailed if the latest job failed.
waitUntilSynced(options?)Promise<void>Poll isSynced() until the KB is synced with your latest data or the timeout elapses. Throws Timeout if it does not sync in time. Accepts an optional AbortSignal to cancel the wait.

Options

OptionTypeDefaultDescription
sourcestring(required)Document source — local folder path or s3:// URI pointing to a bucket or folder.
chunkingChunkingConfig{ strategy: 'semantic' }How documents are split into chunks.
embeddingDimensions256 | 512 | 10241024Embedding model dimensions.
descriptionstring—Human-readable description for the knowledge base.
removalPolicy'destroy' | 'retain'stack defaultsCDK removal behavior for BB-created data buckets (imported s3:// URI sources are unaffected). When omitted, follows the stack-wide defaults (production → RETAIN, sandbox → DESTROY). Pass 'destroy' to drop the bucket on teardown for this KB — also enables autoDeleteObjects.
loggerChildLogger—Optional logger for internal operations. When omitted, a default Logger at error level is created.

Source Configuration

// Local folder — synced to S3 on deploy
new KnowledgeBase(scope, 'docs', { source: './knowledge' });

// Existing S3 bucket (with optional prefix)
new KnowledgeBase(scope, 'docs', { source: 's3://my-bucket' });
new KnowledgeBase(scope, 'docs', { source: 's3://my-bucket/docs/prefix/' });

S3 URI source: When using an s3:// URI, the CDK construct imports the existing bucket instead of creating a new one. An optional path prefix narrows which objects Bedrock ingests. No BucketDeployment is created — your documents must already be in the bucket. In local development, S3 URI sources are not supported (use a local folder path instead).

Chunking Strategies

StrategyDescription
'semantic'(Default) Splits at natural topic boundaries using breakpoint detection.
'fixed'Fixed-size chunks with configurable chunkSize and chunkOverlap.
'hierarchical'Two-level chunking (parent 1500 tokens, child 300 tokens).
'none'No chunking — each document is a single chunk.

Chunking Options

chunking accepts a ChunkingConfig. Options apply only to the relevant strategy; others are ignored.

OptionTypeDefaultApplies toDescription
strategy'semantic' | 'fixed' | 'hierarchical' | 'none''semantic'allChunking strategy.
chunkSizenumber300'fixed'Max tokens per chunk.
chunkOverlapnumber20'fixed'Overlap percentage between consecutive chunks (0–100).
breakpointPercentilenumber95'semantic'Breakpoint percentile for topic-boundary detection (0–100).
chunking: { strategy: 'fixed', chunkSize: 500, chunkOverlap: 10 }

Retrieve Options

OptionTypeDefaultDescription
maxResultsnumber10Maximum results to return. Range: 1–100.
filterMetadataFilter—Metadata filter with AND semantics across all key-value pairs.

Retrieve Result

FieldTypeDescription
textstringChunk text content.
scorenumberRelevance score 0.0–1.0.
sourcestringSource document path or URL.
metadataRecord<string, string>Document metadata. Includes auto-populated folder from subfolders.

Sync

Bedrock ingestion runs asynchronously after deploy, so immediately after cdk deploy the knowledge base is not yet synced with your latest data — during that initial pre-sync window retrieve() returns an empty array even for queries that will later match. (Once at least one ingestion job has completed, retrieve() always serves the most recent synced snapshot, even while a later re-ingestion is in flight.) Use isSynced() / waitUntilSynced() to gate on ingestion completion:

// Block until the KB is synced with your latest data (e.g. right after deploy), then query
await kb.waitUntilSynced({ timeoutMs: 600_000 });
const results = await kb.retrieve('getting started');

// Or check without blocking
if (await kb.isSynced()) {
  const results = await kb.retrieve('getting started');
}

// Cancel the wait with an AbortSignal (e.g. an overall request deadline)
await kb.waitUntilSynced({ signal: AbortSignal.timeout(120_000) });

waitUntilSynced(options?) accepts timeoutMs (default 300_000), pollIntervalMs (default 5_000, clamped to a 1ms minimum), maxConsecutiveTransientErrors (default 3, minimum 0), and an optional signal (AbortSignal). The poll interval carries a small amount of random jitter (±20%) so that many knowledge bases polling after a shared deploy don't fall into lockstep — the jitter only varies the delay between polls and never pushes a sleep past timeoutMs.

maxConsecutiveTransientErrors is the number of consecutive transient control-plane errors tolerated before giving up; the counter resets on any clean poll. Two conditions are treated as transient and ridden out: throttling / transient network failures, and a not-yet-visible knowledge base — in the post-deploy window the control plane can briefly return ResourceNotFoundException (the freshly-created KB or data source hasn't propagated yet), which waitUntilSynced() absorbs rather than giving up on. Terminal errors always short-circuit immediately regardless of the limit: a FAILED ingestion job, and a missing-KB config error (the KB_ID env var is unset — distinct from the transient not-yet-visible case). When signal is provided, the wait is cancelled promptly (checked before each poll and during the inter-poll delay), rejecting with the signal's abort reason (by default a DOMException named 'AbortError').

Both local-folder and imported s3:// sources register a BB-managed data source, so sync state reflects that data source's ingestion job in either case. (A deployment predating this sync API has no data source id injected, so isSynced() returns true immediately — there is nothing to track.) This pre-feature deployment is the only case where isSynced() returns true without consulting an actual ingestion job — re-deploying injects DATA_SOURCE_ID and restores real tracking, so a freshly deployed KB always reflects a real job status (don't mistake the "nothing to track" shortcut for "ingestion confirmed complete" when gating live traffic). In local development the mock is always synced. Note that a local isSynced() of true does not imply retrieve() works for an s3:// source — the mock rejects s3:// with InvalidSourceConfigException (the inverse of the production contract), so validate s3:// sources in sandbox/production where sync state genuinely reflects queryability.

Metadata Filtering

Filter results by document metadata. All conditions use AND semantics:

// Only return chunks from the 'faq' folder
const results = await kb.retrieve('how do I reset my password', {
  filter: { folder: { equals: 'faq' } },
});

// Multiple filters (AND)
const results = await kb.retrieve('pricing', {
  filter: {
    folder: { equals: 'products' },
    category: { equals: 'enterprise' },
  },
});

Subfolder paths automatically populate the folder metadata key. For example, a file at ./knowledge/faq/billing.md gets metadata.folder = 'faq'.

Trust Boundary

A knowledge base is one index, not one per user or tenant, and retrieve() returns whatever matches. Two consequences:

  • A filter is a query scope, not an access control. If you keep several users' or tenants' documents in one knowledge base, set the filter in your server code from the authenticated caller (for example filter: { tenant: { equals: user.tenantId } }). Never take it from the request body or from an agent tool's input, or a caller can read other tenants' documents by changing it.
  • Indexed text is untrusted. If a source can receive content you don't write yourself, for example an s3:// source that is a FileBucket your users upload to, that content reaches anyone who retrieves it. When results go to an agent, they can carry instructions that try to make it misuse its tools (indirect prompt injection). Mark the agent tool that calls retrieve() with untrustedOutput: true, and see Retrieved content is untrusted in the Agent docs.

Error Handling

import { isBlocksError } from '@aws-blocks/core';
import { KnowledgeBaseErrors } from '@aws-blocks/bb-knowledge-base';

try {
  const results = await kb.retrieve('query');
} catch (e: unknown) {
  if (isBlocksError(e, KnowledgeBaseErrors.NotReady)) {
    // KB not yet deployed or ingested
  }
  if (isBlocksError(e, KnowledgeBaseErrors.ValidationError)) {
    // Empty query
  }
  throw e;
}
Error ConstantNameWhen
KnowledgeBaseErrors.RetrievalFailedRetrievalFailedExceptionBedrock retrieval call failed
KnowledgeBaseErrors.NotReadyKnowledgeBaseNotReadyExceptionKB not deployed or env vars missing
KnowledgeBaseErrors.IngestionFailedIngestionFailedExceptionThe most recent ingestion job failed (message includes failureReasons) — thrown by isSynced() / waitUntilSynced()
KnowledgeBaseErrors.TimeoutKnowledgeBaseTimeoutExceptionwaitUntilSynced() exceeded its timeout before ingestion completed
KnowledgeBaseErrors.InvalidSourceInvalidSourceConfigExceptionSource folder not found or invalid config
KnowledgeBaseErrors.InvalidFilterInvalidFilterExceptionInvalid filter keys in Bedrock query
KnowledgeBaseErrors.ValidationErrorKnowledgeBaseValidationErrorEmpty or invalid query
KnowledgeBaseErrors.BrowserNotSupportedBrowserNotSupportedExceptionUsed in a browser context — KnowledgeBase is server-side only

Deploy Behavior

cdk deploy automatically triggers document ingestion (fire-and-forget). Ingestion runs asynchronously after the deploy completes. Check the AWS console to monitor ingestion progress, or call isSynced() / waitUntilSynced() from your code to gate queries on ingestion completion.

Scaling & Cost (AWS)

  • Embedding model: Amazon Titan Text Embeddings V2
  • Vector store: S3 Vectors (serverless, no provisioning)
  • Embedding cost: ~$0.00002 per 1,000 tokens (ingestion)
  • Retrieval cost: ~$0.00002 per 1,000 tokens (query embedding) + S3 Vectors query cost
  • Storage: S3 standard pricing for source documents + S3 Vectors for embeddings
  • Max document size: 50 MB per file
  • Supported formats: .md, .txt, .html, .htm, .csv, .json (plus binary formats parsed on AWS: .pdf, .doc, .docx, .xls, .xlsx)

Local Development

In local dev mode, KnowledgeBase reads documents from the source folder, splits them into chunks according to the configured chunking strategy, and uses TF-IDF for relevance scoring. Results are cached to .bb-data/{fullId}/chunks.json for fast restarts; the cache is keyed on the source folder's contents and the chunking configuration, and is rebuilt automatically when documents are added, edited, or removed, or the chunking settings change.

Parity notes:

  • Scoring uses TF-IDF (keyword-based) rather than real embeddings. Scores are relative within the mock and won't match production Bedrock scores exactly.
  • The TF-IDF tokenizer is Unicode-aware: accents are normalized (so resume matches résumé) and CJK text is matched via character bigrams.
  • Chunking is approximated locally: 'fixed' uses word-count windows (chunkSize/chunkOverlap), 'none' keeps each document whole, and 'semantic' (and 'hierarchical') split on paragraph boundaries.
  • chunkOverlap is a percentage of chunkSize in both environments: locally the mock overlaps by chunkSize × chunkOverlap / 100 words, and the CDK layer maps it to Bedrock's overlapPercentage (1–99). The value is directly transferable between local dev and production.
  • The API contract (method signatures, error types, result shape) is identical to AWS.
  • maxResults works identically. Metadata filtering uses the same equals/AND semantics, with one asymmetry: in production an unknown or invalid filter key is typically rejected server-side by Bedrock (surfaced as InvalidFilterException when the service flags the filter), whereas locally the mock silently matches nothing and returns an empty result set.
  • source must be a relative path inside the project directory — absolute paths and paths that escape the project (via ..) are rejected with InvalidSourceConfigException. S3 URI sources are not supported in local development — use a local folder path.

Wipe cached data with rm -rf .bb-data.

See Also

版本与发布记录

@aws-blocks/bb-knowledge-base 共发布 15 个版本,首次发布于 2026/06/16;过去 12 个月发布了 15 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.3.0latest2026/11/025 天前
0.2.62026/10/1622 天前
0.0.0-canary.esql-canary.c93c81b.1791235863canary-esql-canary2026/10/061 个月前
0.2.52026/10/051 个月前
0.0.0-canary.esql-canary.f7f39ac.17909891272026/10/031 个月前
0.0.0-canary.ci-publish-canary-npm.f53dfdc.1790988617canary-ci-publish-canary-npm2026/10/031 个月前

关于 @aws-blocks/bb-knowledge-base 的常见问题

@aws-blocks/bb-knowledge-base 是什么?

Semantic document retrieval backed by Amazon Bedrock Knowledge Bases.

如何安装 @aws-blocks/bb-knowledge-base?

在项目目录运行 npm install @aws-blocks/bb-knowledge-base,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:constructs(^10.6.0)、aws-cdk-lib(^2.257.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws-blocks/bb-knowledge-base 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws-blocks/bb-knowledge-base 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@aws-blocks/bb-knowledge-base 可以商用吗?

@aws-blocks/bb-knowledge-base 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws-blocks/bb-knowledge-base 的下载量有多少?

根据 npm 官方下载统计,@aws-blocks/bb-knowledge-base 在 2026/10/07 – 2026/11/05 这 30 天内被下载 63,114 次,日均约 2,104 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws-blocks/bb-knowledge-base 还在维护吗?

最新版本 0.3.0 发布于 2026/11/02(5 天前);至今共发布 15 个版本,其中过去 12 个月发布了 15 个;首次发布于 2026/06/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。