> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aiandgpu.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Web Search

export const ClaudeChatResponse = ({successJson, title = "Sync Chat Response", streaming = false, groupId = ""}) => {
  const prefix = groupId ? `[${groupId}] ` : "";
  const error400 = `{
    "type": "error",
    "error": {
      "type": "invalid_request_error",
      "message": "parameter 'ARGUMENT' is required"
    }
  }`;
  const error401 = `{
    "type": "error",
    "error": {
      "type": "authentication_error",
      "message": "Invalid API Key"
    }
  }`;
  const error402 = `{
    "type": "error",
    "error": {
      "type": "insufficient_balance",
      "message": "Insufficient balance"
    }
  }`;
  const error403 = `{
    "type": "error",
    "error": {
      "type": "quota_exceeded",
      "message": "Quota exceeded"
    }
  }`;
  const error404 = `{
    "type": "error",
    "error": {
      "type": "invalid_request_error",
      "message": "Invalid URL"
    }
  }`;
  const error429 = `{
    "type": "error",
    "error": {
      "type": "rate_limit_error",
      "message": "Too many requests"
    }
  }`;
  const error500 = `{
    "type": "error",
    "error": {
      "type": "internal_server_error",
      "message": "Internal server error"
    }
  }`;
  return <>
      <h3>{title}</h3>

      <CodeGroup>
        <CodeBlock language={streaming ? "text" : "json"} filename={streaming ? `${prefix}200 - Success (SSE)` : `${prefix}200 - Success`}>
          {successJson}
        </CodeBlock>
        <CodeBlock language="json" filename={`${prefix}400 - Bad Request`}>
          {error400}
        </CodeBlock>
        <CodeBlock language="json" filename={`${prefix}401 - Unauthorized`}>
          {error401}
        </CodeBlock>
        <CodeBlock language="json" filename={`${prefix}402 - Insufficient Balance`}>
          {error402}
        </CodeBlock>
        <CodeBlock language="json" filename={`${prefix}403 - Quota Exceeded`}>
          {error403}
        </CodeBlock>
        <CodeBlock language="json" filename={`${prefix}404 - Invalid URL`}>
          {error404}
        </CodeBlock>
        <CodeBlock language="json" filename={`${prefix}429 - Too Many Requests`}>
          {error429}
        </CodeBlock>
        <CodeBlock language="json" filename={`${prefix}500 - Internal Server Error`}>
          {error500}
        </CodeBlock>
      </CodeGroup>
    </>;
};

export const ClaudeWebSearch = ({model = "claude-haiku-4-5-20251001"}) => {
  const curlExample = `curl --location 'https://aiandgpu.com/v1/messages' \\
--header 'Authorization: Bearer <YOUR_API_KEY>' \\
--header 'Content-Type: application/json' \\
--data '{
  "model": "${model}",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": [
        {
            "type": "text",
            "text": "World Snooker Championship winner in 2025??"
        }
      ]
    }
  ],
  "tools": [
    {
      "type": "web_search_20250305",
      "name": "web_search",
      "max_uses": 5
    }
  ]
}'`;
  const pythonExample = `import requests

url = "https://aiandgpu.com/v1/messages"

payload = {
    "model": "${model}",
    "max_tokens": 1024,
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "World Snooker Championship winner in 2025??"
                }
            ]
        }
    ],
    "tools": [
        {
            "type": "web_search_20250305",
            "name": "web_search",
            "max_uses": 5
        }
    ]
}

headers = {
    "Authorization": "Bearer <YOUR_API_KEY>",
    "Content-Type": "application/json",
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())`;
  const jsExample = `const response = await fetch('https://aiandgpu.com/v1/messages', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <YOUR_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: '${model}',
    max_tokens: 1024,
    messages: [
      {
        role: 'user',
        content: [
          {
            type: 'text',
            text: "World Snooker Championship winner in 2025??"
          }
        ]
      }
    ],
    tools: [
      {
        "type": "web_search_20250305",
        "name": "web_search",
        "max_uses": 5
      }
    ]
  })
});

const data = await response.json();
console.log(data);`;
  const goExample = `package main

import (
\t"fmt"
\t"io"
\t"net/http"
\t"strings"
)

func main() {
\turl := "https://aiandgpu.com/v1/messages"

\tpayload := strings.NewReader(\`{
\t\t"model": "${model}",
\t\t"max_tokens": 1024,
\t\t"messages": [{"role": "user", "content": [{"type": "text", "text": "World Snooker Championship winner in 2025??"}]}],
\t\t"tools": [{ "type": "web_search_20250305", "name": "web_search", "max_uses": 5 }]
\t}\`)

\treq, _ := http.NewRequest("POST", url, payload)

\treq.Header.Add("Authorization", "Bearer <YOUR_API_KEY>")
\treq.Header.Add("Content-Type", "application/json")

\tres, _ := http.DefaultClient.Do(req)
\tdefer res.Body.Close()

\tbody, _ := io.ReadAll(res.Body)
\tfmt.Println(string(body))
}`;
  const javaExample = `import java.net.http.*;
import java.net.URI;

HttpClient client = HttpClient.newHttpClient();

String body = """
{
  "model": "${model}",
  "max_tokens": 1024,
  "messages": [
    {
      "role": "user",
      "content": [
        {"type": "text", "text": "World Snooker Championship winner in 2025??"}
      ]
    }
  ],
  "tools": [
    {
      "type": "web_search_20250305",
      "name": "web_search",
      "max_uses": 5
    }
  ]
}
""";

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://aiandgpu.com/v1/messages"))
    .header("Authorization", "Bearer <YOUR_API_KEY>")
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());`;
  const phpExample = `<?php

$curl = curl_init();

$payload = json_encode([
    'model' => '${model}',
    'max_tokens' => 1024,
    'messages' => [
        [
            'role' => 'user',
            'content' => [
                ['type' => 'text', 'text' => "World Snooker Championship winner in 2025??"]
            ]
        ]
    ],
    'tools' => [
        [
            'type' => 'web_search_20250305',
            'name' => 'web_search',
            'max_uses' => 5
        ]
    ]
]);

curl_setopt_array($curl, [
    CURLOPT_URL => "https://aiandgpu.com/v1/messages",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => $payload,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer <YOUR_API_KEY>",
        "Content-Type: application/json",
    ],
]);

$response = curl_exec($curl);
curl_close($curl);

echo $response;`;
  const csharpExample = `using System.Net.Http;
using System.Text;

var client = new HttpClient();

var payload = @"{
    ""model"": ""${model}"",
    ""max_tokens"": 1024,
    ""messages"": [
        {
            ""role"": ""user"",
            ""content"": [
                {""type"": ""text"", ""text"": ""World Snooker Championship winner in 2025??""}
            ]
        }
    ],
    ""tools"": [
        {
            ""type"": ""web_search_20250305"",
            ""name"": ""web_search"",
            ""max_uses"": 5
        }
    ]
}";

var request = new HttpRequestMessage(HttpMethod.Post, "https://aiandgpu.com/v1/messages");
request.Headers.Add("Authorization", "Bearer <YOUR_API_KEY>");
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");

var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);`;
  return <>
      <h2>Request Examples</h2>

      <CodeGroup>
        <CodeBlock language="bash" filename="cURL">{curlExample}</CodeBlock>
        <CodeBlock language="python" filename="Python">{pythonExample}</CodeBlock>
        <CodeBlock language="javascript" filename="JavaScript">{jsExample}</CodeBlock>
        <CodeBlock language="go" filename="Go">{goExample}</CodeBlock>
        <CodeBlock language="java" filename="Java">{javaExample}</CodeBlock>
        <CodeBlock language="php" filename="PHP">{phpExample}</CodeBlock>
        <CodeBlock language="csharp" filename="C#">{csharpExample}</CodeBlock>
      </CodeGroup>
    </>;
};

## Authorization

* **Auth Type**: `Bearer Auth` (In: `header`)
* **Format**: `Authorization: Bearer <YOUR_API_KEY>`
* **Description**: Use `Bearer <YOUR_API_KEY>`. Format: `Authorization: Bearer sk-xxxxxx.`
* **API Key**: where <strong>API Key</strong> is your <a href="https://developer.aiandgpu.com" target="_blank" rel="noopener noreferrer">AGCloud API KEY</a>

<ClaudeWebSearch model="claude-opus-4-1-20250805" />

<Expandable title="Sync Responses">
  <ClaudeChatResponse
    successJson={`{
  "model": "claude-opus-4-1-20250805",
  "id": "msg_bdrk_01LQUV5bYD9xZbYC46bLhzub",
  "type": "message",
  "role": "assistant",
  "content": [
      {
          "type": "text",
          "text": "I don't have a real-time weather tool available in my current set of tools. However, I can search the web for you to find the current weather in NYC."
      },
      {
          "type": "tool_use",
          "id": "toolu_bdrk_017KRUUMZystbdPik3aNbG9g",
          "name": "web_search",
          "input": {
              "query": "weather NYC New York City current"
          }
      }
  ],
  "stop_reason": "tool_use",
  "stop_sequence": null,
  "usage": {
      "input_tokens": 561,
      "cache_creation_input_tokens": 0,
      "cache_read_input_tokens": 0,
      "cache_creation": {
          "ephemeral_5m_input_tokens": 0,
          "ephemeral_1h_input_tokens": 0
      },
      "output_tokens": 94
  }
}`}
    title=""
    groupId="sync"
  />
</Expandable>

<Expandable title="Async Responses">
  <ClaudeChatResponse
    successJson={`{
  "id": "6e06be0e-de35-4a68-83dd-5caf4cd639fe",
  "object": "task",
  "status": "pending",
  "created_at": 1773142523
}`}
    title=""
    groupId="async"
  />
</Expandable>

<Expandable title="Streaming Responses">
  <ClaudeChatResponse
    groupId="stream"
    successJson={`
data: {"type":"message_start","message":{"model":"claude-opus-4-1-20250805","id":"msg_01AYiJR1dKUNjjaCwuR3YoSN","type":"message","role":"assistant","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":13,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"}}               }

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}          }

event: ping
data: {"type": "ping"}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"你"}            }

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"好！"}              }

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"👋 "} }

...
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"有"} }

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"什么我可以帮助"}               }

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"你的吗？"} }

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"😊"}        }

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"input_tokens":13,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":169}        }

event: message_stop
data: {"type":"message_stop"}
`}
    title="Streaming Responses"
    streaming="true"
  />
</Expandable>

### Async Chat Response Field Description

| Field        | Type     | Range                                                          | Description                                                               |
| :----------- | :------- | :------------------------------------------------------------- | :------------------------------------------------------------------------ |
| `id`         | `string` | -                                                              | The current chat task id.                                                 |
| `object`     | `string` | -                                                              | The type of object returned by the API. In this case it is always `task`. |
| `status`     | `string` | `pending` <br /> `processing` <br /> `success` <br /> `failed` | Current status of the task.                                               |
| `created_at` | `number` | -                                                              | Unix timestamp (in seconds) indicating when the task was created.         |

## Parameters

| Field            | Type                      | Required | Default           | Description                                                                                                                                      |
| :--------------- | :------------------------ | :------- | :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------------- |
| `model`          | `string`                  | ✅        | `claude-opus-4-6` | The model ID to use for this request.                                                                                                            |
| `messages`       | `string \| array<object>` | ✅        | -                 | An array of message objects representing the conversation history.                                                                               |
| `max_tokens`     | `integer`                 | ✅        | `1024`            | The maximum number of tokens the model can generate in the response. Range `1-32000`                                                             |
| `tools`          | `array<object>`           | ✅        | -                 | Array of tool objects. For web search, must include the web\_search tool configuration with type web\_search\_20250305.                          |
| `async`          | `boolean`                 | -        | `false`           | Whether to return an asynchronous response. Only supported for non-streaming requests. See [Tools](#tools-object-structure).                     |
| `stream`         | `boolean`                 | -        | `false`           | If `true`, returns a stream of server-sent events (SSE) as the response is generated.                                                            |
| `system`         | `string \| array<object>` | -        | -                 | System prompt that sets the behavior and context for the assistant.                                                                              |
| `temperature`    | `number`                  | -        | `1.0`             | Controls the randomness of the output. Lower values produce more focused responses, higher values produce more creative outputs. Range `0.0-1.0` |
| `top_p`          | `number`                  | -        | `1.0`             | Nucleus sampling parameter. The model considers tokens with top\_p cumulative probability mass. Range `0.0-1.0`                                  |
| `top_k`          | `integer`                 | -        | -                 | Limits token selection to the K most probable tokens at each step.                                                                               |
| `stop_sequences` | `array<string>`           | -        | -                 | An array of strings that will stop generation when encountered.                                                                                  |

### Tools Object Structure

| Field                     | Type            | Required | Description                                                                            |
| :------------------------ | :-------------- | :------- | :------------------------------------------------------------------------------------- |
| `type`                    | `string`        | ✅        | The tool type. Must be `web_search_20250305` for web search.                           |
| `name`                    | `string`        | ✅        | Override the default tool name. Default: `web_search`.                                 |
| `max_uses`                | `integer`       | -        | Maximum number of web search requests allowed per model turn. Range `1-20`.            |
| `allowed_domains`         | `array<string>` | -        | Only include search results from these domains. Cannot be used with blocked\_domains.  |
| `blocked_domains`         | `array<string>` | -        | Never include search results from these domains. Cannot be used with allowed\_domains. |
| `user_location`           | `object`        | -        | Approximate user location for localized search results.                                |
| `>user_location.type`     | `string`        | -        | Must be `approximate` if provided.                                                     |
| `>user_location.city`     | `string`        | -        | City name (e.g., `"San Francisco"`).                                                   |
| `>user_location.region`   | `string`        | -        | Region or state (e.g., `"California"`).                                                |
| `>user_location.country`  | `string`        | -        | Two-letter country code (e.g., `"US"`).                                                |
| `>user_location.timezone` | `string`        | -        | IANA timezone (e.g., `"America/New_York"`).                                            |

```json theme={null}
{
  "type": "web_search_20250305",
  "name": "web_search",
  "max_uses": 5,
  "allowed_domains": ["example.com", "trusteddomain.org"],
  "user_location": {
    "type": "approximate",
    "city": "San Francisco",
    "region": "California",
    "country": "US",
    "timezone": "America/Los_Angeles"
  }
}
```

### Max Uses

The `max_uses` parameter limits the number of searches performed. If Claude attempts more searches than allowed, the `web_search_tool_result` will be an error with the `max_uses_exceeded` error code.
​

### Domain Filtering

When using domain filters:

* Domains should not include the HTTP/HTTPS scheme (use `example.com` instead of `https://example.com`)
* Subdomains are automatically included (`example.com` covers `docs.example.com`)
* Specific subdomains restrict results to only that subdomain (`docs.example.com` returns only results from that subdomain, not from `example.com` or `api.example.com`)
* Subpaths are supported (`example.com/blog`)
* You can use either `allowed_domains` or `blocked_domains`, but not both in the same request
* Request-level domain restrictions must be compatible with organization-level domain restrictions configured in the Console

<StreamEvent />
