概要
Claude APIでは、検索結果の適切な引用機能と多言語サポートにより、グローバルなRAG(Retrieval-Augmented Generation)アプリケーションの構築を可能にします。 この章では、検索結果機能、Citations API、そして多言語サポートの技術的詳細と実装パターンについて解説します。
検索結果機能
検索結果機能は、RAGアプリケーションにおいて自然な引用システムを実現するコンテンツブロック機能です。 Web検索のような高品質な引用を任意のコンテンツに適用できるため、カスタムアプリケーションでのソース属性付与が可能になります。
この機能により、従来のRAGシステムで必要だった複雑なドキュメント回避策が不要になり、一貫した引用フォーマットでClaudeのWeb検索機能と同等の引用品質を実現できます。
対応モデルと利用方法
検索結果機能は以下のモデルで利用可能です。
対応モデル一覧
- Claude Opus 4.5 (
claude-opus-4-5-20251101) - Claude Opus 4.1 (
claude-opus-4-1-20250805) - Claude Opus 4 (
claude-opus-4-20250514) - Claude Sonnet 4.5 (
claude-sonnet-4-5-20250929) - Claude Sonnet 4 (
claude-sonnet-4-20250514) - Claude Sonnet 3.7 (
claude-3-7-sonnet-20250219)(非推奨) - Claude Haiku 4.5 (
claude-haiku-4-5-20251001) - Claude Haiku 3.5 (
claude-3-5-haiku-20241022)(非推奨)
Claude Sonnet 3.7使用時の注意点
Claude Sonnet 3.7は他のClaudeモデルと比較して、明示的な指示がないと引用を生成しにくい傾向があります。 Claude Sonnet 3.7で引用機能を使用する場合は、ユーザーターンに「回答を裏付けるために引用を使用してください」などの追加指示を含めることを推奨します。
また、モデルに応答の構造化を求める場合(例えば<result>タグを使用する場合)、引用がその形式内で使用されない傾向があります。
このような場合は「<result>タグ内でも常に引用を使用してください」のような指示を追加してください。
検索結果のデフォルト動作
検索結果の引用はデフォルトで無効になっています。
引用を有効にするには、citations: { enabled: true }を明示的に設定する必要があります。
citationsフィールドを省略した場合、引用はデフォルトで無効になります。
citations.enabledをtrueに設定すると、Claude は検索結果の情報を使用する時に引用参照を含めるようになります。
これにより、カスタムRAGアプリケーションでの自然な引用、独自のナレッジベースとのインターフェース時のソース属性、検索結果を返すカスタムツールでのWeb検索品質の引用が可能になります。
検索結果は2つの方法で提供できます。 動的RAGアプリケーション向けのツールコールからの返却と、プリフェッチやキャッシュされたコンテンツ向けのトップレベルコンテンツでの提供があります。
検索結果のスキーマ設計
検索結果は以下の構造で定義します。
{
"type": "search_result",
"source": "https://example.com/article",
"title": "Article Title",
"content": [
{
"type": "text",
"text": "The actual content of the search result..."
}
],
"citations": {
"enabled": true
}
}必須フィールド
type"search_result"を指定します。sourceコンテンツのソースURLまたは識別子を指定します。title検索結果の説明タイトルを指定します。content実際のコンテンツを含むテキストブロックの配列を指定します。
オプションフィールド
-
citations引用設定を指定します。
enabledブール値フィールドで引用の有効/無効を制御します。 -
cache_controlキャッシュ制御設定を指定します(例:
{"type": "ephemeral"})。
content配列の各項目は以下の構造を持つテキストブロックである必要があります。
{
"type": "text",
"text": "非空文字列の実際のテキストコンテンツ"
}このスキーマ設計により、検索結果に必要なメタデータと実際のコンテンツを適切に構造化できます。
sourceフィールドでソースの追跡が可能になり、citations設定で引用の自動生成を制御できます。
ツールベースの検索実装
動的RAGシステムの構築
最も強力な使用例は、カスタムツールから検索結果を返却することです。 これにより、動的RAGアプリケーションでツールが関連コンテンツを取得し、自動引用付きで返却できます。
以下は、企業ナレッジベース検索ツールの実装例です。
from anthropic import Anthropic
from anthropic.types import (
MessageParam,
TextBlockParam,
SearchResultBlockParam,
ToolResultBlockParam
)
client = Anthropic()
# ナレッジベース検索ツールの定義
knowledge_base_tool = {
"name": "search_knowledge_base",
"description": "企業ナレッジベースから情報を検索",
"input_schema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "検索クエリ"
}
},
"required": ["query"]
}
}
# ツールコール処理関数
def search_knowledge_base(query):
# 実際の検索ロジックをここに実装
# 正しいフォーマットで検索結果を返却
return [
SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/product-guide",
title="プロダクト設定ガイド",
content=[
TextBlockParam(
type="text",
text="プロダクトを設定するには、Settings > Configuration に移動してください。デフォルトタイムアウトは30秒ですが、ニーズに応じて10-120秒の間で調整可能です。"
)
],
citations={"enabled": True}
),
SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/troubleshooting",
title="トラブルシューティングガイド",
content=[
TextBlockParam(
type="text",
text="タイムアウトエラーが発生した場合、まず設定を確認してください。一般的な原因には、ネットワーク遅延と不正なタイムアウト値があります。"
)
],
citations={"enabled": True}
)
]このコードでは、search_knowledge_base関数でナレッジベース検索を実装しています。
knowledge_base_toolとして定義されたツールがClaudeによって呼び出されると、企業内のドキュメントを検索し、適切なSearchResultBlockParam形式で結果を返却します。
各検索結果にはsourceにドキュメントのURLを、titleに分かりやすいタイトルを設定し、content配列に実際の情報を格納します。
citations={"enabled": True}により、Claudeが回答で情報を使用する時に自動的に引用が付与されます。
実際の使用例は以下のようになります。
# ツールを使用したメッセージの作成
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=[knowledge_base_tool],
messages=[
MessageParam(
role="user",
content="タイムアウト設定の変更方法を教えてください"
)
]
)
# Claudeがツールを呼び出した場合の処理
if response.content[0].type == "tool_use":
tool_result = search_knowledge_base(response.content[0].input["query"])
# ツール結果をClaudeに返却
final_response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[
MessageParam(role="user", content="タイムアウト設定の変更方法を教えてください"),
MessageParam(role="assistant", content=response.content),
MessageParam(
role="user",
content=[
ToolResultBlockParam(
type="tool_result",
tool_use_id=response.content[0].id,
content=tool_result
)
]
)
]
)Claudeは提供された検索結果から情報を抽出し、適切な引用付きで回答を生成します。 これにより、企業内ドキュメントへの正確な参照を含む回答が可能になります。
高度な検索パターン
実際のプロダクション環境では、より複雑な検索パターンが必要になります。
複数検索結果の統合処理
def advanced_search(query, max_results=5):
"""複数ソースからの検索結果を統合"""
results = []
# 複数の検索エンジンから結果を取得
for search_engine in [internal_docs, api_docs, troubleshooting_db]:
try:
engine_results = search_engine.search(query, limit=2)
for result in engine_results:
results.append(SearchResultBlockParam(
type="search_result",
source=result.url,
title=result.title,
content=[
TextBlockParam(
type="text",
text=result.content
)
],
citations={"enabled": True},
cache_control={"type": "ephemeral"}
))
except Exception as e:
# エラーログを記録するが処理は継続
logger.warning(f"検索エンジン {search_engine.name} でエラー: {e}")
# 関連度による結果のソート
sorted_results = sort_by_relevance(results, query)
return sorted_results[:max_results]この関数では、複数の検索エンジン(社内ドキュメント、APIドキュメント、トラブルシューティングDB)から並行して結果を取得し、関連度でソートしています。
エラーハンドリングとフォールバック戦略
def search_with_fallback(query):
"""フォールバック機能付き検索"""
try:
# プライマリ検索の実行
results = primary_search_engine.search(query)
if not results:
# 結果が空の場合はセカンダリ検索を試行
results = secondary_search_engine.search(query)
if results:
return format_search_results(results)
else:
# 検索結果がない場合のメッセージ
return [
TextBlockParam(
type="text",
text="申し訳ございませんが、該当する情報が見つかりませんでした。別のキーワードで検索をお試しください。"
)
]
except Exception as e:
# エラー時のフォールバック
return [
TextBlockParam(
type="text",
text=f"検索中にエラーが発生しました: {str(e)}。システム管理者にお問い合わせください。"
)
]これらの実装により、堅牢で信頼性の高い動的RAGシステムを構築できます。 複数のデータソースからの情報統合、エラー状況での適切なフォールバック、そしてユーザーエクスペリエンスを損なわない方法でのエラー処理が可能になります。
直接検索結果の活用
プリフェッチコンテンツの処理
ツールベースの検索に加えて、検索結果をユーザーメッセージ内で直接提供することも可能です。 この方法は、事前に取得したコンテンツや外部検索サービスからの結果に適用できます。
from anthropic import Anthropic
from anthropic.types import (
MessageParam,
TextBlockParam,
SearchResultBlockParam
)
client = Anthropic()
# ユーザーメッセージ内で直接検索結果を提供
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[
MessageParam(
role="user",
content=[
SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/api-reference",
title="API リファレンス - 認証",
content=[
TextBlockParam(
type="text",
text="すべてのAPIリクエストには、AuthorizationヘッダーにAPIキーを含める必要があります。キーはダッシュボードから生成できます。レート制限: 標準プランで1時間あたり1000リクエスト、プレミアムで10000リクエスト。"
)
],
citations={"enabled": True}
),
SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/quickstart",
title="クイックスタートガイド",
content=[
TextBlockParam(
type="text",
text="開始方法: 1) アカウント作成、2) ダッシュボードからAPIキー生成、3) uv pip install company-sdkでSDKインストール、4) APIキーでクライアント初期化。"
)
],
citations={"enabled": True}
),
TextBlockParam(
type="text",
text="これらの検索結果に基づいて、APIリクエストの認証方法とレート制限について説明してください。"
)
]
)
]
)このコードでは、ユーザーメッセージのcontent配列内に複数のSearchResultBlockParamを配置しています。
各検索結果には企業ドキュメントからの情報が含まれており、最後のTextBlockParamでClaudeに対する具体的な質問を提示しています。
Claudeは提供された検索結果を分析し、API認証とレート制限について適切な引用付きで回答します。 この方法は、検索インフラストラクチャから事前に取得した結果や、キャッシュされた検索結果の再利用に特に有効です。
複合コンテンツの組み合わせ
検索結果は他のコンテンツタイプと組み合わせて使用できます。
検索結果と画像の組み合わせ
user_content = [
SearchResultBlockParam(
type="search_result",
source="https://research.com/ai-performance-study",
title="AI性能研究論文",
content=[
TextBlockParam(
type="text",
text="最新の研究では、大規模言語モデルの多言語性能において、英語以外の言語でも90%以上の性能維持が確認されています。特に、ゼロショット学習における言語間転移の効果が顕著です。"
)
],
citations={"enabled": True}
),
{
"type": "image",
"source": {"type": "url", "url": "https://example.com/performance-chart.png"}
},
TextBlockParam(
type="text",
text="提供されたチャートと研究論文の結果の関連性について分析してください。"
)
]この例では、研究論文の検索結果と画像を同じリクエスト内で組み合わせ、Claudeに両者の関連性分析を依頼しています。
キャッシュコントロールの最適化
大量の検索結果や頻繁に参照されるコンテンツには、キャッシュコントロールを適用してパフォーマンスを向上させることができます。
SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/comprehensive-guide",
title="包括的ガイド",
content=[
TextBlockParam(
type="text",
text="詳細なドキュメンテーション内容..."
)
],
cache_control={"type": "ephemeral"},
citations={"enabled": True}
)cache_control={"type": "ephemeral"}を設定することで、同一コンテンツへの繰り返しアクセス時のレスポンス時間を短縮できます。
混合コンテンツでのツール結果
ツール結果においても、検索結果と通常のテキストを組み合わせることが可能です。
tool_result = [
SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/latest-updates",
title="最新アップデート",
content=[
TextBlockParam(
type="text",
text="バージョン2.5では新しい認証メカニズムが導入されました。"
)
],
citations={"enabled": True}
),
TextBlockParam(
type="text",
text="追加コンテキスト: この変更はバージョン2.0以降に適用されます。"
)
]これらの組み合わせにより、豊富なコンテキストを持つ包括的な回答システムを構築できます。 検索結果による正確な引用と、補足情報やビジュアル要素との組み合わせにより、ユーザーにとってより有用で信頼性の高い情報提供が可能になります。
Citations API
Citations APIの中核機能
Citations APIは、Claudeがソースドキュメントへの正確な参照リンクを提供することを可能にする革新的な機能です。 この機能により、AI生成の回答に検証可能で追跡可能な根拠を提供し、従来のRAGシステムの課題を解決します。
Citations APIの主要な利点は以下の通りです。
精度の向上
- カスタム実装と比較して最大15%のリコール精度改善を実現
- 従来必要だった複雑なプロンプトエンジニアリングが不要
- ソース追跡のための手動実装を大幅に簡素化
ハルシネーションの削減
- 情報の出典を明確化することで、不正確な情報生成を抑制
- ファイル保存が不要で、Messages APIと直接統合
- 従来のドキュメント参照回避策が不要
技術的実装詳細
Citations APIは、ユーザーが提供したドキュメント(PDFおよび平文テキスト)を文レベルでセグメント化して処理します。
sequenceDiagram
participant User
participant Claude
participant Citations API
participant Document
User->>Claude: ドキュメントとクエリを送信
Claude->>Citations API: ドキュメント処理要求
Citations API->>Document: 文レベルセグメント化
Document-->>Citations API: セグメント化された内容
Citations API->>Claude: コンテキスト付きチャンク
Claude->>User: 引用付き回答を生成処理フロー
- ドキュメント投入 PDFまたは平文テキストをAPIに送信します。
- セグメント化 ドキュメントを文レベルでチャンクに分割します。
- コンテキスト統合 セグメントとクエリコンテキストをモデルに渡します。
- 分析・生成 Claudeがリクエストを分析し引用付き回答を生成します。
- 引用リンク 主張を元のソースマテリアルにリンクします。
対応モデルと料金体系
-
対応モデル
Claude 3.5 SonnetおよびClaude 3.5 Haikuで利用可能です。
-
対応プラットフォーム
Anthropic API、Google Cloud Vertex AI、Amazon Bedrockで利用可能です。
-
料金体系
標準のトークンベース課金です。 引用されたテキスト出力トークンに追加料金はかかりません。
引用レスポンスの構造
Citations APIが生成する引用は、詳細な構造情報を含んでいます。
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "APIリクエストの認証には、AuthorizationヘッダーにAPIキーを含める必要があります",
"citations": [
{
"type": "search_result_location",
"source": "https://docs.company.com/api-reference",
"title": "API リファレンス - 認証",
"cited_text": "すべてのAPIリクエストには、AuthorizationヘッダーにAPIキーを含める必要があります",
"search_result_index": 0,
"start_block_index": 0,
"end_block_index": 0
}
]
},
{
"type": "text",
"text": "。APIキーはダッシュボードから生成できます",
"citations": [
{
"type": "search_result_location",
"source": "https://docs.company.com/api-reference",
"title": "API リファレンス - 認証",
"cited_text": "キーはダッシュボードから生成できます",
"search_result_index": 0,
"start_block_index": 0,
"end_block_index": 0
}
]
}
]
}引用フィールドの詳細
| フィールド | 型 | 説明 |
|---|---|---|
type |
string | 検索結果引用の場合は常に"search_result_location" |
source |
string | 元の検索結果のソース |
title |
string/null | 元の検索結果のタイトル |
cited_text |
string | 引用される正確なテキスト |
search_result_index |
integer | 検索結果のインデックス(0ベース) |
start_block_index |
integer | コンテンツ配列内の開始位置 |
end_block_index |
integer | コンテンツ配列内の終了位置 |
search_result_indexは、検索結果の提供方法(ツールコールまたはトップレベルコンテンツ)に関係なく、検索結果コンテンツブロックの0ベースインデックスを参照します。
複数コンテンツブロックでの引用
検索結果のcontent配列に複数のテキストブロックがある場合、Claudeはstart_block_indexとend_block_indexフィールドを使用して特定のブロックを引用できます。
{
"type": "search_result",
"source": "https://docs.company.com/api-guide",
"title": "API ドキュメンテーション",
"content": [
{
"type": "text",
"text": "認証: すべてのAPIリクエストにはAPIキーが必要です。"
},
{
"type": "text",
"text": "レート制限: APIは1時間あたり1000リクエストまで許可します。"
},
{
"type": "text",
"text": "エラーハンドリング: APIは標準的なHTTPステータスコードを返します。"
}
]
}この例では、Claudeがレート制限について言及する場合、start_block_index: 1とend_block_index: 1を使用して2番目のブロックを正確に引用します。
このインデックス指定により、複数のコンテンツブロックを含む検索結果でも、引用元を正確に特定できます。
多言語サポート
クロスリンガル性能
Claudeは複数言語でのタスクに優れており、英語と比較して強力なクロスリンガル性能を維持しています。 特に、広く話されている言語と低リソース言語の両方で一貫した相対的性能を示しており、多言語アプリケーションにとって信頼性の高い選択肢となっています。
以下は、各言語でのゼロショット思考連鎖評価スコアを英語性能に対する百分率で示したデータです。
多言語性能データ
| 言語 | Claude Opus 4.1 | Claude Opus 4 | Claude Sonnet 4.5 | Claude Sonnet 4 | Claude Haiku 4.5 |
|---|---|---|---|---|---|
| 英語(ベースライン) | 100% | 100% | 100% | 100% | 100% |
| スペイン語 | 98.1% | 98.0% | 98.2% | 97.5% | 96.4% |
| ポルトガル語(ブラジル) | 97.8% | 97.3% | 97.8% | 97.2% | 96.1% |
| イタリア語 | 97.7% | 97.5% | 97.9% | 97.3% | 96.0% |
| フランス語 | 97.9% | 97.7% | 97.5% | 97.1% | 95.7% |
| インドネシア語 | 97.3% | 97.2% | 97.3% | 96.2% | 94.2% |
| ドイツ語 | 97.7% | 97.1% | 97.0% | 94.7% | 94.3% |
| アラビア語 | 97.1% | 96.9% | 97.2% | 96.1% | 92.5% |
| 中国語(簡体字) | 97.1% | 96.7% | 96.9% | 95.9% | 94.2% |
| 韓国語 | 96.6% | 96.4% | 96.7% | 95.9% | 93.3% |
| 日本語 | 96.9% | 96.2% | 96.8% | 95.6% | 93.5% |
| ヒンディー語 | 96.8% | 96.7% | 96.7% | 95.8% | 92.4% |
| ベンガル語 | 95.7% | 95.2% | 95.4% | 94.4% | 90.4% |
| スワヒリ語 | 89.8% | 89.5% | 91.1% | 87.1% | 78.3% |
| ヨルバ語 | 80.3% | 78.9% | 79.7% | 76.4% | 52.7% |
これらの評価結果は、MMLU(Massive Multitask Language Understanding)英語テストセットをプロフェッショナルな人間翻訳者によって14の追加言語に翻訳したデータに基づいています。 人間翻訳者の使用により、特にデジタルリソースが少ない言語において高品質な翻訳が確保されています。
性能特性の分析
- 高リソース言語 スペイン語、フランス語、ドイツ語などは97-98%の高い性能維持率です。
- 東アジア言語 日本語、韓国語、中国語は95-97%の安定した性能です。
- インド言語 ヒンディー語、ベンガル語は90-97%の範囲で良好な性能です。
- アフリカ言語 スワヒリ語、ヨルバ語は78-91%で、リソースの少なさを反映しています。
多言語実装のベストプラクティス
多言語コンテンツを扱う際は、以下のガイドラインに従うことで最適な結果を得られます。
明確な言語コンテキストの提供
Claudeは対象言語を自動検出できますが、明示的に希望する入力/出力言語を指定すると信頼性が向上します。
# 言語を明示したプロンプト例
messages = [
MessageParam(
role="user",
content=[
SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/ja/guide",
title="製品ガイド(日本語版)",
content=[
TextBlockParam(
type="text",
text="この製品は高度な多言語サポート機能を提供し、日本語、英語、中国語での操作が可能です。"
)
],
citations={"enabled": True}
),
TextBlockParam(
type="text",
text="日本語で回答してください。この製品の多言語機能について詳しく説明してください。"
)
]
)
]
# より自然な言語使用を求める場合
enhanced_prompt = """
日本語のネイティブスピーカーのような自然で慣用的な表現で回答してください。
提供された検索結果に基づいて、この製品の多言語サポート機能について説明してください。
"""ネイティブスクリプトの使用
音写や転写ではなく、各言語固有の文字体系での入力が最適な結果をもたらします。
# 良い例: ネイティブスクリプトを使用
arabic_search_result = SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/ar/api",
title="دليل واجهة برمجة التطبيقات",
content=[
TextBlockParam(
type="text",
text="تتطلب جميع طلبات واجهة برمجة التطبيقات مفتاح API في عنوان التخويل."
)
],
citations={"enabled": True}
)
# 避けるべき例: 音写を使用
# "Tatalab jamee'a talabat wajihat barmajat al-tatbiqat miftah API"文化的コンテキストの考慮
効果的なコミュニケーションには、純粋な翻訳を超えた文化的および地域的認識が必要です。
# 地域特有のビジネス慣行を考慮した例
regional_context = """
以下の検索結果は日本市場向けのドキュメントです。
日本のビジネス文化と商習慣を考慮して、
敬語と適切なビジネスマナーを用いて回答してください。
"""
japanese_business_result = SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/ja/business-guide",
title="日本市場向けビジネスガイド",
content=[
TextBlockParam(
type="text",
text="日本市場では、初回商談時の名刺交換が重要な儀式とされ、両手で受け取り軽く一礼することがマナーです。"
)
],
citations={"enabled": True}
)この設定により、日本のビジネス文化に適応した検索結果と回答生成が実現できます。
言語別パフォーマンス分析
MMLU評価に基づく詳細分析
これらの評価は、プロフェッショナルな人間翻訳者によって翻訳された高品質なデータセットに基づいており、機械翻訳では捉えきれない言語的ニュアンスも考慮されています。
モデル別性能比較
graph LR
A[Claude Opus 4.1] --> B[最高性能 98.1% スペイン語]
C[Claude Sonnet 4.5] --> D[安定性能 98.2% スペイン語]
E[Claude Haiku 4.5] --> F[効率性 96.4% スペイン語]
A --> G[アフリカ言語 80.3% ヨルバ語]
C --> H[アフリカ言語 79.7% ヨルバ語]
E --> I[アフリカ言語 52.7% ヨルバ語]翻訳品質と文化的適応
多言語サポートにおいては、言語の翻訳精度だけでなく、文化的適応も重要な要素です。
# 文化的に適応された多言語検索の実装例
def culturally_adapted_search(query, target_language, region):
"""文化的コンテキストを考慮した多言語検索"""
cultural_context = get_cultural_context(target_language, region)
localized_query = adapt_query_for_culture(query, cultural_context)
search_results = []
# 地域特化コンテンツを優先
regional_results = search_regional_content(localized_query, region)
for result in regional_results:
search_results.append(SearchResultBlockParam(
type="search_result",
source=result.url,
title=localize_title(result.title, target_language),
content=[
TextBlockParam(
type="text",
text=adapt_content_for_culture(result.content, cultural_context)
)
],
citations={"enabled": True}
))
return search_results
# 使用例
japanese_results = culturally_adapted_search(
query="business meeting etiquette",
target_language="ja",
region="japan"
)パフォーマンス最適化戦略
各言語の特性に応じた最適化戦略も重要です。
# 言語特性に応じた処理最適化
def optimize_for_language(content, language_code):
"""言語特性に応じたコンテンツ最適化"""
if language_code in ['ja', 'ko', 'zh']:
# CJK言語: 文字密度が高いため、短いチャンクサイズを使用
max_chunk_size = 800
sentence_boundary = detect_cjk_sentence_boundary
elif language_code in ['ar', 'he']:
# RTL言語: 特別な文字処理
content = normalize_rtl_text(content)
max_chunk_size = 1000
sentence_boundary = detect_rtl_sentence_boundary
else:
# ラテン文字系言語
max_chunk_size = 1200
sentence_boundary = detect_standard_sentence_boundary
return chunk_content(content, max_chunk_size, sentence_boundary)これらの多言語サポート機能により、グローバルなユーザーベースに対して一貫した高品質なサービスを提供できます。 検索・引用機能と組み合わせることで、文化的に適切で正確な引用付きの多言語RAGシステムの構築が可能になります。
実践的統合パターン
エンタープライズ検索システム
大規模な企業環境では、複数のドキュメントソースからの情報統合が必要です。 検索・引用・多言語サポート機能を組み合わせることで、包括的なエンタープライズ検索システムを構築できます。
class EnterpriseSearchSystem:
"""エンタープライズ向け多言語検索システム"""
def __init__(self):
self.anthropic_client = Anthropic()
self.document_sources = {
'internal_docs': InternalDocumentSearch(),
'api_docs': APIDocumentationSearch(),
'kb_articles': KnowledgeBaseSearch(),
'policies': PolicyDocumentSearch()
}
self.supported_languages = ['en', 'ja', 'ko', 'zh', 'es', 'fr', 'de']
def enterprise_search(self, query, user_language='en', max_results=10):
"""企業内横断検索の実行"""
# 言語検出と正規化
detected_lang = detect_language(query)
target_lang = user_language or detected_lang
# 多言語クエリ展開
expanded_queries = self.expand_query_multilingually(query, target_lang)
all_results = []
# 各ドキュメントソースからの検索
for source_name, search_engine in self.document_sources.items():
try:
for expanded_query in expanded_queries:
source_results = search_engine.search(
query=expanded_query,
language=target_lang,
limit=3
)
for result in source_results:
all_results.append(SearchResultBlockParam(
type="search_result",
source=result.canonical_url,
title=self.localize_title(result.title, target_lang),
content=[
TextBlockParam(
type="text",
text=self.translate_if_needed(result.content, target_lang)
)
],
citations={"enabled": True},
cache_control={"type": "ephemeral"}
))
except Exception as e:
logger.warning(f"検索ソース {source_name} でエラー: {e}")
continue
# 関連度による結果のランキング
ranked_results = self.rank_by_relevance(all_results, query, target_lang)
return ranked_results[:max_results]
def expand_query_multilingually(self, query, target_lang):
"""多言語クエリ展開"""
expanded = [query]
# 同義語と関連語の追加
synonyms = self.get_synonyms(query, target_lang)
expanded.extend(synonyms)
# 英語が対象言語でない場合、英語版も追加
if target_lang != 'en':
english_query = self.translate_to_english(query)
expanded.append(english_query)
return expandedこの実装により、企業内の複数のドキュメントソースを横断的に検索し、多言語対応の結果を統一されたフォーマットで提供できます。 クエリの多言語展開機能により、ユーザーの言語に関係なく関連性の高いドキュメントを発見できます。
Thomson ReutersとEndexの導入事例
実際の企業での導入事例として、Thomson ReutersとEndexの成果が報告されています。
Thomson ReutersはClaudeを用いてAIプラットフォーム「CoCounsel」を構築し、法律・税務の専門家向けに専門知識の統合と包括的なアドバイスを提供しています。 同社 CoCounselのプロダクト責任者であるJake Heller氏は次のように述べています。「CoCounselが弁護士にとって信頼できるツールであるためには、出典の引用が不可欠です。当初は自社で構築しましたが、維持が非常に困難でした。そのためAnthropicのCitations機能をテストできることを大変歓迎しています。この機能により、一次情報源への引用やリンクの構築・維持・展開が格段に容易になりました。ハルシネーションのリスク低減だけでなく、AI生成コンテンツへの信頼強化にも貢献しています。」
金融企業向け自律型Agentを提供するEndexは、Citations APIの導入により定量的な成果を達成しました。 同社CEO のTarun Amasa氏によると、「Anthropicのcitationsにより、ソースのハルシネーションとフォーマット問題が10%から0%に減少し、1回の回答あたりの参照数が20%増加しました。複雑なマルチステージの金融リサーチにおける正確性が向上し、参照に関する複雑なプロンプトエンジニアリングも不要になりました。」と報告されています。
カスタマーサポートシステム
多言語対応のカスタマーサポートシステムでは、リアルタイムでの回答生成と正確な引用が重要です。
class MultilingualSupportSystem:
"""多言語カスタマーサポートシステム"""
def __init__(self):
self.claude_client = Anthropic()
self.support_tools = [
self.create_faq_search_tool(),
self.create_troubleshooting_tool(),
self.create_product_info_tool()
]
def create_faq_search_tool(self):
"""FAQ検索ツールの作成"""
return {
"name": "search_faq",
"description": "よくある質問データベースから情報を検索",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "検索クエリ"},
"language": {"type": "string", "description": "言語コード(ja, en, etc)"},
"category": {"type": "string", "description": "カテゴリ(オプション)"}
},
"required": ["query"]
}
}
def handle_support_request(self, customer_query, customer_language='auto'):
"""サポートリクエストの処理"""
# 言語自動検出
if customer_language == 'auto':
customer_language = detect_language(customer_query)
# 文化的に適応したシステムプロンプト
system_prompt = self.get_culturally_adapted_prompt(customer_language)
response = self.claude_client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2000,
system=system_prompt,
tools=self.support_tools,
messages=[
MessageParam(
role="user",
content=f"[{customer_language}] {customer_query}"
)
]
)
# ツールが呼び出された場合の処理
if response.content[0].type == "tool_use":
tool_result = self.execute_support_tool(
response.content[0].name,
response.content[0].input,
customer_language
)
# 最終回答の生成
final_response = self.claude_client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2000,
system=system_prompt,
messages=[
MessageParam(
role="user",
content=f"[{customer_language}] {customer_query}"
),
MessageParam(role="assistant", content=response.content),
MessageParam(
role="user",
content=[
ToolResultBlockParam(
type="tool_result",
tool_use_id=response.content[0].id,
content=tool_result
)
]
)
]
)
return final_response
return response
def execute_support_tool(self, tool_name, tool_input, language):
"""サポートツールの実行"""
if tool_name == "search_faq":
return self.search_multilingual_faq(
query=tool_input["query"],
language=language,
category=tool_input.get("category")
)
# 他のツールの処理...
def search_multilingual_faq(self, query, language, category=None):
"""多言語FAQ検索"""
# 現地語での検索を優先
results = self.faq_database.search(
query=query,
language=language,
category=category,
limit=3
)
# 結果が少ない場合、英語FAQも検索
if len(results) < 2 and language != 'en':
english_query = translate_to_english(query)
english_results = self.faq_database.search(
query=english_query,
language='en',
category=category,
limit=2
)
# 英語結果を現地語に翻訳
for result in english_results:
translated_result = self.translate_faq_result(result, language)
results.append(translated_result)
# SearchResultBlockParam形式に変換
search_results = []
for result in results:
search_results.append(SearchResultBlockParam(
type="search_result",
source=f"https://support.company.com/{language}/faq/{result.id}",
title=result.title,
content=[
TextBlockParam(
type="text",
text=result.content
)
],
citations={"enabled": True}
))
return search_results
def get_culturally_adapted_prompt(self, language):
"""言語に応じたシステムプロンプト"""
prompts = {
'ja': """
あなたは丁寧で親切なカスタマーサポート担当者です。
敬語を適切に使用し、日本のビジネスマナーに従って回答してください。
回答には必ず適切な引用を含めてください。
""",
'en': """
You are a helpful and professional customer support representative.
Provide clear, concise answers with appropriate citations.
Maintain a friendly but professional tone.
""",
'ko': """
귀하는 정중하고 도움이 되는 고객 지원 담당자입니다.
한국의 비즈니스 에티켓에 따라 존댓말을 사용하여 답변해 주세요.
답변에는 항상 적절한 인용을 포함해 주세요.
"""
}
return prompts.get(language, prompts['en'])このMultilingualSupportSystemクラスでは、言語に応じた文化的なプロンプト設定とツール連携を実装しています。
開発・運用のベストプラクティス
エラーハンドリングとフォールバック戦略
class RobustSearchSystem:
"""堅牢な検索システムの実装"""
def __init__(self):
self.primary_search = PrimarySearchEngine()
self.fallback_search = FallbackSearchEngine()
self.cache = SearchCache()
def search_with_resilience(self, query, language='en'):
"""レジリエントな検索実行"""
# キャッシュチェック
cache_key = f"{query}:{language}"
cached_results = self.cache.get(cache_key)
if cached_results:
return cached_results
results = []
errors = []
try:
# プライマリ検索の試行
primary_results = self.primary_search.search(query, language)
results.extend(primary_results)
except Exception as e:
errors.append(f"Primary search error: {e}")
logger.warning(f"プライマリ検索失敗: {e}")
try:
# フォールバック検索の試行
if len(results) < 3:
fallback_results = self.fallback_search.search(query, language)
results.extend(fallback_results)
except Exception as e:
errors.append(f"Fallback search error: {e}")
logger.warning(f"フォールバック検索失敗: {e}")
# 結果が全くない場合のエラーハンドリング
if not results:
error_message = SearchResultBlockParam(
type="search_result",
source="system://error",
title="検索エラー",
content=[
TextBlockParam(
type="text",
text=f"申し訳ございませんが、検索中にエラーが発生しました。別のキーワードで検索をお試しいただくか、サポートチームまでお問い合わせください。エラー詳細: {'; '.join(errors)}"
)
],
citations={"enabled": False}
)
return [error_message]
# 成功した結果をキャッシュ
self.cache.set(cache_key, results, ttl=3600)
return resultsパフォーマンス監視と最適化
class SearchPerformanceMonitor:
"""検索パフォーマンスの監視"""
def __init__(self):
self.metrics_collector = MetricsCollector()
self.alert_system = AlertSystem()
def monitor_search_performance(self, func):
"""検索パフォーマンス監視デコレーター"""
def wrapper(*args, **kwargs):
start_time = time.time()
try:
result = func(*args, **kwargs)
# 成功メトリクス
execution_time = time.time() - start_time
self.metrics_collector.record_search_success(
execution_time=execution_time,
result_count=len(result) if result else 0
)
# パフォーマンス警告
if execution_time > 5.0: # 5秒以上
self.alert_system.send_performance_alert(
f"検索処理時間が{execution_time:.2f}秒と長時間です"
)
return result
except Exception as e:
execution_time = time.time() - start_time
self.metrics_collector.record_search_error(
execution_time=execution_time,
error_type=type(e).__name__
)
self.alert_system.send_error_alert(
f"検索エラー: {str(e)}"
)
raise
return wrapperセキュリティと信頼性の確保
class SecureSearchSystem:
"""セキュアな検索システム"""
def __init__(self):
self.access_controller = AccessController()
self.content_filter = ContentFilter()
def secure_search(self, query, user_id, language='en'):
"""セキュアな検索実行"""
# アクセス権限チェック
if not self.access_controller.check_search_permission(user_id):
raise PermissionError("検索権限がありません")
# クエリサニタイズ
sanitized_query = self.sanitize_query(query)
# 検索実行
raw_results = self.execute_search(sanitized_query, language)
# コンテンツフィルタリング
filtered_results = []
for result in raw_results:
# 機密情報チェック
if not self.content_filter.contains_sensitive_info(result.content):
# ユーザーアクセス権限チェック
if self.access_controller.can_access_document(user_id, result.source):
filtered_results.append(result)
return filtered_results
def sanitize_query(self, query):
"""クエリのサニタイズ"""
# SQLインジェクション防止
sanitized = re.sub(r'[;\'"\\]', '', query)
# 長すぎるクエリの制限
if len(sanitized) > 500:
sanitized = sanitized[:500]
return sanitized.strip()このSecureSearchSystemクラスでは、アクセス制御とクエリサニタイズによりセキュアな検索機能を実装しています。
Embeddings統合
Embeddings概要
Claude APIでは、独自のEmbedding モデルを提供していませんが、Voyage AIなど高品質なEmbeddingsプロバイダーとの統合が推奨されています。 Embeddingsは、テキストの数値表現を作成し、セマンティック類似性の測定を可能にします。
Voyage AI統合
検索システムでのEmbeddings活用には、Voyage AIが推奨されています。
推奨モデル
| モデル | コンテキスト長 | 次元数 | 説明 |
|---|---|---|---|
voyage-3-large |
32,000 | 1024 | 最高品質の汎用・多言語検索 |
voyage-3.5 |
32,000 | 1024 | 汎用・多言語検索に最適化 |
voyage-3.5-lite |
32,000 | 1024 | 低レイテンシ・低コスト |
voyage-code-3 |
32,000 | 1024 | コード検索に最適化 |
voyage-finance-2 |
32,000 | 1024 | 金融分野に最適化 |
voyage-law-2 |
16,000 | 1024 | 法律・長文コンテキストに最適化 |
Embeddings検索の実装例
import voyageai
import numpy as np
def semantic_search_with_citations(query, documents, language='en'):
"""Embeddings による意味検索と Citations API の統合"""
# Voyage AI クライアント
vo = voyageai.Client()
# ドキュメントのEmbedding
doc_embeddings = vo.embed(
documents,
model="voyage-3.5",
input_type="document"
).embeddings
# クエリのEmbedding
query_embedding = vo.embed(
[query],
model="voyage-3.5",
input_type="query"
).embeddings[0]
# 類似度計算(正規化済みのため、ドット積で計算)
similarities = np.dot(doc_embeddings, query_embedding)
# 上位結果を取得
top_indices = np.argsort(similarities)[-3:][::-1]
# SearchResultBlockParam 形式に変換
search_results = []
for i, idx in enumerate(top_indices):
search_results.append(SearchResultBlockParam(
type="search_result",
source=f"https://docs.company.com/doc-{idx}",
title=f"ドキュメント {idx + 1}",
content=[
TextBlockParam(
type="text",
text=documents[idx]
)
],
citations={"enabled": True}
))
return search_resultsこのコードでは、Voyage AIを使用してドキュメントとクエリをEmbeddingに変換し、コサイン類似度で関連文書を特定しています。
input_type="document"とinput_type="query"により、検索に特化したEmbeddingが生成されます。
結果は Citations API と互換性のある SearchResultBlockParam 形式で返却されます。
実際の検索実行では、Voyage AI のEmbeddings により高精度な意味的検索が実現され、Claude の Citations API により正確な引用付きの回答が生成されます。 この組み合わせにより、従来のキーワードベース検索では困難だった、意味的関連性に基づく高品質なRAGシステムが構築できます。
機能制限と注意事項
Search Results機能の制限
対応プラットフォーム
- 検索結果コンテンツブロックはClaude API、Amazon Bedrock、Google Cloud Vertex AIで利用可能
- 検索結果内ではテキストコンテンツのみサポート(画像や他のメディアは非対応)
content配列には最低1つのテキストブロックが必要
Citation制御の制約
- Citations は all-or-nothing 方式です。リクエスト内のすべての検索結果で引用を有効または無効にする必要があります
- 異なる引用設定の検索結果を混在させるとエラーが発生
- 一部のソースで引用を無効化したい場合、そのリクエスト内のすべての検索結果で引用を無効化する必要がある
Citations API の制限
対応ドキュメント形式
- PDFおよび平文テキストのみサポート
- ファイル保存は不要(Messages API と直接統合)
- ドキュメントサイズ制限はAPIの一般的なトークン制限に準拠
対応モデル
- Haiku 3を除くすべてのアクティブモデルで引用をサポート
- 対応プラットフォームはAnthropic API、Google Cloud Vertex AI、Amazon Bedrockです
機能の非互換性
CitationsとStructured Outputs(構造化出力)は同時に使用できません。
ユーザー提供のドキュメント(ドキュメントブロックまたはRequestSearchResultBlock)で引用を有効にし、output_formatパラメータも含めると、APIは400エラーを返します。
これは、引用がテキスト出力に引用ブロックをインターリーブする必要があり、構造化出力の厳格なJSONスキーマ制約と互換性がないためです。
多言語サポートの考慮事項
性能変動
- 言語によって性能が変動(英語比で78-98%の範囲)
- 低リソース言語(ヨルバ語等)では性能が大幅に低下する可能性
- デジタルリソースの少ない言語では、文脈によって理解度に差が生じる
推奨事項
- 重要なユースケースでは、対象言語での十分なテストを実施
- 業界特有の専門用語については、言語ごとの用語集を準備
- 文化的コンテキストの違いを考慮したローカライゼーションを実施
ベストプラクティス
パフォーマンス最適化
- 検索結果数を適切に制限(通常3-5件)
- キャッシュコントロールを活用してレスポンス時間を短縮
- バックグラウンド処理での事前Embedding計算を検討
エラーハンドリング
- 検索失敗時の適切なフォールバック戦略を実装
- タイムアウトやAPI制限への対応を準備
- ユーザーフレンドリーなエラーメッセージを提供
これらの実践的統合パターンと制限事項の理解により、エンタープライズレベルでの検索・引用・多言語対応システムを安全かつ効率的に構築できます。 堅牢なエラーハンドリング、パフォーマンス監視、セキュリティ対策を組み合わせることで、プロダクション環境での安定運用が可能になります。