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

# Chat

> Create an chat message

export const GeminiApiResponse = ({successJson, successTitle = "200 - Success", streaming = false}) => {
  const error400 = `{
   "error": {
        "code": 400,
        "message": "Invalid request error",
        "status": "INVALID_ARGUMENT"
   }
}`;
  const error401 = `{
   "error": {
        "code": 401,
        "message": "Invalid API Key",
        "status": "UNAUTHENTICATED"
   }
}`;
  const error402 = `{
   "error": {
        "code": 402,
        "message": "Insufficient balance",
        "status": "INSUFFICIENT_BALANCE"
   }
}`;
  const error403 = `{
   "error": {
        "code": 403,
        "message": "Permission denied on this model",
        "status": "PERMISSION_DENIED"
   }
}`;
  const error404 = `{
   "error": {
        "code": 404,
        "message": "Invalid URL",
        "status": "INVALID_ARGUMENT"
   }
}`;
  const error429 = `{
   "error": {
        "code": 429,
        "message": "Too many requests",
        "status": "RATE_LIMIT_ERROR"
   }
}`;
  const error500 = `{
    "error": {
        "code": 500,
        "message": "Internal server error",
        "status": "INTERNAL_ERROR"
   }
}`;
  return <>
      <h2>Response Examples</h2>

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

export const GeminiChatOfficialRequest = ({model = "gemini-2.5-flash"}) => {
  const curlExample = `curl --request POST \\
  --url https://aiandgpu.com/v1beta/models/${model}:generateContent \\
  --header 'Authorization: Bearer <YOUR_API_KEY>' \\
  --header 'Content-Type: application/json' \\
  --data '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "who are you?"
          }
        ]
      }
    ],
    "generationConfig": {
      "thinkingConfig": {
        "includeThoughts": true,
        "thinkingBudget": 1000
      }
    }
}'`;
  const pythonExample = `import requests

url = "https://aiandgpu.com/v1beta/models/${model}:generateContent"

payload = {
    "contents": [
        {
            "role": "user",
            "parts": [
                {
                    "text": "who are you?"
                }
            ]
        }
    ],
    "generationConfig": {
        "thinkingConfig": {
            "includeThoughts": True,
            "thinkingBudget": 1000
        }
    }
}

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/v1beta/models/${model}:generateContent', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <YOUR_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    contents: [
      {
        role: 'user',
        parts: [
          {
            text: 'who are you?'
          }
        ]
      }
    ],
    generationConfig: {
      thinkingConfig: {
        includeThoughts: true,
        thinkingBudget: 1000
      }
    }
  })
});

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/v1beta/models/${model}:generateContent"

\tpayload := strings.NewReader("{\\"contents\\": [{\\"role\\": \\"user\\", \\"parts\\": [{\\"text\\": \\"who are you?\\"}]}], \\"generationConfig\\": {\\"thinkingConfig\\": {\\"includeThoughts\\": true, \\"thinkingBudget\\": 1000}}}")

\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 = """
{
  "contents": [
    {
      "role": "user",
      "parts": [{"text": "who are you?"}]
    }
  ],
  "generationConfig": {
    "thinkingConfig": {
      "includeThoughts": true,
      "thinkingBudget": 1000
    }
  }
}
""";

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://aiandgpu.com/v1beta/models/${model}:generateContent"))
    .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([
    'contents' => [
        [
            'role' => 'user',
            'parts' => [
                ['text' => 'who are you?']
            ]
        ]
    ],
    'generationConfig' => [
        'thinkingConfig' => [
            'includeThoughts' => true,
            'thinkingBudget' => 1000
        ]
    ]
]);

curl_setopt_array($curl, [
    CURLOPT_URL => "https://aiandgpu.com/v1beta/models/${model}:generateContent",
    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 = @"{
    ""contents"": [
        {
            ""role"": ""user"",
            ""parts"": [{""text"": ""who are you?""}]
        }
    ],
    ""generationConfig"": {
        ""thinkingConfig"": {
            ""includeThoughts"": true,
            ""thinkingBudget"": 1000
        }
    }
}";

var request = new HttpRequestMessage(HttpMethod.Post, "https://aiandgpu.com/v1beta/models/${model}:generateContent");
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>
    </>;
};

export const PathParameters = ({model = "gemini-2.0-flash"}) => {
  return <>
      <h2>Path Parameters</h2>
      <p>Endpoint: <code>{"https://aiandgpu.com/v1beta/models/{model}:{action}"}</code></p>

      <table>
        <thead>
          <tr>
            <th>Action</th>
            <th>Example</th>
            <th>Description</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td><code>{`generateContent`}</code></td>
            <td>
              <code>{`/v1beta/models/${model}:generateContent`}</code>
            </td>
            <td>The action to generate content using the specified model.</td>
          </tr>
          <tr>
            <td><code>{`streamGenerateContent`}</code></td>
            <td>
              <code>{`/v1beta/models/${model}:streamGenerateContent`}</code>
            </td>
            <td>The action to stream generated content using the specified model.</td>
          </tr>
        </tbody>
      </table>
    </>;
};

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

<PathParameters model="gemini-3.1-pro-preview-customtools" />

<GeminiChatOfficialRequest model="gemini-3.1-pro-preview-customtools" />

<GeminiApiResponse
  successJson={`{
"candidates": [
    {
        "content": {
            "parts": [
                {
                    "text": "Hello! How can I help you today?"
                }
            ],
            "role": "model"
        },
        "finishReason": "STOP",
        "index": 0
    }
],
"usageMetadata": {
    "promptTokenCount": 2,
    "candidatesTokenCount": 9,
    "totalTokenCount": 43,
    "promptTokensDetails": [
        {
            "modality": "TEXT",
            "tokenCount": 2
        }
    ],
    "thoughtsTokenCount": 32
},
"modelVersion": "gemini-3.1-pro-preview-customtools",
"responseId": "2oqmafK8M-7D-sAP2vKm2QU"
}`}
/>

## Request Body

### Core Parameters

| Field                   | Type   | Required | Default | Description                                                                                                                                                                                                  |
| :---------------------- | :----- | :------- | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `contents`              | array  | ✅        | -       | Content of the current conversation with the model. For single-turn queries, this contains one instance. For multi-turn queries (e.g., chat), this contains the conversation history and the latest request. |
| `>contents.role`        | string | ✅        | -       | The role of the message sender. Can be `user` `model`.                                                                                                                                                       |
| `>contents.parts`       | array  | ✅        | -       | The content parts of the message, which can contain different types of content (text, inlineData, etc.).                                                                                                     |
| `>>contents.parts.text` | string | ✅        | -       | Text content of the part. For multimodal input details                                                                                                                                                       |

### Advanced Parameters

| Field               | Type            | Required | Description                                                                                                                                                                 |
| :------------------ | :-------------- | :------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `generationConfig`  | `object`        | -        | Configuration options for content generation. See [Generation Configuration](#generation-configuration-structure)                                                           |
| `safetySettings`    | `array<object>` | -        | List of unique SafetySetting instances for filtering unsafe content. Each SafetyCategory should have at most one setting. See [Safety Settings](#safety-settings-structure) |
| `tools`             | `array<object>` | -        | List of tools the model may use to generate the next response. Supported tools include Function and codeExecution.                                                          |
| `systemInstruction` | `object`        | -        | See [System instruction](#system-instruction-structure).                                                                                                                    |
| `async`             | `boolean`       | -        | Whether to provide asynchronous responses (only supports non-streaming requests)                                                                                            |

### Generation Configuration Structure

| Field              | Type            | Required | Description                                                        |
| :----------------- | :-------------- | :------- | :----------------------------------------------------------------- |
| `temperature`      | `number`        | -        | Controls the randomness of the output. Range in `0.0 - 1.0`.       |
| `topP`             | `number`        | -        | Nucleus sampling probability threshold. Range in `0.0 - 1.0`.      |
| `topK`             | `integer`       | -        | Top-k sampling parameter.                                          |
| `maxOutputTokens`  | `integer`       | -        | Maximum number of tokens to generate.                              |
| `stopSequences`    | `array<string>` | -        | Sequences at which to stop generation.                             |
| `responseMimeType` | `string`        | -        | MIME type of the response. Can be `text/plain` `application/json`. |

### Safety Settings Structure

| Field       | Type     | Required | Range                                                                                                                                                      | Description                                       |
| :---------- | :------- | :------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------ |
| `category`  | `string` | ✅        | `HARM_CATEGORY_HATE_SPEECH` `HARM_CATEGORY_SEXUALLY_EXPLICIT` `HARM_CATEGORY_DANGEROUS_CONTENT` `HARM_CATEGORY_HARASSMENT` `HARM_CATEGORY_CIVIC_INTEGRITY` | The harm category to apply the safety setting to. |
| `threshold` | `string` | ✅        | `BLOCK_ONLY_HIGH` `BLOCK_MEDIUM_AND_ABOVE` `BLOCK_LOW_AND_ABOVE` `BLOCK_NONE`                                                                              | The threshold for blocking content.               |

### Tools Structure

| Field                                      | Type     | Required | Range                               | Description                                                                                                                        |
| :----------------------------------------- | :------- | :------- | :---------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- |
| `googleSearch`                             | `object` | -        | -                                   | Array of tools to use for the request.                                                                                             |
| `>googleSearch.timeRangeFilter`            | `object` | -        | -                                   | Optional time range filter for the search.                                                                                         |
| `>>googleSearch.timeRangeFilter.startTime` | `string` | -        | `2024-01-01T00:00:00Z` or timestamp | Optional start time for the search in ISO 8601 format or timestamp.                                                                |
| `>>googleSearch.timeRangeFilter.endTime`   | `string` | -        | `2024-01-01T00:00:00Z` or timestamp | Optional end time for the search in ISO 8601 format or timestamp. Note: For Gemini 3 models, the time span cannot exceed 24 hours. |

### System Instruction Structure

| Field         | Type            | Required | Range  | Description                                                                                                                       |
| :------------ | :-------------- | :------- | :----- | :-------------------------------------------------------------------------------------------------------------------------------- |
| `role`        | `string`        | -        | `user` | The role for the system instruction. If specified, must be `user`.                                                                |
| `parts`       | `array<object>` | ✅        | -      | The content parts of the system instruction, containing the instructional text for the model.                                     |
| `>parts.text` | `string`        | ✅        | -      | The text content of the system instruction. Used to set the model's behavior, persona, or context before the conversation begins. |
