Errors, usage and safe integration
Separate failures before retrying
An API integration can fail before sending a request, while waiting for a response or after receiving invalid output. The Python SDK documents APIConnectionError, APITimeoutError, RateLimitError and APIStatusError; authentication and permission errors are not transient by default. Some 429 responses indicate quota exhaustion rather than temporary throttling. Inspect provider error details and classify failures; retry only approved transient cases. A timeout does not establish that the server did no work, so even a text-only retry may incur duplicate cost. Never automatically repeat a side effect. Refusals, invalid parameters, unsupported features and semantic failures should stop or go to review, not be treated as transient transport failures.
Limit attempts explicitly
The following function operates on preclassified, invented outcomes. Limit includes the first attempt, so limit 3 permits at most two retries. The first fixture times out and then succeeds; the second stops after an authorization error; the third runs out of attempts. This example does not sleep or perform network requests. In a real application, select one retry owner: either configure SDK retries or set max_retries=0 and manage them yourself. Avoid accidentally multiplying retry layers. For approved temporary failures use bounded exponential backoff with jitter, respect provider delay hints when available, and stop if a total deadline or spend allowance would be exceeded. A disconnected stream needs separate handling; never blindly append a new stream to an old prefix.
def run_bounded(attempt, limit): # attempt() returns an application-classified mock outcome. if type(limit) is not int or limit < 1: raise ValueError("positive integer attempt limit required") for number in range(1, limit + 1): outcome = attempt() if outcome == "ok": return "ok", number if outcome not in ("timeout", "rate_temporary", "server_temporary"): return "stop", number return "exhausted", limit
outcomes = iter(["timeout", "ok"])print(run_bounded(lambda: next(outcomes), 3))print(run_bounded(lambda: "auth_error", 3))print(run_bounded(lambda: "rate_temporary", 2))Estimate usage without inventing prices
Responses usage reports input and output token totals and may include detailed categories. Token usage is not necessarily equal to the number of visible words or visible output tokens. The cost estimator below assumes only uncached text input and output, hypothetical whole-dollar rates per million tokens, no other charges. Multiplying token counts by rates yields integer microdollars (one millionth of a dollar). For 1,200 input tokens at an invented rate of 2 and 300 output tokens at 8, the estimate is 4,800 microdollars, or $0.0048. These are not OpenAI prices. The exact fraction avoids floating-point rounding in the teaching calculation. Production pricing can include fractional rates, cache categories, tools, tiers or other fees; use a versioned rate table and reconcile with actual billing. Missing usage after errors is unknown, not zero. Reserve budget before requests and retries; a local estimate is not a provider spending cap.
from fractions import Fraction
def estimate_microdollars(input_tokens, output_tokens, in_rate, out_rate): # Hypothetical USD per million tokens, represented as whole integers. values = (input_tokens, output_tokens, in_rate, out_rate) if any(type(x) is not int or x < 0 for x in values): raise ValueError("nonnegative integers required") return input_tokens * in_rate + output_tokens * out_rate
micro = estimate_microdollars(1200, 300, 2, 8)print(micro)print(Fraction(micro, 1_000_000))Design a release gate
Keep secrets server-side and log only necessary metadata: correlation IDs, approved model and SDK versions, status, latency, attempt count, usage when reported and sanitized error categories. Do not log full prompts, keys, personal records or raw model output by default. Review current model access, billing, rate limits, data retention and pricing for the actual organization and endpoint. Test local fixtures for success, temporary timeout followed by success, permanent quota failure, authentication failure, incomplete output and refusal. Validate generated content against independent evidence. For live evaluation require explicit approval, synthetic or approved data, a hard local attempt/deadline/spend policy and current SDK verification. No assertion about this learner’s account or rates is made.
Practice: calculate and classify
Predict the result for limit 1 and a temporary server failure; for a permanent quota failure with limit 4; and for an immediate success. Add a fake counter to confirm the function never calls attempt more than limit. Calculate the invented cost for 10 input and 5 output tokens at rates 2 and 8. Then explain why this estimator cannot infer the final bill of a timed-out request. Build the project worksheet using only synthetic fixtures. A passing local test is evidence about the local adapter, not the live provider.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Errors, usage and safe integration quiz
Apply the offline API integration contract.
With an attempt limit of 3, how many retries are possible after the first request?
Which failure should normally stop rather than retry?
Why avoid independent retry loops in both the SDK and application?
At invented rates of 2 and 8 dollars per million tokens, what is the microdollar estimate for 10 input and 5 output tokens?
How should missing usage after a timeout be recorded?