Claude Platform Docs
Messages模型功能

搜尋結果

透過提供附帶來源歸屬的搜尋結果,為 RAG 應用程式啟用自然的引用功能

搜尋結果內容區塊讓 Claude 能夠以引用網頁搜尋結果的相同方式引用您自己的內容:每個引用都帶有您所提供的來源與標題。請在「Retrieval-Augmented Generation」(檢索增強生成),即 RAG 應用程式中使用它們,讓 Claude 能將答案歸屬於您的文件。

所有現行模型皆支援附帶引用的搜尋結果,Claude Haiku 3 除外。不需要 beta 標頭:搜尋結果是標準 Messages API 的一部分。

運作方式

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

  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,或內部識別碼,例如 kb://article-1234
titlestring搜尋結果的描述性標題
contentarray包含實際內容的文字區塊陣列

選用欄位

欄位類型說明
citationsobject引用設定,包含 enabled 布林欄位。引用預設為停用;本頁的每個範例都明確設定 "enabled": true。同一請求中的所有搜尋結果必須使用相同的設定(請參閱引用控制
cache_controlobject快取控制設定(例如 {"type": "ephemeral"}

content 陣列中的每個項目都必須是具備以下欄位的文字區塊:

  • type:必須為 "text"
  • text:實際的文字內容(非空字串)

搜尋結果僅能容納文字。content 陣列內不支援圖片及其他媒體。

方法 1:來自工具呼叫的搜尋結果

從您的自訂工具回傳搜尋結果可實現動態 RAG 應用程式:工具在執行階段擷取內容,Claude 則在回應中引用它。以下範例使用 tool_choice 強制進行工具呼叫,因此檢索步驟每次都會執行。

範例:知識庫工具

from anthropic.types import (
    MessageParam,
    TextBlockParam,
    SearchResultBlockParam,
    ToolResultBlockParam,
)

client = Anthropic()

# 定義知識庫搜尋工具
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"],
    },
}


# 處理工具呼叫的函式
def search_knowledge_base(query):
    # 在此放入您的搜尋邏輯
    # 以正確格式回傳搜尋結果
    return [
        SearchResultBlockParam(
            type="search_result",
            source="https://docs.company.com/product-guide",
            title="Product Configuration Guide",
            content=[
                TextBlockParam(
                    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},
        ),
        SearchResultBlockParam(
            type="search_result",
            source="https://docs.company.com/troubleshooting",
            title="Troubleshooting Guide",
            content=[
                TextBlockParam(
                    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},
        ),
    ]


# 以清單建立對話,從使用者的問題開始
messages = [
    MessageParam(role="user", content="How do I configure the timeout settings?")
]

# 建立帶有工具的訊息
response = client.messages.create(
    model="claude-opus-5",
    max_tokens=1024,
    tools=[knowledge_base_tool],
    tool_choice={"type": "tool", "name": "search_knowledge_base"},
    messages=messages,
)

# 當 Claude 呼叫工具時,提供搜尋結果。
# tool_use 區塊不一定在最前面:請逐一尋找。
tool_use = next((block for block in response.content if block.type == "tool_use"), None)
if tool_use is not None:
    tool_result = search_knowledge_base(tool_use.input["query"])

    # 將 Claude 的回合與工具結果依序附加到進行中的對話
    messages.append(MessageParam(role="assistant", content=response.content))
    messages.append(
        MessageParam(
            role="user",
            content=[
                ToolResultBlockParam(
                    type="tool_result",
                    tool_use_id=tool_use.id,
                    content=tool_result,  # Search results go here
                )
            ],
        )
    )

    # 將工具結果傳回
    final_response = client.messages.create(
        model="claude-opus-5",
        max_tokens=1024,
        messages=messages,
    )
    print(final_response)

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

您也可以直接在使用者訊息中提供搜尋結果。這適用於:

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

範例:直接提供搜尋結果

from anthropic.types import MessageParam, TextBlockParam, SearchResultBlockParam

client = Anthropic()

# 直接在使用者訊息中提供搜尋結果
response = client.messages.create(
    model="claude-opus-5",
    max_tokens=1024,
    messages=[
        MessageParam(
            role="user",
            content=[
                SearchResultBlockParam(
                    type="search_result",
                    source="https://docs.company.com/api-reference",
                    title="API Reference - Authentication",
                    content=[
                        TextBlockParam(
                            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},
                ),
                SearchResultBlockParam(
                    type="search_result",
                    source="https://docs.company.com/quickstart",
                    title="Getting Started Guide",
                    content=[
                        TextBlockParam(
                            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},
                ),
                TextBlockParam(
                    type="text",
                    text="Based on these search results, how do I authenticate API requests and what are the rate limits?",
                ),
            ],
        )
    ],
)

print(response)

Claude 附帶引用的回應

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

{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "All API requests must include an API key in the Authorization header. Keys can be generated from the dashboard.",
      "citations": [
        {
          "type": "search_result_location",
          "cited_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.",
          "source": "https://docs.company.com/api-reference",
          "title": "API Reference - Authentication",
          "search_result_index": 0,
          "start_block_index": 0,
          "end_block_index": 1
        }
      ]
    },
    {
      "type": "text",
      "text": "\n\nTo set this up from scratch, you'll need to "
    },
    {
      "type": "text",
      "text": "sign up for an account, generate an API key from the dashboard, install the SDK using `pip install company-sdk`, and initialize the client with your API key.",
      "citations": [
        {
          "type": "search_result_location",
          "cited_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.",
          "source": "https://docs.company.com/quickstart",
          "title": "Getting Started Guide",
          "search_result_index": 1,
          "start_block_index": 0,
          "end_block_index": 1
        }
      ]
    }
  ]
}

引用欄位

每個引用包含:

欄位類型說明
typestring對於搜尋結果引用,一律為 "search_result_location"
sourcestring來自原始搜尋結果的來源
titlestring 或 null來自原始搜尋結果的標題
cited_textstring被引用區塊的完整文字,串接而成。等同於 content[start_block_index:end_block_index] 的內容連接在一起。不計入輸出 token。
search_result_indexinteger被引用的搜尋結果在請求中所有 search_result 區塊之間的索引(從 0 起算),依其出現順序排列(跨所有訊息與工具結果)。
start_block_indexinteger搜尋結果 content 陣列中第一個被引用區塊的索引(從 0 起算)。
end_block_indexinteger搜尋結果 content 陣列中被引用區塊範圍的結束索引(不含)。一律大於 start_block_index

區塊索引標識出搜尋結果 content 陣列的一個切片,而 cited_text 即為該切片的完整文字。文字區塊是最小的可引用單位:Claude 引用的是整個區塊,而非區塊內的子字串。若要取得更細緻的引用,請將您的搜尋結果內容拆分為較小的區塊(請參閱多個內容區塊)。

多個內容區塊

搜尋結果可以在 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."
    }
  ],
  "citations": { "enabled": true }
}

參照速率限制區塊的引用如下所示:

{
  "type": "search_result_location",
  "cited_text": "Rate Limits: The API allows 1000 requests per hour per key.",
  "source": "https://docs.company.com/api-guide",
  "title": "API Documentation",
  "search_result_index": 0,
  "start_block_index": 1,
  "end_block_index": 2
}

當此搜尋結果被引用時,start_block_indexend_block_index 會標識出引用涵蓋了其中哪些區塊,而 cited_text 則精確包含這些區塊的文字。將內容拆分為較小、聚焦的區塊可讓 Claude 擁有更細緻的引用邊界;將內容合併為單一區塊則意味著每個引用都會回傳完整文字。這與引用功能中自訂內容文件所使用的模型相同。

進階用法

結合兩種方法

您可以在同一對話中混合使用兩種方法。Claude 會引用任一來源,而 search_result_index 會依請求順序計算所有 search_result 區塊,不論其來源為何。

以下範例重現了一段完整的對話。第一則使用者訊息帶有一個預先擷取的搜尋結果,助理回合呼叫了知識庫工具,而工具結果回傳了第二個搜尋結果。Claude 的回答同時引用了兩個來源:

from anthropic.types import (
    MessageParam,
    SearchResultBlockParam,
    TextBlockParam,
    ToolResultBlockParam,
    ToolUseBlockParam,
)

client = Anthropic()

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"],
    },
}

# 重播一段以兩種方式提供搜尋結果的對話:第一則
# 使用者訊息帶有預先擷取的結果,工具結果則回傳另一個
response = client.messages.create(
    model="claude-opus-5",
    max_tokens=1024,
    tools=[knowledge_base_tool],
    messages=[
        MessageParam(
            role="user",
            content=[
                SearchResultBlockParam(
                    type="search_result",
                    source="https://docs.company.com/overview",
                    title="Product Overview",
                    content=[
                        TextBlockParam(
                            type="text",
                            text="Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards.",
                        )
                    ],
                    citations={"enabled": True},
                ),
                TextBlockParam(
                    type="text",
                    text="What does Acme Dashboard do, and what plans is it available on?",
                ),
            ],
        ),
        MessageParam(
            role="assistant",
            content=[
                TextBlockParam(
                    type="text", text="Let me check the pricing information."
                ),
                ToolUseBlockParam(
                    type="tool_use",
                    id="toolu_01A09q90qw90lq917835lq9",
                    name="search_knowledge_base",
                    input={"query": "Acme Dashboard pricing plans"},
                ),
            ],
        ),
        MessageParam(
            role="user",
            content=[
                ToolResultBlockParam(
                    type="tool_result",
                    tool_use_id="toolu_01A09q90qw90lq917835lq9",
                    content=[
                        SearchResultBlockParam(
                            type="search_result",
                            source="https://docs.company.com/pricing",
                            title="Pricing Plans",
                            content=[
                                TextBlockParam(
                                    type="text",
                                    text="Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing.",
                                )
                            ],
                            citations={"enabled": True},
                        )
                    ],
                )
            ],
        ),
    ],
)

print(response)

回應同時引用了兩個來源。預先擷取的結果為 search_result_index: 0,工具回傳的結果為 search_result_index: 1,與 search_result 區塊在對話中出現的順序一致:

{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Here's what I found about Acme Dashboard:\n\n**What it does:** "
    },
    {
      "type": "text",
      "text": "Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards.",
      "citations": [
        {
          "type": "search_result_location",
          "cited_text": "Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards.",
          "source": "https://docs.company.com/overview",
          "title": "Product Overview",
          "search_result_index": 0,
          "start_block_index": 0,
          "end_block_index": 1
        }
      ]
    },
    {
      "type": "text",
      "text": "\n\n**Available plans:** "
    },
    {
      "type": "text",
      "text": "Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing.",
      "citations": [
        {
          "type": "search_result_location",
          "cited_text": "Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing.",
          "source": "https://docs.company.com/pricing",
          "title": "Pricing Plans",
          "search_result_index": 1,
          "start_block_index": 0,
          "end_block_index": 1
        }
      ]
    }
  ]
}

與其他內容類型混合

在使用者訊息中,search_result 區塊可以與任何其他內容區塊並列。方法 2 的範例將搜尋結果與一個 text 問題搭配,圖片或文件區塊也可以用相同方式加入。

工具結果則較為嚴格:如果 tool_result 內容陣列中有任何區塊是 search_result,則其所有區塊都必須是 search_result。在同一工具結果中將搜尋結果與其他區塊類型混合會回傳驗證錯誤。若要在工具來源的搜尋結果旁回傳輔助文字,請將其作為文字區塊放入其中一個搜尋結果的 content 陣列內,如此它也會變得可引用。

快取控制

在搜尋結果區塊上加入 cache_control,即可將其快取以便跨請求重複使用。它與 citations 並列於同一區塊上:

{
  "type": "search_result",
  "source": "https://docs.company.com/guide",
  "title": "User Guide",
  "content": [{ "type": "text", "text": "..." }],
  "citations": { "enabled": true },
  "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.enabled 設為 true 時,Claude 會將引用參照附加到取材自該搜尋結果的文字區塊上。

最佳實務

針對基於工具的搜尋(方法 1)

  • 動態內容: 用於即時搜尋與動態 RAG 應用程式
  • 錯誤處理: 在搜尋失敗時回傳適當的訊息
  • 結果限制: 僅回傳最相關的結果,以避免上下文溢位

針對頂層搜尋(方法 2)

  • 預先擷取的內容: 在您已擁有搜尋結果時使用
  • 批次處理: 非常適合一次處理多個搜尋結果
  • 測試: 非常適合以已知內容測試引用行為

一般最佳實務

  1. 有效地組織結果:

    • 使用清晰、永久的來源 URL
    • 提供描述性標題
    • 將長內容拆分為邏輯性的文字區塊,讓 Claude 擁有更細緻的引用邊界
  2. 維持一致性:

    • 在您的應用程式中使用一致的來源格式
    • 確保標題準確反映內容
    • 保持格式一致
  3. 妥善處理錯誤: 當搜尋失敗或沒有回傳任何結果時,請回傳描述結果的純文字區塊(例如 {"type": "text", "text": "No results found."}),而非拋出錯誤:Claude 會向使用者說明空結果,對話得以繼續。

限制

  • 搜尋結果內容區塊可在 Claude API、Amazon Bedrock 及 Google Cloud 上使用。
  • 搜尋結果內僅支援文字內容(不支援圖片或其他媒體)。
  • search_result 區塊只能出現在使用者訊息中(包括工具結果內部)。帶有搜尋結果的助理訊息會被拒絕。
  • 當同一請求中啟用了網頁搜尋工具時,所有 search_result 區塊都必須啟用引用。

後續步驟

在串流回應中偵測並處理拒絕停止原因,並在備援模型上重試被拒絕的請求。

讓 Claude 的回應以您的來源文件為依據。引用會回傳支持每項主張的確切段落,讓您能夠驗證答案並向使用者呈現來源。

讓 Claude 存取附帶引用來源的最新網頁內容,並提供選用的動態篩選與網域控制。

查看完整的 Messages API 文件,包括內容區塊類型。

使用 cache_control 快取搜尋結果,以降低重複請求的成本與延遲。

Was this page helpful?