> ## 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.

# Text To Text

> Create an chat message

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 ClaudeChat = ({model = "claude-haiku-4-5-20251001"}) => {
  const curlExample = `curl --request POST \\
  --url 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": "Hello"}]
        }
    ]
}'`;
  const pythonExample = `import requests

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

payload = {
    "model": "${model}",
    "max_tokens": 1024,
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Hello"
                }
            ]
        }
    ]
}

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

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

print(response.text)`;
  const jsExample = `const options = {
  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: 'Hello'}]}]
  })
};

fetch('https://aiandgpu.com/v1/messages', options)
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.error(err));`;
  const goExample = `package main

import (
\t"bytes"
\t"encoding/json"
\t"fmt"
\t"net/http"
\t"io"
)

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

\tpayload := strings.NewReader("{\\"model\\": \\"claude-haiku-4-5-20251001\\", \\"max_tokens\\": 1024, \\"messages\\": [{\\"role\\": \\"user\\", \\"content\\": [{ \\"type\\": \\"text\\", \\"text\\": \\"who are you?\\"}]}]}")

\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()
\tresBody, _ := io.ReadAll(res.Body)

\tfmt.Println(string(resBody))
}`;
  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": "Hello"}]
    }
  ]
}
""";

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' => 'Hello']
            ]
        ]
    ]
]);

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);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {
    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"": ""Hello""}]
        }
    ]
}";

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="shellscript" 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>

<ClaudeChat model="claude-sonnet-4-6" />

## Response Examples

<Expandable title="Sync Responses">
  <ClaudeChatResponse
    groupId="sync"
    successJson={`{
"model": "claude-opus-4-6-v1",
"id": "msg_01CStyGUyAva65uTfcD1vVi5",
"type": "message",
"role": "assistant",
"content": [
    {
        "type": "text",
        "text": "你好！我是Claude，一个由Anthropic公司开发的AI助手。\n\n我可以帮助你：\n- 回答各种问题\n- 进行写作和编辑\n- 分析和解决问题\n- 进行创意头脑风暴\n- 提供学习和研究帮助\n- 进行日常对话\n\n有什么我可以帮助你的吗？"
    }
],
"stop_reason": "end_turn",
"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": 115,
    "service_tier": "standard",
    "inference_geo": "not_available"
}
}`}
  />
</Expandable>

<Expandable title="Async Responses">
  <ClaudeChatResponse
    groupId="async"
    successJson={`{
"id": "6e3d4989-9ea4-44d7-bce6-2f53916ea29c",
"object": "task",
"status": "pending",
"created_at": 1773041803
}`}
    title="Async Chat Responses"
  />
</Expandable>

<Expandable title="Streaming Responses">
  <ClaudeChatResponse
    groupId="stream"
    successJson={`
data: {"type":"message_start","message":{"model":"claude-sonnet-4-6","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 Chat 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.         |

### Streaming Events

| Event                 | Description                                           |
| --------------------- | ----------------------------------------------------- |
| `message_start`       | Indicates the start of a new message                  |
| `content_block_start` | Indicates the start of a content block                |
| `content_block_delta` | Contains incremental text content                     |
| `content_block_stop`  | Indicates the end of a content block                  |
| `message_delta`       | Contains final message metadata (stop\_reason, usage) |
| `message_stop`        | Indicates the end of the message                      |

## Parameters

| Field            | Type                      | Required | Default | Description                                                                                                                                      |
| :--------------- | :------------------------ | :------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------- |
| `model`          | `string`                  | ✅        | -       | The model ID to use for this request.                                                                                                            |
| `messages`       | `array<object>`           | ✅        | -       | An array of message objects representing the conversation history. See [Messages](#messages-array-structure)                                     |
| `max_tokens`     | `integer`                 | ✅        | `4096`  | The maximum number of tokens the model can generate in the response. Range `1-32000`                                                             |
| `async`          | `boolean`                 | -        | `false` | Whether to return an asynchronous response. Only supported for non-streaming requests.                                                           |
| `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. See [System](#system-array-structure)                                        |
| `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`          | `array<object>`           | -        | -       | A list of tools the model may call to generate the response. See [Tools](#tools-array-structure)                                                 |
| `tool_choice`    | `object`                  | -        | `auto`  | Controls how the model selects which tool(s) to use. Can be `auto` `any` `tool`. See [Tool Choices](#tool-choices-structure)                     |
| `thinking`       | `object`                  | -        | -       | Configuration for extended thinking (chain-of-thought) mode. See [Thinking](#thinking-structure)                                                 |
| `metadata`       | `object`                  | -        | -       | Optional metadata to associate with the request. See [Metadata](#metadata-structure)                                                             |

<Warning>
  If both `stream` and `async` are true, `stream` takes precedence.
</Warning>

### Messages Array Structure

| Field           | Type                | Required                | Default | Description                                                                                                                     |
| :-------------- | :------------------ | :---------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------ |
| `role`          | `string`            | ✅                       | -       | The role of the message. Can be: `user` or `assistant`                                                                          |
| `content`       | `string` \| `array` | ✅                       | -       | The content of the message. Can be a simple string for text-only messages, or an array of content blocks for multimodal content |
| `>content.type` | `string`            | ✅ if `content` is array | -       | Must be text                                                                                                                    |
| `>content.text` | `string`            | ✅ if `content` is array | -       | The text content                                                                                                                |

### System Array Structure

| Field  | Type     | Required | Default | Description                        |
| :----- | :------- | :------- | :------ | :--------------------------------- |
| `type` | `string` | ✅        | -       | The system tips, default `text`    |
| `text` | `string` | ✅        | -       | Describe the role the model plays. |

### Tools Array Structure

| Field             | Type      | Required | Default | Description                                                                                     |
| :---------------- | :-------- | :------- | :------ | :---------------------------------------------------------------------------------------------- |
| `type`            | `string`  | ✅        | -       | The type of tool. Must be web\_search\_20250305 for web search                                  |
| `name`            | `string`  | ✅        | -       | The name of the tool. Use web\_search                                                           |
| `max_uses`        | `integer` | -        | -       | Maximum number of times the web search tool can be used in a single request, range in `1-10`    |
| `allowed_domains` | `array`   | -        | -       | Only include search results from these domains. Cannot be used with blocked\_domains            |
| `blocked_domains` | `array`   | -        | -       | Never include search results from these domains. Cannot be used with allowed\_domains           |
| `user_location`   | `object`  | -        | -       | Localize search results based on user’s location. See [User Location](#user-location-structure) |

**Max Uses Structure**

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](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

### User Location Structure

The `user_location` object allows you to localize search results based on user's location:

| Field      | Type     | Required | Description                                                |
| :--------- | :------- | :------- | :--------------------------------------------------------- |
| `type`     | `string` | ✅        | The type of location. Must be `approximate`                |
| `city`     | `string` | -        | The city name (e.g., `San Francisco`)                      |
| `region`   | `string` | -        | The region or state (e.g., `California`)                   |
| `country`  | `string` | -        | The country code in ISO 3166-1 alpha-2 format (e.g., `US`) |
| `timezone` | `string` | -        | The IANA timezone ID (e.g., `America/Los_Angeles`)         |

### Tool Choices Structure

| Field  | Type     | Required | Description                                                                                                                                                                       |
| :----- | :------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type` | `string` | ✅        | Tool selection mode. `auto`: model decides whether to use a tool, `any`: model must use one of the available tools, `tool`: model must use the specific tool specified by `name`. |
| `name` | `string` | -        | The name of the specific tool to use. Required only when `type` is `tool`.                                                                                                        |

### Thinking Structure

| Field           | Type      | Required | Description                                                                                                                                                     |
| :-------------- | :-------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type`          | `string`  | ✅        | Thinking mode. `enabled`: model uses extended thinking for internal reasoning before generating the response, `disabled`: standard response mode.               |
| `budget_tokens` | `integer` | -        | Maximum tokens allocated for thinking. Required when `type` is `enabled`. The model uses these tokens for internal reasoning before producing the final output. |

### Metadata Structure

| Field     | Type     | Required | Description                                                                                                 |
| :-------- | :------- | :------- | :---------------------------------------------------------------------------------------------------------- |
| `user_id` | `string` | -        | An external identifier for the user making the request. Useful for analytics, abuse detection, and logging. |
