Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    入門
    Claude 簡介快速開始
    模型與定價
    模型概覽選擇模型Claude 4.6 新功能遷移指南模型棄用定價
    使用 Claude 構建
    功能概覽使用 Messages API處理停止原因提示詞最佳實踐
    上下文管理
    上下文視窗壓縮上下文編輯
    功能
    提示詞快取延伸思考自適應思考思考力度串流訊息批次處理引用多語言支援Token 計數嵌入視覺PDF 支援Files API搜尋結果結構化輸出
    工具
    概覽如何實作工具使用細粒度工具串流Bash 工具程式碼執行工具程式化工具呼叫電腦使用工具文字編輯器工具網頁擷取工具網頁搜尋工具記憶工具工具搜尋工具
    Agent Skills
    概覽快速開始最佳實踐企業級 Skills透過 API 使用 Skills
    Agent SDK
    概覽快速開始TypeScript SDKTypeScript V2(預覽版)Python SDK遷移指南
    API 中的 MCP
    MCP 連接器遠端 MCP 伺服器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示詞工程
    概覽提示詞產生器使用提示詞範本提示詞改進器清晰直接使用範例(多範例提示)讓 Claude 思考(CoT)使用 XML 標籤賦予 Claude 角色(系統提示詞)串聯複雜提示詞長上下文技巧延伸思考技巧
    測試與評估
    定義成功標準開發測試案例使用評估工具降低延遲
    強化防護機制
    減少幻覺提高輸出一致性防範越獄攻擊串流拒絕減少提示詞洩漏讓 Claude 保持角色
    管理與監控
    Admin API 概覽資料駐留工作區用量與成本 APIClaude Code Analytics API零資料保留
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    功能

    搜尋結果

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

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

    搜尋結果功能可在以下模型上使用:

    • Claude Opus 4.6 (claude-opus-4-6)
    • Claude Sonnet 4.5 (claude-sonnet-4-5-20250929)
    • 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 (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)

    主要優勢

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

    運作方式

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

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

    在這兩種情況下,Claude 都能自動從搜尋結果中引用資訊,並附帶適當的來源歸屬。

    搜尋結果結構

    搜尋結果使用以下結構:

    {
      "type": "search_result",
      "source": "https://example.com/article",  // 必填:來源 URL 或識別碼
      "title": "Article Title",                  // 必填:結果的標題
      "content": [                               // 必填:文字區塊陣列
        {
          "type": "text",
          "text": "The actual content of the search result..."
        }
      ],
      "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 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}
            )
        ]
    
    # 使用工具建立訊息
    response = client.messages.create(
        model="claude-opus-4-6",  # 適用於所有支援的模型
        max_tokens=1024,
        tools=[knowledge_base_tool],
        messages=[
            MessageParam(
                role="user",
                content="How do I configure the timeout settings?"
            )
        ]
    )
    
    # 當 Claude 呼叫工具時,提供搜尋結果
    if response.content[0].type == "tool_use":
        tool_result = search_knowledge_base(response.content[0].input["query"])
        
        # 將工具結果送回
        final_response = client.messages.create(
            model="claude-opus-4-6",  # 適用於所有支援的模型
            max_tokens=1024,
            messages=[
                MessageParam(role="user", content="How do I configure the timeout settings?"),
                MessageParam(role="assistant", content=response.content),
                MessageParam(
                    role="user",
                    content=[
                        ToolResultBlockParam(
                            type="tool_result",
                            tool_use_id=response.content[0].id,
                            content=tool_result  # 搜尋結果放在這裡
                        )
                    ]
                )
            ]
        )

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

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

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

    範例:直接搜尋結果

    from anthropic import Anthropic
    from anthropic.types import (
        MessageParam,
        TextBlockParam,
        SearchResultBlockParam
    )
    
    client = Anthropic()
    
    # 直接在使用者訊息中提供搜尋結果
    response = client.messages.create(
        model="claude-opus-4-6",
        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.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 或 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_index 和 end_block_index 欄位來引用特定區塊。

    進階用法

    結合兩種方法

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

    # 第一則訊息包含頂層搜尋結果
    messages = [
        MessageParam(
            role="user",
            content=[
                SearchResultBlockParam(
                    type="search_result",
                    source="https://docs.company.com/overview",
                    title="Product Overview",
                    content=[
                        TextBlockParam(type="text", text="Our product helps teams collaborate...")
                    ],
                    citations={"enabled": True}
                ),
                TextBlockParam(
                    type="text",
                    text="Tell me about this product and search for pricing information"
                )
            ]
        )
    ]
    
    # Claude 可能會回應並呼叫工具來搜尋定價資訊
    # 然後您提供包含更多搜尋結果的工具結果

    與其他內容類型結合

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

    # 在工具結果中
    tool_result = [
        SearchResultBlockParam(
            type="search_result",
            source="https://docs.company.com/guide",
            title="User Guide",
            content=[TextBlockParam(type="text", text="Configuration details...")],
            citations={"enabled": True}
        ),
        TextBlockParam(
            type="text",
            text="Additional context: This applies to version 2.0 and later."
        )
    ]
    
    # 在頂層內容中
    user_content = [
        SearchResultBlockParam(
            type="search_result",
            source="https://research.com/paper",
            title="Research Paper",
            content=[TextBlockParam(type="text", text="Key findings...")],
            citations={"enabled": True}
        ),
        {
            "type": "image",
            "source": {"type": "url", "url": "https://example.com/chart.png"}
        },
        TextBlockParam(
            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  // 啟用此結果的引用
      }
    }

    當 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": "No results found."}
              return format_as_search_results(results)
          except Exception as e:
              return {"type": "text", "text": f"Search error: {str(e)}"}

    限制

    • 搜尋結果內容區塊可在 Claude API、Amazon Bedrock 和 Google Cloud 的 Vertex AI 上使用
    • 搜尋結果中僅支援文字內容(不支援圖片或其他媒體)
    • content 陣列必須包含至少一個文字區塊

    Was this page helpful?

    • 方法 1:從工具呼叫取得搜尋結果
    • 方法 2:搜尋結果作為頂層內容
    • Claude 的引用回應
    • 基於工具的搜尋(方法 1)
    • 頂層搜尋(方法 2)