> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ascn.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Генерация текста

> Chat Completions, Responses и потоковый вывод.

Для текста доступны два протокола OpenAI. Используйте модели с `kind: text` из `GET /v1/models`.

## Chat Completions

```http theme={null}
POST /v1/chat/completions
```

Каждое поле протокола передаётся модели как есть — `tools`, `tool_choice`, `response_format`, `logprobs`, `seed`, `stop` и остальные. Учитывает ли модель поле, решает сама модель.

<ParamField body="model" type="string" required>
  `id` модели, например `deepseek/deepseek-v4-flash`.
</ParamField>

<ParamField body="messages" type="object[]" required>
  История диалога. `role`: `system`, `developer`, `user`, `assistant` или `tool`. `content`: текст или массив частей (`text`, `image_url`, …).
</ParamField>

<ParamField body="max_tokens" type="integer">
  Лимит выходных токенов, включая рассуждения.
</ParamField>

<ParamField body="stream" default="false" type="boolean" />

<ParamField body="temperature" type="number">
  От 0 до 2.
</ParamField>

<ParamField body="reasoning_effort" type="string">
  `minimal`, `low`, `medium` или `high`.
</ParamField>

<ParamField body="tools" type="object[]" />

<ParamField body="tool_choice" type="string | object">
  `none`, `auto`, `required` или выбор конкретного инструмента.
</ParamField>

Ответ — стандартный объект `chat.completion` с `choices` (`message`, `finish_reason`: `stop`, `length`, `tool_calls`, `content_filter`) и `usage`. `completion_tokens` включает скрытые токены рассуждений.

```bash Вызов инструментов theme={null}
curl https://b2b.api.ascn.ai/api/ai-gateway/v1/chat/completions \
  -H "X-API-KEY: $ASCN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "messages": [{"role": "user", "content": "What is the weather in Berlin?"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Current weather for a city.",
        "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
      }
    }]
  }'
```

## Responses

```http theme={null}
POST /v1/responses
```

Для кода, написанного под `client.responses.create`. Обязательные поля — `model` и `input` (строка или массив сообщений); также `instructions`, `max_output_tokens`, `temperature`, `tools`, `stream`.

<Warning>
  Ответы не сохраняются. `previous_response_id` и получение ответа позже не поддерживаются — передавайте всю историю в `input`.
</Warning>

```python theme={null}
response = client.responses.create(
    model="openai/gpt-4o-mini",
    input="Summarise the CAP theorem in three bullets.",
    max_output_tokens=400,
)
print(response.output_text)
```

## Потоковый вывод

Передайте `"stream": true`, чтобы получать ответ через Server-Sent Events. Поток заканчивается `data: [DONE]`.

* **Chat Completions** — `stream_options.include_usage` включён всегда, последний чанк содержит `usage`.
* **Responses** — события `response.output_text.delta`, …, `response.completed`; `usage` — в `response.completed`.

<Tip>
  Используйте поток для длинных ответов. Длинный ответ без потока может быть отклонён с `streaming_required`.
</Tip>

```python theme={null}
stream = client.chat.completions.create(
    model="anthropic/claude-haiku-4.5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Explain mixture-of-experts in one paragraph."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
```

Уже начавшийся поток не переключается на другой бэкенд. При сбое посреди ответа поток завершится чанком `data: {"error": {…}}` и затем `data: [DONE]` — считайте полученное неполным ответом.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.