OpenAI API Interview Questions: Build a Client That Handles Structured Output and Failure
Quick Overview
Use a Python SDK adapter and application classifier to handle refusal, incomplete response, invalid business data, and retry without duplicate commits.
Your OpenAI API client sometimes receives a valid parsed object, sometimes a refusal, and sometimes an incomplete response. A temporary failure can also arrive after the remote request already ran. Which results can update the application? In an OpenAI API interview, distinguish transport errors, response states, and the conditions for accepting a draft. A successful parse is one checkpoint in the operation.
This original exercise uses the OpenAI Responses API and its Python SDK patterns. The examples read current API documentation and use fake local responses for the practice states. They do not represent OpenAI's hiring questions. For a cross-provider explanation of schemas and refusals, see the structured output interview guide.

Define the acceptance boundary before sending a model request
A support application turns short synthetic equipment notes into inventory-review drafts. The response should contain a known equipment code, a suggested action from a fixed set, and a short explanation. Saving the suggestion does not dispatch work. An authorized operator can independently approve it later. The application must prevent a duplicate draft from the same job and source version. It must preserve what happened when a model call fails, and it may not use an invented equipment code.
OpenAI's Structured Outputs documentation describes requesting a schema-supported output format and shows Python examples of passing a typed model to the SDK parser. Schemas express structure and types, conditional on the documented model and schema features. The app still owns whether a parsed value is meaningful and allowed for the current request. Keep each input as small and appropriate as the task allows. Choose a supported current model and pin the SDK version you test. OpenAI Structured Outputs guide.
A concise example could use a Pydantic model called Draft with fields for equipment code and proposed action. With a supported Python SDK and supported model, the client would call its Responses parse helper using the chosen model, request input and Draft as the text format. The guide shows reading the helper's parsed output, while the Responses API reference describes statuses, output items and incomplete details. Verify the SDK behavior for your chosen version because parsing can raise before your application obtains a usable parsed value. Model calls and SDK parsing do not determine whether a downstream write is authorized. OpenAI Responses create reference.

Separate the outcome categories in code
Check the response status and any refusal content before reading the typed value. An item in the output array can represent different content types. For this simplified non-tool text exercise, inspect message parts for refusals and treat missing usable parsed output as a distinct case. The following application function expects the SDK response object or a fake with the same relevant fields. This is a classification example, with transport exception handling outside it.
def read_draft(response, allowed_codes):
if response.status != "completed":
return ("response_not_completed", None)
for item in response.output:
if item.type == "message":
if any(part.type == "refusal" for part in item.content):
return ("refused", None)
draft = response.output_parsed
if draft is None:
return ("missing_parsed_draft", None)
if draft.equipment_code not in allowed_codes:
return ("invalid_equipment_code", None)
return ("valid_draft", draft)
The production adapter can retain normalized incomplete details or a safe response ID for investigation. Do not commit partial text as an approved draft. Some SDK or model combinations may deliver a parse error from the helper rather than a parsed object with empty content. Catch specific documented transport and validation errors in the calling adapter. Map unexpected paths to a controlled result with appropriate monitoring, and do not rely on array position or parse free text as if it were schema-validated output.
A completed response may carry a refusal. An incomplete response can have content that looks like it contains the desired object. An unknown application code can fit a schema if the schema only asks for a string. Keep these examples distinct. The client can show each outcome in a small status record and indicate the next available application step under the product's policy. A refusal is a supported outcome and should not automatically cause another attempt.
Decide which errors can be retried and by whom
OpenAI documents error types and recommends backoff on eligible rate-limit failures. Some failures require a configuration or permission change. Some 429 responses may reflect an exhausted quota rather than a fleeting rate ceiling. Consider the documented error details and the product's own deadline before retrying. Bound both attempts and elapsed time. If the response supplies applicable retry timing, follow it within the overall deadline. Otherwise use an approved randomized backoff, and avoid an unbounded attempt loop. Failed calls can also contribute to limits. OpenAI rate limits. OpenAI error codes.
In this exercise the application controls attempts explicitly, with SDK retries configured so they do not stack with its policy. A real team might choose to rely on the SDK's configured retries instead and keep the application deadline visible. Validate which errors are retried by the installed SDK. A malformed input, invalid key, unsupported schema, model refusal or a known quota problem does not improve through repeated identical requests. A temporary connection or server problem may be eligible under a bounded retry policy. An unknown return after a timeout is ambiguous. A second model call could create extra latency and cost even if applying its result can be deduplicated.
Test the adapter and the downstream write independently
Start from a job key that includes the source version. If the source text changes, reusing the same job key would mix two intents. An approved write boundary claims the durable key or returns its existing accepted result. If two model calls complete for the same job because of an ambiguous timeout, only one commit under that identity may be accepted by the application. The model request itself can still have been processed more than once. Record who owns the accepted result and how looking it up differs from retrying the upstream API call.
| Fake response or transport event | Expected result | Writes accepted |
|---|---|---|
| Completed with supported code | Valid draft | 1 |
| Completed with refusal part | Refused | 0 |
| Incomplete with partial text | Not completed | 0 |
| Completed parsed code outside authorized inventory | Invalid equipment code | 0 |
| Temporary rate-limit error then valid response | Recover under the bound when timing permits | 1 |
| Permanent validation or quota failure | Controlled error | 0 |
| Two valid results for one stable job after a timeout | One accepted durable result | 1 |
A fixture should check the terminal result and elapsed attempts, not only whether a handler was entered. Trap accidental retries after a refusal and verify the remaining product deadline. Log permitted outcome and correlation references without input contents. If the interviewer changes the downstream write to an external action without idempotency support, say which guarantee is lost and what a human or service needs to reconcile. The same code that parses a structured response cannot establish how the external service applied it.
Show which SDK call your adapter wraps
In a synchronous Python example with an SDK that supports the documented parser, define a small typed draft format. The model identifier is an injected deployment setting instead of a hard-coded promise that a particular current model supports every schema. For this example the application uses an SDK client with no automatic retry because the surrounding adapter owns retry timing. Apply an explicit request timeout and make it shorter as the remaining operation deadline shrinks. The following excerpt shows the typed call. A caller obtains credentials from the approved environment and invokes it only with data authorized for the provider.
from typing import Literal
from pydantic import BaseModel
class Draft(BaseModel):
equipment_code: str
action: Literal["inspect", "review"]
explanation: str
def fetch_draft(client, model, note):
return client.responses.parse(
model=model,
input=[
{"role": "system", "content": "Draft an inventory review."},
{"role": "user", "content": note},
],
text_format=Draft,
)
The call boundary is deliberately small. If the underlying transport returns a timeout or application handles a specific SDK error, route it through the shared attempt policy. Capture the available provider request or response identifier, attempt number, classified error and duration in an approved log. A connection failure may have no provider correlation value. Avoid requiring an ID before you can report a client failure. Use your own operation identifier to join evidence across retries. The parser function checks only the outcome and supported inventory. The app's write function still checks current authorization and source version.
Design a retry test with a fake clock
Suppose the job has eight seconds remaining and receives a temporary limit response with an applicable delay of two seconds. In the fake, let time advance, record one queued retry, and deliver a valid draft before the deadline. A second fixture should provide a delay longer than the remaining time and expect an explicit deferral or failure. Confirm no sleep uses more time than the permitted budget. Set a maximum number of allowed attempts and check that a stream of transient responses reaches the terminal outcome. The exact retry delay depends on which headers and failure details the real SDK and endpoint expose.
If the model responds with a supported refusal, test that a policy for temporary failures does not retry it. If a transient wait turns into an unsupported schema error, the workflow must stop even if another attempt would fit. Use a fake sink that retains the stable job key to test downstream deduplication. Verify both the accepted operation count and whether any stale version could overwrite a new draft. This demonstrates timing, classification, business acceptance and write safety under independently observable outcomes.
A final follow-up asks how you would know an SDK upgrade carried the same behavior. Pin the test version and keep one approved provider contract test with a supported current model for the response shape. The local fake tests exercise deliberate status and transport inputs reliably. An integration check establishes what the actual parser returns under the chosen version and which errors it raises. Run the suite before changing SDK and model together, then vary one dependency at a time when practical. A release comparison should report both the observed response and what the downstream application decided to accept.
Make the returned state useful to callers. A terminal temporary failure can preserve the job identity and show when the system may attempt it under the approved policy. A completed valid draft can point to the exact stored version. A rejected business value may need a queue for review rather than another model call. Separate flags help an operator compare apparent error rates with real unusable outcomes.
Related PracHub interview practice
For each exercise, specify the API result and what state a caller is allowed to commit. Test at least one uncertain failure with a stable job identity.
| PracHub question | What to practise |
|---|---|
| Design an OpenAI chatbot in two hours | Define an application's model call and acceptance boundaries. |
| Implement retry wrapper and interdependent validators | Bound and verify retry timing around an eligible error. |
| Build a Streaming Chat Input | Distinguish an incomplete stream from a completed usable response. |
| Design an Evaluation Platform for AI Agents Across Prompt and Model Changes | Build a fixture set for each response and business category. |
| Design a Localized Usage-Limit Response and Compose Snackbar | Represent a quota or temporary rate limit as a clear user outcome. |
Give an interview answer with an explicit write rule
“I'd use a supported Responses schema and parse into a typed draft. I'd branch separately on API failure, incomplete response, refusal, and invalid application value. Only a completed response with an authorized and valid equipment code can reach our draft write. A bounded retry can handle eligible transient failures, while the application uses a durable operation key for a replay. My fake transport fixtures prove what each branch returns, and an approved integration test verifies the chosen SDK behavior.”
Use the schema and validation exercise and change the failure: the model answered, but the response did not reach your caller in time. Explain which work might be repeated and how the downstream operation remains bounded.
Comments (0)