This feature is eligible for Zero Data Retention (ZDR). When your organization has a ZDR arrangement, data sent through this feature is not stored after the API response is returned.
Os blocos de conteúdo de resultados de busca permitem citações naturais com atribuição adequada de fonte, trazendo citações de qualidade de busca na web para suas aplicações personalizadas. Este recurso é particularmente poderoso para aplicações RAG (Retrieval-Augmented Generation) onde você precisa que Claude cite fontes com precisão.
O recurso de resultados de busca está disponível nos seguintes modelos:
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-3-7-sonnet-20250219)claude-haiku-4-5-20251001)claude-3-5-haiku-20241022)Os resultados de busca podem ser fornecidos de duas maneiras:
Em ambos os casos, Claude pode citar automaticamente informações dos resultados de busca com atribuição adequada de fonte.
Os resultados de busca usam a seguinte estrutura:
{
"type": "search_result",
"source": "https://example.com/article", // Obrigatório: URL de fonte ou identificador
"title": "Article Title", // Obrigatório: Título do resultado
"content": [
// Obrigatório: Array de blocos de texto
{
"type": "text",
"text": "The actual content of the search result..."
}
],
"citations": {
// Opcional: Configuração de citação
"enabled": true // Ativar/desativar citações para este resultado
}
}| Campo | Tipo | Descrição |
|---|---|---|
type | string | Deve ser "search_result" |
source | string | A URL de fonte ou identificador para o conteúdo |
title | string | Um título descritivo para o resultado de busca |
content | array | Um array de blocos de texto contendo o conteúdo real |
| Campo | Tipo | Descrição |
|---|---|---|
citations | object | Configuração de citação com campo booleano enabled |
cache_control | object | Configurações de controle de cache (por exemplo, {"type": "ephemeral"}) |
Cada item no array content deve ser um bloco de texto com:
type: Deve ser "text"text: O conteúdo de texto real (string não vazia)O caso de uso mais poderoso é retornar resultados de busca de suas ferramentas personalizadas. Isso permite aplicações RAG dinâmicas onde ferramentas buscam e retornam conteúdo relevante com citações automáticas.
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-opus-4-7", # 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-opus-4-7", # 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
)
],
),
],
)Você também pode fornecer resultados de busca diretamente em mensagens de usuário. Isso é útil para:
from anthropic.types import MessageParam, TextBlockParam, SearchResultBlockParam
client = Anthropic()
# Provide search results directly in the user message
response = client.messages.create(
model="claude-opus-4-7",
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))Independentemente de como os resultados de busca são fornecidos, Claude inclui automaticamente citações ao usar informações deles:
{
"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
}
]
}
]
}Cada citação inclui:
| Campo | Tipo | Descrição |
|---|---|---|
type | string | Sempre "search_result_location" para citações de resultados de busca |
source | string | A fonte do resultado de busca original |
title | string ou null | O título do resultado de busca original |
cited_text | string | O texto exato sendo citado |
search_result_index | integer | Índice do resultado de busca (baseado em 0) |
start_block_index | integer | Posição inicial no array de conteúdo |
end_block_index | integer | Posição final no array de conteúdo |
Nota: O search_result_index refere-se ao índice do bloco de conteúdo do resultado de busca (baseado em 0), independentemente de como os resultados de busca foram fornecidos (chamada de ferramenta ou conteúdo de nível superior).
Os resultados de busca podem conter múltiplos blocos de texto no array 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 pode citar blocos específicos usando os campos start_block_index e end_block_index.
Você pode usar resultados de busca baseados em ferramentas e de nível superior na mesma conversa:
from anthropic.types import MessageParam, SearchResultBlockParam, TextBlockParam
# 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 resultsAmbos os métodos suportam misturar resultados de busca com outro conteúdo:
from anthropic.types import SearchResultBlockParam, TextBlockParam
# 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?"
),
]Adicione controle de cache para melhor desempenho:
{
"type": "search_result",
"source": "https://docs.company.com/guide",
"title": "User Guide",
"content": [{ "type": "text", "text": "..." }],
"cache_control": {
"type": "ephemeral"
}
}Por padrão, as citações são desabilitadas para resultados de busca. Você pode habilitar citações definindo explicitamente a configuração 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
}
}Quando citations.enabled é definido como true, Claude inclui referências de citação ao usar informações do resultado de busca. Isso habilita:
Se o campo citations for omitido, as citações serão desabilitadas por padrão.
As citações são tudo ou nada: ou todos os resultados de busca em uma solicitação devem ter citações habilitadas, ou todos devem tê-las desabilitadas. Misturar resultados de busca com diferentes configurações de citação resulta em um erro. Se você precisar desabilitar citações para algumas fontes, você deve desabilitá-las para todos os resultados de busca nessa solicitação.
Estruture os resultados efetivamente
Mantenha consistência
Trate erros com elegância
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 deve conter pelo menos um bloco de textoWas this page helpful?