mcpField
C
citations-retrieval

citations-retrieval

github.com/thelobbiエージェントワークフロー2163 回インストール1 日前に更新
リポジトリ

citations-retrieval について

Citations & Retrieval Skillは、文書に基づく引用と検索拡張生成を実装するためのガイドです。根拠を追跡・検証できるAIアプリケーションを開発する人向けに、引用形式、検索フロー、書式設定、検証方法を扱います。

主な機能

  1. 01テキスト、PDF、コンテンツブロックの引用に対応
  2. 02基本的なRAGとコンテキスト検索を解説
  3. 03複数文書の質問応答パターンを提示
  4. 04学術引用形式の整形方法を説明
  5. 05引用の整合性検証を案内
  6. 06文書分割とキャッシュの実践を紹介

活用シーン

  1. 01文書Q&Aに出典表示を追加
  2. 02文書に基づくRAGアプリを構築
  3. 03引用と原文の対応を検証
  4. 04複数文書を横断した調査回答を作成

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/thelobbi/claude --skill citations-retrieval

インストール後、Claude Code で/citations-retrievalを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

OUTLINE.md
QUICK-REFERENCE.md
README.md
RESEARCH-SUMMARY.md

詳細

引用と検索のスキル

根拠に基づいた検証可能なAIレスポンスを実現するために、ドキュメントに基づく引用とRAGパターンを実装します。

このスキルを使用する場面

  • 出典を明記したドキュメントの質疑応答
  • RAG(検索拡張生成)システム
  • 提供されたドキュメントに基づくレスポンスの生成
  • 信頼できるAIアプリケーションの構築
  • 引用を伴う調査と分析

基本概念

引用の種類
種類用途形式
char_locationテキストドキュメント文字範囲
page_locationPDFページ番号
content_block_locationカスタムコンテンツブロックインデックス

基本的な引用

引用を有効にする
import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    documents=[
        {
            "type": "document",
            "source": {
                "type": "text",
                "media_type": "text/plain",
                "data": "The company was founded in 2020. Revenue reached $10M in 2023."
            },
            "title": "Company Overview",
            "citations": {"enabled": True}  # Enable citations!
        }
    ],
    messages=[{"role": "user", "content": "When was the company founded and what was the revenue?"}]
)

# Extract citations from response
for block in response.content:
    if block.type == "text":
        for citation in block.citations:
            print(f"Cited: {citation.document_title}")
            print(f"Location: chars {citation.start_char_index}-{citation.end_char_index}")
カスタムコンテンツブロック
# Fine-grained control over citation granularity
documents = [{
    "type": "document",
    "source": {
        "type": "content",
        "content": [
            {"type": "text", "text": "Section 1: Introduction..."},
            {"type": "text", "text": "Section 2: Methods..."},
            {"type": "text", "text": "Section 3: Results..."}
        ]
    },
    "title": "Research Paper",
    "citations": {"enabled": True}
}]

RAGの実装

基本的なRAGパイプライン
from sentence_transformers import SentenceTransformer
import numpy as np

# 1. Embed documents
embedder = SentenceTransformer('all-MiniLM-L6-v2')

def embed_documents(documents):
    chunks = []
    embeddings = []
    for doc in documents:
        # Chunk the document
        doc_chunks = chunk_document(doc, chunk_size=512)
        chunks.extend(doc_chunks)
        embeddings.extend(embedder.encode(doc_chunks))
    return chunks, np.array(embeddings)

# 2. Retrieve relevant chunks
def retrieve(query, chunks, embeddings, top_k=5):
    query_embedding = embedder.encode([query])[0]
    similarities = np.dot(embeddings, query_embedding)
    top_indices = np.argsort(similarities)[-top_k:][::-1]
    return [chunks[i] for i in top_indices]

# 3. Generate with retrieved context
def rag_query(query, chunks, embeddings):
    relevant_chunks = retrieve(query, chunks, embeddings)

    response = client.messages.create(
        model="claude-sonnet-5",
        max_tokens=1024,
        documents=[{
            "type": "document",
            "source": {"type": "text", "media_type": "text/plain", "data": chunk},
            "title": f"Source {i+1}",
            "citations": {"enabled": True}
        } for i, chunk in enumerate(relevant_chunks)],
        messages=[{"role": "user", "content": query}]
    )
    return response
コンテキスト検索(49~67%向上)
# Add context to each chunk before embedding
def add_chunk_context(chunk, full_document):
    """Prepend context to improve retrieval accuracy by 49-67%"""

    context_prompt = f"""<document>
{full_document}
</document>

Please provide a short, succinct context for this chunk that will help with retrieval:

<chunk>
{chunk}
</chunk>

Context:"""

    response = client.messages.create(
        model="claude-haiku-4-5",  # Fast, cheap
        max_tokens=100,
        messages=[{"role": "user", "content": context_prompt}]
    )

    context = response.content[0].text
    return f"{context}\n\n{chunk}"

# Apply to all chunks
contextual_chunks = [add_chunk_context(chunk, full_doc) for chunk in chunks]

引用の書式設定

番号付きの参考文献として書式設定する
def format_with_citations(response):
    """Format response with numbered inline citations"""
    text = ""
    citations = []
    citation_map = {}

    for block in response.content:
        if block.type == "text":
            current_text = block.text

            for citation in block.citations:
                key = (citation.document_title, citation.start_char_index)
                if key not in citation_map:
                    citation_map[key] = len(citations) + 1
                    citations.append(citation)

                # Insert citation number
                ref_num = citation_map[key]
                current_text += f" [{ref_num}]"

            text += current_text

    # Add references section
    text += "\n\n## References\n"
    for i, citation in enumerate(citations, 1):
        text += f"[{i}] {citation.document_title}\n"

    return text
学術的な引用形式
def format_apa(author, year, title, source):
    """APA format: Author (Year). Title. Source."""
    return f"{author} ({year}). {title}. {source}."

def format_mla(author, title, source, year):
    """MLA format: Author. "Title." Source, Year."""
    return f'{author}. "{title}." {source}, {year}.'

def format_chicago(author, title, source, year):
    """Chicago format: Author. Title. Source, Year."""
    return f"{author}. {title}. {source}, {year}."

複数ドキュメントの質疑応答

def multi_doc_qa(question, documents):
    """Answer questions across multiple documents with citations"""

    doc_inputs = []
    for i, doc in enumerate(documents):
        doc_inputs.append({
            "type": "document",
            "source": {
                "type": "text",
                "media_type": "text/plain",
                "data": doc["content"]
            },
            "title": doc.get("title", f"Document {i+1}"),
            "citations": {"enabled": True}
        })

    response = client.messages.create(
        model="claude-sonnet-5",
        max_tokens=2048,
        documents=doc_inputs,
        messages=[{
            "role": "user",
            "content": f"Answer this question based on the provided documents. Cite your sources.\n\nQuestion: {question}"
        }]
    )

    return response

RAGのプロンプトキャッシュ

# Cache static documents for repeated queries
response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    documents=[{
        "type": "document",
        "source": {"type": "text", "media_type": "text/plain", "data": large_document},
        "title": "Knowledge Base",
        "citations": {"enabled": True},
        "cache_control": {"type": "ephemeral"}  # Cache this document!
    }],
    messages=[{"role": "user", "content": query}]
)

エラー処理と検証

引用の整合性を検証する
def validate_citations(response, documents):
    """Ensure all citations reference provided documents"""

    cited_titles = set()
    for block in response.content:
        if block.type == "text":
            for citation in block.citations:
                cited_titles.add(citation.document_title)

    provided_titles = {doc.get("title") for doc in documents}

    # Check for invalid citations
    invalid = cited_titles - provided_titles
    if invalid:
        raise ValueError(f"Citations reference unknown documents: {invalid}")

    return True

def extract_citation_spans(response):
    """Extract text spans for each citation"""

    citation_data = []
    for block in response.content:
        if block.type == "text":
            text = block.text
            for citation in block.citations:
                span = text[citation.start_char_index:citation.end_char_index]
                citation_data.append({
                    "text": span,
                    "document": citation.document_title,
                    "start": citation.start_char_index,
                    "end": citation.end_char_index
                })

    return citation_data

ベストプラクティス

推奨事項:
  • ドキュメントに基づくすべてのクエリで引用を有効にする
  • 精度を高めるためにコンテキスト検索を使用する(+49~67%)
  • cache_controlを使用して静的ドキュメントをキャッシュする
  • 出典を明記できるよう、ドキュメントにわかりやすいタイトルを付ける
  • ドキュメントを適切なサイズに分割する(512~1024トークン)
  • レスポンスを使用する前に、引用の整合性を検証する
  • 引用形式を統一する(APA、MLA、Chicago)
  • 本番システムで引用の抽出をテストする
非推奨事項:
  • 引用を有効にせず、引用に頼る
  • 非常に小さなチャンクを使用する(<100トークン)
  • 本番環境で引用の検証を軽視する
  • ドキュメントの前処理を省略する
  • 同じドキュメント内で引用形式を混在させる
  • すべてのLLMレスポンスにデフォルトで引用が付くと思い込む
  • 引用検証テストを行わずにデプロイする

トラブルシューティング

引用が返されない
# Ensure citations are enabled
documents = [{
    "type": "document",
    "source": {"type": "text", "media_type": "text/plain", "data": content},
    "citations": {"enabled": True}  # Must be explicit!
}]
引用が誤ったテキストを指している
# Verify character indexes match actual text
text = block.text
cited_text = text[citation.start_char_index:citation.end_char_index]
print(f"Cited text: {cited_text}")
print(f"Expected: {expected_text}")
大きなドキュメントのパフォーマンス
# Use chunking for large documents
def chunk_with_overlap(text, chunk_size=1024, overlap=256):
    chunks = []
    for i in range(0, len(text), chunk_size - overlap):
        chunks.append(text[i:i + chunk_size])
    return chunks

# Pass chunks individually for better retrieval
large_chunks = chunk_with_overlap(large_text)

統合例

#!/usr/bin/env python3
"""Complete RAG + Citations example"""

import anthropic
from sentence_transformers import SentenceTransformer
import numpy as np

def create_rag_system():
    """Initialize RAG system with citations"""

    client = anthropic.Anthropic()
    embedder = SentenceTransformer('all-MiniLM-L6-v2')

    # Sample documents
    documents = [
        {
            "title": "Python Guide",
            "content": "Python 3.11 introduced exception groups..."
        },
        {
            "title": "Web Standards",
            "content": "HTTP/2 introduced multiplexing capabilities..."
        }
    ]

    # Embed documents
    chunks = []
    embeddings = []
    for doc in documents:
        # Add document title as context
        chunk = f"[{doc['title']}]\n{doc['content']}"
        chunks.append(chunk)
        embeddings.append(embedder.encode(chunk))

    embeddings = np.array(embeddings)

    # Query function
    def query(question):
        # Retrieve relevant chunks
        query_emb = embedder.encode(question)
        similarities = np.dot(embeddings, query_emb)
        top_idx = np.argmax(similarities)
        relevant_chunk = chunks[top_idx]

        # Get cited answer
        response = client.messages.create(
            model="claude-sonnet-5",
            max_tokens=1024,
            documents=[{
                "type": "document",
                "source": {
                    "type": "text",
                    "media_type": "text/plain",
                    "data": relevant_chunk
                },
                "title": documents[top_idx]["title"],
                "citations": {"enabled": True}
            }],
            messages=[{
                "role": "user",
                "content": question
            }]
        )

        return response

    return query

if __name__ == "__main__":
    query_fn = create_rag_system()
    response = query_fn("What is Python 3.11?")

    # Display with citations
    for block in response.content:
        if block.type == "text":
            print(f"Answer: {block.text}")
            for citation in block.citations:
                print(f"  - Cited from: {citation.document_title}")

パフォーマンスのヒント

  • クエリをバッチ処理することでスループットを向上させます(同時リクエスト10~20件)
  • 頻繁に使うドキュメントをプロンプトキャッシュでキャッシュします
  • コンテキストの生成にはHaikuを使用します(高速で低コスト)
  • 戦略的に分割します(文や段落の境界を使用)
  • トークンの使用量を監視します(引用によるオーバーヘッドは約5~10%)

制限事項

  • 引用元は提供されたドキュメントに限られます
  • 文字インデックスによる引用には、テキストの完全一致が必要です
  • PDFのサポートには構造化解析が必要です
  • 引用の抽出にはトークンがかかります(オーバーヘッドは約5~10%)
  • 引用付きレスポンスではバッチ操作がサポートされていません

関連項目

  • [[llm-integration]] - APIの基本と認証
  • [[prompt-caching]] - コスト削減のためのドキュメントのキャッシュ
  • [[vision-multimodal]] - PDFと画像の処理
  • [[complex-reasoning]] - 引用を伴う拡張思考

コメント