DocumentaçãoLimites e erros
Operar
Limites e erros
O que a API recusa, porquê, e o que o teu código deve fazer com cada resposta.
Nesta página
Os limites
| Limite | Valor | Acima do limite |
|---|---|---|
| Pedidos | 300 por minuto e por chave | 429, com o tempo de espera em retry-after |
| Pedidos simultâneos | Conforme o teu plano | 429, nova tentativa após 5 segundos |
| Tokens por dia, semana ou mês | Conforme o teu plano | 429, sem retry-after |
| Tamanho de um pedido | 50 MB | Recusado |
Os erros
| Código | Causa | O que fazer |
|---|---|---|
400 | Pedido mal formado ou modelo desconhecido. A mensagem indica o campo em causa. | Corrigir o pedido |
401 | Chave em falta, desconhecida, revogada ou expirada | Verificar a chave, sem repetir em ciclo |
403 | Modelo ou funcionalidade não incluído no teu plano | Mudar de modelo ou de plano |
429 | Demasiados pedidos, ou limite de tokens atingido | Esperar por retry-after se estiver presente, caso contrário parar |
502 | O modelo não respondeu corretamente | Tentar de novo um pouco mais tarde |
503 | Serviço temporariamente indisponível | Tentar de novo um pouco mais tarde |
O corpo de um erro contém sempre uma mensagem legível:
{
"error": {
"message": "model \"max\" is not part of this plan",
"type": "router_error"
}
}Tentar de novo da forma certa
Tenta de novo só quando a API te disser quanto tempo esperar. Um limite de tokens atingido não se resolve a insistir.
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")
}