搜尋結果
透過提供具有來源歸屬的搜尋結果,為 RAG 應用程式取得自然的引用
用法因產品而異
search_result 區塊。user.custom_tool_result 事件),不接受於 user.message 事件中。搜尋結果內容區塊讓 Claude 能以引用網路搜尋結果的相同方式引用您自己的內容:每個引用都會帶有您提供的來源和標題。請在 Claude 需要將答案歸屬於您的文件的「Retrieval-Augmented Generation」(檢索增強生成),即 RAG 應用程式中使用它們。
運作方式
搜尋結果可以透過兩種方式提供:
- 來自工具呼叫: 您的自訂工具回傳搜尋結果,讓您能夠建構動態 RAG 應用程式。
- 作為頂層內容: 您直接在使用者訊息中提供搜尋結果,適用於預先擷取或快取的內容。
在這兩種情況下,啟用引用時 Claude 都會自動引用搜尋結果。不需要特殊的提示:只需提出您的問題,引用就會出現在使用您內容的文字區塊上。不過,如果您的提示只要求 JSON,回應可能只包含少量引用或完全沒有引用。若要擷取每個值都附有引用的結構化資料,請參閱取得附帶引用的結構化資料。
搜尋結果結構描述
搜尋結果使用以下結構:
{
"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
}
}必要欄位
| 欄位 | 類型 | 說明 |
|---|---|---|
type | string | 必須是 "search_result" |
source | string | 內容的來源。任何穩定的字串都可以:URL,或是內部識別碼,例如 kb://article-1234 |
title | string | 搜尋結果的描述性標題 |
content | array | 包含實際內容的文字區塊陣列 |
選用欄位
| 欄位 | 類型 | 說明 |
|---|---|---|
citations | object | 具有 enabled 布林欄位的引用設定。引用預設為停用;本頁的每個範例都明確設定了 "enabled": true。請求中的所有搜尋結果必須使用相同的設定(請參閱引用控制) |
cache_control | object | 快取控制設定(例如 {"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: list[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",
"disable_parallel_tool_use": True,
},
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({"role": "assistant", "content": response.content})
messages.append(
{
"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 TextBlockParam, SearchResultBlockParam
client = Anthropic()
# 直接在使用者訊息中提供搜尋結果
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[
{
"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
}
]
}
]
}引用欄位
每個引用包含:
| 欄位 | 類型 | 說明 |
|---|---|---|
type | string | 對於搜尋結果引用,一律為 "search_result_location" |
source | string | 來自原始搜尋結果的來源 |
title | string 或 null | 來自原始搜尋結果的標題 |
cited_text | string | 被引用區塊的完整文字,串接在一起。等於 content[start_block_index:end_block_index] 的內容合併後的結果。不計入輸出 token。 |
search_result_index | integer | 被引用的搜尋結果在請求中所有 search_result 區塊之間的索引(從 0 開始),依其出現順序排列(跨所有訊息和工具結果)。 |
start_block_index | integer | 第一個被引用區塊在搜尋結果 content 陣列中的索引(從 0 開始)。 |
end_block_index | integer | 被引用區塊範圍在搜尋結果 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_index 和 end_block_index 會標識該引用涵蓋哪些區塊,而 cited_text 恰好包含這些區塊的文字。將內容拆分為較小、聚焦的區塊可讓 Claude 有更細緻的引用邊界;將內容合併為一個區塊則表示每個引用都會回傳完整文字。這與引用功能中的自訂內容文件所使用的模型相同。
進階用法
結合兩種方法
您可以在同一個對話中混合使用兩種方法。Claude 會從任一來源進行引用,而 search_result_index 會依請求順序計算所有 search_result 區塊,無論其來源為何。
以下範例重現一個完整的對話。第一則使用者訊息帶有預先擷取的搜尋結果,助理回合呼叫知識庫工具,而工具結果回傳第二個搜尋結果。Claude 的答案引用了兩個來源:
from anthropic.types import (
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-5",
max_tokens=1024,
tools=[knowledge_base_tool],
messages=[
{
"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?",
),
],
},
{
"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"},
),
],
},
{
"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)
- 預先擷取的內容: 在您已經擁有搜尋結果時使用
- 批次處理: 用於一次處理多個搜尋結果
- 測試: 用於以已知內容測試引用行為
一般最佳實踐
-
有效地組織結果:
- 使用清晰、永久的來源 URL
- 提供描述性標題
- 將長內容拆分為合乎邏輯的文字區塊,讓 Claude 有更細緻的引用邊界
-
保持一致性:
- 在您的應用程式中使用一致的來源格式
- 確保標題準確反映內容
- 保持格式一致
-
妥善處理錯誤: 當搜尋失敗或沒有回傳任何結果時,請回傳描述結果的純文字區塊(例如
{"type": "text", "text": "No results found."}),而不是引發錯誤:Claude 會向使用者說明空白結果,對話也會繼續進行。
限制
- 搜尋結果中僅支援文字內容(不支援圖片或其他媒體)。
search_result區塊只能出現在使用者訊息中(包括工具結果內)。包含搜尋結果的助理訊息會被拒絕。- 當在同一個請求中啟用網路搜尋工具時,所有
search_result區塊都必須啟用引用。
後續步驟
在串流回應中偵測並處理拒絕的停止原因,並在備援模型上重試被拒絕的請求。
讓 Claude 的回應以您的來源文件為依據。引用會回傳支持每項陳述的確切段落,讓您可以驗證答案並向使用者呈現來源。
讓 Claude 存取最新的網路內容,並提供引用來源、選用的動態篩選和網域控制。
查看完整的 Messages API 文件,包括內容區塊類型。
使用 cache_control 快取搜尋結果,以降低重複請求的成本和延遲。
可用性
Claude API
- API
- Messages API
- Managed Agents
- 模型
- 所有模型
Claude Platform on AWS
- API
- Messages API
- Managed Agents
- 模型
- 所有模型
Amazon Bedrock
- API
- Messages API
- 模型
- 所有模型
Amazon Bedrock (InvokeModel)
- API
- Messages API
- 模型
- 所有模型
Claude Models on Google Cloud (Google managed)
- API
- Messages API
- 模型
- 所有模型
Microsoft Foundry
- API
- Messages API
- 模型
- 所有模型
資料處理
資料處理概覽適用端點
/v1/messages搭配search_results來源
不含 涵蓋的模型
這個頁面有幫助嗎?