AWS、RAGの限界を越えるタスク認識型知識圧縮技術を公開
AWS は、数百文書にわたる複雑な分析タスクで RAG が抱える課題に対処するため、タスク認識型の知識圧縮技術を紹介した。
AI深層分析を開く2026年7月28日 02:05
AI深層分析
キーポイント
RAG の限界と TAKC の登場
従来の RAG は類似度検索に依存するため、文書間の構造的な接続を見逃す課題があり、TAKC はこれをタスク指向の事前圧縮で解決する。
タスク固有の圧縮メカニズム
同じ文書でも財務分析用とコンプライアンスレビュー用などタスクごとに異なる要約を生成し、情報密度を最大化する仕組みを採用している。
オフライン処理とクエリ時の柔軟性
ドキュメントはタスクタイプごとに一度だけオフラインで圧縮され、クエリ時は圧縮表現が利用されるが、詳細不足時には低圧縮ティアへルーティングする。
運用上の構成管理
生産環境では圧縮プロンプトをバージョン管理された設定ストアに保存し、変更時の監査性と再圧縮のトリガーを可能にする設計が推奨される。
重要な引用
Similarity search surfaces relevant fragments but often misses cross-document connections.
TAKC compresses documents through the lens of a specific task, keeping what matters and discarding the rest.
The system answers questions using the compressed version instead of the full document.
編集コメントを表示
編集コメント
この技術は、単なる検索精度の向上を超え、企業データの本質的な意味構造をタスク単位で再構築するアプローチを示している。実装がオープンソースとして提供される点は、即座に検証や導入を進めたい開発者にとって極めて価値が高い。
数百の文書にわたる複雑な分析タスク、例えば財務デューデリジェンスや規制コンプライアンスレビューなどで Retrieval-Augmented Generation(RAG)を利用している場合、その限界に直面した経験があるかもしれません。類似度検索は関連する断片を提示しますが、文書間のつながりを捉えることはできません。本記事では、タスク固有の知識圧縮(TAKC)という手法を用いてこの課題に対処する方法を紹介します。これは、基盤となる知識全体をタスクに特化した表現として事前圧縮し、AWS 上で展開する技術です。完全なオープンソースの実装は、ご自身の AWS アカウントでもすぐにデプロイ可能です。
タスク認識型知識圧縮
5000 億ドル規模の製造業買収を検討しているプライベート・エクイティ企業を想像してください。デューデリジェンスチームは、12 の子会社と過去 5 年間にわたる財務諸表を分析する必要があります。さらに、サプライヤーとの契約書が 200 件以上、8 つの施設からの環境コンプライアンス報告書、そして 50 件以上の訴訟案件にも直面しています。
あるアナリストが「現在のサプライヤー条件と係争中の訴訟を踏まえた、連結財務リスクはどうなっているか」と質問したとき、RAG の類似度検索ではその回答を提示できません。関連する情報は数百の文書に散在しており、それらの間には言葉の表面的な類似性すら見当たらないからです。
TAKC はこの種の課題に対処するために、LLM(大規模言語モデル)を活用して、文書のより短く、タスクに焦点を当てた要約を作成します。そして、タスクごとに異なる要約を生成する仕組みです。
同じ文書でも、タスクによって必要な情報は異なります。財務分析用の年次報告書を要約する場合は、収益数値、利益率、キャッシュフローデータが重要です。一方、コンプライアンス監査用であれば、規制関連の条文や違反履歴が必要になります。
汎用的な要約はあらゆる情報を網羅しようとしますが、特定のユースケースにおける情報の密度を低下させてしまいます。TAKC は特定のタスクに焦点を当てて文書を圧縮するため、重要な情報だけを保持し、不要な部分は削除します。"Ingestion pipeline"セクションでは、どの情報を保持すべきかを指定する圧縮プロンプトの仕組みについて解説しています。
本番環境での運用においては、タスクタイプごとのプロンプトをバージョン管理された設定(AWS Systems Manager Parameter Store や、専用の Amazon S3 プレフィックスなど)に保存してください。これにより、プロンプトの変更履歴を追跡可能にし、プロンプトが更新された際に再圧縮をトリガーできるようになります。
このシステムは文書をオフラインで処理し、タスクタイプごとに一度だけ圧縮を行います。クエリ実行時には、元の文書ではなく事前に圧縮された表現を取得します。その後、圧縮版を用いて質問に回答します。もし圧縮表現が詳細に欠けていると判断された場合、クエリ複雑度解析器がより多くのコンテキストを保持する低圧縮ティアへ質問を振り分けます。
TAKC は、類似度検索で返される上位 k 件のチャンクに限定されず、圧縮された形で知識ベース全体へのアクセスを提供します。このシステムは文書同士をまとめて処理するため、文書間のつながりを保持したまま圧縮を行います。また、同じソース資料からでもタスクに応じて異なる圧縮結果を生成します。例えば、10-K 提出書類の財務情報に特化した圧縮と、同様の書類の法的リスクに焦点を当てた圧縮では、その内容や構成は全く異なります。
この手法により、トークン数は最大 8 倍から 64 倍まで削減されながら、タスクに関連する重要な情報の保持が優先されます。
マルチレート圧縮
異なるクエリには、異なる精度レベルが必要です。「第 3 四半期の売上高はいくらか」といった質問には、子会社間の支払条件と四半期キャッシュフローの関係を分析するリクエストに比べて、はるかに少ないコンテキストで対応可能です。
TAKC はこれに対応するため、各タスクタイプに対して 4 つの圧縮階層を維持しています。最も軽い圧縮(8 倍)では、コンテキスト量が約 87.5% 削減されますが、多段階推論や複数文書間の統合に必要な詳細は保持されます。中程度の圧縮(16 倍)では、コンテキスト量は約 93.8% 削減され、中程度の複雑さを持つ分析クエリに適しています。高い圧縮(32 倍)では約 96.9% の削減となり、事実確認や明確な質問への回答に利用されます。最も厳しい圧縮(64 倍)では約 98.4% が削減され、分類タスクやキーワード検索に適したレベルです。
クエリ複雑度解析器は、クエリの長さや質問の種類、分析言語の存在といったシグナルに基づいて、 incoming な質問を適切なティアにルーティングします。単純な事実確認型の質問は超圧縮キャッシュへ、複雑な分析系の質問は軽度の圧縮キャッシュへと送られます。この処理はユーザーには透明に行われます。
エンタープライズでのクエリの多くは参照検索であり、コストを抑えつつ高圧縮ティアから提供可能です。頻度が低い複雑なクエリについては、必要な場合にのみ大きなコンテキスト予算を消費します。このようなティアベースのルーティングは、圧縮適用前にドキュメントセットを絞り込む既存の RAG 最適化手法(メタデータフィルタリングやクエリの再フォーマットなど)を補完するものです。
圧縮品質を検証するには、各ティアでの LLM の応答と、未圧縮の完全なドキュメントから生成された応答を比較します。リファレンス実装には、特定のタスク種別やドキュメントに対してこの比較を実行するテストスクリプトが含まれています。
AWS 上のアーキテクチャ
本実装は、AWS 上でインジェスト用とクエリ用の 2 つの独立したサーバーレスパイプラインとして動作します。図 1 に両方のパイプラインを示します。

TAKC アーキテクチャ。パイプラインフローはデータ取り込みと圧縮を処理し、ユーザーフローは認証されたクエリを処理します
計算リソースには AWS Lambda を採用しました。各関数呼び出しが短時間で完了し、イベント駆動型であるためです。データ取り込み時にはバースト状に処理が行われ、その間はクエリ負荷が変動するため、サーバーレスアーキテクチャが自然な選択となります。
クエリインターフェースは REST エンドポイントとして公開するために Amazon API Gateway を選定しました。キャッシュには、シャード管理なしで複合キー(takc:{task}:{rate})による読み取りを可能にする Amazon ElastiCache Serverless を採用しています。JWT の発行とトークンの更新は Amazon Cognito が担当し、独自認証コードの実装が不要となるため、実装範囲を最小限に抑えています。
取り込みパイプライン
document がタスクタイプ接頭辞(例:raw-data/financial/)付きで Amazon S3 に格納されると、S3 イベント通知が AWS Lambda 関数をトリガーします。この関数は、境界部での情報損失を防ぐため、50 トークンのオーバーラップを持たせて文書を 256 トークンセグメントに分割します。その後、各チャンクに対して非同期で圧縮用 Lambda 関数を呼び出し、並列処理を可能にしています。大規模な取り込みを行う場合は、圧縮関数に予約済み同時実行を設定し、チャンキングと圧縮の間に Amazon SQS キューを配置して、スロットリングを適切に処理できるようにしてください。
2 つ目の関数は、Amazon Bedrock を呼び出して、4 つの圧縮階層すべてでチャンクを圧縮します。各圧縮呼び出しには、モデルに何を保持すべきかを指示するタスク認識型のプロンプトが含まれています。
TASK: Financial analysis. Preserve revenue metrics, margins, cash flow, debt obligations, and financial risk indicators.
COMPRESSION TARGET: Reduce to approximately 1/16 of original length.
INSTRUCTIONS:
- Focus on facts and relationships relevant to the task
- Preserve numerical data and metrics
- Maintain entities and their attributes
- Keep causal relationships and dependencies
- Remove redundant or irrelevant information
モデルが何を保持すべきかを知っているのは、プロンプトでタスクに重要な情報を指定しているからです。この「何を守るか」の区別こそが、汎用的な圧縮ではなくタスク認識型である所以です。
システムは、圧縮された出力を Amazon ElastiCache Serverless に保存します。キーには takc:financial:medium のような形式が使われ、耐久性のために S3 にもバックアップされます。Redis OSS データモデルは、マルチレートでのキャッシュ参照に必要な階層的なキー構造をサポートしています。
キャッシュエントリには 24 時間の TTL(有効期限)が設定され、S3 へもバックアップされています。もしキャッシュエントリが削除された場合や期限切れになった場合は、クエリ関数が S3 のバックアップにフォールバックし、読み取り時にキャッシュを再構築します。
クエリパイプライン
ユーザーは Amazon Cognito を通じて認証を行い、JWT を取得します。その後、Amazon API Gateway を経由してクエリを送信します。この API には AWS WAF が前面に配置されており、レート制限と脅威からの保護を行っています。
Lambda 関数がヒューリスティック(キーワードのシグナルやクエリの長さなど)を用いてクエリの複雑さを分析し、Amazon ElastiCache Serverless から適切な圧縮キャッシュを取得します。取得した圧縮コンテキストとクエリは Amazon Bedrock に送信され、推論処理が行われます。ルーティングの信頼度が低い場合は、安全なフォールバックとして中程度の圧縮ティアが自動的に選択されます。
高コストとなる Bedrock での圧縮呼び出しは、データ取り込み時に一度だけ実行されます。クエリ処理パスでは、圧縮されたコンテキストに対するキャッシュ検索と推論のみが行われます。
このアーキテクチャでは、圧縮と推論に Amazon Bedrock(Anthropic の Claude 3 Haiku、Claude 3 Sonnet、および Amazon Titan Text)を利用しています。モデルの選定はコードを変更せずに CDK のコンテキスト値で設定可能です。
データ処理やクエリロジックは AWS Lambda(Python 3.12 以上)が担当します。圧縮されたキャッシュは Amazon ElastiCache Serverless に保存され、生データ、チャンク、キャッシュのバックアップは Amazon S3 に格納されます(KMS による暗号化済み)。
REST API エンドポイントは Amazon API Gateway で公開され、認証には JWT ベースの Amazon Cognito を採用しています。API の前面には AWS WAF を配置し、レート制限と管理されたセキュリティルールで保護します。
監視とメトリクスは Amazon CloudWatch が提供し、暗号化キーの管理は AWS Key Management Service(AWS KMS)が行います。
インフラストラクチャは、単一の AWS Cloud Development Kit (AWS CDK) スタックとして定義し、1 つのコマンドでデプロイします。AWS CDK を使えば、圧縮チャンクのサイズや Lambda のメモリ割り当て、ElastiCache のストレージ制限といったパラメータをコンテキスト値を通じてカスタマイズでき、繰り返し可能なデプロイが可能になります。
本番環境向けには、状態保持リソース(S3、ElastiCache、Cognito)を別スタックに分離し、計算層とストレージ層のライフサイクル管理を独立させることで、障害時の影響範囲(ブラスト・レイジス)を小さくするのがおすすめです。
コスト比較
10 万トークンの知識ベースに対し、1 日あたり 1,000 回のクエリが行われる場合の入力トークン使用量です。出力トークンはコンテキストサイズに依存しないため除外しています:
| アプローチ | クエリあたりの入力トークン数 | 1 日の合計入力トークン数 | 相対的な入力コスト |
|---|---|---|---|
| フルコンテキスト | 100,000 | 100,000,000 | 100% |
| RAG (上位 10 チャンク) | ~10,000 | 10,000,000 | 10% |
| TAKC Light (8 倍圧縮) | ~12,500 | 12,500,000 | 12.5% |
| TAKC Medium (16 倍圧縮) | ~6,250 | 6,250,000 | 6.25% |
| TAKC High (32 倍圧縮) | ~3,125 | 3,125,000 | 3.1% |
| TAKC Ultra (64 倍圧縮) | ~1,563 | 1,563,000 | 1.6% |
トークン削減効果は、圧縮率から直接導き出されたものです。実際の節約額は、ご自身の Bedrock モデルの価格設定やクエリパターンによって異なります。
TAKC は、データ取り込み時に Bedrock を一度呼び出すことで事前圧縮コストが発生します。ただし、このコストは頻繁に更新されず、繰り返し照会されるナレッジベースであれば、時間とともに相殺されます。一方で、1 時間に 1 回以上更新されるナレッジベースでは、RAG のクエリごとの検索モデルの方が実用的な場合があります。
TAKC と RAG、あるいは両者の使い分け
この表は、ワークロードの特性に基づき、各アプローチがどの状況でより適しているかを要約したものです。
| 要素 | TAKC が有利なケース | RAG が有利なケース |
|---|---|---|
| クエリの種類 | 文書横断的な推論や要約 | 特定の事実情報の検索 |
| ナレッジベースの安定性 | 1 日以内の変更頻度 | 1 時間以内の変更頻度 |
| タスクの予測可能性 | 明確に定義されたタスクタイプ | 予測不能なクエリパターン |
| カバレッジ要件 | コーパス全体を考慮する必要がある | 関連する文書は数件程度で十分 |
| 出典の明示 | 不要 | 必須(ユーザーが出典を確認したい場合) |
| トークン予算 | 限定的 | 柔軟に設定可能 |
実運用では、両方のアプローチを組み合わせることでシステムがより効果的に機能します。RAG は迅速な参照に優れており、TAKC は従来の検索ベースの手法では見逃されやすい分析クエリに対応できます。クエリの複雑さを解析するコンポーネントが、どちらのアプローチを使うかを自動的に振り分けます。
ユーザーが回答の根拠を特定のソース文書まで遡って確認したい場合は RAG を利用します。また、ドキュメント間の推論と監査証跡の両方が求められる規制対応ワークロードでは、TAKC と RAG を併用するのが有効です。具体的には、分析結果の生成に TAKC を使い、監査証跡のために裏付けとなるソース文書の取得を RAG に任せる構成が推奨されます。
始め方
事前準備
このリファレンス実装をデプロイするには、以下の環境が整っていることを確認してください。
- Amazon Bedrock のモデルアクセス権限を持つ AWS アカウント
- AWS CDK CLI
- Python 3.12 以降
- Node.js 18 以降
デプロイとテスト
リポジトリ aws-samples/sample-bedrock-takc-compression をクローンし、CDK スack をデプロイします。
git clone https://github.com/aws-samples/sample-bedrock-takc-compression
cd sample-bedrock-takc-compression/cdk
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
cdk deploy
デプロイが完了したら、パイプラインの動作を確認します。
ドキュメントを S3 バケットにアップロードします。
aws s3 cp your-document.pdf s3://$(aws cloudformation describe-stacks --stack-name TakcStack \
--query 'Stacks[0].Outputs[?OutputKey==DataBucketName].OutputValue' \
--output text)/raw-data/financial/
インジェストパイプラインがドキュメントをチャンク化し、4 つの圧縮階層で圧縮処理を行うのを 2〜3 分待ちます。
API エンドポイントにクエリを送信します。
curl -X POST $(aws cloudformation describe-stacks --stack-name TakcStack \
--query 'Stacks[0].Outputs[?OutputKey==ApiEndpoint].OutputValue' \
--output text)/query \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"question": "What are the key financial risks?"}'
このシステムは、追加の設定なしでチャンク化、多段階圧縮、キャッシュ、クエリルーティングを自動処理します。
クリーンアップ
テスト終了後に継続課金を防ぐため、CDK スタックを削除してください。まず S3 バケットの中身を空にします。CDK はオブジェクトが存在するバケットの削除ができないためです。
aws s3 rm s3://$(aws cloudformation describe-stacks --stack-name TakcStack \
--query 'Stacks[0].Outputs[?OutputKey==DataBucketName].OutputValue' \
--output text) --recursive
その後、スタックを削除します。
cd sample-bedrock-takc-compression/cdk
source .venv/bin/activate
cdk destroy
これにより、Lambda 関数、API Gateway、Amazon ElastiCache Serverless キャッシュ、Amazon Cognito ユーザープール、WAF Web ACL、および Amazon CloudWatch アラームがすべて削除されます。KMS キーは 30 日間の保留期間付きで保持されます。すぐに削除スケジュールを設定するには、以下のコマンドを実行してください。
aws kms schedule-key-deletion --key-id [キー ID] --pending-window-in-days 7
結論
数百ドキュメントにわたる複雑な分析タスクには、断片的な検索だけでは不十分です。TAKC はそのような課題に対応するために設計されたアプローチを提供します。特定のタスクの視点からフルテキストのナレッジベースをオフラインで圧縮し、その表現を複数の忠実度レベルでキャッシュします。そして、各クエリの複雑さに応じて適切な圧縮階層を選択してマッチングさせます。
AWS での実装では、圧縮と推論に Amazon Bedrock を、キャッシングに Amazon ElastiCache Serverless を使用し、需要に応じてスケーリングする完全なサーバーレスアーキテクチャを採用しています。参考実装、CDK インフラストラクチャ、およびデプロイスクリプトは aws-samples/sample-bedrock-takc-compression で入手できます。
まずは、独自のドキュメントで CDK スタックをデプロイし、システムが異なる種類のクエリにどのように応答するかを確認してください。安定したナレッジベースにおけるクロスドキュメント推論を必要とするワークロードであれば、TAKC がその役割を果たします。
原文を表示
If you’re using Retrieval-Augmented Generation (RAG) for complex analytical tasks that span hundreds of documents, such as financial due diligence or regulatory compliance reviews, you’ve likely hit its ceiling. Similarity search surfaces relevant fragments but often misses cross-document connections. This post shows you how to address that gap using task-aware knowledge compression (TAKC), a technique that pre-compresses entire knowledge bases into task-specific representations deployed on AWS. You can deploy a complete open-source implementation in your own account.
Task-aware knowledge compression
Consider a private equity firm evaluating a $500 million acquisition of a manufacturing company. The due diligence team must analyze financial statements spanning 12 subsidiaries and 5 years. They also face 200+ supplier contracts, environmental compliance reports from 8 facilities, and 50+ legal cases. When an analyst asks about consolidated financial risks given current supplier terms and pending litigation, RAG’s similarity search cannot surface that response. Hundreds of documents hold the relevant information, and the connections between them share no lexical similarity.
TAKC addresses this type of problem by using an LLM to produce shorter, task-focused summaries of documents, with different summaries for different tasks.
Different tasks require different information from the same document. An annual report compressed for financial analysis needs revenue figures, margins, and cash flow data. The same report compressed for a compliance review needs regulatory citations and violation histories. Generic summarization attempts to cover everything, which dilutes the information density for any specific use case. TAKC compresses documents through the lens of a specific task, keeping what matters and discarding the rest. The Ingestion pipeline section shows how the compression prompt specifies exactly what information to preserve. For production deployments, store task-type prompts in a versioned configuration (such as AWS Systems Manager Parameter Store or a dedicated Amazon Simple Storage Service (Amazon S3) prefix) so that prompt changes are auditable and recompression can be triggered when prompts are updated.
The system compresses documents offline, once per document per task type. At query time, the system retrieves a pre-compressed representation rather than the original document. The system then answers questions using the compressed version instead of the full document. If the compressed representation lacks sufficient detail, the query complexity analyzer routes the question to a lower compression tier that retains more context.
TAKC provides access to the *entire* knowledge base in compressed form, not just the top-k chunks that a similarity search returns. The system preserves connections between documents because the compression sees documents together. It also produces different compressed outputs for different tasks from the same source material. The financial compression of a 10-K filing looks nothing like the legal risk compression of that same filing. The compression reduces token count by 8x to 64x while targeting task-relevant information for retention.
Multi-rate compression
Different queries require different levels of fidelity. A question such as “What was Q3 revenue?” needs far less context than a request to analyze relationships between supplier payment terms and quarterly cash flow across subsidiaries.
TAKC addresses this by maintaining four compression tiers for each task type. At the lightest compression (8x), the system retains approximately 87.5% less context. It preserves enough detail for multi-step reasoning and cross-document synthesis. At the medium tier (16x), context reduction reaches approximately 93.8%. This level suits analytical queries with moderate complexity. The high tier (32x) reduces context by approximately 96.9% and serves factual lookups and well-defined questions. At the ultra tier (64x), reduction reaches approximately 98.4%. This level is appropriate for classification tasks and keyword lookups.
A query complexity analyzer routes incoming questions to the appropriate tier based on signals like query length, question type, and presence of analytical language. Straightforward factual questions hit the ultra-compressed cache while complex analytical questions use the lightly compressed cache. This happens transparently to the user.
Most enterprise queries are lookups that can be served from the higher compression tiers at minimal cost. The infrequent complex queries consume larger context budgets only when needed. This tier-based routing complements existing RAG optimizations like metadata filtering and query reformatting, which can narrow the document set before compression is applied. To validate compression quality, compare LLM responses at each tier against responses generated from the full uncompressed document. The reference implementation includes test scripts that run this comparison for your specific task types and documents.
Architecture on AWS
The implementation runs on AWS as two decoupled serverless pipelines: one for ingestion and one for queries. Figure 1 illustrates both pipelines.

TAKC architecture. The pipeline flow handles data ingestion and compression. The user flow handles authenticated queries
We chose AWS Lambda for compute because each function invocation is short-lived and event-driven. The workload processes data in bursts during ingestion and handles variable query loads between bursts, making serverless a natural fit.
We chose Amazon API Gateway to expose the query interface as a REST endpoint. For caching, we chose Amazon ElastiCache Serverless for reads on composite keys (takc:{task}:{rate}) without shard management. Amazon Cognito handles JWT issuance and token refresh without custom auth code, reducing the implementation surface area.
Ingestion pipeline
When a document lands in Amazon S3 under a task-type prefix (for example, raw-data/financial/), an S3 event notification triggers an AWS Lambda function. This function chunks the document into 256-token segments with 50-token overlap to prevent information loss at boundaries. It then invokes a compression Lambda function for each chunk asynchronously, enabling parallel processing. For large-scale ingestion, configure reserved concurrency on the compression function and place an Amazon Simple Queue Service (Amazon SQS) queue between the chunking and compression steps to handle throttling gracefully.
The second function calls Amazon Bedrock to compress the chunks at all four compression tiers. Each compression call includes a task-aware prompt that tells the model what information to preserve:
TASK: Financial analysis. Preserve revenue metrics, margins, cash flow, debt obligations, and financial risk indicators.
COMPRESSION TARGET: Reduce to approximately 1/16 of original length.
INSTRUCTIONS:
- Focus on facts and relationships relevant to the task
- Preserve numerical data and metrics
- Maintain entities and their attributes
- Keep causal relationships and dependencies
- Remove redundant or irrelevant informationThe model knows what to preserve because the prompt specifies what matters for the task. That distinction is what makes this task-aware rather than generic compression. The system stores compressed outputs in Amazon ElastiCache Serverless with keys like takc:financial:medium, and backs them up to S3 for durability. The Redis OSS data model supports the hierarchical key structure needed for multi-rate cache lookups. Cache entries use a 24-hour TTL and are backed up to S3. If a cache entry is evicted or expires, the query function falls back to the S3 backup and re-populates the cache on read.
Query pipeline
A user authenticates through Amazon Cognito, receives a JWT, and sends a query through Amazon API Gateway. AWS WAF fronts the API for rate limiting and threat protection. A Lambda function analyzes query complexity using heuristics (keyword signals and query length), retrieves the appropriate compressed cache from Amazon ElastiCache Serverless, and sends the compressed context plus query to Amazon Bedrock for inference. When routing confidence is low, the system defaults to the medium compression tier as a safe fallback.
The higher-cost Bedrock compression calls happen once during ingestion. The query path is a cache lookup plus inference on compressed context.
The stack uses Amazon Bedrock (Anthropic Claude 3 Haiku, Claude 3 Sonnet, and Amazon Titan Text) for compression and inference. The model selection is configurable through CDK context values without code changes. AWS Lambda (Python 3.12+) handles data processing and query logic. Amazon ElastiCache Serverless stores the compressed cache, while Amazon S3 holds raw data, chunks, and cache backups (KMS-encrypted). Amazon API Gateway exposes the REST endpoints, and Amazon Cognito provides JWT-based authentication. AWS WAF fronts the API with rate limiting and managed security rules. Amazon CloudWatch provides monitoring and metrics, and AWS Key Management Service (AWS KMS) manages encryption keys.
Define the infrastructure as a single AWS Cloud Development Kit (AWS CDK) stack and deploy it with a single command. AWS CDK provides repeatable deployments and lets you customize parameters like compression chunk size, Lambda memory allocation, and ElastiCache storage limits through context values. For production deployments, consider separating stateful resources (S3, ElastiCache, Cognito) into their own stack to reduce blast radius and enable independent lifecycle management of compute and storage layers.
Cost comparison
Input token usage for a 100,000-token knowledge base queried 1,000 times per day (output tokens are excluded because response length is independent of context size):
Approach
Input tokens per query
Daily input tokens
Relative input cost
Full context
100,000
100,000,000
100%
RAG (top-10 chunks)
~10,000
10,000,000
10%
TAKC Light (8×)
~12,500
12,500,000
12.5%
TAKC Medium (16×)
~6,250
6,250,000
6.25%
TAKC High (32×)
~3,125
3,125,000
3.1%
TAKC Ultra (64×)
~1,563
1,563,000
1.6%
The token savings from compression are derived directly from the compression ratios. Actual savings depend on your specific Bedrock model pricing and query patterns.
TAKC requires upfront compression cost through one-time Bedrock calls during ingestion. This cost amortizes for knowledge bases that change infrequently and get queried repeatedly. For knowledge bases that change hourly, RAG’s per-query retrieval model may be more practical.
When to choose TAKC, RAG, or both
This table summarizes when each approach is the better fit, based on your workload characteristics:
Factor
Favors TAKC
Favors RAG
Query type
Cross-document reasoning, synthesis
Narrow factual lookups
Knowledge base stability
Changes daily or less
Changes hourly or more
Task predictability
Well-defined task types
Unpredictable query patterns
Coverage requirement
Must consider full corpus
Only a few documents are relevant
Source attribution
Not required
Required (user needs to see source)
Token budget
Tight
Flexible
In practice, a production system often benefits from both. RAG handles quick lookups efficiently. TAKC handles the analytical queries where retrieval-based approaches miss connections. A query complexity analyzer can route between them. Use RAG when users need to trace responses back to specific source documents. For regulated workloads that require both cross-document reasoning and auditability, combine TAKC with RAG: use TAKC for the analytical response and RAG to retrieve the supporting source documents for the audit trail.
Getting started
Prerequisites
To deploy this reference implementation, check that you have the following:
- An AWS account with Amazon Bedrock model access.
- AWS CDK CLI.
- Python 3.12 or later.
- Node.js 18 or later.
Deploy and test
Clone the repository aws-samples/sample-bedrock-takc-compression and deploy the CDK stack:
git clone https://github.com/aws-samples/sample-bedrock-takc-compression
cd sample-bedrock-takc-compression/cdk
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
cdk deployAfter deployment completes, test the pipeline:
- Upload a document to the S3 bucket:
aws s3 cp your-document.pdf s3://$(aws cloudformation describe-stacks --stack-name TakcStack \
--query 'Stacks[0].Outputs[?OutputKey==`DataBucketName`].OutputValue' \
--output text)/raw-data/financial/- Wait 2-3 minutes for the ingestion pipeline to chunk and compress the document at all four compression tiers.
- Query the API endpoint:
curl -X POST $(aws cloudformation describe-stacks --stack-name TakcStack \
--query 'Stacks[0].Outputs[?OutputKey==`ApiEndpoint`].OutputValue' \
--output text)/query \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"question": "What are the key financial risks?"}'The system handles chunking, multi-rate compression, caching, and query routing without additional configuration.
Clean up
To avoid ongoing charges, destroy the CDK stack when you’re done testing. First, empty the S3 bucket because CDK cannot delete buckets that contain objects:
aws s3 rm s3://$(aws cloudformation describe-stacks --stack-name TakcStack \
--query 'Stacks[0].Outputs[?OutputKey==`DataBucketName`].OutputValue' \
--output text) --recursiveThen destroy the stack:
cd sample-bedrock-takc-compression/cdk
source .venv/bin/activate
cdk destroyThis removes the Lambda functions, API Gateway, Amazon ElastiCache Serverless cache, Amazon Cognito user pool, WAF web ACL, and Amazon CloudWatch alarms. The KMS key is retained with a 30-day pending deletion window. To schedule its deletion immediately, run the following command:
aws kms schedule-key-deletion --key-id --pending-window-in-days 7まとめ
Complex analytical tasks that span hundreds of documents require more than fragment retrieval. TAKC offers an approach built for this. Compress the full knowledge base offline through the lens of specific tasks, cache those representations at multiple fidelity levels, and match the right compression tier to each query’s complexity.
The AWS implementation uses Amazon Bedrock for compression and inference, Amazon ElastiCache Serverless for caching, and a fully serverless architecture that scales with demand. Access the reference implementation, CDK infrastructure, and deployment scripts at aws-samples/sample-bedrock-takc-compression.
To get started, deploy the CDK stack with your own documents and see how the system responds to different query types. If your workload involves cross-document reasoning over stable knowledge bases, TAKC can r
関連記事
今日のまとめ
AIデイリーブリーフで今日の重要ニュースをまとめ読み