SPB Git

Repository Public

search-results.md 81.9 KB 2,174 lines markdown

1---2title: Search results3url: https://platform.claude.com/docs/en/build-with-claude/search-results4description: Enable natural citations for RAG applications by providing search results with source attribution5---67<Note>8  To learn how zero data retention (ZDR) applies to this feature, see [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention).9</Note>1011Search result content blocks let Claude cite your own content the same way it cites web search results: each citation carries the source and title you provided. Use them in RAG (Retrieval-Augmented Generation) applications where Claude needs to attribute answers to your documents.1213All [active models](https://platform.claude.com/docs/en/models/overview) support search results with citations, with the exception of Claude Haiku 3. No beta header is required: search results are part of the standard Messages API.1415## How it works1617Search results can be provided in two ways:18191. **From tool calls:** Your custom tools return search results, enabling dynamic RAG applications202. **As top-level content:** You provide search results directly in user messages for pre-fetched or cached content2122In both cases, Claude cites the search results automatically when citations are enabled. No special prompting is needed: ask your question, and citations appear on the text blocks that draw on your content.2324### Search result schema2526Search results use the following structure:2728```json29{30  "type": "search_result",31  "source": "https://example.com/article", // Required: Source URL or identifier32  "title": "Article Title", // Required: Title of the result33  "content": [34    // Required: Array of text blocks35    {36      "type": "text",37      "text": "The actual content of the search result..."38    }39  ],40  "citations": {41    // Optional: Citation configuration42    "enabled": true // Enable/disable citations for this result43  }44}45```4647### Required fields4849| Field     | Type   | Description                                                                                                      |50| --------- | ------ | ---------------------------------------------------------------------------------------------------------------- |51| `type`    | string | Must be `"search_result"`                                                                                        |52| `source`  | string | The source of the content. Any stable string works: a URL, or an internal identifier such as `kb://article-1234` |53| `title`   | string | A descriptive title for the search result                                                                        |54| `content` | array  | An array of text blocks containing the actual content                                                            |5556### Optional fields5758| Field           | Type   | Description                                                                                                                                                                                                                                                                                                                     |59| --------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |60| `citations`     | object | Citation configuration with `enabled` Boolean field. Citations are disabled by default; every example on this page sets `"enabled": true` explicitly. All search results in a request must use the same setting (see [Citation control](https://platform.claude.com/docs/en/build-with-claude/search-results#citation-control)) |61| `cache_control` | object | Cache control settings (for example, `{"type": "ephemeral"}`)                                                                                                                                                                                                                                                                   |6263Each item in the `content` array must be a text block with:6465* `type`: Must be `"text"`66* `text`: The actual text content (non-empty string)6768Search results hold text only. Images and other media are not supported inside the `content` array.6970## Method 1: Search results from tool calls7172Returning search results from your custom tools enables dynamic RAG applications: tools fetch content at runtime, and Claude cites it in the response. The following example forces the tool call with [`tool_choice`](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools#forcing-tool-use), so the retrieval step runs every time.7374### Example: Knowledge base tool7576<CodeGroup>77  ```bash cURL78  # The tool-calling flow needs application-side search logic that doesn't79  # translate to a one-off shell command. See the SDK tabs for the full flow.80  # The raw shape of a tool conversation with search results is shown in the81  # Combining both methods cURL tab; Method 2 shows the top-level shape.82  ```8384  ```bash CLI85  # The tool-calling flow needs application-side search logic that doesn't86  # translate to a one-off shell command. See the SDK tabs for the full flow.87  # The raw shape of a tool conversation with search results is shown in the88  # Combining both methods cURL tab; Method 2 shows the top-level shape.89  ```9091  ```python Python92  from anthropic.types import (93      MessageParam,94      TextBlockParam,95      SearchResultBlockParam,96      ToolResultBlockParam,97  )9899  client = Anthropic()100101  # Define a knowledge base search tool102  knowledge_base_tool = {103      "name": "search_knowledge_base",104      "description": "Search the company knowledge base for information",105      "input_schema": {106          "type": "object",107          "properties": {"query": {"type": "string", "description": "The search query"}},108          "required": ["query"],109      },110  }111112113  # Function to handle the tool call114  def search_knowledge_base(query):115      # Your search logic here116      # Returns search results in the correct format117      return [118          SearchResultBlockParam(119              type="search_result",120              source="https://docs.company.com/product-guide",121              title="Product Configuration Guide",122              content=[123                  TextBlockParam(124                      type="text",125                      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.",126                  )127              ],128              citations={"enabled": True},129          ),130          SearchResultBlockParam(131              type="search_result",132              source="https://docs.company.com/troubleshooting",133              title="Troubleshooting Guide",134              content=[135                  TextBlockParam(136                      type="text",137                      text="If you encounter timeout errors, first check the configuration settings. Common causes include network latency and incorrect timeout values.",138                  )139              ],140              citations={"enabled": True},141          ),142      ]143144145  # Build up the conversation in a list, starting with the user's question146  messages = [147      MessageParam(role="user", content="How do I configure the timeout settings?")148  ]149150  # Create a message with the tool151  response = client.messages.create(152      model="claude-opus-5",153      max_tokens=1024,154      tools=[knowledge_base_tool],155      tool_choice={"type": "tool", "name": "search_knowledge_base"},156      messages=messages,157  )158159  # When Claude calls the tool, provide the search results.160  # The tool_use block is not always first: iterate to find it.161  tool_use = next((block for block in response.content if block.type == "tool_use"), None)162  if tool_use is not None:163      tool_result = search_knowledge_base(tool_use.input["query"])164165      # Append Claude's turn, then the tool result, to the running conversation166      messages.append(MessageParam(role="assistant", content=response.content))167      messages.append(168          MessageParam(169              role="user",170              content=[171                  ToolResultBlockParam(172                      type="tool_result",173                      tool_use_id=tool_use.id,174                      content=tool_result,  # Search results go here175                  )176              ],177          )178      )179180      # Send the tool result back181      final_response = client.messages.create(182          model="claude-opus-5",183          max_tokens=1024,184          messages=messages,185      )186      print(final_response)187  ```188189  ```typescript TypeScript190  const client = new Anthropic();191192  // Define a knowledge base search tool193  const knowledgeBaseTool: Anthropic.Tool = {194    name: "search_knowledge_base",195    description: "Search the company knowledge base for information",196    input_schema: {197      type: "object" as const,198      properties: {199        query: {200          type: "string",201          description: "The search query"202        }203      },204      required: ["query"]205    }206  };207208  // Function to handle the tool call209  function searchKnowledgeBase(query: string) {210    // Your search logic here211    // Returns search results in the correct format212    return [213      {214        type: "search_result" as const,215        source: "https://docs.company.com/product-guide",216        title: "Product Configuration Guide",217        content: [218          {219            type: "text" as const,220            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."221          }222        ],223        citations: { enabled: true }224      },225      {226        type: "search_result" as const,227        source: "https://docs.company.com/troubleshooting",228        title: "Troubleshooting Guide",229        content: [230          {231            type: "text" as const,232            text: "If you encounter timeout errors, first check the configuration settings. Common causes include network latency and incorrect timeout values."233          }234        ],235        citations: { enabled: true }236      }237    ];238  }239240  // Build up the conversation in a list, starting with the user's question241  const messages: Anthropic.MessageParam[] = [242    { role: "user", content: "How do I configure the timeout settings?" }243  ];244245  // Create a message with the tool246  const response = await client.messages.create({247    model: "claude-opus-5",248    max_tokens: 1024,249    tools: [knowledgeBaseTool],250    tool_choice: { type: "tool", name: "search_knowledge_base" },251    messages252  });253254  // Handle tool use and provide results.255  // The tool_use block is not always first: find it in the content array.256  const toolUse = response.content.find(257    (block): block is Anthropic.ToolUseBlock => block.type === "tool_use"258  );259  if (toolUse) {260    const input = toolUse.input as { query: string };261    const toolResult = searchKnowledgeBase(input.query);262263    // Append Claude's turn, then the tool result, to the running conversation264    messages.push({ role: "assistant", content: response.content });265    messages.push({266      role: "user",267      content: [268        {269          type: "tool_result" as const,270          tool_use_id: toolUse.id,271          content: toolResult // Search results go here272        }273      ]274    });275276    // Send the tool result back277    const finalResponse = await client.messages.create({278      model: "claude-opus-5",279      max_tokens: 1024,280      messages281    });282    console.log(finalResponse);283  }284  ```285286  ```csharp C#287  AnthropicClient client = new();288289  var tools = new List<ToolUnion>290  {291      new ToolUnion(new Tool()292      {293          Name = "search_knowledge_base",294          Description = "Search the company knowledge base for information",295          InputSchema = new InputSchema()296          {297              Properties = new Dictionary<string, JsonElement>298              {299                  ["query"] = JsonSerializer.SerializeToElement(new { type = "string", description = "The search query" }),300              },301              Required = ["query"],302          },303      }),304  };305306  // Function to handle the tool call307  static List<Block> SearchKnowledgeBase(string query)308  {309      // Your search logic here310      // Returns search results in the correct format311      return312      [313          new SearchResultBlockParam314          {315              Source = "https://docs.company.com/product-guide",316              Title = "Product Configuration Guide",317              Content = [new() { 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." }],318              Citations = new() { Enabled = true },319          },320          new SearchResultBlockParam321          {322              Source = "https://docs.company.com/troubleshooting",323              Title = "Troubleshooting Guide",324              Content = [new() { Text = "If you encounter timeout errors, first check the configuration settings. Common causes include network latency and incorrect timeout values." }],325              Citations = new() { Enabled = true },326          },327      ];328  }329330  // Build up the conversation in a list, starting with the user's question331  List<MessageParam> messages = [new() { Role = Role.User, Content = "How do I configure the timeout settings?" }];332333  // Create a message with the tool334  var response = await client.Messages.Create(new()335  {336      Model = Model.ClaudeOpus5,337      MaxTokens = 1024,338      Tools = tools,339      ToolChoice = new ToolChoiceTool { Name = "search_knowledge_base" },340      Messages = messages,341  });342343  // When Claude calls the tool, provide the search results.344  // The tool_use block is not always first: find the first one.345  foreach (var block in response.Content)346  {347      if (block.TryPickToolUse(out var toolUse))348      {349          var query = toolUse.Input["query"].GetString() ?? "";350          var toolResults = SearchKnowledgeBase(query);351352          // Append Claude's turn, then the tool result, to the running conversation353          messages.Add(new() { Role = Role.Assistant, Content = response.Content.Select(contentBlock => new ContentBlockParam(contentBlock.Json)).ToList() });354          messages.Add(new()355          {356              Role = Role.User,357              Content = new MessageParamContent(358                  [new ContentBlockParam(new ToolResultBlockParam() { ToolUseID = toolUse.ID, Content = new ToolResultBlockParamContent(toolResults) })]359              ),360          });361362          // Send the tool result back363          var finalResponse = await client.Messages.Create(new()364          {365              Model = Model.ClaudeOpus5,366              MaxTokens = 1024,367              Messages = messages,368          });369          Console.WriteLine(finalResponse);370          break;371      }372  }373  ```374375  ```go Go376  	client := anthropic.NewClient()377378  	knowledgeBaseTool := anthropic.ToolUnionParam{379  		OfTool: &anthropic.ToolParam{380  			Name:        "search_knowledge_base",381  			Description: anthropic.String("Search the company knowledge base for information"),382  			InputSchema: anthropic.ToolInputSchemaParam{383  				Properties: map[string]any{384  					"query": map[string]any{385  						"type":        "string",386  						"description": "The search query",387  					},388  				},389  				Required: []string{"query"},390  			},391  		},392  	}393394  	// Build up the conversation in a slice, starting with the user's question395  	messages := []anthropic.MessageParam{396  		anthropic.NewUserMessage(anthropic.NewTextBlock("How do I configure the timeout settings?")),397  	}398399  	response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{400  		Model:      anthropic.ModelClaudeOpus5,401  		MaxTokens:  1024,402  		Tools:      []anthropic.ToolUnionParam{knowledgeBaseTool},403  		ToolChoice: anthropic.ToolChoiceUnionParam{OfTool: &anthropic.ToolChoiceToolParam{Name: "search_knowledge_base"}},404  		Messages:   messages,405  	})406  	if err != nil {407  		log.Fatal(err)408  	}409410  	// The tool_use block is not always first: find it in the content list411  	var toolUse *anthropic.ToolUseBlock412  	for _, block := range response.Content {413  		if variant, ok := block.AsAny().(anthropic.ToolUseBlock); ok {414  			toolUse = &variant415  			break416  		}417  	}418419  	if toolUse != nil {420  		var input struct {421  			Query string `json:"query"`422  		}423  		if err := json.Unmarshal(toolUse.Input, &input); err != nil {424  			log.Fatal(err)425  		}426  		toolResults := searchKnowledgeBase(input.Query)427428  		// Append Claude's turn, then the tool result, to the running conversation429  		messages = append(messages, response.ToParam())430  		messages = append(messages, anthropic.NewUserMessage(anthropic.ContentBlockParamUnion{431  			OfToolResult: &anthropic.ToolResultBlockParam{432  				ToolUseID: toolUse.ID,433  				Content:   toolResults,434  			},435  		}))436437  		// Send the tool result back438  		finalResponse, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{439  			Model:     anthropic.ModelClaudeOpus5,440  			MaxTokens: 1024,441  			Messages:  messages,442  		})443  		if err != nil {444  			log.Fatal(err)445  		}446  		fmt.Println(finalResponse)447  	}448  // ...449  func searchKnowledgeBase(query string) []anthropic.ToolResultBlockParamContentUnion {450  	return []anthropic.ToolResultBlockParamContentUnion{451  		{OfSearchResult: &anthropic.SearchResultBlockParam{452  			Content: []anthropic.TextBlockParam{453  				{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."},454  			},455  			Source:    "https://docs.company.com/product-guide",456  			Title:     "Product Configuration Guide",457  			Citations: anthropic.CitationsConfigParam{Enabled: anthropic.Bool(true)},458  		}},459  		{OfSearchResult: &anthropic.SearchResultBlockParam{460  			Content: []anthropic.TextBlockParam{461  				{Text: "If you encounter timeout errors, first check the configuration settings. Common causes include network latency and incorrect timeout values."},462  			},463  			Source:    "https://docs.company.com/troubleshooting",464  			Title:     "Troubleshooting Guide",465  			Citations: anthropic.CitationsConfigParam{Enabled: anthropic.Bool(true)},466  		}},467  	}468  }469  ```470471  ```java Java472  import com.anthropic.models.messages.ContentBlockParam;473  import com.anthropic.models.messages.CitationsConfigParam;474  // ...475  import com.anthropic.models.messages.MessageParam;476  import com.anthropic.models.messages.Model;477  import com.anthropic.models.messages.SearchResultBlockParam;478  import com.anthropic.models.messages.TextBlockParam;479  import com.anthropic.models.messages.Tool;480  import com.anthropic.models.messages.ToolChoice;481  import com.anthropic.models.messages.ToolChoiceTool;482  import com.anthropic.models.messages.ToolResultBlockParam;483  import com.anthropic.core.JsonValue;484  // ...485486  void main() {487      AnthropicClient client = AnthropicOkHttpClient.fromEnv();488489      Tool knowledgeBaseTool = Tool.builder()490          .name("search_knowledge_base")491          .description("Search the company knowledge base for information")492          .inputSchema(Tool.InputSchema.builder()493              .properties(JsonValue.from(Map.of(494                  "query", Map.of(495                      "type", "string",496                      "description", "The search query"497                  )498              )))499              .putAdditionalProperty("required", JsonValue.from(List.of("query")))500              .build())501          .build();502503      // Build up the conversation in a list, starting with the user's question504      List<MessageParam> messages = new ArrayList<>();505      messages.add(MessageParam.builder()506          .role(MessageParam.Role.USER)507          .content("How do I configure the timeout settings?")508          .build());509510      MessageCreateParams params = MessageCreateParams.builder()511          .model(Model.CLAUDE_OPUS_5)512          .maxTokens(1024L)513          .addTool(knowledgeBaseTool)514          .toolChoice(ToolChoice.ofTool(ToolChoiceTool.builder()515              .name("search_knowledge_base")516              .build()))517          .messages(messages)518          .build();519520      Message response = client.messages().create(params);521522      // The tool_use block is not always first: find it in the content list523      response.content().stream()524          .flatMap(contentBlock -> contentBlock.toolUse().stream())525          .findFirst()526          .ifPresent(toolUse -> {527              Map<String, JsonValue> input =528                  (Map<String, JsonValue>) toolUse._input().asObject().get();529              List<ToolResultBlockParam.Content.Block> toolResult = searchKnowledgeBase(530                  input.get("query").asStringOrThrow()531              );532533              // Append Claude's entire turn to the running conversation, then the tool result.534              // Rebuilding only the tool_use block would drop any other content blocks Claude535              // returned (e.g. leading text when the tool call is not forced) — append the536              // full turn, as the other language tabs do.537              messages.add(MessageParam.builder()538                  .role(MessageParam.Role.ASSISTANT)539                  .contentOfBlockParams(540                      response.content().stream()541                          .map(block -> block.toParam())542                          .toList()543                  )544                  .build());545              messages.add(MessageParam.builder()546                  .role(MessageParam.Role.USER)547                  .contentOfBlockParams(List.of(548                      ContentBlockParam.ofToolResult(549                          ToolResultBlockParam.builder()550                              .toolUseId(toolUse.id())551                              .contentOfBlocks(toolResult)552                              .build()553                      )554                  ))555                  .build());556557              // Send the tool result back558              MessageCreateParams finalParams = MessageCreateParams.builder()559                  .model(Model.CLAUDE_OPUS_5)560                  .maxTokens(1024L)561                  .messages(messages)562                  .build();563564              Message finalResponse = client.messages().create(finalParams);565              System.out.println(finalResponse);566          });567  }568569  static List<ToolResultBlockParam.Content.Block> searchKnowledgeBase(String query) {570      return List.of(571          ToolResultBlockParam.Content.Block.ofSearchResult(572              SearchResultBlockParam.builder()573                  .source("https://docs.company.com/product-guide")574                  .title("Product Configuration Guide")575                  .content(List.of(576                      TextBlockParam.builder()577                          .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.")578                          .build()579                  ))580                  .citations(CitationsConfigParam.builder().enabled(true).build())581                  .build()582          ),583          ToolResultBlockParam.Content.Block.ofSearchResult(584              SearchResultBlockParam.builder()585                  .source("https://docs.company.com/troubleshooting")586                  .title("Troubleshooting Guide")587                  .content(List.of(588                      TextBlockParam.builder()589                          .text("If you encounter timeout errors, first check the configuration settings. Common causes include network latency and incorrect timeout values.")590                          .build()591                  ))592                  .citations(CitationsConfigParam.builder().enabled(true).build())593                  .build()594          )595      );596  }597  ```598599  ```php PHP600  $client = new Client();601602  $knowledgeBaseTool = [603      'name' => 'search_knowledge_base',604      'description' => 'Search the company knowledge base for information',605      'input_schema' => [606          'type' => 'object',607          'properties' => [608              'query' => [609                  'type' => 'string',610                  'description' => 'The search query'611              ]612          ],613          'required' => ['query']614      ]615  ];616617  function searchKnowledgeBase($query) {618      return [619          [620              'type' => 'search_result',621              'source' => 'https://docs.company.com/product-guide',622              'title' => 'Product Configuration Guide',623              'content' => [624                  [625                      'type' => 'text',626                      '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.'627                  ]628              ],629              'citations' => ['enabled' => true]630          ],631          [632              'type' => 'search_result',633              'source' => 'https://docs.company.com/troubleshooting',634              'title' => 'Troubleshooting Guide',635              'content' => [636                  [637                      'type' => 'text',638                      'text' => 'If you encounter timeout errors, first check the configuration settings. Common causes include network latency and incorrect timeout values.'639                  ]640              ],641              'citations' => ['enabled' => true]642          ]643      ];644  }645646  // Build up the conversation in a list, starting with the user's question647  $messages = [648      ['role' => 'user', 'content' => 'How do I configure the timeout settings?']649  ];650651  $response = $client->messages->create(652      maxTokens: 1024,653      messages: $messages,654      model: 'claude-opus-5',655      toolChoice: ['type' => 'tool', 'name' => 'search_knowledge_base'],656      tools: [$knowledgeBaseTool],657  );658659  $toolUseBlock = null;660  foreach ($response->content as $block) {661      if ($block->type === 'tool_use') {662          $toolUseBlock = $block;663          break;664      }665  }666667  if ($toolUseBlock !== null) {668      $toolResult = searchKnowledgeBase($toolUseBlock->input['query']);669670      // Append Claude's turn, then the tool result, to the running conversation671      $messages[] = ['role' => 'assistant', 'content' => $response->content];672      $messages[] = [673          'role' => 'user',674          'content' => [675              [676                  'type' => 'tool_result',677                  'tool_use_id' => $toolUseBlock->id,678                  'content' => $toolResult679              ]680          ]681      ];682683      // Send the tool result back684      $finalResponse = $client->messages->create(685          maxTokens: 1024,686          messages: $messages,687          model: 'claude-opus-5',688      );689      echo $finalResponse;690  } else {691      echo $response;692  }693  ```694695  ```ruby Ruby696  client = Anthropic::Client.new697698  knowledge_base_tool = {699    name: "search_knowledge_base",700    description: "Search the company knowledge base for information",701    input_schema: {702      type: "object",703      properties: {704        query: { type: "string", description: "The search query" }705      },706      required: ["query"]707    }708  }709710  def search_knowledge_base(query)711    [712      {713        type: "search_result",714        source: "https://docs.company.com/product-guide",715        title: "Product Configuration Guide",716        content: [717          {718            type: "text",719            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."720          }721        ],722        citations: { enabled: true }723      },724      {725        type: "search_result",726        source: "https://docs.company.com/troubleshooting",727        title: "Troubleshooting Guide",728        content: [729          {730            type: "text",731            text: "If you encounter timeout errors, first check the configuration settings. Common causes include network latency and incorrect timeout values."732          }733        ],734        citations: { enabled: true }735      }736    ]737  end738739  # Build up the conversation in a list, starting with the user's question740  messages = [741    { role: "user", content: "How do I configure the timeout settings?" }742  ]743744  response = client.messages.create(745    model: "claude-opus-5",746    max_tokens: 1024,747    tools: [knowledge_base_tool],748    tool_choice: { type: "tool", name: "search_knowledge_base" },749    messages: messages750  )751752  # The tool_use block is not always first: find it in the content array753  tool_use = response.content.find { |block| block.type == :tool_use }754755  if tool_use756    tool_result = search_knowledge_base(tool_use.input[:query])757758    # Append Claude's turn, then the tool result, to the running conversation759    messages << { role: "assistant", content: response.content }760    messages << {761      role: "user",762      content: [763        {764          type: "tool_result",765          tool_use_id: tool_use.id,766          content: tool_result767        }768      ]769    }770771    # Send the tool result back772    final_response = client.messages.create(773      model: "claude-opus-5",774      max_tokens: 1024,775      messages: messages776    )777    puts final_response778  end779  ```780</CodeGroup>781782## Method 2: Search results as top-level content783784You can also provide search results directly in user messages. This is useful for:785786* Pre-fetched content from your search infrastructure787* Cached search results from previous queries788* Content from external search services789* Testing and development790791### Example: Direct search results792793<CodeGroup>794  ```bash cURL795  curl https://api.anthropic.com/v1/messages \796    -H "x-api-key: $ANTHROPIC_API_KEY" \797    -H "anthropic-version: 2023-06-01" \798    -H "content-type: application/json" \799    -d '{800      "model": "claude-opus-5",801      "max_tokens": 1024,802      "messages": [803        {804          "role": "user",805          "content": [806            {807              "type": "search_result",808              "source": "https://docs.company.com/api-reference",809              "title": "API Reference - Authentication",810              "content": [811                {812                  "type": "text",813                  "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."814                }815              ],816              "citations": {817                "enabled": true818              }819            },820            {821              "type": "search_result",822              "source": "https://docs.company.com/quickstart",823              "title": "Getting Started Guide",824              "content": [825                {826                  "type": "text",827                  "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."828                }829              ],830              "citations": {831                "enabled": true832              }833            },834            {835              "type": "text",836              "text": "Based on these search results, how do I authenticate API requests and what are the rate limits?"837            }838          ]839        }840      ]841    }'842  ```843844  ```bash CLI845  ant messages create <<'YAML'846  model: claude-opus-5847  max_tokens: 1024848  messages:849    - role: user850      content:851        - type: search_result852          source: https://docs.company.com/api-reference853          title: API Reference - Authentication854          content:855            - type: text856              text: >-857                All API requests must include an API key in the Authorization858                header. Keys can be generated from the dashboard. Rate limits:859                1000 requests per hour for standard tier, 10000 for premium.860          citations:861            enabled: true862        - type: search_result863          source: https://docs.company.com/quickstart864          title: Getting Started Guide865          content:866            - type: text867              text: >-868                To get started: 1) Sign up for an account, 2) Generate an API869                key from the dashboard, 3) Install our SDK using pip install870                company-sdk, 4) Initialize the client with your API key.871          citations:872            enabled: true873        - type: text874          text: >-875            Based on these search results, how do I authenticate API requests876            and what are the rate limits?877  YAML878  ```879880  ```python Python881  from anthropic.types import MessageParam, TextBlockParam, SearchResultBlockParam882883  client = Anthropic()884885  # Provide search results directly in the user message886  response = client.messages.create(887      model="claude-opus-5",888      max_tokens=1024,889      messages=[890          MessageParam(891              role="user",892              content=[893                  SearchResultBlockParam(894                      type="search_result",895                      source="https://docs.company.com/api-reference",896                      title="API Reference - Authentication",897                      content=[898                          TextBlockParam(899                              type="text",900                              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.",901                          )902                      ],903                      citations={"enabled": True},904                  ),905                  SearchResultBlockParam(906                      type="search_result",907                      source="https://docs.company.com/quickstart",908                      title="Getting Started Guide",909                      content=[910                          TextBlockParam(911                              type="text",912                              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.",913                          )914                      ],915                      citations={"enabled": True},916                  ),917                  TextBlockParam(918                      type="text",919                      text="Based on these search results, how do I authenticate API requests and what are the rate limits?",920                  ),921              ],922          )923      ],924  )925926  print(response)927  ```928929  ```typescript TypeScript930  const client = new Anthropic();931932  // Provide search results directly in the user message933  const response = await client.messages.create({934    model: "claude-opus-5",935    max_tokens: 1024,936    messages: [937      {938        role: "user",939        content: [940          {941            type: "search_result" as const,942            source: "https://docs.company.com/api-reference",943            title: "API Reference - Authentication",944            content: [945              {946                type: "text" as const,947                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."948              }949            ],950            citations: { enabled: true }951          },952          {953            type: "search_result" as const,954            source: "https://docs.company.com/quickstart",955            title: "Getting Started Guide",956            content: [957              {958                type: "text" as const,959                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."960              }961            ],962            citations: { enabled: true }963          },964          {965            type: "text" as const,966            text: "Based on these search results, how do I authenticate API requests and what are the rate limits?"967          }968        ]969      }970    ]971  });972973  console.log(response);974  ```975976  ```csharp C#977  AnthropicClient client = new();978979  // Provide search results directly in the user message980  var response = await client.Messages.Create(new()981  {982      Model = Model.ClaudeOpus5,983      MaxTokens = 1024,984      Messages =985      [986          new()987          {988              Role = Role.User,989              Content = new MessageParamContent(990              [991                  new ContentBlockParam(new SearchResultBlockParam992                  {993                      Source = "https://docs.company.com/api-reference",994                      Title = "API Reference - Authentication",995                      Content = [new() { 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." }],996                      Citations = new() { Enabled = true },997                  }),998                  new ContentBlockParam(new SearchResultBlockParam999                  {1000                      Source = "https://docs.company.com/quickstart",1001                      Title = "Getting Started Guide",1002                      Content = [new() { 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." }],1003                      Citations = new() { Enabled = true },1004                  }),1005                  new ContentBlockParam(new TextBlockParam { Text = "Based on these search results, how do I authenticate API requests and what are the rate limits?" }),1006              ]),1007          },1008      ],1009  });10101011  Console.WriteLine(response);1012  ```10131014  ```go Go1015  client := anthropic.NewClient()10161017  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{1018  	Model:     anthropic.ModelClaudeOpus5,1019  	MaxTokens: 1024,1020  	Messages: []anthropic.MessageParam{1021  		anthropic.NewUserMessage(1022  			anthropic.ContentBlockParamUnion{OfSearchResult: &anthropic.SearchResultBlockParam{1023  				Content: []anthropic.TextBlockParam{1024  					{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."},1025  				},1026  				Source:    "https://docs.company.com/api-reference",1027  				Title:     "API Reference - Authentication",1028  				Citations: anthropic.CitationsConfigParam{Enabled: anthropic.Bool(true)},1029  			}},1030  			anthropic.ContentBlockParamUnion{OfSearchResult: &anthropic.SearchResultBlockParam{1031  				Content: []anthropic.TextBlockParam{1032  					{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."},1033  				},1034  				Source:    "https://docs.company.com/quickstart",1035  				Title:     "Getting Started Guide",1036  				Citations: anthropic.CitationsConfigParam{Enabled: anthropic.Bool(true)},1037  			}},1038  			anthropic.NewTextBlock("Based on these search results, how do I authenticate API requests and what are the rate limits?"),1039  		),1040  	},1041  })1042  if err != nil {1043  	log.Fatal(err)1044  }1045  fmt.Println(response)1046  ```10471048  ```java Java1049  import com.anthropic.models.messages.ContentBlockParam;1050  import com.anthropic.models.messages.CitationsConfigParam;1051  // ...1052  import com.anthropic.models.messages.SearchResultBlockParam;1053  import com.anthropic.models.messages.TextBlockParam;1054  // ...10551056  void main() {1057      AnthropicClient client = AnthropicOkHttpClient.fromEnv();10581059      MessageCreateParams params = MessageCreateParams.builder()1060          .model(Model.CLAUDE_OPUS_5)1061          .maxTokens(1024L)1062          .addUserMessageOfBlockParams(List.of(1063              ContentBlockParam.ofSearchResult(1064                  SearchResultBlockParam.builder()1065                      .source("https://docs.company.com/api-reference")1066                      .title("API Reference - Authentication")1067                      .content(List.of(1068                          TextBlockParam.builder()1069                              .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.")1070                              .build()1071                      ))1072                      .citations(CitationsConfigParam.builder().enabled(true).build())1073                      .build()1074              ),1075              ContentBlockParam.ofSearchResult(1076                  SearchResultBlockParam.builder()1077                      .source("https://docs.company.com/quickstart")1078                      .title("Getting Started Guide")1079                      .content(List.of(1080                          TextBlockParam.builder()1081                              .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.")1082                              .build()1083                      ))1084                      .citations(CitationsConfigParam.builder().enabled(true).build())1085                      .build()1086              ),1087              ContentBlockParam.ofText(1088                  TextBlockParam.builder()1089                      .text("Based on these search results, how do I authenticate API requests and what are the rate limits?")1090                      .build()1091              )1092          ))1093          .build();10941095      Message response = client.messages().create(params);1096      System.out.println(response);1097  }1098  ```10991100  ```php PHP1101  $client = new Client();11021103  $message = $client->messages->create(1104      maxTokens: 1024,1105      messages: [1106          [1107              'role' => 'user',1108              'content' => [1109                  [1110                      'type' => 'search_result',1111                      'source' => 'https://docs.company.com/api-reference',1112                      'title' => 'API Reference - Authentication',1113                      'content' => [1114                          [1115                              'type' => 'text',1116                              '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.'1117                          ]1118                      ],1119                      'citations' => ['enabled' => true]1120                  ],1121                  [1122                      'type' => 'search_result',1123                      'source' => 'https://docs.company.com/quickstart',1124                      'title' => 'Getting Started Guide',1125                      'content' => [1126                          [1127                              'type' => 'text',1128                              '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.'1129                          ]1130                      ],1131                      'citations' => ['enabled' => true]1132                  ],1133                  [1134                      'type' => 'text',1135                      'text' => 'Based on these search results, how do I authenticate API requests and what are the rate limits?'1136                  ]1137              ]1138          ]1139      ],1140      model: 'claude-opus-5',1141  );11421143  echo json_encode($message, JSON_PRETTY_PRINT);1144  ```11451146  ```ruby Ruby1147  client = Anthropic::Client.new11481149  message = client.messages.create(1150    model: "claude-opus-5",1151    max_tokens: 1024,1152    messages: [1153      {1154        role: "user",1155        content: [1156          {1157            type: "search_result",1158            source: "https://docs.company.com/api-reference",1159            title: "API Reference - Authentication",1160            content: [1161              {1162                type: "text",1163                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."1164              }1165            ],1166            citations: { enabled: true }1167          },1168          {1169            type: "search_result",1170            source: "https://docs.company.com/quickstart",1171            title: "Getting Started Guide",1172            content: [1173              {1174                type: "text",1175                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."1176              }1177            ],1178            citations: { enabled: true }1179          },1180          {1181            type: "text",1182            text: "Based on these search results, how do I authenticate API requests and what are the rate limits?"1183          }1184        ]1185      }1186    ]1187  )11881189  puts message1190  ```1191</CodeGroup>11921193## Claude's response with citations11941195Regardless of how search results are provided, Claude automatically includes citations when using information from them:11961197```json1198{1199  "role": "assistant",1200  "content": [1201    {1202      "type": "text",1203      "text": "All API requests must include an API key in the Authorization header. Keys can be generated from the dashboard.",1204      "citations": [1205        {1206          "type": "search_result_location",1207          "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.",1208          "source": "https://docs.company.com/api-reference",1209          "title": "API Reference - Authentication",1210          "search_result_index": 0,1211          "start_block_index": 0,1212          "end_block_index": 11213        }1214      ]1215    },1216    {1217      "type": "text",1218      "text": "\n\nTo set this up from scratch, you'll need to "1219    },1220    {1221      "type": "text",1222      "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.",1223      "citations": [1224        {1225          "type": "search_result_location",1226          "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.",1227          "source": "https://docs.company.com/quickstart",1228          "title": "Getting Started Guide",1229          "search_result_index": 1,1230          "start_block_index": 0,1231          "end_block_index": 11232        }1233      ]1234    }1235  ]1236}1237```12381239### Citation fields12401241Each citation includes:12421243| Field                 | Type           | Description                                                                                                                                                               |1244| --------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |1245| `type`                | string         | Always `"search_result_location"` for search result citations                                                                                                             |1246| `source`              | string         | The source from the original search result                                                                                                                                |1247| `title`               | string or null | The title from the original search result                                                                                                                                 |1248| `cited_text`          | string         | The full text of the cited block(s), concatenated. Equals the contents of `content[start_block_index:end_block_index]` joined together. Not counted toward output tokens. |1249| `search_result_index` | integer        | 0-based index of the cited search result among all `search_result` blocks in the request, in the order they appear (across all messages and tool results).                |1250| `start_block_index`   | integer        | 0-based index of the first cited block in the search result's `content` array.                                                                                            |1251| `end_block_index`     | integer        | Exclusive end index of the cited block range in the search result's `content` array. Always greater than `start_block_index`.                                             |12521253The block indices identify a slice of the search result's `content` array, and `cited_text` is the full text of that slice. The text block is the minimal citable unit: Claude cites whole blocks, not substrings within a block. To get finer-grained citations, split your search result content into smaller blocks (see [Multiple content blocks](https://platform.claude.com/docs/en/build-with-claude/search-results#multiple-content-blocks)).12541255## Multiple content blocks12561257Search results can contain multiple text blocks in the `content` array:12581259```json1260{1261  "type": "search_result",1262  "source": "https://docs.company.com/api-guide",1263  "title": "API Documentation",1264  "content": [1265    {1266      "type": "text",1267      "text": "Authentication: All API requests require an API key."1268    },1269    {1270      "type": "text",1271      "text": "Rate Limits: The API allows 1000 requests per hour per key."1272    },1273    {1274      "type": "text",1275      "text": "Error Handling: The API returns standard HTTP status codes."1276    }1277  ],1278  "citations": { "enabled": true }1279}1280```12811282A citation referencing the rate limits block looks like:12831284```json1285{1286  "type": "search_result_location",1287  "cited_text": "Rate Limits: The API allows 1000 requests per hour per key.",1288  "source": "https://docs.company.com/api-guide",1289  "title": "API Documentation",1290  "search_result_index": 0,1291  "start_block_index": 1,1292  "end_block_index": 21293}1294```12951296When this search result is cited, `start_block_index` and `end_block_index` identify which of these blocks the citation covers, and `cited_text` contains exactly those blocks' text. Splitting content into smaller, focused blocks gives Claude finer citation boundaries; combining content into one block means every citation returns the full text. This is the same model used by [custom content documents](https://platform.claude.com/docs/en/build-with-claude/citations#custom-content-documents) in the Citations feature.12971298## Advanced usage12991300### Combining both methods13011302You can mix both methods in the same conversation. Claude cites from either source, and `search_result_index` counts all `search_result` blocks in request order, regardless of source.13031304The following example replays a complete conversation. The first user message carries a pre-fetched search result, the assistant turn calls a knowledge base tool, and the tool result returns a second search result. Claude's answer cites both sources:13051306<CodeGroup>1307  ```bash cURL1308  curl https://api.anthropic.com/v1/messages \1309    -H "x-api-key: $ANTHROPIC_API_KEY" \1310    -H "anthropic-version: 2023-06-01" \1311    -H "content-type: application/json" \1312    -d '{1313      "model": "claude-opus-5",1314      "max_tokens": 1024,1315      "tools": [1316        {1317          "name": "search_knowledge_base",1318          "description": "Search the company knowledge base for information",1319          "input_schema": {1320            "type": "object",1321            "properties": {1322              "query": {"type": "string", "description": "The search query"}1323            },1324            "required": ["query"]1325          }1326        }1327      ],1328      "messages": [1329        {1330          "role": "user",1331          "content": [1332            {1333              "type": "search_result",1334              "source": "https://docs.company.com/overview",1335              "title": "Product Overview",1336              "content": [1337                {1338                  "type": "text",1339                  "text": "Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards."1340                }1341              ],1342              "citations": {"enabled": true}1343            },1344            {1345              "type": "text",1346              "text": "What does Acme Dashboard do, and what plans is it available on?"1347            }1348          ]1349        },1350        {1351          "role": "assistant",1352          "content": [1353            {1354              "type": "text",1355              "text": "Let me check the pricing information."1356            },1357            {1358              "type": "tool_use",1359              "id": "toolu_01A09q90qw90lq917835lq9",1360              "name": "search_knowledge_base",1361              "input": {"query": "Acme Dashboard pricing plans"}1362            }1363          ]1364        },1365        {1366          "role": "user",1367          "content": [1368            {1369              "type": "tool_result",1370              "tool_use_id": "toolu_01A09q90qw90lq917835lq9",1371              "content": [1372                {1373                  "type": "search_result",1374                  "source": "https://docs.company.com/pricing",1375                  "title": "Pricing Plans",1376                  "content": [1377                    {1378                      "type": "text",1379                      "text": "Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing."1380                    }1381                  ],1382                  "citations": {"enabled": true}1383                }1384              ]1385            }1386          ]1387        }1388      ]1389    }'1390  ```13911392  ```bash CLI1393  ant messages create <<'YAML'1394  model: claude-opus-51395  max_tokens: 10241396  tools:1397    - name: search_knowledge_base1398      description: Search the company knowledge base for information1399      input_schema:1400        type: object1401        properties:1402          query:1403            type: string1404            description: The search query1405        required: [query]1406  messages:1407    - role: user1408      content:1409        - type: search_result1410          source: https://docs.company.com/overview1411          title: Product Overview1412          content:1413            - type: text1414              text: >-1415                Acme Dashboard is a monitoring tool for distributed systems.1416                It supports real-time alerting and custom metric dashboards.1417          citations:1418            enabled: true1419        - type: text1420          text: What does Acme Dashboard do, and what plans is it available on?1421    - role: assistant1422      content:1423        - type: text1424          text: Let me check the pricing information.1425        - type: tool_use1426          id: toolu_01A09q90qw90lq917835lq91427          name: search_knowledge_base1428          input:1429            query: Acme Dashboard pricing plans1430    - role: user1431      content:1432        - type: tool_result1433          tool_use_id: toolu_01A09q90qw90lq917835lq91434          content:1435            - type: search_result1436              source: https://docs.company.com/pricing1437              title: Pricing Plans1438              content:1439                - type: text1440                  text: >-1441                    Acme Dashboard is available on the Starter plan at $10 per1442                    user per month and the Enterprise plan with custom pricing.1443              citations:1444                enabled: true1445  YAML1446  ```14471448  ```python Python1449  from anthropic.types import (1450      MessageParam,1451      SearchResultBlockParam,1452      TextBlockParam,1453      ToolResultBlockParam,1454      ToolUseBlockParam,1455  )14561457  client = Anthropic()14581459  knowledge_base_tool = {1460      "name": "search_knowledge_base",1461      "description": "Search the company knowledge base for information",1462      "input_schema": {1463          "type": "object",1464          "properties": {"query": {"type": "string", "description": "The search query"}},1465          "required": ["query"],1466      },1467  }14681469  # Replay a conversation that provides search results both ways: the first1470  # user message carries a pre-fetched result, the tool result returns another1471  response = client.messages.create(1472      model="claude-opus-5",1473      max_tokens=1024,1474      tools=[knowledge_base_tool],1475      messages=[1476          MessageParam(1477              role="user",1478              content=[1479                  SearchResultBlockParam(1480                      type="search_result",1481                      source="https://docs.company.com/overview",1482                      title="Product Overview",1483                      content=[1484                          TextBlockParam(1485                              type="text",1486                              text="Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards.",1487                          )1488                      ],1489                      citations={"enabled": True},1490                  ),1491                  TextBlockParam(1492                      type="text",1493                      text="What does Acme Dashboard do, and what plans is it available on?",1494                  ),1495              ],1496          ),1497          MessageParam(1498              role="assistant",1499              content=[1500                  TextBlockParam(1501                      type="text", text="Let me check the pricing information."1502                  ),1503                  ToolUseBlockParam(1504                      type="tool_use",1505                      id="toolu_01A09q90qw90lq917835lq9",1506                      name="search_knowledge_base",1507                      input={"query": "Acme Dashboard pricing plans"},1508                  ),1509              ],1510          ),1511          MessageParam(1512              role="user",1513              content=[1514                  ToolResultBlockParam(1515                      type="tool_result",1516                      tool_use_id="toolu_01A09q90qw90lq917835lq9",1517                      content=[1518                          SearchResultBlockParam(1519                              type="search_result",1520                              source="https://docs.company.com/pricing",1521                              title="Pricing Plans",1522                              content=[1523                                  TextBlockParam(1524                                      type="text",1525                                      text="Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing.",1526                                  )1527                              ],1528                              citations={"enabled": True},1529                          )1530                      ],1531                  )1532              ],1533          ),1534      ],1535  )15361537  print(response)1538  ```15391540  ```typescript TypeScript1541  const client = new Anthropic();15421543  const knowledgeBaseTool: Anthropic.Tool = {1544    name: "search_knowledge_base",1545    description: "Search the company knowledge base for information",1546    input_schema: {1547      type: "object" as const,1548      properties: {1549        query: { type: "string", description: "The search query" }1550      },1551      required: ["query"]1552    }1553  };15541555  // Replay a conversation that provides search results both ways: the first1556  // user message carries a pre-fetched result, the tool result returns another1557  const response = await client.messages.create({1558    model: "claude-opus-5",1559    max_tokens: 1024,1560    tools: [knowledgeBaseTool],1561    messages: [1562      {1563        role: "user",1564        content: [1565          {1566            type: "search_result" as const,1567            source: "https://docs.company.com/overview",1568            title: "Product Overview",1569            content: [1570              {1571                type: "text" as const,1572                text: "Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards."1573              }1574            ],1575            citations: { enabled: true }1576          },1577          {1578            type: "text" as const,1579            text: "What does Acme Dashboard do, and what plans is it available on?"1580          }1581        ]1582      },1583      {1584        role: "assistant",1585        content: [1586          { type: "text" as const, text: "Let me check the pricing information." },1587          {1588            type: "tool_use" as const,1589            id: "toolu_01A09q90qw90lq917835lq9",1590            name: "search_knowledge_base",1591            input: { query: "Acme Dashboard pricing plans" }1592          }1593        ]1594      },1595      {1596        role: "user",1597        content: [1598          {1599            type: "tool_result" as const,1600            tool_use_id: "toolu_01A09q90qw90lq917835lq9",1601            content: [1602              {1603                type: "search_result" as const,1604                source: "https://docs.company.com/pricing",1605                title: "Pricing Plans",1606                content: [1607                  {1608                    type: "text" as const,1609                    text: "Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing."1610                  }1611                ],1612                citations: { enabled: true }1613              }1614            ]1615          }1616        ]1617      }1618    ]1619  });16201621  console.log(response);1622  ```16231624  ```csharp C#1625  AnthropicClient client = new();16261627  // Replay a conversation that provides search results both ways: the first1628  // user message carries a pre-fetched result, the tool result returns another1629  var response = await client.Messages.Create(new()1630  {1631      Model = Model.ClaudeOpus5,1632      MaxTokens = 1024,1633      Tools =1634      [1635          new ToolUnion(new Tool()1636          {1637              Name = "search_knowledge_base",1638              Description = "Search the company knowledge base for information",1639              InputSchema = new InputSchema()1640              {1641                  Properties = new Dictionary<string, JsonElement>1642                  {1643                      ["query"] = JsonSerializer.SerializeToElement(new { type = "string", description = "The search query" }),1644                  },1645                  Required = ["query"],1646              },1647          }),1648      ],1649      Messages =1650      [1651          new()1652          {1653              Role = Role.User,1654              Content = new MessageParamContent(1655              [1656                  new ContentBlockParam(new SearchResultBlockParam1657                  {1658                      Source = "https://docs.company.com/overview",1659                      Title = "Product Overview",1660                      Content = [new() { Text = "Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards." }],1661                      Citations = new() { Enabled = true },1662                  }),1663                  new ContentBlockParam(new TextBlockParam { Text = "What does Acme Dashboard do, and what plans is it available on?" }),1664              ]),1665          },1666          new()1667          {1668              Role = Role.Assistant,1669              Content = new MessageParamContent(1670              [1671                  new ContentBlockParam(new TextBlockParam { Text = "Let me check the pricing information." }),1672                  new ContentBlockParam(new ToolUseBlockParam1673                  {1674                      ID = "toolu_01A09q90qw90lq917835lq9",1675                      Name = "search_knowledge_base",1676                      Input = new Dictionary<string, JsonElement>1677                      {1678                          ["query"] = JsonSerializer.SerializeToElement("Acme Dashboard pricing plans"),1679                      },1680                  }),1681              ]),1682          },1683          new()1684          {1685              Role = Role.User,1686              Content = new MessageParamContent(1687              [1688                  new ContentBlockParam(new ToolResultBlockParam()1689                  {1690                      ToolUseID = "toolu_01A09q90qw90lq917835lq9",1691                      Content = new ToolResultBlockParamContent(1692                      [1693                          new SearchResultBlockParam1694                          {1695                              Source = "https://docs.company.com/pricing",1696                              Title = "Pricing Plans",1697                              Content = [new() { Text = "Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing." }],1698                              Citations = new() { Enabled = true },1699                          },1700                      ]),1701                  }),1702              ]),1703          },1704      ],1705  });17061707  Console.WriteLine(response);1708  ```17091710  ```go Go1711  client := anthropic.NewClient()17121713  knowledgeBaseTool := anthropic.ToolUnionParam{1714  	OfTool: &anthropic.ToolParam{1715  		Name:        "search_knowledge_base",1716  		Description: anthropic.String("Search the company knowledge base for information"),1717  		InputSchema: anthropic.ToolInputSchemaParam{1718  			Properties: map[string]any{1719  				"query": map[string]any{"type": "string", "description": "The search query"},1720  			},1721  			Required: []string{"query"},1722  		},1723  	},1724  }17251726  // Replay a conversation that provides search results both ways: the first1727  // user message carries a pre-fetched result, the tool result returns another1728  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{1729  	Model:     anthropic.ModelClaudeOpus5,1730  	MaxTokens: 1024,1731  	Tools:     []anthropic.ToolUnionParam{knowledgeBaseTool},1732  	Messages: []anthropic.MessageParam{1733  		anthropic.NewUserMessage(1734  			anthropic.ContentBlockParamUnion{OfSearchResult: &anthropic.SearchResultBlockParam{1735  				Content: []anthropic.TextBlockParam{1736  					{Text: "Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards."},1737  				},1738  				Source:    "https://docs.company.com/overview",1739  				Title:     "Product Overview",1740  				Citations: anthropic.CitationsConfigParam{Enabled: anthropic.Bool(true)},1741  			}},1742  			anthropic.NewTextBlock("What does Acme Dashboard do, and what plans is it available on?"),1743  		),1744  		anthropic.NewAssistantMessage(1745  			anthropic.NewTextBlock("Let me check the pricing information."),1746  			anthropic.ContentBlockParamUnion{OfToolUse: &anthropic.ToolUseBlockParam{1747  				ID:    "toolu_01A09q90qw90lq917835lq9",1748  				Name:  "search_knowledge_base",1749  				Input: map[string]any{"query": "Acme Dashboard pricing plans"},1750  			}},1751  		),1752  		anthropic.NewUserMessage(1753  			anthropic.ContentBlockParamUnion{OfToolResult: &anthropic.ToolResultBlockParam{1754  				ToolUseID: "toolu_01A09q90qw90lq917835lq9",1755  				Content: []anthropic.ToolResultBlockParamContentUnion{1756  					{OfSearchResult: &anthropic.SearchResultBlockParam{1757  						Content: []anthropic.TextBlockParam{1758  							{Text: "Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing."},1759  						},1760  						Source:    "https://docs.company.com/pricing",1761  						Title:     "Pricing Plans",1762  						Citations: anthropic.CitationsConfigParam{Enabled: anthropic.Bool(true)},1763  					}},1764  				},1765  			}},1766  		),1767  	},1768  })1769  if err != nil {1770  	log.Fatal(err)1771  }1772  fmt.Println(response)1773  ```17741775  ```java Java1776  import com.anthropic.core.JsonValue;1777  import com.anthropic.models.messages.CitationsConfigParam;1778  import com.anthropic.models.messages.ContentBlockParam;1779  // ...1780  import com.anthropic.models.messages.SearchResultBlockParam;1781  import com.anthropic.models.messages.TextBlockParam;1782  import com.anthropic.models.messages.Tool;1783  import com.anthropic.models.messages.ToolResultBlockParam;1784  import com.anthropic.models.messages.ToolUseBlockParam;1785  // ...17861787  void main() {1788      AnthropicClient client = AnthropicOkHttpClient.fromEnv();17891790      Tool knowledgeBaseTool = Tool.builder()1791          .name("search_knowledge_base")1792          .description("Search the company knowledge base for information")1793          .inputSchema(Tool.InputSchema.builder()1794              .properties(JsonValue.from(Map.of(1795                  "query", Map.of("type", "string", "description", "The search query")1796              )))1797              .putAdditionalProperty("required", JsonValue.from(List.of("query")))1798              .build())1799          .build();18001801      // Replay a conversation that provides search results both ways: the first1802      // user message carries a pre-fetched result, the tool result returns another1803      MessageCreateParams params = MessageCreateParams.builder()1804          .model(Model.CLAUDE_OPUS_5)1805          .maxTokens(1024L)1806          .addTool(knowledgeBaseTool)1807          .addUserMessageOfBlockParams(List.of(1808              ContentBlockParam.ofSearchResult(SearchResultBlockParam.builder()1809                  .source("https://docs.company.com/overview")1810                  .title("Product Overview")1811                  .content(List.of(TextBlockParam.builder()1812                      .text("Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards.")1813                      .build()))1814                  .citations(CitationsConfigParam.builder().enabled(true).build())1815                  .build()),1816              ContentBlockParam.ofText(TextBlockParam.builder()1817                  .text("What does Acme Dashboard do, and what plans is it available on?")1818                  .build())1819          ))1820          .addAssistantMessageOfBlockParams(List.of(1821              ContentBlockParam.ofText(TextBlockParam.builder()1822                  .text("Let me check the pricing information.")1823                  .build()),1824              ContentBlockParam.ofToolUse(ToolUseBlockParam.builder()1825                  .id("toolu_01A09q90qw90lq917835lq9")1826                  .name("search_knowledge_base")1827                  .input(JsonValue.from(Map.of("query", "Acme Dashboard pricing plans")))1828                  .build())1829          ))1830          .addUserMessageOfBlockParams(List.of(1831              ContentBlockParam.ofToolResult(ToolResultBlockParam.builder()1832                  .toolUseId("toolu_01A09q90qw90lq917835lq9")1833                  .contentOfBlocks(List.of(1834                      ToolResultBlockParam.Content.Block.ofSearchResult(SearchResultBlockParam.builder()1835                          .source("https://docs.company.com/pricing")1836                          .title("Pricing Plans")1837                          .content(List.of(TextBlockParam.builder()1838                              .text("Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing.")1839                              .build()))1840                          .citations(CitationsConfigParam.builder().enabled(true).build())1841                          .build())1842                  ))1843                  .build())1844          ))1845          .build();18461847      Message response = client.messages().create(params);1848      System.out.println(response);1849  }1850  ```18511852  ```php PHP1853  $client = new Client();18541855  $knowledgeBaseTool = [1856      'name' => 'search_knowledge_base',1857      'description' => 'Search the company knowledge base for information',1858      'input_schema' => [1859          'type' => 'object',1860          'properties' => [1861              'query' => ['type' => 'string', 'description' => 'The search query']1862          ],1863          'required' => ['query']1864      ]1865  ];18661867  // Replay a conversation that provides search results both ways: the first1868  // user message carries a pre-fetched result, the tool result returns another1869  $response = $client->messages->create(1870      maxTokens: 1024,1871      tools: [$knowledgeBaseTool],1872      messages: [1873          [1874              'role' => 'user',1875              'content' => [1876                  [1877                      'type' => 'search_result',1878                      'source' => 'https://docs.company.com/overview',1879                      'title' => 'Product Overview',1880                      'content' => [1881                          [1882                              'type' => 'text',1883                              'text' => 'Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards.'1884                          ]1885                      ],1886                      'citations' => ['enabled' => true]1887                  ],1888                  [1889                      'type' => 'text',1890                      'text' => 'What does Acme Dashboard do, and what plans is it available on?'1891                  ]1892              ]1893          ],1894          [1895              'role' => 'assistant',1896              'content' => [1897                  ['type' => 'text', 'text' => 'Let me check the pricing information.'],1898                  [1899                      'type' => 'tool_use',1900                      'id' => 'toolu_01A09q90qw90lq917835lq9',1901                      'name' => 'search_knowledge_base',1902                      'input' => ['query' => 'Acme Dashboard pricing plans']1903                  ]1904              ]1905          ],1906          [1907              'role' => 'user',1908              'content' => [1909                  [1910                      'type' => 'tool_result',1911                      'tool_use_id' => 'toolu_01A09q90qw90lq917835lq9',1912                      'content' => [1913                          [1914                              'type' => 'search_result',1915                              'source' => 'https://docs.company.com/pricing',1916                              'title' => 'Pricing Plans',1917                              'content' => [1918                                  [1919                                      'type' => 'text',1920                                      'text' => 'Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing.'1921                                  ]1922                              ],1923                              'citations' => ['enabled' => true]1924                          ]1925                      ]1926                  ]1927              ]1928          ]1929      ],1930      model: 'claude-opus-5',1931  );19321933  echo json_encode($response, JSON_PRETTY_PRINT);1934  ```19351936  ```ruby Ruby1937  client = Anthropic::Client.new19381939  knowledge_base_tool = {1940    name: "search_knowledge_base",1941    description: "Search the company knowledge base for information",1942    input_schema: {1943      type: "object",1944      properties: {1945        query: { type: "string", description: "The search query" }1946      },1947      required: ["query"]1948    }1949  }19501951  # Replay a conversation that provides search results both ways: the first1952  # user message carries a pre-fetched result, the tool result returns another1953  response = client.messages.create(1954    model: "claude-opus-5",1955    max_tokens: 1024,1956    tools: [knowledge_base_tool],1957    messages: [1958      {1959        role: "user",1960        content: [1961          {1962            type: "search_result",1963            source: "https://docs.company.com/overview",1964            title: "Product Overview",1965            content: [1966              {1967                type: "text",1968                text: "Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards."1969              }1970            ],1971            citations: { enabled: true }1972          },1973          {1974            type: "text",1975            text: "What does Acme Dashboard do, and what plans is it available on?"1976          }1977        ]1978      },1979      {1980        role: "assistant",1981        content: [1982          { type: "text", text: "Let me check the pricing information." },1983          {1984            type: "tool_use",1985            id: "toolu_01A09q90qw90lq917835lq9",1986            name: "search_knowledge_base",1987            input: { query: "Acme Dashboard pricing plans" }1988          }1989        ]1990      },1991      {1992        role: "user",1993        content: [1994          {1995            type: "tool_result",1996            tool_use_id: "toolu_01A09q90qw90lq917835lq9",1997            content: [1998              {1999                type: "search_result",2000                source: "https://docs.company.com/pricing",2001                title: "Pricing Plans",2002                content: [2003                  {2004                    type: "text",2005                    text: "Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing."2006                  }2007                ],2008                citations: { enabled: true }2009              }2010            ]2011          }2012        ]2013      }2014    ]2015  )20162017  puts response2018  ```2019</CodeGroup>20202021The response cites both sources. The pre-fetched result is `search_result_index: 0` and the tool-returned result is `search_result_index: 1`, matching the order the `search_result` blocks appear in the conversation:20222023```json2024{2025  "role": "assistant",2026  "content": [2027    {2028      "type": "text",2029      "text": "Here's what I found about Acme Dashboard:\n\n**What it does:** "2030    },2031    {2032      "type": "text",2033      "text": "Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards.",2034      "citations": [2035        {2036          "type": "search_result_location",2037          "cited_text": "Acme Dashboard is a monitoring tool for distributed systems. It supports real-time alerting and custom metric dashboards.",2038          "source": "https://docs.company.com/overview",2039          "title": "Product Overview",2040          "search_result_index": 0,2041          "start_block_index": 0,2042          "end_block_index": 12043        }2044      ]2045    },2046    {2047      "type": "text",2048      "text": "\n\n**Available plans:** "2049    },2050    {2051      "type": "text",2052      "text": "Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing.",2053      "citations": [2054        {2055          "type": "search_result_location",2056          "cited_text": "Acme Dashboard is available on the Starter plan at $10 per user per month and the Enterprise plan with custom pricing.",2057          "source": "https://docs.company.com/pricing",2058          "title": "Pricing Plans",2059          "search_result_index": 1,2060          "start_block_index": 0,2061          "end_block_index": 12062        }2063      ]2064    }2065  ]2066}2067```20682069### Mixing with other content types20702071In user messages, `search_result` blocks can sit alongside any other content block. The Method 2 example pairs search results with a `text` question, and image or document blocks can join them the same way.20722073Tool results are stricter: if any block in a `tool_result` content array is a `search_result`, all of its blocks must be `search_result`. Mixing search results with other block types in the same tool result returns a validation error. To return supporting text alongside tool-sourced search results, include it as a text block inside one of the search results' `content` arrays, where it also becomes citable.20742075### Cache control20762077Add `cache_control` on the search result block to cache it for reuse across requests. It sits alongside `citations` on the same block:20782079```json2080{2081  "type": "search_result",2082  "source": "https://docs.company.com/guide",2083  "title": "User Guide",2084  "content": [{ "type": "text", "text": "..." }],2085  "citations": { "enabled": true },2086  "cache_control": { "type": "ephemeral" }2087}2088```20892090See [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) for minimum cacheable lengths and other requirements.20912092### Citation control20932094By default, citations are disabled for search results. You can enable citations by explicitly setting the `citations` configuration:20952096```json2097{2098  "type": "search_result",2099  "source": "https://docs.company.com/guide",2100  "title": "User Guide",2101  "content": [{ "type": "text", "text": "Important documentation..." }],2102  "citations": {2103    "enabled": true // Enable citations for this result2104  }2105}2106```21072108When `citations.enabled` is set to `true`, Claude attaches citation references to the text blocks that draw on the search result.21092110<Warning>2111  Citations are all-or-nothing: either all search results in a request must have citations enabled, or all must have them disabled. Mixing search results with different citation settings results in an error.2112</Warning>21132114## Best practices21152116### For tool-based search (Method 1)21172118* **Dynamic content:** Use for real-time searches and dynamic RAG applications2119* **Error handling:** Return appropriate messages when searches fail2120* **Result limits:** Return only the most relevant results to avoid context overflow21212122### For top-level search (Method 2)21232124* **Pre-fetched content:** Use when you already have search results2125* **Batch processing:** Ideal for processing multiple search results at once2126* **Testing:** Great for testing citation behavior with known content21272128### General best practices212921301. **Structure results effectively:**21312132   * Use clear, permanent source URLs2133   * Provide descriptive titles2134   * Break long content into logical text blocks to give Claude finer citation boundaries213521362. **Maintain consistency:**21372138   * Use consistent source formats across your application2139   * Ensure titles accurately reflect content2140   * Keep formatting consistent214121423. **Handle errors gracefully:** when a search fails or returns nothing, return a plain text block describing the outcome (for example, `{"type": "text", "text": "No results found."}`) instead of raising an error: Claude explains the empty result to the user, and the conversation continues.21432144## Limitations21452146* Search result content blocks are available on Claude API, Amazon Bedrock, and Google Cloud.2147* Only text content is supported within search results (no images or other media).2148* `search_result` blocks can only appear in user messages (including inside tool results). Assistant messages with search results are rejected.2149* When the [web search tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool) is enabled in the same request, citations must be enabled on all `search_result` blocks.21502151## Next steps21522153<CardGroup cols={2}>2154  <Card title="Streaming refusals" icon="lock" href="https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/handle-streaming-refusals">2155    Detect and handle refusal stop reasons in streaming responses, and retry refused requests on a fallback model.2156  </Card>21572158  <Card title="Citations" icon="book" href="https://platform.claude.com/docs/en/build-with-claude/citations">2159    Ground Claude's responses in your source documents. Citations return the exact passages that support each claim, so you can verify answers and surface sources to your users.2160  </Card>21612162  <Card title="Web search tool" icon="magnifying-glass" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool">2163    Give Claude access to current web content with cited sources, optional dynamic filtering, and domain controls.2164  </Card>21652166  <Card title="Messages API reference" icon="code" href="https://platform.claude.com/docs/en/api/messages/create">2167    See the complete Messages API documentation, including content block types.2168  </Card>21692170  <Card title="Prompt caching" icon="database" href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching">2171    Cache search results with `cache_control` to reduce cost and latency on repeated requests.2172  </Card>2173</CardGroup>2174
Files main
Menu

Theme