# Запрос чату

{% hint style="info" %}
Чтобы отправлять авторизованные запросы нужно получить API ключ, как это сделать написано в разделе [**С чего начать?**](https://docs.gptunnel.ru/)
{% endhint %}

## Диалог с чатом

<mark style="color:green;">`POST`</mark> `https://gptunnel.ru/v1/chat/completions`

Синхронный запрос к моделям ChatGPT

#### Headers

| Name                                            | Type   | Description |
| ----------------------------------------------- | ------ | ----------- |
| Authorization<mark style="color:red;">\*</mark> | string | API ключ    |

#### Request Body

| Name                                       | Type   | Description              |
| ------------------------------------------ | ------ | ------------------------ |
| model<mark style="color:red;">\*</mark>    | string | ID модели чата           |
| messages<mark style="color:red;">\*</mark> | array  | Контекст сообщений       |
| max\_tokens                                | number | Длина ответа (MAX 4096)  |
| temperature                                | number | Креативность (от 0 до 1) |
| top\_p                                     | number |                          |
| frequency\_penalty                         | number |                          |
| presence\_penalty                          | number |                          |
| functions                                  | object |                          |
| useWalletBalance                           | bool   | Использовать личный счет |

{% tabs %}
{% tab title="200: OK Успешный ответ" %}
{% code fullWidth="false" %}

```
{
  "id": "chatcmpl-8FheRf68Hi4pnuiRqYPHyZJr3UlAU",
  "object": "chat.completion",
  "created": 1698753407,
  "model": "gpt-3.5-turbo-0613",
  "choices": [
    {
      "index": 0,
      "message": {
      	"role": "assistant",
        "content": "Меня зовут Robert."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 24,
    "completion_tokens": 8,
    "total_tokens": 32,
    "prompt_cost": 0.01608,
    "completion_cost": 0.007200000000000001,
    "total_cost": 0.023280000000000002
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="404: Not Found Модель не найдена" %}

```json
{
  "error": {
    "message": "The model 'gpt-5' does not exist",
    "type": "invalid_request_error",
    "param": null,
    "code": "model_not_found"
  }
}
```

{% endtab %}

{% tab title="400: Bad Request Неверный запрос" %}

```json
{
  "error": {
    "message": "'model' is a required property",
    "type": "invalid_request_error",
    "param": null,
    "code": null
  }
}
```

{% endtab %}

{% tab title="402: Payment Required Недостаточно средств" %}

```json
{
  "error": {
    "message": "Organization balance is too low to use API",
    "type": "insufficient_balance_error",
    "param": null,
    "code": null
  }
}
```

{% endtab %}

{% tab title="401: Unauthorized Ошибка авторизации" %}

```json
{
  "error": {
    "message": "Unauthorized",
    "type": "unauthorized_request_error",
    "param": null,
    "code": null,
  }
}
```

{% endtab %}
{% endtabs %}

### Пример запроса

{% tabs %}
{% tab title="NodeJS" %}

```typescript
import axios from 'axios'

const request = axios({
  method: 'POST',
  url: 'https://gptunnel.ru/v1/chat/completions',
  headers: {
    // use your API key here
    Authorization: 'YOUR_API_KEY',
  },
  data: {
    model: "gpt-3.5-turbo",
    max_tokens: 100,
    messages: [
      {
        role: "system",
        content: "My name is Robert.",
      },
      {
        role: "user",
        content: "как тебя зовут",
      },
    ],
  },
})

request.then((result) => {
  console.log(result)
}).catch((error) => {
  console.error(error)
})
```

{% endtab %}

{% tab title="Curl" %}

```bash
curl --request POST \
  --url https://gptunnel.ru/v1/chat/completions \
  --header 'Authorization: YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
	"model": "gpt-3.5-turbo",
	"max_tokens": 100,
	"messages": [
		{
			"role": "system",
			"content": "My name is Robert."
		},
		{
			"role": "user",
			"content": "как тебя зовут"
		}
	]
}'
```

{% endtab %}
{% endtabs %}

### Пример ответа

```json
{
  "id": "chatcmpl-8FheRf68Hi4pnuiRqYPHyZJr3UlAU",
  "object": "chat.completion",
  "created": 1698753407,
  "model": "gpt-3.5-turbo-0613",
  "choices": [
    {
      "index": 0,
      "message": {
      	"role": "assistant",
        "content": "Меня зовут Robert."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 24,
    "completion_tokens": 8,
    "total_tokens": 32,
    "prompt_cost": 0.01608,
    "completion_cost": 0.007200000000000001,
    "total_cost": 0.023280000000000002
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.gptunnel.ru/api-chatgpt/chat-completions-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
