> ## 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 OpenAIChatRequest = ({model = "gemini-2.5-flash", path = "/v1/chat/completions"}) => {
  const curlExample = `curl --request POST \\
  --url https://aiandgpu.com${path} \\
  --header 'Authorization: Bearer <YOUR_API_KEY>' \\
  --header 'Content-Type: application/json' \\
  --data '{
    "model": "${model}",
    "messages": [
        {
            "role": "user",
            "content": [
              {
                "type": "text", 
                "text": "Hello"
              }
            ]
        }
    ]
}'`;
  const pythonExample = `import requests

url = "https://aiandgpu.com${path}"

payload = {
    "model": "${model}",
    "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.json())`;
  const jsExample = `const response = await fetch('https://aiandgpu.com${path}', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <YOUR_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: '${model}',
    messages: [
      {
        role: 'user', 
        content: [
          {
            type: 'text', 
            text: 'Hello'
          }
        ]
      }
    ]
  })
});

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${path}"

\tpayload := strings.NewReader("{\\"model\\": \\"${model}\\", \\"messages\\": [{\\"role\\": \\"user\\", \\"content\\": [{\\"type\\": \\"text\\", \\"text\\": \\"Hello\\"}]}]}")

\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}",
  "messages": [
    {
      "role": "user",
      "content": [{"type": "text", "text": "Hello"}]
    }
  ]
}
""";

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://aiandgpu.com${path}"))
    .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}',
    'messages' => [
        [
            'role' => 'user',
            'content' => [
                ['type' => 'text', 'text' => 'Hello']
            ]
        ]
    ]
]);

curl_setopt_array($curl, [
    CURLOPT_URL => "https://aiandgpu.com${path}",
    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}"",
    ""messages"": [
        {
            ""role"": ""user"",
            ""content"": [{""type"": ""text"", ""text"": ""Hello""}]
        }
    ]
}";

var request = new HttpRequestMessage(HttpMethod.Post, "https://aiandgpu.com${path}");
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 OpenAIApiResponse = ({successJson, successTitle = "200 - Success", streaming = false}) => {
  const error400 = `{
    "error": {
        "code": "invalid_params",
        "message": "parameter 'ARGUMENT' is required",
        "param": null,
        "type": "invalid_request_error"
    }
}`;
  const error401 = `{
    "error": {
        "code": "auth_invalid",
        "message": "Invalid API Key",
        "param": null,
        "type": "authentication_error"
    }
}`;
  const error402 = `{
    "error": {
        "code": "insufficient_quota",
        "message": "You exceeded your current quota, please check your plan and billing details.",
        "param": null,
        "type": "insufficient_quota_error"
    }
}`;
  const error403 = `{
    "error": {
        "code": "permission_error",
        "message": "You have no permission to access the model.",
        "type": "permission_error",
        "param": null
    }
}`;
  const error404 = `{
    "error": {
        "code": "invalid_request_error",
        "message": "Invalid URL",
        "param": null,
        "type": "invalid_request_error"
    }
}`;
  const error429 = `{
    "error": {
        "code": "rate_limit_exceeded",
        "message": "Rate limit reached",
        "param": null,
        "type": "rate_limit_error"
    }
}`;
  const error500 = `{
    "error": {
        "code": "server_error",
        "message": "Internal server error",
        "param": null,
        "type": "server_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>
    </>;
};

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

<OpenAIChatRequest model="gpt-5.3-codex" />

<OpenAIApiResponse
  successJson={`{
"choices": [
    {
        "content_filter_results": {},
        "finish_reason": "stop",
        "index": 0,
        "logprobs": null,
        "message": {
            "annotations": [],
            "content": "你好！有什么可以帮助您的吗？",
            "refusal": null,
            "role": "assistant"
        }
    }
],
"created": 1772531821,
"id": "chatcmpl-DFGmrLm5XfAElt3sLtzdaKCVudi0g",
"model": "gpt-5.3-codex",
"object": "chat.completion",
"prompt_filter_results": [
    {
        "prompt_index": 0,
        "content_filter_results": {}
    }
],
"system_fingerprint": null,
"usage": {
    "completion_tokens": 27,
    "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 0,
        "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 7,
    "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 0
    },
    "total_tokens": 34
}
}`}
/>

## Request Body

### Core Parameters

| Field                     | Type         | Required | Default | Description                                                                                             |
| :------------------------ | :----------- | :------- | :------ | :------------------------------------------------------------------------------------------------------ |
| `model`                   | string       | ✅        | -       | The model identifier to use for this request, e.g. `gemini-2.5-flash`.                                  |
| `messages`                | array        | ✅        | -       | An array of message objects representing the conversation history. Messages are processed in order.     |
| `>messages.role`          | string       | ✅        | -       | The role of the message author. Valid values: `system`, `user`, `assistant`.                            |
| `>messages.content`       | string/array | ✅        | -       | The content of the message. Can be a simple string or an array of content blocks for multimodal inputs. |
| `>>messages.content.type` | string       | ✅        | -       | The type of content block. Supported: `text`, `image_url`.                                              |
| `>>messages.content.text` | string       | ✅        | -       | The text content. Required when `type` is `text`.                                                       |

### Generation Parameters

| Field               | Type         | Required | Default | Description                                                                                                                                              |
| :------------------ | :----------- | :------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `max_tokens`        | integer      | -        | -       | The maximum number of tokens the model can generate in the response.                                                                                     |
| `temperature`       | float        | -        | `1.0`   | Controls the randomness of the output. Lower values produce more focused responses, higher values produce more creative outputs. Range in `0.0` - `2.0`. |
| `top_p`             | float        | -        | `1.0`   | Nucleus sampling parameter. The model considers tokens with top\_p cumulative probability mass. Range in `0.0` - `1.0`.                                  |
| `stream`            | boolean      | -        | `false` | If `true`, returns a stream of server-sent events (SSE) as the response is generated.                                                                    |
| `stop`              | string/array | -        | -       | Up to 4 sequences where the API will stop generating further tokens.                                                                                     |
| `n`                 | integer      | -        | `1`     | How many chat completion choices to generate for each input message.                                                                                     |
| `presence_penalty`  | float        | -        | `0`     | Penalizes new tokens based on whether they appear in the text so far. Range in `-2.0` - `2.0`.                                                           |
| `frequency_penalty` | float        | -        | `0`     | Penalizes new tokens based on their existing frequency in the text so far. Range in `-2.0` - `2.0`.                                                      |

### Advanced Parameters

| Field         | Type            | Required | Default | Description                                                                                               |
| :------------ | :-------------- | :------- | :------ | :-------------------------------------------------------------------------------------------------------- |
| `tools`       | `array<object>` | -        | -       | A list of tools the model may call. Use this to provide functions the model can generate JSON inputs for. |
| `tool_choice` | string/object   | -        | `auto`  | Controls which tool is called. `none`: no tool, `auto`: model decides, `required`: must call a tool.      |
| `user`        | string          | -        | -       | A unique identifier representing your end-user, which can help to monitor and detect abuse.               |

### Tools Structure

| Field                            | Type     | Required | Default | Description                                  |
| :------------------------------- | :------- | :------- | :------ | :------------------------------------------- |
| `type`                           | `string` | -        | -       | Utility types, currently generally functions |
| `function`                       | `object` | -        | -       | Function definition                          |
| `>function.name`                 | `string` | -        | -       | The function name                            |
| `>function.description`          | `string` | -        | -       | Function usage description                   |
| `>function.parameters`           | `object` | -        | -       | Function parameter definition                |
| `>>function.parameters.location` | `string` | ✅        | -       | City name                                    |
| `>>function.parameters.unit`     | `string` | -        | -       | Can be `celsius` `fahrenheit`                |
