Блоки содержимого результатов поиска обеспечивают естественное цитирование с надлежащим указанием источников, привнося цитирования качества веб-поиска в ваши пользовательские приложения. Эта функция особенно мощна для приложений RAG (Retrieval-Augmented Generation), где вам нужно, чтобы Claude точно указывал источники.
Функция результатов поиска доступна на следующих моделях:
claude-opus-4-5-20251101)claude-opus-4-1-20250805)claude-opus-4-20250514)claude-sonnet-4-5-20250929)claude-sonnet-4-20250514)claude-3-7-sonnet-20250219)claude-haiku-4-5-20251001)claude-3-5-haiku-20241022)Результаты поиска можно предоставить двумя способами:
В обоих случаях 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 // Включить/отключить цитирования для этого результата
}
}| Поле | Тип | Описание |
|---|---|---|
type | string | Должно быть "search_result" |
source | string | URL источника или идентификатор содержимого |
title | string | Описательное название для результата поиска |
content | array | Массив текстовых блоков, содержащих фактическое содержимое |
| Поле | Тип | Описание |
|---|---|---|
citations | object | Конфигурация цитирования с логическим полем enabled |
cache_control | object | Параметры управления кэшем (например, {"type": "ephemeral"}) |
Каждый элемент в массиве content должен быть текстовым блоком с:
type: Должно быть "text"text: Фактическое текстовое содержимое (непустая строка)Наиболее мощный вариант использования - возврат результатов поиска из ваших пользовательских инструментов. Это обеспечивает динамические приложения RAG, где инструменты извлекают и возвращают релевантное содержимое с автоматическими цитированиями.
from anthropic import Anthropic
from anthropic.types import (
MessageParam,
TextBlockParam,
SearchResultBlockParam,
ToolResultBlockParam
)
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 [
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}
)
]
# Create a message with the tool
response = client.messages.create(
model="claude-sonnet-4-5", # Works with all supported models
max_tokens=1024,
tools=[knowledge_base_tool],
messages=[
MessageParam(
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.messages.create(
model="claude-sonnet-4-5", # Works with all supported models
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 # Search results go here
)
]
)
]
)Вы также можете предоставить результаты поиска непосредственно в сообщениях пользователя. Это полезно для:
from anthropic import Anthropic
from anthropic.types import (
MessageParam,
TextBlockParam,
SearchResultBlockParam
)
client = Anthropic()
# Provide search results directly in the user message
response = client.messages.create(
model="claude-sonnet-4-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.model_dump_json(indent=2))Независимо от того, как предоставляются результаты поиска, 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
}
]
}
]
}Каждое цитирование включает:
| Поле | Тип | Описание |
|---|---|---|
type | string | Всегда "search_result_location" для цитирований результатов поиска |
source | string | Источник из исходного результата поиска |
title | string или null | Название из исходного результата поиска |
cited_text | string | Точный цитируемый текст |
search_result_index | integer | Индекс результата поиска (начиная с 0) |
start_block_index | integer | Начальная позиция в массиве содержимого |
end_block_index | integer | Конечная позиция в массиве содержимого |
Примечание: 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.
Вы можете использовать результаты поиска на основе инструментов и содержимое верхнего уровня в одном разговоре:
# First message with top-level search results
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 might respond and call a tool to search for pricing
# Then you provide tool results with more search resultsОба метода поддерживают смешивание результатов поиска с другим содержимым:
# In tool results
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."
)
]
# In top-level content
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 // Enable citations for this result
}
}Когда citations.enabled установлено на true, Claude будет включать ссылки на цитирования при использовании информации из результата поиска. Это обеспечивает:
Если поле citations опущено, цитирования отключены по умолчанию.
Цитирования - это все или ничего: либо все результаты поиска в запросе должны иметь включенные цитирования, либо все должны иметь их отключенными. Смешивание результатов поиска с разными параметрами цитирования приведет к ошибке. Если вам нужно отключить цитирования для некоторых источников, вы должны отключить их для всех результатов поиска в этом запросе.
Эффективно структурируйте результаты
Поддерживайте согласованность
Обрабатывайте ошибки корректно
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 должен содержать по крайней мере один текстовый блок