# Chat with an assistant

Source: [Chat with an assistant](<https://docs.gptunnel.ru/en/api/assistants/chat/>)

<a id="_top"></a>
Authenticate requests with your [API key](<https://docs.gptunnel.ru/en/#get-an-api-key>).

<a id="request"></a>
## Request

`POST https://gptunnel.ru/v1/assistant/chat`

Send a message to an assistant and receive its reply in the context of the conversation.

### Request headers

| Parameter | Type | Description |
| --- | --- | --- |
| `Authorization` (required) | `string` | API key |

### Request body

| Parameter | Type | Description |
| --- | --- | --- |
| `chatId` (required) | `string` | Unique chat ID generated by the client, 24–36 characters. |
| `assistantCode` (required) | `string` | The mention returned when you create the assistant. |
| `message` (required) | `string` | Message to the assistant |
| `maxContext` | `number` | Number of previous messages to include in context, from 0 to 20. Defaults to 0. To continue the chat, send the same chatId and a positive value. |
| `images` | `Array<string>` | Array of image URLs for vision input. |
| `stream` | `boolean` | true requests a stream response (experimentally). The default returns JSON. |

<a id="example-request"></a>
### Example request

Set `GPTUNNEL_API_KEY` to your key. Set `GPTUNNEL_ASSISTANT_CODE` to the `mention` from the assistant creation response. Generate a UUID for this conversation and store it in `GPTUNNEL_CHAT_ID`. The example sends the first message. For a follow-up such as “What word did I ask you to remember?”, reuse the same `chatId` and pass `maxContext: 2`.

<a id="tab-panel-0-0"></a>
**Python**

```python
import json
import os
from urllib.request import Request, urlopen

body = {
  "assistantCode": os.environ['GPTUNNEL_ASSISTANT_CODE'],
  "chatId": os.environ['GPTUNNEL_CHAT_ID'],
  "message": "Запомни слово КЕДР. Ответь только этим словом.",
  "maxContext": 0
}
request = Request(
    'https://gptunnel.ru/v1/assistant/chat',
    headers={
        'Authorization': os.environ['GPTUNNEL_API_KEY'],
        'Content-Type': 'application/json',
    },
    data=json.dumps(body).encode('utf-8'),
)
with urlopen(request, timeout=60) as response:
    print(json.load(response))
```

<a id="tab-panel-0-1"></a>
**cURL**

```bash
curl --request POST \
  --url 'https://gptunnel.ru/v1/assistant/chat' \
  --header "Authorization: ${GPTUNNEL_API_KEY:?Set GPTUNNEL_API_KEY}" \
  --header 'Content-Type: application/json' \
  --data '{
  "assistantCode": "'"${GPTUNNEL_ASSISTANT_CODE:?Set GPTUNNEL_ASSISTANT_CODE}"'",
  "chatId": "'"${GPTUNNEL_CHAT_ID:?Set GPTUNNEL_CHAT_ID}"'",
  "message": "Запомни слово КЕДР. Ответь только этим словом.",
  "maxContext": 0
}'
```

<a id="tab-panel-0-2"></a>
**JavaScript (Node.js)**

```javascript
const response = await fetch('https://gptunnel.ru/v1/assistant/chat', {
  method: 'POST',
  headers: {
    Authorization: process.env.GPTUNNEL_API_KEY,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "assistantCode": process.env.GPTUNNEL_ASSISTANT_CODE,
    "chatId": process.env.GPTUNNEL_CHAT_ID,
    "message": "Запомни слово КЕДР. Ответь только этим словом.",
    "maxContext": 0
  }),
})
if (!response.ok) throw new Error(await response.text())
console.log(await response.json())
```

<a id="example-response"></a>
### Example response

`usage` covers the entire turn. If the assistant calls functions, MCP tools, or knowledge base search as a tool, the token counts and charges from all calls are added together. For a billed request, `total_cost` is the amount actually charged in RUB after your discount.

Knowledge base search in the every-request or first-message mode runs before the model call. It is billed separately and is excluded from `usage`. Search in function mode is included. When there is no charge, such as for a free model, the cost fields show an estimate. The `prompt_cost` and `completion_cost` fields are parts of the same charge, so token count multiplied by the list price may give a different amount.

<a id="tab-panel-1-0"></a>
**200 OK**

Part of the response to the request to repeat “KEDR”.

```json
{
  "chatId": "a11e52c2-5ecc-4d86-a9fa-0cac92414a72",
  "assistantId": "68c9b2d1e4b0a2d3c4f5e6b8",
  "assistantCode": "example-assistant",
  "message": "КЕДР",
  "model": "gpt-6-luna",
  "usage": {
    "context_messages": 2,
    "prompt_tokens": 1175,
    "completion_tokens": 37,
    "total_tokens": 1212,
    "total_cost": 0.03116
  }
}
```

<a id="tab-panel-1-1"></a>
**404 Not Found**

```json
{
  "error": {
    "param": null,
    "code": null,
    "type": "invalid_request_error",
    "message": "Assistant not found"
  }
}
```

<a id="tab-panel-1-2"></a>
**401 Unauthorized**

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

<a id="tab-panel-1-3"></a>
**403 Model Not Allowed**

The assistant’s model is not on the list of authorized models for this API key. The list is set up in key settings in a dashboard.

```json
{
  "error": {
    "message": "Model 'gpt-6-luna' is not allowed for this API key.",
    "type": "permission_error",
    "param": "model",
    "code": "model_not_allowed"
  }
}
```

<a id="streaming-response"></a>
### Streaming response

With `stream: true`, the server returns `Content-Type: text/event-stream`. Each nonempty line contains a JSON object without a `data:` prefix. Read the stream line by line, skip blank lines, and append each `delta` to the response text. The final object contains `finishReason`.

For a response of “4”, the first object contained `"delta": ""`, followed by an object with `"delta": "4"` and `"finishReason": "stop"`. See the separate [Chat Completions streaming format](<https://docs.gptunnel.ru/en/api/chat-completions/streaming/>).
