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?

Claude APIとFAISSでRAGシステムを実装する:社内文書をClaudeに読ませる完全ガイド【Python】

0
Last updated at Posted at 2026-08-26

はじめに

「社内の規約・マニュアル・過去の提案書をAIに読ませて質問したい」

この要求、現場でよく聞きます。しかしClaude APIに直接全文書を渡すのはトークン数・コスト・レイテンシの観点で現実的ではありません。

解決策が**RAG(Retrieval-Augmented Generation)**です。

本記事ではPythonとFAISSを使い、Claude APIとRAGシステムを30分で構築する手順を解説します。


RAGとは

通常のLLM:
ユーザー質問 → Claude → 回答(学習済み知識のみ)

RAG:
ユーザー質問
    ↓
[Vector DB検索] ← 社内文書をベクトル化して蓄積
    ↓ 関連文書を取得
[Claude API] + 取得した文書をコンテキストに追加
    ↓
回答(社内文書に基づく・ハルシネーション抑制)

メリット:

  • 最新情報・社内情報をClaudeに反映できる
  • ハルシネーション(誤情報生成)を抑制
  • 参照元の文書を明示できる
  • モデルの追加学習(Fine-tuning)が不要

環境構築

pip install anthropic faiss-cpu sentence-transformers numpy
ライブラリ 用途
anthropic Claude API クライアント
faiss-cpu 高速ベクトル検索(Facebook AI製)
sentence-transformers テキストのベクトル化
numpy 数値計算

実装

indexer.py:文書のベクトル化

import faiss
import numpy as np
import pickle
from sentence_transformers import SentenceTransformer

class DocumentIndexer:
    def __init__(self, model_name: str = "intfloat/multilingual-e5-large"):
        # multilingual-e5-large: 日本語を含む多言語対応モデル
        self.model = SentenceTransformer(model_name)
        self.index = None
        self.documents = []

    def add_documents(self, documents: list[str]) -> None:
        # テキストをベクトルに変換
        embeddings = self.model.encode(
            documents,
            normalize_embeddings=True,
            show_progress_bar=True
        )
        if self.index is None:
            dim = embeddings.shape[1]
            self.index = faiss.IndexFlatIP(dim)

        self.index.add(embeddings.astype(np.float32))
        self.documents.extend(documents)

    def save(self, path: str) -> None:
        faiss.write_index(self.index, f"{path}.faiss")
        with open(f"{path}.docs", "wb") as f:
            pickle.dump(self.documents, f)

    @classmethod
    def load(cls, path: str) -> "DocumentIndexer":
        indexer = cls()
        indexer.index = faiss.read_index(f"{path}.faiss")
        with open(f"{path}.docs", "rb") as f:
            indexer.documents = pickle.load(f)
        return indexer

retriever.py:関連文書の検索

import numpy as np

class DocumentRetriever:
    def __init__(self, indexer):
        self.indexer = indexer
        self.model = indexer.model

    def search(self, query: str, top_k: int = 5, score_threshold: float = 0.3) -> list[dict]:
        query_embedding = self.model.encode(
            [query], normalize_embeddings=True
        ).astype(np.float32)

        scores, indices = self.indexer.index.search(query_embedding, top_k)

        results = []
        for score, idx in zip(scores[0], indices[0]):
            if idx == -1 or score < score_threshold:
                continue
            results.append({"text": self.indexer.documents[idx], "score": float(score)})

        return results

generator.py:Claude APIで回答生成

import anthropic
from typing import Optional

class RAGGenerator:
    def __init__(self, model: str = "claude-sonnet-5"):
        self.client = anthropic.Anthropic()
        self.model = model

    def generate(self, query: str, context_docs: list[dict]) -> dict:
        if not context_docs:
            return {"answer": "関連する文書が見つかりませんでした。", "has_answer": False}

        context = "\n\n---\n\n".join([
            f"[文書{i+1}(関連度: {doc['score']:.2f})]\n{doc['text']}"
            for i, doc in enumerate(context_docs)
        ])

        system_prompt = (
            "あなたは社内情報を参照して質問に答えるアシスタントです。\n"
            "必ず提供された文書の内容に基づいて回答してください。\n"
            "文書に記載がない内容については明示してください。"
        )

        message = self.client.messages.create(
            model=self.model,
            max_tokens=2048,
            system=system_prompt,
            messages=[{
                "role": "user",
                "content": f"以下の文書を参照して質問に答えてください。\n\n## 参照文書\n{context}\n\n## 質問\n{query}"
            }]
        )

        return {
            "answer": message.content[0].text,
            "has_answer": True,
            "input_tokens": message.usage.input_tokens,
            "output_tokens": message.usage.output_tokens
        }

main.py:統合して使う

from indexer import DocumentIndexer
from retriever import DocumentRetriever
from generator import RAGGenerator

def main():
    # 文書の準備(実際はPDF・Excelから読み込む)
    documents = [
        "有給休暇の取得は原則として2週間前までに申請が必要です。",
        "出張旅費の精算は出張後5営業日以内に提出してください。新幹線は普通車指定席が上限です。",
        "リモートワークは月10日まで申請可能です。申請はSlackの #remote チャンネルで。",
        "セキュリティポリシーにより、社外からのアクセスにはVPN接続が必須です。",
        "経費申請の上限は1件あたり10万円。超過する場合は部長承認が必要です。",
    ]

    # インデックス作成
    indexer = DocumentIndexer()
    indexer.add_documents(documents)
    indexer.save("company_docs")

    retriever = DocumentRetriever(indexer)
    generator = RAGGenerator()

    # 質問して回答を得る
    queries = [
        "有給休暇はどのくらい前に申請すればいいですか?",
        "出張の新幹線代はどこまで出ますか?",
    ]

    for query in queries:
        print(f"\n質問: {query}")
        relevant_docs = retriever.search(query, top_k=3)
        result = generator.generate(query, relevant_docs)
        print(f"回答: {result['answer']}")

if __name__ == "__main__":
    main()

PDFから文書を読み込む

import pdfplumber

def load_pdf_as_chunks(pdf_path: str, chunk_size: int = 500) -> list[str]:
    chunks = []
    with pdfplumber.open(pdf_path) as pdf:
        full_text = "".join(page.extract_text() or "" for page in pdf.pages)

    for i in range(0, len(full_text), chunk_size - 50):
        chunk = full_text[i:i + chunk_size]
        if len(chunk) > 100:
            chunks.append(chunk)

    return chunks

コスト目安(Claude Sonnet 5使用)

項目 トークン数 コスト概算
検索した文書(コンテキスト) 〜2,000 tokens $0.003
質問文 〜100 tokens $0.0002
回答 〜500 tokens $0.003
1クエリ合計 〜2,600 tokens 約1円

100件/日質問しても約100円。非常にコスト効率が高いです。


まとめ

ステップ 内容
1. 文書の分割 テキストを適切なサイズにチャンク化
2. ベクトル化 sentence-transformersでエンベディング生成
3. インデックス FAISSで高速検索を実現
4. 検索 ユーザークエリに関連する文書を取得
5. 生成 Claude APIにコンテキストとして渡して回答

Qiitaでは他にもIT実務・資格関連の技術記事を発信しています。


著者の書籍

RAGや生成AIの活用は、高度情報技術データ・AI試験でも扱われるテーマです。試験範囲を体系的に学びたい方向けに、テキストと問題集を出版しました。

高度情報技術試験[データ・AI]テキスト&問題集 2027年度版

無料の問題演習(全341問・解説付き)は 高度情報技術試験 問題演習道場 で公開しています。

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?