Python for AI Engineers · Part A · Lesson 7 of 26
Python exceptions, retries and context managers
Python error handling for a Java or JavaScript developer: try/except/else/finally, catching the right exception, custom exceptions and raise from, EAFP, with statements, writing your own context managers, retries with backoff, logging, and turning LLM SDK errors into messages users understand.
⏱ 40 min3 exercises that check your codeRuns in your browser
By the end you can
- Use
try / except / else / finally, catch specific exceptions, and know why a bareexcept:is a bug - Raise your own exception classes and keep the original cause with
raise ... from e - Use
withfor files and locks, and write your own context manager as a class and with@contextmanager - Retry only temporary failures with backoff, log errors instead of swallowing them, and map LLM SDK errors to clear user messages
1try, except, else and finally
Python's try is Java's try, with two differences in spelling: catch is called except, and you write except ValueError as e: to get the exception object into e. finally means the same thing as in Java and JavaScript: it always runs, even when the try block returns or raises.
Python adds one block Java does not have: else runs only when the try block raised nothing. Put the code that should run "on success" there, so the try block holds only the one line that can fail. Then an error in your success code cannot be mistaken for the error you meant to catch.
There are no checked exceptions: nothing like throws in a signature, and the compiler never forces you to catch anything. You read the docs (or the traceback) to know what a call can raise.
def parse_tokens(raw):
try:
n = int(raw) # the only line that can fail: int("lots") raises ValueError
except ValueError:
print(f"not a number: {raw!r}")
return None
else:
print("parsed", n) # runs only when the try block raised nothing
return n
finally:
print("done with", repr(raw)) # always runs, even after a return
print(parse_tokens("512"))
print(parse_tokens("lots"))
Expected output
parsed 512 done with '512' 512 not a number: 'lots' done with 'lots' None
Integer parseTokens(String raw) {
try {
int n = Integer.parseInt(raw);
System.out.println("parsed " + n); // no "else": success code sits in the try
return n;
} catch (NumberFormatException e) { // catch = except
System.out.println("not a number: " + raw);
return null;
} finally {
System.out.println("done with " + raw);
}
} function parseConfig(raw) {
try {
return JSON.parse(raw);
} catch (e) { // JS catches everything...
if (!(e instanceof SyntaxError)) throw e; // ...so you filter by hand
console.log("not JSON:", raw);
return null;
} finally {
console.log("done");
}
} Read the output in order. For "512": the else block prints and prepares return n, then finally prints before the function actually returns, and only then does the outer print show 512. For "lots": int() raises, the except block runs, finally runs, and the function returns None. {raw!r} in an f-string prints the value with repr(), which is why the strings appear in quotes.
Tip Keep the try block as small as possible: just the call that can fail. Everything that should run after a success goes in else (or after the whole statement).
2Catch the specific exception
Each except names the exception class it handles, and Python checks the clauses from top to bottom: the first one that matches wins. A clause also matches every subclass of the class it names, exactly like catch in Java. To handle several classes the same way, put them in a tuple: except (TypeError, ValueError) as e:.
All the built-in errors you normally catch inherit from Exception. Above it sits BaseException, which also covers KeyboardInterrupt (the user pressed Ctrl+C) and SystemExit (the program called sys.exit()). A bare except: with no class catches those too, so your program can no longer be stopped. Never write it.
def read_setting(settings, key):
try:
return float(settings[key])
except KeyError: # the key is not in the dict at all
return f"missing setting {key!r}"
except (TypeError, ValueError) as e: # the key exists but the value is not a number
return f"bad value for {key!r}: {e}"
settings = {"temperature": "0.2", "top_p": "high", "seed": None}
print(read_setting(settings, "temperature"))
print(read_setting(settings, "max_tokens"))
print(read_setting(settings, "top_p"))
print(read_setting(settings, "seed"))
# part of the built-in hierarchy
print(issubclass(KeyError, LookupError), issubclass(LookupError, Exception))
print(issubclass(KeyboardInterrupt, Exception), issubclass(KeyboardInterrupt, BaseException))
Expected output
0.2 missing setting 'max_tokens' bad value for 'top_p': could not convert string to float: 'high' bad value for 'seed': float() argument must be a string or a real number, not 'NoneType' True True False True
A small part of the tree, so you know what a clause will match:
BaseException
├── KeyboardInterrupt, SystemExit (do not catch these)
└── Exception (the widest class you should ever catch)
├── LookupError → KeyError, IndexError
├── ValueError → json.JSONDecodeError
├── TypeError
├── OSError → FileNotFoundError, PermissionError, TimeoutError, ConnectionError
└── ...your own exception classes
One surprise for Java developers: TimeoutError and ConnectionError are subclasses of OSError in Python.
Watch out Order matters. If you write except Exception: first, the more specific clauses below it never run. Always list the subclass before its parent, the same rule as stacked catch blocks in Java (where it is a compile error; in Python it silently never matches).
3Raise your own exceptions, and keep the cause with from
raise is Java's throw. You raise an instance: raise ValueError("prompt is empty"). Inside an except block, a bare raise re-raises the exception you just caught, unchanged.
A custom exception is just a class that inherits from Exception. Give your app one base class (here LLMError) and a subclass per case. Callers then choose: catch one case, or catch the base class to handle them all. Extra data, like how long to wait after a rate limit, goes in attributes.
When you turn a low-level error into your own, write raise NewError(...) from e. The original is kept in the new exception's __cause__, and the traceback shows both. In Java you would pass it as the cause argument of the constructor.
import json
class LLMError(Exception):
"""Base class for every error our LLM code raises."""
class RateLimited(LLMError):
def __init__(self, retry_after: float):
super().__init__(f"rate limited, retry after {retry_after}s") # the message str(e) shows
self.retry_after = retry_after # extra data for the caller
class BadResponse(LLMError):
pass # no extra data: the class name says it all
def parse_answer(raw: str) -> dict:
try:
return json.loads(raw)
except json.JSONDecodeError as e:
raise BadResponse(f"model did not return JSON: {raw[:22]!r}") from e
try:
raise RateLimited(retry_after=2.0)
except LLMError as e: # the base class catches every subclass
print(type(e).__name__, "|", e, "|", e.retry_after)
try:
parse_answer("Sure! Here is the JSON you asked for")
except BadResponse as e:
print(e)
print("caused by:", repr(e.__cause__))
Expected output
RateLimited | rate limited, retry after 2.0s | 2.0
model did not return JSON: 'Sure! Here is the JSON'
caused by: JSONDecodeError('Expecting value: line 1 column 1 (char 0)')class LLMException extends RuntimeException {
LLMException(String msg, Throwable cause) { super(msg, cause); }
}
class BadResponse extends LLMException {
BadResponse(String msg, Throwable cause) { super(msg, cause); }
}
try {
return mapper.readTree(raw);
} catch (JsonProcessingException e) {
throw new BadResponse("model did not return JSON", e); // e = the cause
} If nobody catches the BadResponse, the traceback prints the JSONDecodeError first, then the line "The above exception was the direct cause of the following exception:", then the BadResponse. Without from e you get "During handling of the above exception, another exception occurred:" instead, which reads like a second bug. Use raise ... from None only when the original error is noise you really want to hide.
Tip Name exception classes after what went wrong (RateLimited, BadResponse), not after where (ClientError). The name is what a caller reads in except and what you search for in logs.
4EAFP: try it, instead of checking first
Java style is often LBYL, "look before you leap": check that something is allowed, then do it. Python style is usually EAFP, "easier to ask forgiveness than permission": just do it, and catch the specific error if it fails.
EAFP is not only a matter of taste. With LBYL, the world can change between the check and the action: a file can be deleted, a key removed by another thread. The try version has no such gap. And in Python 3.11 and later, a try block costs almost nothing when no exception is raised.
config = {"model": "llama3.2:3b"}
# LBYL: check first, then act
if "timeout" in config:
timeout = config["timeout"]
else:
timeout = 30.0
print("LBYL:", timeout)
# EAFP: act, and catch the one error you expect
try:
timeout = config["timeout"]
except KeyError:
timeout = 30.0
print("EAFP:", timeout)
# for a default value from a dict, .get() says it in one line
print("get:", config.get("timeout", 30.0))
# where EAFP really wins: there is no gap between "check" and "open"
try:
with open("/no/such/prompt.txt", encoding="utf-8") as f:
text = f.read()
except FileNotFoundError:
text = ""
print("file:", repr(text))
Expected output
LBYL: 30.0 EAFP: 30.0 get: 30.0 file: ''
Tip EAFP does not mean "wrap everything in try". Catch one specific error around one small action. Use the simplest tool when there is one: dict.get(key, default) beats both styles for a missing key.
5with: files and locks that clean up after themselves
Some things must be released when you are done: a file must be closed, a lock released, a connection returned to its pool. The with statement does it for you. with open(path) as f: opens the file, gives it to you as f, and closes it when the indented block ends, whether the block finishes normally, returns, or raises.
It is the same idea as Java's try-with-resources. JavaScript developers usually write the try / finally by hand. An object that works with with is called a context manager. Files, locks, database connections, HTTP clients (httpx.Client) and temporary folders all are.
The example uses tempfile.TemporaryDirectory(), a context manager that creates a temporary folder and deletes it, with everything inside, when its block ends.
import tempfile
import threading
from pathlib import Path
with tempfile.TemporaryDirectory() as folder: # folder is a path string
path = Path(folder) / "prompt.txt" # / joins paths in pathlib
with open(path, "w", encoding="utf-8") as f: # "w" = write, replacing any old content
f.write("You are a helpful assistant.\n")
print("closed after the block:", f.closed)
try:
with open(path, encoding="utf-8") as f: # the default mode is "r" (read)
print(f.readline().strip())
raise RuntimeError("boom inside the block")
except RuntimeError as e:
print("error:", e, "| closed anyway:", f.closed)
print("folder deleted:", not Path(folder).exists())
lock = threading.Lock()
with lock: # lock.acquire() here...
print("locked inside:", lock.locked())
print("locked after:", lock.locked()) # ...lock.release() when the block ends
Expected output
closed after the block: True You are a helpful assistant. error: boom inside the block | closed anyway: True folder deleted: True locked inside: True locked after: False
try (var reader = Files.newBufferedReader(path)) {
System.out.println(reader.readLine());
} // reader.close() runs here, even on an exception
lock.lock();
try {
count++;
} finally {
lock.unlock(); // Java has no "with" for locks
} const file = await fs.promises.open(path);
try {
console.log(await file.readFile("utf8"));
} finally {
await file.close(); // you must remember this yourself
} Watch out f = open(path) without with leaves the file open if anything raises before f.close(). In a long-running server that leaks file handles until the process hits its limit. Always open files with with.
6Write a context manager as a class
Any class with two special methods works with with. __enter__(self) runs at the start of the block; what it returns is what as name receives. __exit__(self, exc_type, exc, tb) runs at the end. If the block raised, the three arguments are the exception's class, the exception object and its traceback; if it did not, all three are None.
The return value of __exit__ matters: return False (or nothing, which is None) and the exception keeps going to the caller; return True and it is swallowed. You almost always want the first.
The example is a tiny tracing span: it prints when a step of a RAG pipeline starts and ends, and whether it failed. Tracing tools for LLM apps, such as OpenTelemetry, work the same way.
class Span:
"""Prints when a block starts and ends, like a tiny tracing span."""
def __init__(self, name):
self.name = name
def __enter__(self):
print(f"start {self.name}")
return self # this is what "as span" receives
def __exit__(self, exc_type, exc, tb):
if exc_type is None:
print(f"end {self.name}: ok")
else:
print(f"end {self.name}: failed with {exc_type.__name__}: {exc}")
return False # do not swallow the error: let it reach the caller
with Span("retrieve") as span:
print("inside", span.name)
try:
with Span("generate"):
raise TimeoutError("model took too long")
except TimeoutError:
print("the caller still sees the TimeoutError")
Expected output
start retrieve inside retrieve end retrieve: ok start generate end generate: failed with TimeoutError: model took too long the caller still sees the TimeoutError
What with does for you. with Span("retrieve") as span: runs, roughly:
manager = Span("retrieve")
span = manager.__enter__()
try:
... # the indented block
except BaseException as e:
if not manager.__exit__(type(e), e, e.__traceback__):
raise # __exit__ returned False: re-raise
else:
manager.__exit__(None, None, None)
Watch out Returning True from __exit__ (or putting return True at the end "to be safe") hides every error raised in the block. The code after the with runs as if nothing happened.
7@contextmanager and a timing context manager
Writing a class for every context manager is a lot of typing. contextlib.contextmanager turns a function with one yield into a context manager: the code before yield is the "enter" part, the body of the with block runs at the yield, and the code after it is the "exit" part. (A function with yield is a generator; lesson 8 explains them. Here you only need "the function pauses at yield".)
If the block raises, the exception is raised at the yield line inside your function. That is why the exit part goes in a finally: without it, the cleanup is skipped exactly when something went wrong.
A timer is the classic first one. Use it to see how long each step of an LLM request takes: retrieval, the model call, parsing.
import time
from contextlib import contextmanager
@contextmanager
def timed(label):
start = time.perf_counter() # enter: runs when the with block starts
try:
yield # the with block runs here
finally:
ms = (time.perf_counter() - start) * 1000
print(f"{label} took {ms:.0f} ms") # exit: runs even if the block raised
with timed("embed"):
time.sleep(0.1)
try:
with timed("chat"):
time.sleep(0.2)
raise ConnectionError("server closed the connection")
except ConnectionError as e:
print("error:", e)
Expected output
embed took 100 ms chat took 200 ms error: server closed the connection
time.perf_counter() is a clock for measuring durations, like System.nanoTime() in Java or performance.now() in JavaScript. Write yield value to hand something to as name, for example yield client. And contextlib.suppress(FileNotFoundError) is a ready-made context manager that ignores one named error on purpose, which is the honest way to say "a missing file is fine here".
Watch out Forgetting the try / finally around yield. The timer then prints nothing for a failed call, which is exactly the call you wanted to measure.
8Retry with backoff, revisited
In lesson 4 you wrote a @retry decorator. Now that you can define your own exceptions, the retry loop can do better: retry only errors that may succeed next time, honour the server's retry_after on a rate limit, and when it finally gives up, raise one clear error that keeps the last failure as its cause (from e).
The sleep function is a parameter that defaults to time.sleep. The demo passes waits.append instead, so nothing actually waits and you can see every wait in a list. Passing a dependency in like this is how you test retry code without slow tests.
import random
import time
class LLMError(Exception):
pass
class RateLimited(LLMError):
def __init__(self, retry_after):
super().__init__(f"rate limited, retry after {retry_after}s")
self.retry_after = retry_after
class GaveUp(LLMError):
pass
RETRYABLE = (TimeoutError, ConnectionError, RateLimited) # errors that may pass next time
def call_with_retry(fn, *, attempts=4, base=0.5, jitter=0.1, sleep=time.sleep):
for attempt in range(1, attempts + 1):
try:
return fn()
except RETRYABLE as e: # anything else (a bug, bad input) is NOT caught
if attempt == attempts:
raise GaveUp(f"failed after {attempts} attempts") from e
if isinstance(e, RateLimited):
wait = e.retry_after # the server told us how long to wait
else:
wait = base * 2 ** (attempt - 1) + random.uniform(0, jitter)
print(f"attempt {attempt} failed ({type(e).__name__}: {e}), waiting {wait:.1f}s")
sleep(wait)
# a fake model call: fails twice, then answers
script = [TimeoutError("read timed out"), RateLimited(1.5), "Paris"]
def flaky():
item = script.pop(0)
if isinstance(item, Exception):
raise item
return item
waits = []
print(call_with_retry(flaky, jitter=0, sleep=waits.append)) # jitter=0 keeps the output identical every run
print("waited:", waits)
def always_down():
raise ConnectionError("connection refused")
try:
call_with_retry(always_down, attempts=3, jitter=0, sleep=waits.append)
except GaveUp as e:
print(e, "| last error:", repr(e.__cause__))
def bad_prompt():
raise ValueError("prompt is empty")
try:
call_with_retry(bad_prompt, sleep=waits.append)
except ValueError as e:
print("not retried:", e)
Expected output
attempt 1 failed (TimeoutError: read timed out), waiting 0.5s
attempt 2 failed (RateLimited: rate limited, retry after 1.5s), waiting 1.5s
Paris
waited: [0.5, 1.5]
attempt 1 failed (ConnectionError: connection refused), waiting 0.5s
attempt 2 failed (ConnectionError: connection refused), waiting 1.0s
failed after 3 attempts | last error: ConnectionError('connection refused')
not retried: prompt is emptyWhat the key lines do
except RETRYABLE as e:catches only the classes in the tuple. TheValueErrorfrombad_promptpasses straight through on the first try, with no waiting.*,in the signature makes every parameter after it keyword-only: you must writeattempts=3, never a bare3.raise GaveUp(...) from egives the caller one error to handle, ande.__cause__still says what really happened.
The openai SDK already retries for you: by default it makes 2 extra attempts with backoff on connection errors, timeouts, 408, 409, 429 and 5xx responses (OpenAI(max_retries=2)). Write your own loop for your own tools and services, or for errors the SDK does not know are temporary, like a reply that is not valid JSON.
Tip Only retry an action that is safe to run twice (reading, or a write with an idempotency key). Retrying a payment because the response timed out can charge the user twice.
9Log errors, and tell the user something useful
At the edge of your app (the web handler, the CLI command, the agent loop), every error must end up somewhere: either it is handled and the user gets a clear message, or it is logged with its traceback so you can fix it. The one thing never to do is except Exception: pass, which turns a crash you would notice into a wrong answer you will not.
log.exception("...") inside an except block logs your message plus the full traceback. log.warning and log.error log just the message, which is right for errors you expected and handled.
The openai SDK raises a different class for each failure. The demo defines small stand-in classes with the same names and the same parents so it runs here in your browser; the code under it is the same mapping with the real SDK, for your labs.
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
log = logging.getLogger("chat")
# stand-ins with the same names and parents as the openai SDK's exceptions
class APIError(Exception): pass
class APIConnectionError(APIError): pass
class APITimeoutError(APIConnectionError): pass # a timeout IS a connection error
class APIStatusError(APIError): pass # the server answered with 4xx or 5xx
class RateLimitError(APIStatusError): pass # 429
class AuthenticationError(APIStatusError): pass # 401
def answer(question, call_model):
try:
return call_model(question)
except APITimeoutError: # before APIConnectionError, or it never matches
log.warning("model timed out")
return "The model is taking too long. Please try again."
except APIConnectionError:
log.warning("cannot reach the model server")
return "We cannot reach the AI service right now. Please try again in a minute."
except RateLimitError:
log.warning("rate limited")
return "Lots of people are asking right now. Please wait a few seconds."
except AuthenticationError:
log.error("API key rejected: check LLM_API_KEY") # our bug, not the user's
return "Something is wrong on our side. We are on it."
except Exception:
log.exception("unexpected error while answering") # message + full traceback
return "Something went wrong. Please try again."
def fails_with(error):
def call(question):
raise error
return call
print(answer("hi", lambda q: f"Answer to {q}"))
print(answer("hi", fails_with(APITimeoutError("timed out"))))
print(answer("hi", fails_with(RateLimitError("429 Too Many Requests"))))
print(answer("hi", fails_with(KeyError("choices"))))
Expected output
Answer to hi
WARNING chat: model timed out
The model is taking too long. Please try again.
WARNING chat: rate limited
Lots of people are asking right now. Please wait a few seconds.
ERROR chat: unexpected error while answering
Traceback (most recent call last):
File "...", line 19, in answer
return call_model(question)
^^^^^^^^^^^^^^^^^^^^
File "...", line 39, in call
raise error
KeyError: 'choices'
Something went wrong. Please try again.import logging
import openai
log = logging.getLogger("chat")
client = openai.OpenAI(base_url="http://localhost:11434/v1", api_key="ollama",
timeout=30.0, max_retries=2) # the SDK retries before raising
def answer(question: str) -> str:
try:
resp = client.chat.completions.create(
model="llama3.2:3b",
messages=[{"role": "user", "content": question}],
)
return resp.choices[0].message.content or ""
except openai.APITimeoutError: # subclass of APIConnectionError: catch it first
log.warning("model timed out")
return "The model is taking too long. Please try again."
except openai.APIConnectionError:
log.warning("cannot reach the model server")
return "We cannot reach the AI service right now. Please try again in a minute."
except openai.RateLimitError as e: # 429, after the SDK's own retries
log.warning("rate limited, request id %s", e.request_id)
return "Lots of people are asking right now. Please wait a few seconds."
except openai.AuthenticationError: # 401
log.error("API key rejected: check LLM_API_KEY")
return "Something is wrong on our side. We are on it."
except openai.APIStatusError as e: # any other 4xx or 5xx
log.error("model API returned %s: %s", e.status_code, e.message)
return "The AI service had a problem. Please try again." The traceback lines will show your own file name and line numbers. logging.basicConfig(...) sets up logging once at program start: here it sends logs to the same output as print, at level INFO and above, in the format LEVEL logger-name: message. request_id is the ID the provider gives each request; put it in your logs so their support can find your failed call.
Watch out except Exception: pass (or except Exception: return None) hides real bugs: a typo, a changed response shape, a missing key. If you catch broadly, do it only at the edge of the app, and always log with log.exception first.
Common mistakes
- Writing a bare
except:. It also catchesKeyboardInterruptandSystemExit, so Ctrl+C stops working. The widest you should catch isexcept Exception:, and only at the edge of the app. - Swallowing errors with
except Exception: pass. The program keeps running with wrong data and nothing in the logs says why. Handle the error, or log it withlog.exception, or let it propagate. - Putting a parent class before its subclass:
except APIConnectionError:aboveexcept APITimeoutError:means the timeout branch never runs. - Raising a new exception inside
exceptwithoutfrom e, which loses the clear "direct cause" link to the original error in the traceback. - Writing a
@contextmanagerwithouttry / finallyaround theyield, or an__exit__that returnsTrue: the cleanup is skipped on errors, or the errors disappear. - Retrying every exception, including bad requests and wrong API keys. Retry only timeouts, connection errors, 429 and 5xx, and only actions that are safe to repeat.
Practice
Write the code, then press Check. Your work is saved in this browser.
1Catch only what you expect
to_int should return int(text), or default when the text is not a number. Right now its bare except: also hides bugs: calling it with None (a programming error) quietly returns the default. Change it so it catches only ValueError, and a TypeError reaches the caller.
def to_int(text, default):
try:
return int(text)
except:
return default
print(to_int("12", 0), to_int("twelve", 0))
Hint
Replace `except:` with `except ValueError:`. `int(None)` raises TypeError, which then passes through.
2A timer that survives errors
timer() yields a dict and should store the elapsed milliseconds in it under "ms" when the block ends, even if the block raises. It must not swallow the error. Fix the starter.
import time
from contextlib import contextmanager
@contextmanager
def timer():
result = {}
start = time.perf_counter()
yield result
result["ms"] = (time.perf_counter() - start) * 1000
with timer() as t:
time.sleep(0.05)
print(round(t["ms"]))
Hint
Wrap `yield result` in `try:` and move the line that sets `result["ms"]` into a `finally:` block.
3Wrap the error with from
load_settings(text) parses a JSON string and returns the dict. Make it raise ConfigError (already defined) in two cases: the text is not valid JSON (chain the original json.JSONDecodeError with from), and the JSON has no "model" key (message: missing "model").
import json
class ConfigError(Exception):
pass
def load_settings(text):
return json.loads(text)
print(load_settings('{"model": "llama3.2:3b"}'))
Hint
Put `data = json.loads(text)` in a `try`, and in `except json.JSONDecodeError as e:` write `raise ConfigError("invalid JSON") from e`. Then check `if "model" not in data:`.
Interview questions
Q1What is the difference between else and finally in a try statement?
else runs only when the try block raised no exception; it is the place for code that should run on success, so that the try block holds only the code that can fail. finally always runs, after success, after an exception, and even after a return, and is used for cleanup.
Q2Why should you never use a bare except?
A bare except: catches BaseException, which includes KeyboardInterrupt and SystemExit, so the program cannot be stopped, and it hides every bug. Catch the specific exceptions you can handle. except Exception: is acceptable only at the outer edge of an app, together with logging.
Q3What does raise ... from e do?
It raises a new exception and stores the original in its __cause__, so the traceback shows both, linked by "The above exception was the direct cause". It is how you translate a low-level error (a JSON error, an HTTP error) into your own domain error without losing information. from None hides the original.
Q4Explain EAFP and LBYL.
LBYL (look before you leap) checks conditions before acting; EAFP (easier to ask forgiveness than permission) acts and catches the specific exception. Python favours EAFP: it is often shorter, and it avoids the race where the situation changes between the check and the action, such as a file being deleted.
Q5How does a with statement work, and how do you write a context manager?
The object's __enter__ runs at the start and its return value is bound by as; __exit__(exc_type, exc, tb) runs at the end, even on an exception, and returning True from it suppresses the exception. You can write a class with those two methods, or a generator function decorated with @contextlib.contextmanager that does setup, yields inside try, and cleans up in finally.
Q6How would you handle errors from an LLM API in production?
Retry only transient failures (timeouts, connection errors, 429, 5xx) with exponential backoff and jitter, honouring any retry-after, and only for safe-to-repeat calls. Do not retry 400 or 401. Catch the SDK's specific exception classes, subclasses first, and map each to a clear user message. Log the status code and request ID, and log unexpected errors with their traceback instead of swallowing them.