プロンプトエンジニアリングによってモデルに出典を引用させる手法は、本質的に妥協の産物に過ぎませんでした。リーガルテック、金融分析、コンプライアンス監査などのミッションクリティカルな分野で検索拡張生成(RAG)を構築する際、多くのエンジニアが「角括弧内に出典文書名、正確なページ番号、原文の引用を含めて回答してください」といった指示を与えてきました。
しかし、実際の現場で起こるのは見破りにくいハルシネーションです。モデルはもっともらしい架空のページ番号を捏造し、一見すると逐語引用のように見えて微妙に語句を言い換え、あるいは文脈の全く異なる段落に事実の根拠を紐付けます。社内デモでは許容されても、規制当局の監査や法的な証拠提示、与信審査の現場では、不確定な証拠チェーンは致命的な運用リスクとなります。
私たち 365Finds は、Anthropic が提供する Claude のネイティブ Citations API を、決定論的かつ監査可能な生成 AI を実現するための極めて重要なマイルストーンであると評価しています。プロンプトによる確率的なテキスト生成に頼るのではなく、Citations API は引用のトラッキングを推論とトークン化の基礎レイヤーへと落とし込みました。Claude は、厳密な文字オフセット(start_char_index および end_char_index)、ページ番号、そしてサーバー側で切り出された正確な原文スライスを構造化オブジェクトとして返します。
本稿では 365Finds の視点から、Claude Citations API のアーキテクチャ、文字レベルインデックスの仕組み、本番対応の Python コード、そしてバックエンドで完全な事実検証を行う監査パイプラインの構築手法を徹底解説します。
アーキテクチャ:ネイティブポインタとプロンプトによるハルシネーションの決定的差異
Citations API の本質を理解するには、確率的生成と決定論的ソフトウェア工学の境界線を捉える必要があります。
従来のプロンプト指示で Claude に [文書1, 14ページ: "売上高は14%増加"] と記述させた場合、その引用文の各トークンは言語モデルの次トークン予測確率に従って出力されます。モデルのアテンションがわずかに揺らぐだけで、ページ番号や引用テキストは容易に変質します。
一方、Anthropic Citations API では、引用情報はモデルが自由生成するテキストトークンではありません。テキストブロックに紐付く独立した構造化メタデータとして出力されます。
+-------------------------------------------------------------------+
| ユーザーのリクエスト |
| 「第3四半期の営業利益率は何%か?またその低下要因は何か?」 |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| ドキュメント入力ブロック |
| - type: "document" |
| - source: { type: "text", media_type: "text/plain", data: ... } |
| - citations: { "enabled": true } |
| - cache_control: { "type": "ephemeral" } |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| Anthropic Claude ネイティブ推論・チャンキング |
| - ソースドキュメントに対する文単位の自動分割 |
| - アテンションと文書位置ポインタの内部アライメント |
| - サーバー側での正確な原文抽出と構造化引用オブジェクトの生成 |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| 構造化レスポンスブロック |
| テキストブロック1:「営業利益率は18.2%に低下しました」 |
| └── 引用メタデータ:char_location [412:478] -> 「営業利益率は...」|
| テキストブロック2:「主な要因は長距離幹線輸送コストの高騰です」 |
| └── 引用メタデータ:char_location [502:580] -> 「海上輸送費...」 |
+---------------------------------+---------------------------------+
|
v
+-------------------------------------------------------------------+
| バックエンド決定論的検証エンジン |
| アサーション:raw_doc[start_char_index:end_char_index] == cited_text|
| 未引用の重要主張や数値を即座に検知・遮断 |
+-------------------------------------------------------------------+
コスト面での絶大な利点:引用テキストが出力トークンに計上されない
大規模システムを設計する上で見落とされがちなのが、経済的なメリットです。API が構造化して返す cited_text の文字列は、出力トークン(Output Tokens)の消費としてカウントされません。
プロンプトで長大な規約や法的条文を逐語引用させると、コンテキストからコピーされたトークンに対しても出力料金が課されます。何万件もの監査文書を処理する場合、この差は膨大です。Citations API ではサーバー側で内部ポインタを解決して cited_text を抽出するため、このフィールドに出力トークン課金は発生しません。さらに、マルチターンの会話でこのフィールドをコンテキストに戻す際も、入力トークン課金から除外されます。
3 つのドキュメントタイプとインデックス基準
Claude Citations API は 3 種類のドキュメント形式をサポートしており、それぞれ参照粒度が異なります:
| ドキュメントタイプ | ソース形式 | サーバー側チャンキング | 引用オブジェクト種別 | 位置オフセットの基準 |
|---|---|---|---|---|
| プレーンテキスト(Plain Text) | text/plain 文字列または Files API の file_id | 文(Sentence)単位の自動分割 | char_location | start_char_index(0始まり・含む)〜 end_char_index(含まない) |
| PDF 文書 | Base64 エンコード、HTTPS URL、または file_id | 抽出テキストをページ内で文分割 | page_location | start_page_number(1始まり・含む)〜 end_page_number(含まない) |
| カスタムコンテンツ(Custom Content) | 独自コンテンツブロック配列 | 開発者が指定したブロックを保持(再分割なし) | content_block_location | start_block_index(0始まり・含む)〜 end_block_index(含まない) |
365Finds の推奨方針:
- 文字単位の完全な証跡やフロントエンドでのピンポイントハイライトが必要な場合は、迷わず**プレーンテキスト(Plain Text)**を採用してください。
- 社内のベクトル検索ですでに意味単位(QAペア、ログ行、対話履歴など)に分割されており、Anthropic による文分割でコンテキストが分断されるのを防ぎたい場合は、**カスタムコンテンツ(Custom Content)**を選択します。
- 該当する PDF ページ番号へのジャンプ表示で十分な場合は、**PDF(
page_location)**を利用します。
本番実装:Python による完全コード例
以下は、金融融資契約の条項を送信し、Prompt Caching を適用した上で、正確な文字オフセットを抽出する実装例です。
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
credit_agreement_text = """
CREDIT AGREEMENT SECTION 4.02: FINANCIAL COVENANTS.
The Borrower shall not permit the Consolidated Leverage Ratio as of the end of any
fiscal quarter of the Borrower to exceed 3.50 to 1.00; provided that, following any
Material Acquisition, such maximum ratio shall increase to 4.00 to 1.00 for the four
consecutive fiscal quarters immediately following the consummation of such acquisition.
The Borrower shall maintain a minimum Interest Coverage Ratio of not less than 2.50 to 1.00
at all times during the term of this Facility.
"""
response = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=2048,
messages=[
{
"role": "user",
"content": [
{
"type": "document",
"source": {
"type": "text",
"media_type": "text/plain",
"data": credit_agreement_text,
},
"title": "Facility Credit Agreement - Exhibit A",
"context": "Governing syndicated lending documentation dated January 15, 2025.",
"citations": {"enabled": True},
"cache_control": {"type": "ephemeral"}, # ドキュメントのキャッシュ有効化
},
{
"type": "text",
"text": (
"What is the maximum allowed Consolidated Leverage Ratio, "
"and does it change after an acquisition?"
),
},
],
}
],
)
# 構造化引用の解析
for block in response.content:
if block.type == "text":
print(f"\n[生成テキスト]:\n{block.text}")
if hasattr(block, "citations") and block.citations:
for citation in block.citations:
if citation.type == "char_location":
print(" --> [グラウンディング検証情報]:")
print(f" ドキュメント番号: {citation.document_index} ({citation.document_title})")
print(f" 文字スパン: [{citation.start_char_index}:{citation.end_char_index}]")
print(f" 引用原文スライス: \"{citation.cited_text.strip()}\"")
レスポンスペイロードの内部構造
上記を実行すると、Claude は一般的な接続詞と、事実の主張部分を明確に分割して返します:
{
"content": [
{
"type": "text",
"text": "The Borrower's Consolidated Leverage Ratio cannot exceed "
},
{
"type": "text",
"text": "3.50 to 1.00 as of the end of any fiscal quarter.",
"citations": [
{
"type": "char_location",
"document_index": 0,
"document_title": "Facility Credit Agreement - Exhibit A",
"start_char_index": 52,
"end_char_index": 216,
"cited_text": "The Borrower shall not permit the Consolidated Leverage Ratio as of the end of any \nfiscal quarter of the Borrower to exceed 3.50 to 1.00;"
}
]
},
{
"type": "text",
"text": " However, following a Material Acquisition, this limit increases to "
},
{
"type": "text",
"text": "4.00 to 1.00 for the next four consecutive fiscal quarters.",
"citations": [
{
"type": "char_location",
"document_index": 0,
"document_title": "Facility Credit Agreement - Exhibit A",
"start_char_index": 217,
"end_char_index": 384,
"cited_text": "provided that, following any \nMaterial Acquisition, such maximum ratio shall increase to 4.00 to 1.00 for the four \nconsecutive fiscal quarters immediately following the consummation of such acquisition."
}
]
}
]
}
一般的な前置き文には引用が付かず、契約の数値条件を述べるテキストブロックにのみ厳密な範囲が紐付けられている点に注目してください。
決定論的 RAG 監査エンジン:ゼロトラスト検証の実装
API から引用を受け取っただけでは、エンタープライズのコンプライアンス要件を満たしたとは言えません。365Finds では、レスポンスを下流のユーザーや後続システムに渡す前に、バックエンドで以下の 2 段階の検証を実施するパイプラインを推奨しています。
- 部分文字列の物理一致検証(Sub-string Parity):
original_document[start_char_index:end_char_index] == citation.cited_textを直接計算し、1文字のズレも許容せず照合します。 - 無根拠な主張の検知・フィルタリング(Grounding Coverage):数値や法的義務を含む文章において引用ブロックが存在しない場合、警告または遮断を行います。
from typing import List, Dict, Any
class GroundingVerificationError(Exception):
pass
class RAGCitationAuditor:
def __init__(self, raw_documents: List[str]):
self.raw_documents = raw_documents
def verify_message_response(self, response_content: List[Any]) -> Dict[str, Any]:
total_text_blocks = 0
cited_text_blocks = 0
verified_citations = 0
for block in response_content:
if block.type != "text":
continue
total_text_blocks += 1
citations = getattr(block, "citations", None)
if citations:
cited_text_blocks += 1
for cit in citations:
if cit.type == "char_location":
doc_idx = cit.document_index
start = cit.start_char_index
end = cit.end_char_index
expected_text = cit.cited_text
if doc_idx >= len(self.raw_documents):
raise GroundingVerificationError(f"不正なドキュメントインデックス: {doc_idx}")
source_slice = self.raw_documents[doc_idx][start:end]
if source_slice != expected_text:
raise GroundingVerificationError(
f"原文の不一致を検出! 抽出: '{source_slice}' != 引用: '{expected_text}'"
)
verified_citations += 1
coverage_ratio = (
cited_text_blocks / total_text_blocks if total_text_blocks > 0 else 0.0
)
return {
"status": "PASS",
"total_blocks": total_text_blocks,
"cited_blocks": cited_text_blocks,
"verified_citations": verified_citations,
"grounding_coverage_ratio": round(coverage_ratio, 3),
}
この検証処理は単純なメモリスライス照合(計算量 $\mathcal{O}(1)$)であるため、処理時間は 1 ミリ秒未満であり、推論レイテンシに一切影響を与えません。
ストリーミング処理:citations_delta イベント
リアルタイムチャット UI において、すべての応答が完了するまで引用のレンダリングを遅延させる必要はありません。Anthropic の SSE ストリームでは、content_block_delta イベント内で citations_delta が配信されます:
with client.messages.stream(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[...],
) as stream:
for event in stream:
if event.type == "content_block_delta":
delta = event.delta
if delta.type == "text_delta":
# 受信テキストの即時描画
sys.stdout.write(delta.text)
sys.stdout.flush()
elif delta.type == "citations_delta":
# 現在のテキストブロックに対する引用情報の到着
citation = delta.citation
print(f"\n[ストリーミング引用: {citation.cited_text[:25]}...]")
フロントエンド実装:文字オフセットによるゼロレイテンシ描画
従来のドキュメントビューア(PDF.js やリッチテキストエディタ)では、引用文をハイライトするために正規表現検索や文字列一致アルゴリズムが使われていました。しかし何百ページもある文書では、正規表現検索はメインスレッドをブロックし、同名フレーズが多数ある場合に誤った場所をハイライトしてしまいます。
Citations API の start_char_index と end_char_index を使えば、モダンブラウザの CSS Custom Highlight API や DOM TreeWalker を直接呼び出し、ミリ秒単位でピンポイント描画が可能です:
function highlightSourcePassage(containerElement, startChar, endChar) {
const textContent = containerElement.textContent;
if (startChar < 0 || endChar > textContent.length) return;
const walker = document.createTreeWalker(
containerElement,
NodeFilter.SHOW_TEXT,
null
);
let currentCharCount = 0;
let startNode = null, endNode = null;
let startNodeOffset = 0, endNodeOffset = 0;
let node;
while ((node = walker.nextNode())) {
const nextCharCount = currentCharCount + node.length;
if (!startNode && startChar >= currentCharCount && startChar < nextCharCount) {
startNode = node;
startNodeOffset = startChar - currentCharCount;
}
if (!endNode && endChar > currentCharCount && endChar <= nextCharCount) {
endNode = node;
endNodeOffset = endChar - currentCharCount;
break;
}
currentCharCount = nextCharCount;
}
if (startNode && endNode) {
const range = document.createRange();
range.setStart(startNode, startNodeOffset);
range.setEnd(endNode, endNodeOffset);
const highlight = new Highlight(range);
CSS.highlights.set("claude-citation-target", highlight);
}
}
設計上の制約事項と 365Finds の評価
365Finds の責務は、ツールの利点だけでなく現場が直面する設計上の制約を明示することです。Citations API を導入する際は、以下の 3 点に留意してください。
1. ネイティブ構造化出力(output_config.format)との非互換性
最も重要な制限事項です。Citations API は、Claude のネイティブ構造化出力(JSON Schema モード)と同時に利用することはできません。 両方を同時に指定すると、Messages API は 400 Bad Request を返します。
引用機能はテキストトークンと引用メタデータをインラインで交互配置する必要があるため、厳格な JSON 構文木検証と競合するためです。
実務上の回避策: 引用付きで構造化データを抽出したい場合は、JSON ではなく行指向のキー・バリュー形式で出力させます:
文書から以下の項目を抽出してください:
revenue: [値]
operating_margin: [値]
各行は「項目名: 値」の形式で1行ずつ出力し、各行に必ず引用を付与してください。
バックエンド側でコロンによる文字列分割を行い、各行に付与された citations 配列をマッピングします。
2. 「すべて有効」または「すべて無効」のルール
同一リクエスト内に含まれるドキュメントブロックや検索結果ブロックにおいて、一部だけ引用を有効化し、他を無効化することはできません。
3. スキャン画像 PDF の非対応
テキスト層を含まないスキャン画像 PDF の場合、OCR 処理が行われないため引用を生成できません。事前に OCR パイプラインを通過させ、プレーンテキストとして渡す必要があります。
365Finds の結論
プロンプトで「引用元を併記してください」と頼む運用は、直ちに廃止すべきです。自己回帰型モデルの性質上、プロンプトだけで引用ハルシネーションを完全に排除することは原理的に不可能です。
Anthropic Claude の Citations API は、根拠付けを「確率的推測」から「決定論的ポインタ」へと転換させました。文字レベルの物理オフセット照合、引用部分の出力トークン無料化、そしてドキュメントキャッシュの組み合わせにより、法的説明責任や規制遵守が求められるシステムにおいて、真に監査可能な技術基盤を提供します。