A
AIエージェントの仕組み
ch5-s4 · Claude with RAG

Claude with RAG

約 16 分

この回のゴール

1. 全体パイプライン

tools = [
    {"name": "calculator",        "description": "数式を計算する", ...},
    {"name": "get_current_time",  "description": "現在時刻を返す", ...},
    {"name": "search_dictionary", "description": "辞書を検索する", ...},
    {"name": "get_weather",       "description": "天気を取得する", ...},
]

2. RAG プロンプトの設計

system プロンプトの基本型

response = client.messages.create(
    ...,
    tools=tools,
    tool_choice={"type": "auto"},  # 👈 ここ
)

user メッセージの組み方

User: 東京と大阪の天気、あと 1+2+3 を計算して

Claude: [tool_use: get_weather(city="東京")]
        [tool_use: get_weather(city="大阪")]
        [tool_use: calculator(expression="1+2+3")]

なぜこの形式?

3. Citation — 引用元を出す

回答例:

messages = [
    ...,
    {"role": "assistant", "content": response.content},  # 3 つの tool_use
    {"role": "user", "content": [
        {"type": "tool_result", "tool_use_id": "toolu_A", "content": "..."},
        {"type": "tool_result", "tool_use_id": "toolu_B", "content": "..."},
        {"type": "tool_result", "tool_use_id": "toolu_C", "content": "..."},
    ]},
]

Claude に「[1] のような番号で引用してね」と指示し、実装側で番号 → 原文にマッピングして表示します。

なぜ引用が重要?

4. 検索失敗時のフォールバック

質問が文書にない場合:

悪い応答: LLM の学習知識から勝手に回答してしまう 良い応答: 「その情報は確認できません」と明確に伝える

system プロンプトで強く釘を刺すのが定石です。

5. RAG 改善の技術(発展)

これらを 組み合わせる ことで、意味検索だけでは拾えない 固有名詞・数字 も取れる。

Reranking

Top-k を多めに取ってから、別の軽量モデル(Cross-Encoder)でリランク する:

response = client.messages.create(
    ...,
    tool_choice={"type": "auto", "disable_parallel_tool_use": True},
)

Query Expansion

質問を Claude で 言い換え・展開 してから検索:

{
    "type": "tool_result",
    "tool_use_id": "toolu_ABC",
    "content": "Error: ネットワーク接続に失敗しました",
    "is_error": True,
}

Contextual Retrieval (Anthropic, 2024)

各チャンクに 文脈情報を先に付けてから埋め込む。精度大幅向上。


まとめ

第 5 章のクロージング → 次章への接続

ここまでで「自分の文書から答える Claude」が作れた。でも: - 「文書になかったら Web 検索する」フォールバック - 「DB から具体的数字を取る」必要 - 質問によって検索するかどうかを判断する 動的な対応

👉 これらは AI エージェント(次章)で解決します。RAG は「検索というツールを持ったエージェント」の特殊ケースと見なせます。

参考文献

📝 理解度クイズ (3 問) 💡 ログインすると進捗が保存されます

💬 このサブステップの Q&A

まだ質問はありません。最初の質問を投稿してみましょう。

質問の投稿にはログインが必要です。