API-справочник
POST /audio/transcriptions принимает JSON: model, input_audio.data с base64 байтов и input_audio.format. Форматы: mp3, wav, flac, m4a, ogg, webm, aac; они также должны быть разрешены политикой файлов. Необязательные language, temperature и response_format=json/verbose_json. timestamp_granularities=word/segment требует verbose_json. Multipart пока не поддерживается.
POST /audio/speech принимает model, input и voice. Необязательные response_format=mp3/pcm и speed зависят от модели; исходный формат — pcm. HTTP 200 возвращает бинарные байты audio/mpeg либо audio/pcm. X-Generation-ID — собственный ID для состояния и расчёта через /requests/{id}. HTTP 202 возвращает JSON задачи; файл появится в её результате.
Для транскрибации задайте AI_SERVICE_AUDIO_BASE64 и AI_SERVICE_AUDIO_FORMAT; PHP-пример использует файл AI_SERVICE_AUDIO_PATH. Для голоса задайте AI_SERVICE_VOICE. Сохранённое аудио выдаётся только владельцу через /media/{id}; истечение срока хранения не создаёт повторную генерацию.
Аудио пока проверено на локальных ответах. Реальные платные проверки и публикация моделей требуют разрешённого объёма тестов и настроенных расчётов.
cURL · POST /audio/transcriptions
curl "https://formula-ai.ru/api/v1/audio/transcriptions" \
-H "Authorization: Bearer $AI_SERVICE_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: example-transcription-1" \
--data-binary "{
\"model\": \"$AI_SERVICE_MODEL\",
\"input_audio\": {
\"data\": \"$AI_SERVICE_AUDIO_BASE64\",
\"format\": \"$AI_SERVICE_AUDIO_FORMAT\"
}
}"
cURL · POST /audio/speech
curl "https://formula-ai.ru/api/v1/audio/speech" \
-H "Authorization: Bearer $AI_SERVICE_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: example-speech-1" \
--data-binary "{
\"model\": \"$AI_SERVICE_MODEL\",
\"input\": \"Hello from Formula AI\",
\"voice\": \"$AI_SERVICE_VOICE\",
\"response_format\": \"mp3\"
}" \
--output speech.bin --dump-header speech.headers --write-out "%{http_code}"
PHP · POST /audio/transcriptions
<?php
$key = getenv("AI_SERVICE_API_KEY");
$url = "https://formula-ai.ru/api/v1/audio/transcriptions";
$handle = curl_init($url);
curl_setopt_array($handle, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(["model" => getenv("AI_SERVICE_MODEL"), "input_audio" => ["data" => base64_encode(file_get_contents(getenv("AI_SERVICE_AUDIO_PATH"))), "format" => getenv("AI_SERVICE_AUDIO_FORMAT")]], JSON_THROW_ON_ERROR),
CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $key, "Content-Type: application/json", "Idempotency-Key: php-transcription-1"],
]);
if (getenv("AI_SERVICE_CA")) {
curl_setopt($handle, CURLOPT_CAINFO, getenv("AI_SERVICE_CA"));
}
$body = curl_exec($handle);
if ($body === false) {
throw new RuntimeException(curl_error($handle));
}
$status = curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
curl_close($handle);
$result = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
echo json_encode(["status" => $status, "result" => $result], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
PHP · POST /audio/speech
<?php
$key = getenv("AI_SERVICE_API_KEY");
$url = "https://formula-ai.ru/api/v1/audio/speech";
$handle = curl_init($url);
curl_setopt_array($handle, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode(["model" => getenv("AI_SERVICE_MODEL"), "input" => "Hello from Formula AI", "voice" => getenv("AI_SERVICE_VOICE"), "response_format" => "mp3"], JSON_THROW_ON_ERROR),
CURLOPT_HTTPHEADER => ["Authorization: Bearer " . $key, "Content-Type: application/json", "Idempotency-Key: php-speech-1"],
]);
if (getenv("AI_SERVICE_CA")) {
curl_setopt($handle, CURLOPT_CAINFO, getenv("AI_SERVICE_CA"));
}
$body = curl_exec($handle);
if ($body === false) {
throw new RuntimeException(curl_error($handle));
}
$status = curl_getinfo($handle, CURLINFO_RESPONSE_CODE);
curl_close($handle);
if ($status === 200) {
file_put_contents("speech.bin", $body);
echo "Saved speech.bin";
exit;
}
$result = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
echo json_encode(["status" => $status, "result" => $result], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
Схемы метода
Обязательные поля, типы, параметры и ответы описаны в OpenAPI 3.1. Полный машинный справочник
Показать JSON-схемы
{
"openapi": "3.1.1",
"info": {
"title": "Formula AI API",
"version": "1",
"description": "Методы нашего сервиса. Доступность модели и её параметров определяется опубликованным проверенным маршрутом. Suno: 23 музыкальные и вспомогательные операции, схемы и ограничения параметров. Streaming текста, изображений и аудио: SSE, сохранённые части и собственный расчёт."
},
"servers": [
{
"url": "https://formula-ai.ru/api/v1"
}
],
"security": [
{
"ClientKey": []
}
],
"paths": {
"/audio/transcriptions": {
"post": {
"operationId": "createTranscription",
"summary": "Преобразование речи в текст",
"description": "JSON-объект. Действуют ограничения выбранной модели и серверного окружения. Параметры допускаются только совместимым проверенным маршрутом; неподдержанные поля не отбрасываются. Повтор с прежним Idempotency-Key возвращает существующую операцию. После очистки её содержимого возвращается 410.",
"parameters": [
{
"name": "Idempotency-Key",
"in": "header",
"required": false,
"schema": {
"type": "string",
"minLength": 1,
"maxLength": 191,
"pattern": "^[A-Za-z0-9._:\\-]+$"
},
"description": "Область ключа — клиент. Изменение параметров с прежним ключом даёт 409."
},
{
"name": "Prefer",
"in": "header",
"schema": {
"type": "string"
},
"description": "respond-async: вернуть собственный ID без ожидания поставщика, в том числе при stream=true. Формат тела и Idempotency-Key сохраняются. Готовый повтор возвращает сохранённый результат."
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/TranscriptionInput"
}
}
}
},
"responses": {
"200": {
"description": "Готовый результат и клиентский расчёт.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/TranscriptionResult"
}
}
},
"headers": {
"X-Generation-ID": {
"schema": {
"$ref": "#/components/schemas/PublicId"
}
}
}
},
"202": {
"description": "Операция принята. Опросите GET /requests/{id}.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Request"
}
}
},
"headers": {
"X-Generation-ID": {
"schema": {
"$ref": "#/components/schemas/PublicId"
}
},
"Location": {
"schema": {
"type": "string"
},
"description": "Путь GET /api/v1/requests/{id}."
},
"Preference-Applied": {
"schema": {
"type": "string",
"const": "respond-async"
}
}
}
},
"502": {
"description": "Генерация завершилась ошибкой. Проверьте billing.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GenerationError"
}
}
},
"headers": {
"X-Generation-ID": {
"schema": {
"$ref": "#/components/schemas/PublicId"
}
}
}
},
"default": {
"description": "Ошибка валидации, настроек, доступа или баланса.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
},
"headers": {
"X-Generation-ID": {
"schema": {
"$ref": "#/components/schemas/PublicId"
}
}
}
}
}
}
},
"/audio/speech": {
"post": {
"operationId": "createSpeech",
"summary": "Синтез речи",
"description": "JSON-объект. Действуют ограничения выбранной модели и серверного окружения. Параметры допускаются только совместимым проверенным маршрутом; неподдержанные поля не отбрасываются. Повтор с прежним Idempotency-Key возвращает существующую операцию. После очистки её содержимого возвращается 410.",
"parameters": [
{
"name": "Idempotency-Key",
"in": "header",
"required": false,
"schema": {
"type": "string",
"minLength": 1,
"maxLength": 191,
"pattern": "^[A-Za-z0-9._:\\-]+$"
},
"description": "Область ключа — клиент. Изменение параметров с прежним ключом даёт 409."
},
{
"name": "Prefer",
"in": "header",
"schema": {
"type": "string"
},
"description": "respond-async: вернуть собственный ID без ожидания поставщика, в том числе при stream=true. Формат тела и Idempotency-Key сохраняются. Готовый повтор возвращает сохранённый результат."
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SpeechInput"
}
}
}
},
"responses": {
"202": {
"description": "Операция принята. Опросите GET /requests/{id}.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Request"
}
}
},
"headers": {
"X-Generation-ID": {
"schema": {
"$ref": "#/components/schemas/PublicId"
}
},
"Location": {
"schema": {
"type": "string"
},
"description": "Путь GET /api/v1/requests/{id}."
},
"Preference-Applied": {
"schema": {
"type": "string",
"const": "respond-async"
}
}
}
},
"502": {
"description": "Генерация завершилась ошибкой. Проверьте billing.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GenerationError"
}
}
},
"headers": {
"X-Generation-ID": {
"schema": {
"$ref": "#/components/schemas/PublicId"
}
}
}
},
"default": {
"description": "Ошибка валидации, настроек, доступа или баланса.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
},
"headers": {
"X-Generation-ID": {
"schema": {
"$ref": "#/components/schemas/PublicId"
}
}
}
},
"200": {
"description": "Готовые бинарные байты аудио. Состояние и расчёт доступны через GET /requests/{X-Generation-ID}.",
"headers": {
"X-Generation-ID": {
"schema": {
"$ref": "#/components/schemas/PublicId"
}
}
},
"content": {
"audio/mpeg": {
"schema": {
"type": "string",
"format": "binary"
}
},
"audio/pcm": {
"schema": {
"type": "string",
"format": "binary"
}
}
}
}
}
}
}
},
"components": {
"securitySchemes": {
"ClientKey": {
"type": "http",
"scheme": "bearer",
"description": "API-ключ клиента Formula AI."
}
},
"schemas": {
"PublicId": {
"type": "string",
"pattern": "^[a-f0-9]{32}$"
},
"Billing": {
"type": "object",
"properties": {
"currency": {
"const": "RUB"
},
"charged": {
"type": "string",
"pattern": "^-?[0-9]+\\.[0-9]{7}$",
"description": "Рубли, точная десятичная строка с 7 знаками."
},
"refunded": {
"type": "string",
"pattern": "^-?[0-9]+\\.[0-9]{7}$",
"description": "Рубли, точная десятичная строка с 7 знаками."
},
"status": {
"enum": [
"pending",
"confirmed"
]
}
},
"required": [
"currency",
"charged",
"refunded",
"status"
]
},
"Usage": {
"type": "object",
"description": "Применимые единицы: prompt_tokens, completion_tokens, total_tokens, input_tokens, output_tokens, token_details, images, videos, audio_seconds, duration_seconds. Счётчики могут быть точными численными строками. Поля себестоимости не выдаются."
},
"ErrorDetail": {
"type": "object",
"properties": {
"message": {
"type": "string"
},
"code": {
"type": "string"
},
"type": {
"type": "string"
},
"param": {
"type": [
"string",
"null"
]
}
},
"required": [
"message",
"code"
]
},
"Error": {
"type": "object",
"properties": {
"error": {
"$ref": "#/components/schemas/ErrorDetail"
},
"request_id": {
"$ref": "#/components/schemas/PublicId"
}
},
"required": [
"error",
"request_id"
]
},
"GenerationError": {
"type": "object",
"properties": {
"error": {
"$ref": "#/components/schemas/ErrorDetail"
},
"request_id": {
"$ref": "#/components/schemas/PublicId"
},
"billing": {
"$ref": "#/components/schemas/Billing"
}
},
"required": [
"error",
"request_id",
"billing"
]
},
"Request": {
"type": "object",
"properties": {
"id": {
"$ref": "#/components/schemas/PublicId"
},
"object": {
"const": "ai_service.request"
},
"model": {
"type": "string"
},
"operation": {
"type": "string"
},
"status": {
"enum": [
"queued",
"running",
"waiting",
"saving_media",
"uncertain",
"completed",
"failed",
"cancelled"
]
},
"created_at": {
"type": [
"string",
"null"
],
"description": "Время сервиса Europe/Moscow: YYYY-MM-DD HH:mm:ss, возможно дробная часть секунд."
},
"finished_at": {
"type": [
"string",
"null"
],
"description": "Время сервиса Europe/Moscow: YYYY-MM-DD HH:mm:ss, возможно дробная часть секунд."
},
"content_expires_at": {
"type": [
"string",
"null"
],
"description": "Время сервиса Europe/Moscow: YYYY-MM-DD HH:mm:ss, возможно дробная часть секунд."
},
"content_expired": {
"type": "boolean"
},
"usage": {
"$ref": "#/components/schemas/Usage"
},
"billing": {
"$ref": "#/components/schemas/Billing"
},
"result": {
"type": [
"object",
"null"
],
"description": "Результат выбранной операции. Файлы — только адреса Formula AI либо запрошенный base64."
},
"error": {
"anyOf": [
{
"$ref": "#/components/schemas/ErrorDetail"
},
{
"type": "null"
}
]
}
},
"required": [
"id",
"object",
"model",
"operation",
"status",
"created_at",
"finished_at",
"content_expires_at",
"content_expired",
"usage",
"billing",
"result",
"error"
]
},
"TranscriptionInput": {
"type": "object",
"properties": {
"model": {
"type": "string",
"minLength": 1
},
"input_audio": {
"type": "object",
"properties": {
"data": {
"type": "string",
"minLength": 1,
"maxLength": 16000000,
"description": "Base64 байтов файла; data URI не принимается."
},
"format": {
"enum": [
"mp3",
"wav",
"flac",
"m4a",
"ogg",
"webm",
"aac"
]
}
},
"required": [
"data",
"format"
]
},
"language": {
"type": "string",
"pattern": "^[a-z]{2}$"
},
"temperature": {
"type": "number",
"minimum": 0,
"maximum": 2
},
"response_format": {
"enum": [
"json",
"verbose_json"
]
},
"timestamp_granularities": {
"type": "array",
"items": {
"enum": [
"word",
"segment"
]
},
"description": "Только при response_format=verbose_json."
}
},
"required": [
"model",
"input_audio"
],
"additionalProperties": false
},
"SpeechInput": {
"type": "object",
"properties": {
"model": {
"type": "string",
"minLength": 1
},
"input": {
"type": "string",
"minLength": 1,
"maxLength": 1000000
},
"voice": {
"type": "string",
"minLength": 1,
"maxLength": 255
},
"response_format": {
"enum": [
"mp3",
"pcm"
],
"description": "По умолчанию pcm; поддержка формата зависит от модели."
},
"speed": {
"type": "number",
"exclusiveMinimum": 0
}
},
"required": [
"model",
"input",
"voice"
],
"additionalProperties": false
},
"TranscriptionResult": {
"type": "object",
"properties": {
"id": {
"$ref": "#/components/schemas/PublicId"
},
"model": {
"type": "string"
},
"usage": {
"$ref": "#/components/schemas/Usage"
},
"ai_service": {
"type": "object",
"properties": {
"request_id": {
"$ref": "#/components/schemas/PublicId"
},
"billing": {
"$ref": "#/components/schemas/Billing"
}
},
"required": [
"request_id",
"billing"
]
},
"text": {
"type": "string"
},
"task": {
"type": "string"
},
"language": {
"type": "string"
},
"duration": {
"type": "number"
},
"segments": {
"type": "array",
"items": {
"type": "object"
}
},
"words": {
"type": "array",
"items": {
"type": "object"
}
}
},
"required": [
"id",
"model",
"ai_service",
"text"
]
}
}
},
"externalDocs": {
"url": "https://formula-ai.ru/docs"
}
}Примеры cURL используют Bash. Задайте AI_SERVICE_API_KEY и AI_SERVICE_MODEL; модель выберите из /models. В PHP для опроса/файла задайте AI_SERVICE_REQUEST_ID/AI_SERVICE_MEDIA_ID, для правки — AI_SERVICE_SOURCE_URL. Для локального сертификата используйте доверенный CA через --cacert, для PHP — AI_SERVICE_CA. Проверку TLS сохраняйте включённой.