DocumentaciónLímites y errores
Operar
Límites y errores
Lo que la API rechaza, por qué, y qué debe hacer tu código con cada respuesta.
En esta página
Los límites
| Límite | Valor | Si se supera |
|---|---|---|
| Solicitudes | 300 por minuto y por clave | 429, con la espera indicada en retry-after |
| Solicitudes simultáneas | Según tu plan | 429, nuevo intento tras 5 segundos |
| Tokens por día, semana o mes | Según tu plan | 429, sin retry-after |
| Tamaño de una solicitud | 50 MB | Rechazada |
Los errores
| Código | Causa | Qué hacer |
|---|---|---|
400 | Solicitud mal formada o modelo desconocido. El mensaje indica el campo afectado. | Corregir la solicitud |
401 | Clave ausente, desconocida, revocada o caducada | Verificar la clave, sin reintentar en bucle |
403 | Modelo o función no incluidos en tu plan | Cambiar de modelo o de plan |
429 | Demasiadas solicitudes, o límite de tokens alcanzado | Esperar lo que indique retry-after si está presente, si no, detenerse |
502 | El modelo no ha respondido correctamente | Reintentar un poco más tarde |
503 | Servicio no disponible temporalmente | Reintentar un poco más tarde |
El cuerpo de un error siempre lleva un mensaje legible:
{
"error": {
"message": "model \"max\" is not part of this plan",
"type": "router_error"
}
}Reintentar correctamente
Reintenta solo cuando la API te indique cuánto esperar. Un límite de tokens alcanzado no se resuelve insistiendo.
import time
from openai import OpenAI, RateLimitError
client = OpenAI(
base_url="https://api.learnya.ai/v1",
api_key=os.environ["LEARNYA_API_KEY"],
max_retries=0,
)
def complete(**request):
for attempt in range(5):
try:
return client.chat.completions.create(**request)
except RateLimitError as error:
# The gateway says how long to wait.
# A spent token budget says nothing: stop there.
wait = error.response.headers.get("retry-after")
if wait is None:
raise
time.sleep(int(wait) + attempt)
raise RuntimeError("still limited after five attempts")import OpenAI, { RateLimitError } from "openai"
const client = new OpenAI({
baseURL: "https://api.learnya.ai/v1",
apiKey: process.env.LEARNYA_API_KEY,
maxRetries: 0,
})
async function complete(request) {
for (let attempt = 0; attempt < 5; attempt++) {
try {
return await client.chat.completions.create(request)
} catch (error) {
// The gateway says how long to wait.
// A spent token budget says nothing: stop there.
const wait =
error instanceof RateLimitError
? error.headers?.get("retry-after")
: null
if (!wait) throw error
await new Promise((done) =>
setTimeout(done, (Number(wait) + attempt) * 1000),
)
}
}
throw new Error("still limited after five attempts")
}import OpenAI, { RateLimitError } from "openai"
import type {
ChatCompletion,
ChatCompletionCreateParamsNonStreaming,
} from "openai/resources"
const client = new OpenAI({
baseURL: "https://api.learnya.ai/v1",
apiKey: process.env.LEARNYA_API_KEY,
maxRetries: 0,
})
async function complete(
request: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion> {
for (let attempt = 0; attempt < 5; attempt++) {
try {
return await client.chat.completions.create(request)
} catch (error) {
// The gateway says how long to wait.
// A spent token budget says nothing: stop there.
const wait =
error instanceof RateLimitError
? error.headers?.get("retry-after")
: null
if (!wait) throw error
await new Promise((done) =>
setTimeout(done, (Number(wait) + attempt) * 1000),
)
}
}
throw new Error("still limited after five attempts")
}