搜尋結果內容區塊目前處於測試階段。使用 search-results-2025-06-09 測試標頭 來啟用此功能。

搜尋結果內容區塊能夠實現具有適當來源歸屬的自然引用,為您的自訂應用程式帶來網路搜尋品質的引用。此功能對於需要 Claude 準確引用來源的 RAG(檢索增強生成)應用程式特別強大。

主要優勢

  • 自然引用 - 為任何內容實現與網路搜尋相同的引用品質
  • 靈活整合 - 在工具回傳中用於動態 RAG,或作為預取資料的頂層內容
  • 適當的來源歸屬 - 每個結果都包含來源和標題資訊,以便清楚歸屬
  • 無需文件變通方法 - 消除對基於文件的變通方法的需求
  • 一致的引用格式 - 符合 Claude 網路搜尋功能的引用品質和格式

運作方式

搜尋結果可以透過兩種方式提供:

  1. 來自工具呼叫 - 您的自訂工具回傳搜尋結果,啟用動態 RAG 應用程式
  2. 作為頂層內容 - 您直接在使用者訊息中提供搜尋結果,用於預取或快取的內容

在這兩種情況下,Claude 都可以自動引用搜尋結果中的資訊,並提供適當的來源歸屬。

搜尋結果架構

搜尋結果使用以下結構:

{
  "type": "search_result",
  "source": "https://example.com/article",  // 必需:來源 URL 或識別符
  "title": "文章標題",                  // 必需:結果的標題
  "content": [ // 必需:文字區塊陣列
    {
      "type": "text",
      "text": "搜尋結果的實際內容..."
    }
  ],
  "citations": {                             // 可選:引用配置
    "enabled": true                          // 啟用/停用此結果的引用
  }
}

必需欄位

欄位類型描述
typestring必須是 "search_result"
sourcestring內容的來源 URL 或識別符
titlestring搜尋結果的描述性標題
contentarray包含實際內容的文字區塊陣列

可選欄位

欄位類型描述
citationsobject引用配置,包含 enabled 布林欄位
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()

# 定義知識庫搜尋工具
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 [
        BetaSearchResultBlockParam(
            type="search_result",
            source="https://docs.company.com/product-guide",
            title="產品配置指南",
            content=[
                BetaTextBlockParam(
                    type="text",
                    text="要配置產品,請導航至設定 > 配置。預設超時時間為 30 秒,但可以根據您的需求在 10-120 秒之間調整。"
                )
            ],
            citations={"enabled": True}
        ),
        BetaSearchResultBlockParam(
            type="search_result",
            source="https://docs.company.com/troubleshooting",
            title="故障排除指南",
            content=[
                BetaTextBlockParam(
                    type="text",
                    text="如果您遇到超時錯誤,請首先檢查配置設定。常見原因包括網路延遲和不正確的超時值。"
                )
            ],
            citations={"enabled": True}
        )
    ]

# 使用工具建立訊息
response = client.beta.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1024,
    betas=["search-results-2025-06-09"],
    tools=[knowledge_base_tool],
    messages=[
        BetaMessageParam(
            role="user",
            content="如何配置超時設定?"
        )
    ]
)

# 當 Claude 呼叫工具時,提供搜尋結果
if response.content[0].type == "tool_use":
    tool_result = search_knowledge_base(response.content[0].input["query"])
    
    # 將工具結果發送回去
    final_response = client.beta.messages.create(
        model="claude-opus-4-20250514",
        max_tokens=1024,
        betas=["search-results-2025-06-09"],
        messages=[
            BetaMessageParam(role="user", content="如何配置超時設定?"),
            BetaMessageParam(role="assistant", content=response.content),
            BetaMessageParam(
                role="user",
                content=[
                    BetaToolResultBlockParam(
                        type="tool_result",
                        tool_use_id=response.content[0].id,
                        content=tool_result  # 搜尋結果放在這裡
                    )
                ]
            )
        ]
    )

方法 2:搜尋結果作為頂層內容

您也可以直接在使用者訊息中提供搜尋結果。這對以下情況很有用:

  • 來自您搜尋基礎設施的預取內容
  • 來自先前查詢的快取搜尋結果
  • 來自外部搜尋服務的內容
  • 測試和開發

範例:直接搜尋結果

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

client = Anthropic()

# 直接在使用者訊息中提供搜尋結果
response = client.beta.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1024,
    betas=["search-results-2025-06-09"],
    messages=[
        BetaMessageParam(
            role="user",
            content=[
                BetaSearchResultBlockParam(
                    type="search_result",
                    source="https://docs.company.com/api-reference",
                    title="API 參考 - 身份驗證",
                    content=[
                        BetaTextBlockParam(
                            type="text",
                            text="所有 API 請求都必須在 Authorization 標頭中包含 API 金鑰。金鑰可以從儀表板生成。速率限制:標準層每小時 1000 個請求,高級層每小時 10000 個。"
                        )
                    ],
                    citations={"enabled": True}
                ),
                BetaSearchResultBlockParam(
                    type="search_result",
                    source="https://docs.company.com/quickstart",
                    title="入門指南",
                    content=[
                        BetaTextBlockParam(
                            type="text",
                            text="開始使用:1) 註冊帳戶,2) 從儀表板生成 API 金鑰,3) 使用 pip install company-sdk 安裝我們的 SDK,4) 使用您的 API 金鑰初始化客戶端。"
                        )
                    ],
                    citations={"enabled": True}
                ),
                BetaTextBlockParam(
                    type="text",
                    text="根據這些搜尋結果,我如何驗證 API 請求以及速率限制是什麼?"
                )
            ]
        )
    ]
)

print(response.model_dump_json(indent=2))

Claude 的引用回應

無論搜尋結果如何提供,Claude 在使用其中的資訊時都會自動包含引用:

{
  "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": "text",
      "text": "。速率限制為標準層每小時 1,000 個請求,高級層每小時 10,000 個請求。",
      "citations": [
        {
          "type": "search_result_location",
          "source": "https://docs.company.com/api-reference",
          "title": "API 參考 - 身份驗證",
          "cited_text": "速率限制:標準層每小時 1000 個請求,高級層每小時 10000 個",
          "search_result_index": 0,
          "start_block_index": 0,
          "end_block_index": 0
        }
      ]
    }
  ]
}

引用欄位

每個引用包含:

欄位類型描述
typestring搜尋結果引用始終為 "search_result_location"
sourcestring來自原始搜尋結果的來源
titlestring 或 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 文件",
  "content": [
    {
      "type": "text",
      "text": "身份驗證:所有 API 請求都需要 API 金鑰。"
    },
    {
      "type": "text",
      "text": "速率限制:API 允許每個金鑰每小時 1000 個請求。"
    },
    {
      "type": "text",
      "text": "錯誤處理:API 回傳標準 HTTP 狀態碼。"
    }
  ]
}

Claude 可以使用 start_block_indexend_block_index 欄位引用特定區塊。

進階用法

結合兩種方法

您可以在同一對話中同時使用基於工具和頂層的搜尋結果:

# 第一個訊息包含頂層搜尋結果
messages = [
    BetaMessageParam(
        role="user",
        content=[
            BetaSearchResultBlockParam(
                type="search_result",
                source="https://docs.company.com/overview",
                title="產品概述",
                content=[
                    BetaTextBlockParam(type="text", text="我們的產品幫助團隊協作...")
                ],
                citations={"enabled": True}
            ),
            BetaTextBlockParam(
                type="text",
                text="告訴我這個產品並搜尋定價資訊"
            )
        ]
    )
]

# Claude 可能會回應並呼叫工具來搜尋定價
# 然後您提供包含更多搜尋結果的工具結果

與其他內容類型結合

兩種方法都支援將搜尋結果與其他內容混合:

# 在工具結果中
tool_result = [
    BetaSearchResultBlockParam(
        type="search_result",
        source="https://docs.company.com/guide",
        title="使用者指南",
        content=[BetaTextBlockParam(type="text", text="配置詳細資訊...")],
        citations={"enabled": True}
    ),
    BetaTextBlockParam(
        type="text",
        text="額外背景:這適用於 2.0 版及更高版本。"
    )
]

# 在頂層內容中
user_content = [
    BetaSearchResultBlockParam(
        type="search_result",
        source="https://research.com/paper",
        title="研究論文",
        content=[BetaTextBlockParam(type="text", text="主要發現...")],
        citations={"enabled": True}
    ),
    {
        "type": "image",
        "source": {"type": "url", "url": "https://example.com/chart.png"}
    },
    BetaTextBlockParam(
        type="text",
        text="圖表如何與研究發現相關?"
    )
]

快取控制

新增快取控制以獲得更好的效能:

{
  "type": "search_result",
  "source": "https://docs.company.com/guide",
  "title": "使用者指南",
  "content": [{"type": "text", "text": "..."}],
  "cache_control": {
    "type": "ephemeral"
  }
}

引用控制

預設情況下,搜尋結果的引用是停用的。您可以透過明確設定 citations 配置來啟用引用:

{
  "type": "search_result",
  "source": "https://docs.company.com/guide",
  "title": "使用者指南",
  "content": [{"type": "text", "text": "重要文件..."}],
  "citations": {
    "enabled": true  // 為此結果啟用引用
  }
}

citations.enabled 設定為 true 時,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": "找不到結果。"}
            return format_as_search_results(results)
        except Exception as e:
            return {"type": "text", "text": f"搜尋錯誤:{str(e)}"}
    

限制

  • 搜尋結果內容區塊僅在使用測試標頭時可用
  • 搜尋結果中僅支援文字內容(不支援圖片或其他媒體)
  • content 陣列必須包含至少一個文字區塊