検索結果コンテンツブロックは現在ベータ版です。この機能を有効にするには、search-results-2025-01-01 ベータヘッダーを使用してください。

検索結果コンテンツブロックは、適切なソース帰属による自然な引用を可能にし、カスタムアプリケーションにウェブ検索品質の引用をもたらします。この機能は、Claudeが正確にソースを引用する必要があるRAG(Retrieval-Augmented Generation)アプリケーションに特に強力です。

主な利点

  • 自然な引用 - あらゆるコンテンツに対してウェブ検索と同じ引用品質を実現
  • 柔軟な統合 - 動的RAGのツール戻り値として、または事前取得データのトップレベルコンテンツとして使用
  • 適切なソース帰属 - 各結果には明確な帰属のためのソースとタイトル情報が含まれる
  • ドキュメントの回避策は不要 - ドキュメントベースの回避策の必要性を排除
  • 一貫した引用形式 - Claudeのウェブ検索機能の引用品質と形式に一致

仕組み

検索結果は2つの方法で提供できます:

  1. ツール呼び出しから - カスタムツールが検索結果を返し、動的RAGアプリケーションを可能にする
  2. トップレベルコンテンツとして - 事前取得またはキャッシュされたコンテンツのユーザーメッセージに検索結果を直接提供

どちらの場合も、Claudeは検索結果からの情報を適切なソース帰属で自動的に引用できます。

検索結果のスキーマ

検索結果は次の構造を使用します:

{
  "type": "search_result",
  "source": "https://example.com/article",  // Required: Source URL or identifier
  "title": "Article Title",                  // Required: Title of the result
  "content": [                               // Required: Array of text blocks
    {
      "type": "text",
      "text": "The actual content of the search result..."
    }
  ],
  "citations": {                             // Optional: Citation configuration
    "enabled": true                          // Enable/disable citations for this result
  }
}

必須フィールド

フィールドタイプ説明
typestring"search_result"でなければならない
sourcestringコンテンツのソースURLまたは識別子
titlestring検索結果の記述的なタイトル
contentarray実際のコンテンツを含むテキストブロックの配列

オプションフィールド

フィールドタイプ説明
citationsobjectenabledブールフィールドを持つ引用設定
cache_controlobjectキャッシュ制御設定(例:{"type": "ephemeral"}

content配列の各項目は次のテキストブロックでなければなりません:

  • type: "text"でなければならない
  • text: 実際のテキストコンテンツ(空でない文字列)

方法1:ツール呼び出しからの検索結果

最も強力な使用例は、カスタムツールから検索結果を返すことです。これにより、ツールが関連コンテンツを取得して自動引用付きで返す動的RAGアプリケーションが可能になります。

例:ナレッジベースツール

from anthropic import Anthropic
from anthropic.types.beta import (
    BetaMessageParam,
    BetaTextBlockParam,
    BetaSearchResultBlockParam,
    BetaToolResultBlockParam
)

client = Anthropic()

# Define a knowledge base search tool
knowledge_base_tool = {
    "name": "search_knowledge_base",
    "description": "Search the company knowledge base for information",
    "input_schema": {
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": "The search query"
            }
        },
        "required": ["query"]
    }
}

# Function to handle the tool call
def search_knowledge_base(query):
    # Your search logic here
    # Returns search results in the correct format
    return [
        BetaSearchResultBlockParam(
            type="search_result",
            source="https://docs.company.com/product-guide",
            title="Product Configuration Guide",
            content=[
                BetaTextBlockParam(
                    type="text",
                    text="To configure the product, navigate to Settings > Configuration. The default timeout is 30 seconds, but can be adjusted between 10-120 seconds based on your needs."
                )
            ],
            citations={"enabled": True}
        ),
        BetaSearchResultBlockParam(
            type="search_result",
            source="https://docs.company.com/troubleshooting",
            title="Troubleshooting Guide",
            content=[
                BetaTextBlockParam(
                    type="text",
                    text="If you encounter timeout errors, first check the configuration settings. Common causes include network latency and incorrect timeout values."
                )
            ],
            citations={"enabled": True}
        )
    ]

# Create a message with the tool
response = client.beta.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1024,
    betas=["search-results-2025-01-01"],
    tools=[knowledge_base_tool],
    messages=[
        BetaMessageParam(
            role="user",
            content="How do I configure the timeout settings?"
        )
    ]
)

# When Claude calls the tool, provide the search results
if response.content[0].type == "tool_use":
    tool_result = search_knowledge_base(response.content[0].input["query"])
    
    # Send the tool result back
    final_response = client.beta.messages.create(
        model="claude-opus-4-20250514",
        max_tokens=1024,
        betas=["search-results-2025-01-01"],
        messages=[
            BetaMessageParam(role="user", content="How do I configure the timeout settings?"),
            BetaMessageParam(role="assistant", content=response.content),
            BetaMessageParam(
                role="user",
                content=[
                    BetaToolResultBlockParam(
                        type="tool_result",
                        tool_use_id=response.content[0].id,
                        content=tool_result  # Search results go here
                    )
                ]
            )
        ]
    )

方法2:トップレベルコンテンツとしての検索結果

ユーザーメッセージに検索結果を直接提供することもできます。これは次の場合に便利です:

  • 検索インフラストラクチャからの事前取得コンテンツ
  • 以前のクエリからのキャッシュされた検索結果
  • 外部検索サービスからのコンテンツ
  • テストと開発

例:直接検索結果

from anthropic import Anthropic
from anthropic.types.beta import (
    BetaMessageParam,
    BetaTextBlockParam,
    BetaSearchResultBlockParam
)

client = Anthropic()

# Provide search results directly in the user message
response = client.beta.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1024,
    betas=["search-results-2025-01-01"],
    messages=[
        BetaMessageParam(
            role="user",
            content=[
                BetaSearchResultBlockParam(
                    type="search_result",
                    source="https://docs.company.com/api-reference",
                    title="API Reference - Authentication",
                    content=[
                        BetaTextBlockParam(
                            type="text",
                            text="All API requests must include an API key in the Authorization header. Keys can be generated from the dashboard. Rate limits: 1000 requests per hour for standard tier, 10000 for premium."
                        )
                    ],
                    citations={"enabled": True}
                ),
                BetaSearchResultBlockParam(
                    type="search_result",
                    source="https://docs.company.com/quickstart",
                    title="Getting Started Guide",
                    content=[
                        BetaTextBlockParam(
                            type="text",
                            text="To get started: 1) Sign up for an account, 2) Generate an API key from the dashboard, 3) Install our SDK using pip install company-sdk, 4) Initialize the client with your API key."
                        )
                    ],
                    citations={"enabled": True}
                ),
                BetaTextBlockParam(
                    type="text",
                    text="Based on these search results, how do I authenticate API requests and what are the rate limits?"
                )
            ]
        )
    ]
)

print(response.model_dump_json(indent=2))

引用付きのClaudeの応答

検索結果の提供方法に関係なく、Claudeは情報を使用する際に自動的に引用を含めます:

{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "To authenticate API requests, you need to include an API key in the Authorization header",
      "citations": [
        {
          "type": "search_result_location",
          "source": "https://docs.company.com/api-reference",
          "title": "API Reference - Authentication",
          "cited_text": "All API requests must include an API key in the Authorization header",
          "search_result_index": 0,
          "start_block_index": 0,
          "end_block_index": 0
        }
      ]
    },
    {
      "type": "text",
      "text": ". You can generate API keys from your dashboard",
      "citations": [
        {
          "type": "search_result_location",
          "source": "https://docs.company.com/api-reference",
          "title": "API Reference - Authentication",
          "cited_text": "Keys can be generated from the dashboard",
          "search_result_index": 0,
          "start_block_index": 0,
          "end_block_index": 0
        }
      ]
    },
    {
      "type": "text",
      "text": ". The rate limits are 1,000 requests per hour for the standard tier and 10,000 requests per hour for the premium tier.",
      "citations": [
        {
          "type": "search_result_location",
          "source": "https://docs.company.com/api-reference",
          "title": "API Reference - Authentication",
          "cited_text": "Rate limits: 1000 requests per hour for standard tier, 10000 for premium",
          "search_result_index": 0,
          "start_block_index": 0,
          "end_block_index": 0
        }
      ]
    }
  ]
}

引用フィールド

各引用には以下が含まれます:

フィールドタイプ説明
typestring検索結果の引用の場合は常に"search_result_location"
sourcestring元の検索結果からのソース
titlestring or null元の検索結果からのタイトル
cited_textstring引用されている正確なテキスト
search_result_indexinteger検索結果のインデックス(0ベース)
start_block_indexintegerコンテンツ配列の開始位置
end_block_indexintegerコンテンツ配列の終了位置

注:search_result_indexは、検索結果の提供方法(ツール呼び出しまたはトップレベルコンテンツ)に関係なく、検索結果コンテンツブロックのインデックス(0ベース)を指します。

複数のコンテンツブロック

検索結果はcontent配列に複数のテキストブロックを含めることができます:

{
  "type": "search_result",
  "source": "https://docs.company.com/api-guide",
  "title": "API Documentation",
  "content": [
    {
      "type": "text",
      "text": "Authentication: All API requests require an API key."
    },
    {
      "type": "text",
      "text": "Rate Limits: The API allows 1000 requests per hour per key."
    },
    {
      "type": "text",
      "text": "Error Handling: The API returns standard HTTP status codes."
    }
  ]
}

Claudeはstart_block_indexend_block_indexフィールドを使用して特定のブロックを引用できます。

高度な使用法

両方の方法の組み合わせ

同じ会話でツールベースとトップレベルの両方の検索結果を使用できます:

# First message with top-level search results
messages = [
    BetaMessageParam(
        role="user",
        content=[
            BetaSearchResultBlockParam(
                type="search_result",
                source="https://docs.company.com/overview",
                title="Product Overview",
                content=[
                    BetaTextBlockParam(type="text", text="Our product helps teams collaborate...")
                ],
                citations={"enabled": True}
            ),
            BetaTextBlockParam(
                type="text",
                text="Tell me about this product and search for pricing information"
            )
        ]
    )
]

# Claude might respond and call a tool to search for pricing
# Then you provide tool results with more search results

他のコンテンツタイプとの組み合わせ

両方の方法は検索結果を他のコンテンツと混在させることをサポートします:

# In tool results
tool_result = [
    BetaSearchResultBlockParam(
        type="search_result",
        source="https://docs.company.com/guide",
        title="User Guide",
        content=[BetaTextBlockParam(type="text", text="Configuration details...")],
        citations={"enabled": True}
    ),
    BetaTextBlockParam(
        type="text",
        text="Additional context: This applies to version 2.0 and later."
    )
]

# In top-level content
user_content = [
    BetaSearchResultBlockParam(
        type="search_result",
        source="https://research.com/paper",
        title="Research Paper",
        content=[BetaTextBlockParam(type="text", text="Key findings...")],
        citations={"enabled": True}
    ),
    {
        "type": "image",
        "source": {"type": "url", "url": "https://example.com/chart.png"}
    },
    BetaTextBlockParam(
        type="text",
        text="How does the chart relate to the research findings?"
    )
]

キャッシュ制御

より良いパフォーマンスのためにキャッシュ制御を追加:

{
  "type": "search_result",
  "source": "https://docs.company.com/guide",
  "title": "User Guide",
  "content": [{"type": "text", "text": "..."}],
  "cache_control": {
    "type": "ephemeral"
  }
}

引用制御

デフォルトでは、検索結果の引用は無効になっています。citations設定を明示的に設定することで引用を有効にできます:

{
  "type": "search_result",
  "source": "https://docs.company.com/guide",
  "title": "User Guide",
  "content": [{"type": "text", "text": "Important documentation..."}],
  "citations": {
    "enabled": true  // Enable citations for this result
  }
}

citations.enabledtrueに設定されている場合、Claudeは検索結果からの情報を使用する際に引用参照を含めます。これにより以下が可能になります:

  • カスタムRAGアプリケーションの自然な引用
  • 独自のナレッジベースとのインターフェース時のソース帰属
  • 検索結果を返すカスタムツールのウェブ検索品質の引用

citationsフィールドが省略された場合、引用はデフォルトで無効になります。

引用はオールオアナッシングです:リクエスト内のすべての検索結果で引用が有効になっているか、すべてで無効になっている必要があります。異なる引用設定の検索結果を混在させるとエラーになります。一部のソースで引用を無効にする必要がある場合は、そのリクエスト内のすべての検索結果で無効にする必要があります。

ベストプラクティス

ツールベース検索(方法1)の場合

  • 動的コンテンツ:リアルタイム検索と動的RAGアプリケーションに使用
  • エラー処理:検索が失敗した場合に適切なメッセージを返す
  • 結果制限:コンテキストオーバーフローを避けるため、最も関連性の高い結果のみを返す

トップレベル検索(方法2)の場合

  • 事前取得コンテンツ:すでに検索結果がある場合に使用
  • バッチ処理:複数の検索結果を一度に処理するのに最適
  • テスト:既知のコンテンツで引用動作をテストするのに最適

一般的なベストプラクティス

  1. 効果的に結果を構造化する

    • 明確で永続的なソースURLを使用
    • 説明的なタイトルを提供
    • 長いコンテンツを論理的なテキストブロックに分割
  2. 一貫性を維持する

    • アプリケーション全体で一貫したソース形式を使用
    • タイトルがコンテンツを正確に反映していることを確認
    • 書式を一貫して保つ
  3. エラーを優雅に処理する

    def search_with_fallback(query):
        try:
            results = perform_search(query)
            if not results:
                return {"type": "text", "text": "No results found."}
            return format_as_search_results(results)
        except Exception as e:
            return {"type": "text", "text": f"Search error: {str(e)}"}
    

制限事項

  • 検索結果コンテンツブロックはベータヘッダーでのみ利用可能
  • 検索結果内ではテキストコンテンツのみがサポートされる(画像やその他のメディアは不可)
  • content配列には少なくとも1つのテキストブロックが含まれている必要がある