Эта функция соответствует требованиям Zero Data Retention (ZDR) (нулевого хранения данных). Если у вашей организации действует соглашение ZDR, данные, отправленные через эту функцию, не сохраняются после возврата ответа API.
Блоки контента с результатами поиска обеспечивают естественное цитирование с корректным указанием источника, привнося качество цитирования уровня веб-поиска в ваши собственные приложения. Эта функция особенно полезна для приложений «Retrieval-Augmented Generation» (генерация с дополнением извлечёнными данными), или RAG, где требуется, чтобы Claude точно цитировал источники.
Функция результатов поиска доступна для следующих моделей:
claude-opus-4-7)claude-opus-4-6)claude-sonnet-4-6)claude-sonnet-4-5-20250929)claude-opus-4-5-20251101)claude-opus-4-1-20250805)claude-opus-4-20250514)claude-sonnet-4-20250514)claude-haiku-4-5-20251001)claude-3-5-haiku-20241022)Результаты поиска могут предоставляться двумя способами:
В обоих случаях 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
}
}| Поле | Тип | Описание |
|---|---|---|
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.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-8", # Works with all supported models
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-8", # 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.types import MessageParam, TextBlockParam, SearchResultBlockParam
client = Anthropic()
# Предоставьте результаты поиска непосредственно в сообщении пользователя
response = client.messages.create(
model="claude-opus-4-8",
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 автоматически включает цитаты при использовании информации из них:
{
"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], соединённому вместе. Не учитывается в выходных токенах. |
search_result_index | integer | Индекс (с нуля) процитированного результата поиска среди всех блоков search_result в запросе, в порядке их появления (по всем сообщениям и результатам инструментов). |
start_block_index | integer | Индекс (с нуля) первого процитированного блока в массиве content результата поиска. |
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."
}
]
}Цитата, ссылающаяся на блок об ограничениях скорости, выглядит так:
{
"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 более точные границы цитирования; объединение контента в один блок означает, что каждая цитата возвращает полный текст. Это та же модель, которая используется в документах с пользовательским контентом в функции цитирования.
Вы можете использовать как результаты поиска на основе инструментов, так и результаты верхнего уровня в одном разговоре:
from anthropic.types import MessageParam, SearchResultBlockParam, TextBlockParam
# Первое сообщение с результатами поиска верхнего уровня
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 может ответить и вызвать инструмент для поиска цен
# Затем вы предоставляете результаты инструмента с дополнительными результатами поискаОба способа поддерживают смешивание результатов поиска с другим контентом:
from anthropic.types import SearchResultBlockParam, TextBlockParam
# В результатах инструментов
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 // Enable citations for this result
}
}Когда citations.enabled установлено в true, Claude включает ссылки на цитаты при использовании информации из результата поиска. Это обеспечивает:
Цитирование работает по принципу «всё или ничего»: либо у всех результатов поиска в запросе цитирование должно быть включено, либо у всех отключено. Смешивание результатов поиска с разными настройками цитирования приводит к ошибке.
Эффективно структурируйте результаты:
Поддерживайте согласованность:
Корректно обрабатывайте ошибки:
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 должен содержать как минимум один текстовый блокWas this page helpful?