0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Amazon BedrockでマルチカテゴリRAGを安全に分離する方法(Metadata Filtering実践)

0
Posted at

はじめに

マルチカテゴリ構成でAIチャットを導入したところ、

カテゴリAのページなのにカテゴリBの情報を回答してしまう

というRAGあるある問題に遭遇しました。

同じように悩んでいる方の参考になればと思い、実装パターンを整理します。
(プロジェクト固有情報はすべて一般化しています)

想定アーキテクチャ

Frontend (category page)
    ↓ categoryId付きリクエスト
API
    ↓
Bedrock Knowledge Base
    ↓
S3 (全カテゴリドキュメント)

S3構造:

documents/
  ├─ category-a/
  ├─ category-b/
  ├─ category-c/

問題の本質

Knowledge Baseはデフォルトで「横断検索」します。

つまり:

Query → 全カテゴリのベクトル空間から検索

カテゴリ単位のスコープは自動では制御されません。

やりがちな失敗

1. DataSourceをカテゴリごとに分割

  • DataSourceには上限がある
  • カテゴリ増加に対応不可
  • 運用が複雑

2. プロンプトで縛る

  • 検索段階で混在するため不十分
  • セキュリティ保証にならない

正解:Metadata Filtering

Bedrock Knowledge Basesでは、メタデータによるフィルタ検索が可能です。

実装の全体像

S3ドキュメント
   + metadata(categoryId)
        ↓
Ingestion
        ↓
Retrieve(filter: categoryId=xxx)

実装ステップ

1. DataSourceは1つに統合

documents/

すべてのカテゴリを1つのDataSourceにまとめます。

2. 各ドキュメントに metadata を付与

例:

documents/category-a/manual.md
documents/category-a/manual.md.metadata.json

metadata内容:

{
  "metadataAttributes": {
    "categoryId": "category-a"
  }
}

ポイント:

  • categoryId = ディレクトリ名と対応させる
  • メタデータの値には String / Number / Boolean が使用可能
  • metadata追加後は ingestion 再実行が必要

3. Retrieveでフィルタを指定

TypeScript例:

const command = new RetrieveCommand({
  knowledgeBaseId,
  retrievalQuery: { text: query },
  retrievalConfiguration: {
    vectorSearchConfiguration: {
      numberOfResults: 8,
      filter: {
        equals: {
          key: "categoryId",
          value: categoryId,
        },
      },
    },
  },
});

これが最重要ポイントです。

filter には equals 以外にも notEqualsingreaterThanlessThanstartsWithandAllorAll など多くのオペレーターが利用できます。

図解:Before / After

Before(混在)

Query
   ↓
[category-a]
[category-b]
[category-c]
   ↓
回答(混在)

After(分離)

Query + categoryId=category-a
        ↓
Filter(categoryId=category-a)
        ↓
[category-aのみ]
        ↓
回答(安全)

この設計のメリット

  • カテゴリ数が増えてもスケールする
  • DataSource制限に依存しない
  • 明示的な分離が可能
  • AWS公式機能に準拠

運用で気をつけること

  • metadata追加後は必ず ingestion 実行
  • API層でfilter指定を必須化
  • categoryIdは許可リスト管理する

まとめ

マルチカテゴリRAGでは

DataSource分割ではなく
Metadata + Retrieval Filter で制御する

のがベストプラクティスです。

BedrockのMetadata Filteringは、
精度向上だけでなく「スコープ制御機能」として非常に強力でした。

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?