Errori HTTP e sicurezza delle chiavi API
In questa pagina
Aggiornato il 3 novembre 2026, basato sulle pagine Text to Speech e Rate limits di xAI: testo limitato a 60.000 caratteri, errore 404 (voce sconosciuta) e limiti di frequenza per livello. Fonti: Text to Speech · Rate limits.
Gestire gli errori e proteggere le credenziali
In produzione, la tua applicazione deve gestire gli errori dell’API TTS con eleganza e, soprattutto, non esporre mai la tua chiave API sul client. Questa lezione copre i codici di errore, le strategie di nuovo tentativo e l’architettura del proxy backend.
Codici di errore HTTP
L’API TTS restituisce codici di errore HTTP standard. Ecco come reagire a ciascuno di essi.
400: Bad Request
Il server non è riuscito a elaborare la tua richiesta. Cause comuni:
- Testo vuoto o testo superiore a 60.000 caratteri
- Un codec non valido (un errore di battitura nel nome)
- Una frequenza di campionamento non supportata
if response.status_code == 400:
error = response.json()
print(f"Invalid request: {error}")
# Fix the parameters and try again
Non riprovare automaticamente un errore 400: il problema risiede nella tua richiesta, non nel server. Correggi prima i parametri.
401: Unauthorized
La chiave API non è valida, è scaduta o manca:
if response.status_code == 401:
raise AuthenticationError("Invalid or expired API key")
Verifica che:
- L’intestazione
Authorizationsia presente - Il formato sia
Bearer xai-...(con uno spazio dopo Bearer) - La chiave non sia stata revocata nella console xAI
404: Not Found
L’ID voce è sconosciuto: verificalo con GET /v1/tts/voices per una voce integrata o GET /v1/custom-voices per una voce personalizzata. Come per il 400, un 404 non scomparirà se riprovi.
429: Too Many Requests
Hai superato un limite di frequenza: nel livello di ingresso, 50 richieste al secondo e 100 sessioni concurrent per TTS secondo la pagina Rate limits, e 50 sessioni WebSocket concurrent per team secondo la pagina Text to Speech. xAI consiglia di riprovare con un backoff esponenziale:
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", 5))
await asyncio.sleep(retry_after)
# Try again
Implementa il backoff esponenziale per gli errori 429:
async def request_with_backoff(url, payload, headers, max_retries=5):
for attempt in range(max_retries):
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
return response
if response.status_code == 429:
wait = min(2 ** attempt + random.random(), 60)
print(f"Rate limited. Waiting {wait:.1f}s")
await asyncio.sleep(wait)
continue
if response.status_code >= 500:
wait = min(2 ** attempt + random.random(), 30)
await asyncio.sleep(wait)
continue
# Client error (400, 401): don't retry
response.raise_for_status()
raise Exception("Failed after 5 attempts")
500 / 503: Server Error
Il server ha un problema temporaneo. Riprova con backoff:
if response.status_code in (500, 503):
# Retry with exponential backoff
pass
Gli errori 503 sono spesso causati da un sovraccarico temporaneo. Di solito si risolvono entro pochi secondi.
Non esporre mai la chiave API sul client
Questa è la regola di sicurezza più importante. Se la tua chiave API è visibile nel JavaScript del browser, chiunque può:
- Utilizzare la tua quota gratuitamente
- Generare costi sul tuo account
- Accedere a ogni endpoint API xAI con la tua chiave
Architettura del proxy backend
La soluzione consiste nel far passare le chiamate TTS attraverso il tuo backend:
Browser -> Your backend -> xAI API
(no key) (API key) (TTS)
Esempio Express.js
const express = require("express");
const app = express();
app.post("/api/tts", async (req, res) => {
const { text, voice_id, language } = req.body;
// Server-side validation
if (!text || text.length > 60000) {
return res.status(400).json({ error: "Invalid text" });
}
const response = await fetch("https://api.x.ai/v1/tts", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.XAI_API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({ text, voice_id, language })
});
if (!response.ok) {
return res.status(response.status).json({
error: "TTS error"
});
}
// Pass the audio on to the client
res.set("Content-Type", response.headers.get("Content-Type"));
const buffer = await response.arrayBuffer();
res.send(Buffer.from(buffer));
});
Esempio FastAPI (Python)
from fastapi import FastAPI, HTTPException
from fastapi.responses import Response
import httpx
app = FastAPI()
@app.post("/api/tts")
async def proxy_tts(text: str, voice_id: str = "eve", language: str = "en"):
if len(text) > 60000:
raise HTTPException(400, "Text too long")
async with httpx.AsyncClient() as client:
response = await client.post(
"https://api.x.ai/v1/tts",
headers={"Authorization": f"Bearer {os.environ['XAI_API_KEY']}"},
json={"text": text, "voice_id": voice_id, "language": language}
)
if response.status_code != 200:
raise HTTPException(response.status_code, "TTS error")
return Response(
content=response.content,
media_type=response.headers["content-type"]
)
Proxy WebSocket
Per il WebSocket TTS, il tuo backend deve inoltrare i messaggi tra il client e l’API xAI:
const WebSocket = require("ws");
wss.on("connection", (clientWs) => {
const xaiWs = new WebSocket(
"wss://api.x.ai/v1/tts?language=en&voice=eve",
{ headers: { Authorization: `Bearer ${process.env.XAI_API_KEY}` } }
);
// Relay client -> xAI
clientWs.on("message", (msg) => xaiWs.send(msg));
// Relay xAI -> client
xaiWs.on("message", (msg) => clientWs.send(msg));
// Handle closing
clientWs.on("close", () => xaiWs.close());
xaiWs.on("close", () => clientWs.close());
});
Moderazione fail-open
L’API TTS esegue la moderazione dei contenuti in modo asincrono. Ciò significa che la moderazione non blocca la richiesta: l’audio viene generato e restituito anche se la moderazione non ha terminato la sua analisi.
Se un contenuto viene segnalato come inappropriato, il rapporto arriva dopo il fatto. Quindi, la tua applicazione dovrebbe eseguire la propria moderazione a monte, se necessario.
Punti chiave
- 400 = errore di parametro (non riprovare; correggi la richiesta)
- 401 = chiave API non valida (controlla l’intestazione Authorization)
- 429 = limite di frequenza raggiunto (backoff esponenziale)
- 500/503 = errore temporaneo del server (riprova con backoff)
- Non esporre mai la chiave API nel codice client
- Fai passare tutte le chiamate TTS attraverso il tuo backend
- La moderazione è fail-open: aggiungi il tuo filtro se necessario