Retries and Idempotency
Handle 429 responses and transient errors with exponential backoff, sensible timeouts, and safe retries against the Parasail API.
When you'll see 429 Too Many Requests
429 Too Many RequestsExponential backoff
import random
import time
from openai import OpenAI, APIStatusError, APITimeoutError, APIConnectionError
client = OpenAI(
base_url="https://api.parasail.io/v1",
api_key="<PARASAIL_API_KEY>",
timeout=30, # seconds; fail fast instead of hanging
max_retries=0, # disable built-in retries so we control backoff here
)
def chat_with_backoff(messages, model, max_attempts=5):
for attempt in range(max_attempts):
try:
return client.chat.completions.create(model=model, messages=messages)
except (APITimeoutError, APIConnectionError):
retryable = True
except APIStatusError as e:
# Retry on throttling and server errors; fail fast on 4xx like 400/401/404.
retryable = e.status_code == 429 or e.status_code >= 500
if not retryable:
raise
if attempt == max_attempts - 1:
raise
# Exponential backoff with full jitter: 1s, 2s, 4s, ... plus randomness.
sleep = min(2 ** attempt, 30) * (0.5 + random.random() / 2)
time.sleep(sleep)
response = chat_with_backoff(
messages=[{"role": "user", "content": "Hello"}],
model="<your-model>",
)
print(response.choices[0].message.content)Setting timeouts
Safe retries and idempotency
Next steps
Last updated