Коды статуса
The API uses standard HTTP status codes: 2xx means success, 4xx means a problem with the request, and 5xx means an error on our side or a temporarily unavailable model. Rely on the status code first.
API использует стандартные коды HTTP: 2xx — успех, 4xx — ошибка в запросе, 5xx — ошибка на нашей стороне или временная недоступность модели. Ориентируйтесь прежде всего на код статуса.
API standart HTTP kodlaridan foydalanadi: 2xx — muvaffaqiyat, 4xx — so'rovdagi xato, 5xx — bizning tomondagi xato yoki modelning vaqtincha ishlamay qolishi. Avvalo status kodiga qarang.
Формат ошибки
Endpoint errors (request validation, billing, permissions, model failures) use the OpenAI-compatible shape, so the openai SDK raises its usual typed exceptions for them:
Ошибки эндпоинтов (проверка запроса, оплата, права, работа модели) приходят в формате, совместимом с OpenAI, — поэтому SDK openai выбрасывает для них обычные типизированные исключения:
Endpoint xatolari (so'rovni tekshirish, to'lov, ruxsatlar, model ishi) OpenAI bilan mos formatda keladi — shuning uchun openai SDK ular uchun oddiy tiplangan istisnolarni chiqaradi:
{
"error": {
"message": "Model 'zowy-1' not available. Available models: zowy-1-pro, zowy-2",
"type": "invalid_request_error"
}
}
Authentication (401), rate-limit (429) and unknown-path (404) errors are shorter, with the text in a detail field:
Ошибки аутентификации (401), лимитов (429) и неизвестного пути (404) возвращаются короче — с текстом в поле detail:
Autentifikatsiya (401), limitlar (429) va noma'lum yo'l (404) xatolari qisqaroq ko'rinishda — detail maydonidagi matn bilan qaytariladi:
{
"detail": "Invalid API key"
}
If you parse responses yourself, read the text from error.message and fall back to detail:
Если разбираете ответы сами, берите текст из error.message, а если его нет — из detail:
Javoblarni o'zingiz tahlil qilsangiz, matnni error.message dan oling, u bo'lmasa — detail dan:
r = requests.post(url, headers=headers, json=body, timeout=130) if not r.ok: data = r.json() message = (data.get("error") or {}).get("message") or data.get("detail") print(r.status_code, message)
const res = await fetch(url, { method: "POST", headers, body }); if (!res.ok) { const data = await res.json(); const message = data.error?.message ?? data.detail; console.error(res.status, message); }
If the model itself rejects a request (for example, because the context is too long), its status code and error object are passed through to you unchanged.
Если модель сама отклонила запрос (например, из-за слишком длинного контекста), её код статуса и объект error передаются вам без изменений.
Agar model so'rovni o'zi rad etsa (masalan, kontekst juda uzun bo'lgani uchun), uning status kodi va error obyekti sizga o'zgarishsiz uzatiladi.
Справочник кодов
400invalid_request_errorThe body is not JSON;
messagesis not an array or a message lacksrole/content; the model is unknown (the message lists available ones); speech parameters are invalid.Тело не JSON;messagesне массив или в сообщении нетrole/content; неизвестная модель (в тексте ошибки — список доступных); неверные параметры синтеза речи.Tana JSON emas;messagesmassiv emas yoki xabardarole/contentyo'q; noma'lum model (xato matnida mavjud modellar ro'yxati bor); nutq sintezi parametrlari noto'g'ri.Fix the request using
error.message. Don’t retry it unchanged.Исправьте запрос по текстуerror.message. Не повторяйте его без изменений.So'rovnierror.messagematniga qarab tuzating. Uni o'zgarishsiz qayta yubormang.401The key is missing, invalid, deleted or expired.Ключа нет, он неверный, удалён или просрочен.Kalit yo'q, noto'g'ri, o'chirilgan yoki muddati o'tgan.
Check the
Authorization: Bearer zowy_…header; create a new key if needed. See Authentication.Проверьте заголовокAuthorization: Bearer zowy_…; при необходимости создайте новый ключ. См. Аутентификация.Authorization: Bearer zowy_…sarlavhasini tekshiring; kerak bo'lsa, yangi kalit yarating. Autentifikatsiyani qarang.402insufficient_tokensinsufficient_balanceNo active package: the tokens are used up or the package has expired. Chat completions returns
insufficient_tokens; text to speech returnsinsufficient_balance.Нет активного пакета: токены закончились или срок пакета истёк.insufficient_tokensвозвращает chat completions,insufficient_balance— синтез речи.Faol paket yo'q: tokenlar tugagan yoki paket muddati o'tgan.insufficient_tokensni chat completions,insufficient_balanceni nutq sintezi qaytaradi.Buy a package under API & Billing.Купите пакет в разделе API и биллинг.Paketni API va billing bo'limida sotib oling.
403permission_errorThe key lacks the scope the endpoint needs (
ai_chatorvoice_ai).У ключа нет права, которое нужно эндпоинту (ai_chatилиvoice_ai).Kalitda endpoint uchun kerakli ruxsat (ai_chatyokivoice_ai) yo'q.Use a key with the right scopes. See Scopes.Используйте ключ с нужными правами. См. Права доступа.Kerakli ruxsatlarga ega kalitdan foydalaning. Kirish ruxsatlarini qarang.
404The path doesn’t exist.Такого пути нет.Bunday yo'l mavjud emas.
Check the URL: the base is
https://zowy.ai/api/v1.Проверьте URL: базовый адрес —https://zowy.ai/api/v1.URL'ni tekshiring: asosiy manzil —https://zowy.ai/api/v1.422upstream_rejectedText to speech: the speech engine couldn’t voice the text you sent.Синтез речи: движок не смог озвучить переданный текст.Nutq sintezi: dvigatel berilgan matnni ovozlashtira olmadi.
Change the text or parameters — retrying unchanged won’t help.Измените текст или параметры — повтор без изменений не поможет.Matn yoki parametrlarni o'zgartiring — o'zgarishsiz qayta yuborish yordam bermaydi.
429The key’s per-minute or per-hour limit was exceeded.Превышен лимит запросов ключа в минуту или в час.Kalitning daqiqalik yoki soatlik so'rovlar limiti oshib ketdi.
Wait for the number of seconds in
Retry-After. See Rate limits.Подождите столько секунд, сколько указано вRetry-After. См. Лимиты запросов.Retry-Afterda ko'rsatilgan soniyalar kuting. So'rovlar limitlarini qarang.500server_errorAn internal ZOWY error.Внутренняя ошибка ZOWY.ZOWY ichki xatosi.
Retry with exponential backoff. If it persists, contact support.Повторите с экспоненциальной задержкой. Если ошибка не уходит — напишите в поддержку.Eksponensial kechikish bilan qayta yuboring. Xato takrorlanaversa — qo'llab-quvvatlash xizmatiga yozing.
502server_errormodel_errorThe model service returned an error or a malformed response.Сервис модели вернул ошибку или некорректный ответ.Model servisi xato yoki noto'g'ri javob qaytardi.
Retry with backoff.Повторите с задержкой.Kechikish bilan qayta yuboring.
503server_errorThe model is temporarily unavailable.Модель временно недоступна.Model vaqtincha mavjud emas.
Retry with exponential backoff.Повторите с экспоненциальной задержкой.Eksponensial kechikish bilan qayta yuboring.
504server_errorThe model didn’t respond within 120 seconds.Модель не ответила за 120 секунд.Model 120 soniya ichida javob bermadi.
Lower
max_tokensor enablestream, then retry.Уменьшитеmax_tokensили включитеstream, затем повторите.max_tokensni kamaytiring yokistreamni yoqing, so'ng qayta yuboring.
Ошибки при стриминге
With "stream": true, key, scope, billing and request-format errors are returned before the stream starts, with a normal status code. If the model fails after the stream has opened with status 200, you receive an event carrying an error object and the stream then closes:
При "stream": true ошибки ключа, прав, оплаты и формата запроса возвращаются до начала потока, с обычным кодом статуса. Если же модель вернула ошибку, когда поток уже открыт со статусом 200, вы получите событие с объектом error, после которого поток закроется:
"stream": true bo'lganda kalit, ruxsatlar, to'lov va so'rov formati xatolari oqim boshlanishidan oldin, oddiy status kodi bilan qaytariladi. Agar model oqim 200 status bilan ochilganidan keyin xato qaytarsa, error obyektli hodisa keladi va shundan so'ng oqim yopiladi:
data: {"error": {"message": "…", "type": "…"}}
Check each event for an error field before reading choices.
Проверяйте каждое событие на наличие поля error, прежде чем читать choices.
choices ni o'qishdan oldin har bir hodisada error maydoni bor-yo'qligini tekshiring.
Ошибки WebSocket
The voice WebSocket reports an error as a JSON message with "type": "error" and then closes the connection. There is no machine-readable error code — treat any such message as fatal for the session and show or log its message.
Голосовой WebSocket сообщает об ошибке JSON-сообщением с "type": "error" и сразу закрывает соединение. Машинного кода ошибки нет — считайте любое такое сообщение фатальным для сессии и показывайте или логируйте message.
Ovozli WebSocket xato haqida "type": "error" li JSON xabar bilan xabar beradi va ulanishni darhol yopadi. Mashina o'qiydigan xato kodi yo'q — har qanday bunday xabarni sessiya uchun halokatli deb hisoblang va message ni ko'rsating yoki logga yozing.
{ "type": "error", "message": "No Voice AI seconds available. Please purchase a package." }
Authentication required: ?token=YOUR_API_KEYThe URL has no
tokenparameter.В URL нет параметраtoken.URL'datokenparametri yo'q.Invalid API keyThe key is invalid, deleted or expired.Ключ неверный, удалён или просрочен.Kalit noto'g'ri, o'chirilgan yoki muddati o'tgan.
API key required (not JWT)The token is not a
zowy_…API key.Передан не API-ключzowy_….zowy_…API kaliti emas, boshqa narsa yuborilgan.API key missing required scope: voice_aiThe key lacks the
voice_aiscope.У ключа нет праваvoice_ai.Kalitdavoice_airuxsati yo'q.No Voice AI seconds available. Please purchase a package.No active Voice AI package.Нет активного пакета Voice AI.Faol Voice AI paketi yo'q.
Expected JSON config messageThe first config message didn’t arrive within 10 seconds, or wasn’t JSON.Первое сообщение с настройками не пришло в течение 10 секунд или это не JSON.Sozlamalar bilan birinchi xabar 10 soniya ichida kelmadi yoki u JSON emas.
Voice AI service temporarily unavailableThe voice service is temporarily unavailable — reconnect later.Голосовой сервис временно недоступен — переподключитесь позже.Ovoz servisi vaqtincha mavjud emas — keyinroq qayta ulaning.
Voice AI session errorThe session ended because of an error on our side.Сессия прервалась из-за ошибки на нашей стороне.Sessiya bizning tomondagi xato tufayli uzildi.
A session also ends, without an error message, once it reaches 15 minutes. See Voice WebSocket.
Сессия также завершается без ошибки по достижении 15 минут. Подробнее — в Voice WebSocket.
Sessiya 15 daqiqaga yetganda ham xatosiz yakunlanadi. Batafsil — Voice WebSocket sahifasida.
Повторы и задержки
Only retry 429 and 5xx responses — with exponentially growing delays plus a little random jitter. Other 4xx responses mean the request itself is wrong: retrying it unchanged gives the same result.
Повторять имеет смысл только 429 и 5xx — с экспоненциально растущей задержкой и небольшим случайным разбросом. Остальные 4xx означают ошибку в запросе: повтор без изменений даст тот же результат.
Faqat 429 va 5xx ni qayta yuborish ma'noga ega — eksponensial o'sib boradigan kechikish va kichik tasodifiy farq bilan. Boshqa 4xx kodlar so'rovdagi xatoni bildiradi: o'zgarishsiz qayta yuborish xuddi shu natijani beradi.
import random, time, requests RETRYABLE = {429, 500, 502, 503, 504} def post_with_retry(url, headers, body, attempts=5): for attempt in range(attempts): r = requests.post(url, headers=headers, json=body, timeout=130) if r.status_code not in RETRYABLE: return r # Prefer the server's hint, otherwise back off exponentially: 1, 2, 4, 8 s wait = float(r.headers.get("Retry-After", 2 ** attempt)) time.sleep(wait + random.uniform(0, 0.5)) return r
The openai SDK already retries 429 and 5xx automatically (twice by default) and respects Retry-After. Configure the retry count and timeout when you create the client:
SDK openai уже повторяет 429 и 5xx автоматически (по умолчанию дважды) и учитывает Retry-After. Число повторов и таймаут настраиваются при создании клиента:
openai SDK 429 va 5xx ni avtomatik ravishda qayta yuboradi (standart bo'yicha ikki marta) va Retry-After ni hisobga oladi. Qayta urinishlar soni va taym-aut mijozni yaratishda sozlanadi:
client = OpenAI(
api_key=os.environ["ZOWY_API_KEY"],
base_url="https://zowy.ai/api/v1",
max_retries=4, # default: 2
timeout=130,
)
const client = new OpenAI({ apiKey: process.env.ZOWY_API_KEY, baseURL: "https://zowy.ai/api/v1", maxRetries: 4, // default: 2 timeout: 130_000, });