
Retry a failed model call
mediumRetry a failed model call
OpenAI LLM Interview Question
Calling the OpenAI API at volume means a share of requests come back as a rate limit or a server error instead of an answer. Neither is a verdict on the request: a rate limit is the API asking you to slow down, and a server error usually clears on its own. A client that gives up after the first unanswered call looks broken to a user whose request would have worked on the second try.
Write a function ask_with_retry(prompt, attempts) that asks the model and returns the first reply that comes back. Send the prompt as a single user message with client.chat.completions.create, and read the answer off response.choices[0].message.content. A call that fails raises APIError; when that happens, try again, up to the given number of attempts in all. Stop as soon as a call succeeds, and return None when every attempt has failed.
Asked of
- AI Engineer
- ML Engineer
- Data Scientist
Example 1
Input
prompt = "What is the refund window?", attempts = 3
The model says
call 1 -> InternalServerError: The engine is currently overloaded, please try again later. call 2 -> "You can return most items within 30 days of delivery for a full refund."
Output
"You can return most items within 30 days of delivery for a full refund."
Example 2
Input
prompt = "Where is my order?", attempts = 2
The model says
call 1 -> RateLimitError: Rate limit reached for gpt-4o-mini in organization org-dcs on tokens per min (TPM). call 2 -> RateLimitError: Rate limit reached for gpt-4o-mini in organization org-dcs on tokens per min (TPM).
Output
None
Example 3
Input
prompt = "Are you there?", attempts = 3
The model says
call 1 -> "Yes, I'm here. How can I help you today?"
Output
"Yes, I'm here. How can I help you today?"
Explanation
In the first example the first call fails and the second returns a reply, so that reply is the answer. In the second both attempts fail, so there is nothing to return.
Submit also runs 3 hidden test cases that check edge cases.
- Backoff
Similar questions
Company
OpenAI
Difficulty
medium
Topic
LLM
Language
Python
Your code
Loading Python in the background. You can start writing.