Robust LLM API Wrapper
Write a callllmapi(prompt, apicallfn) wrapper that calls the given API function and handles failures gracefully, returning a clear fallback message instead of crashing.
Why a mock instead of a real API? the notes' own version calls a real LLM provider, but an automated judge has no reliable internet access and no API key — so instead, apicallfn is a stand-in function passed in (exactly like the Testing chapter's MagicMock pattern), which can simulate success, a timeout, or a connection failure, letting the wrapper's actual error-handling logic be tested directly.
Approach: call apicallfn(prompt) inside a try block, and return a specific fallback message for a TimeoutError vs a ConnectionError.
Input: Two lines: the scenario to simulate (success, timeout, or connection_error), and the prompt text.
Output: One line: the AI's reply (on success), or a fallback error message (on failure).
success Hello
AI response to: Hello
- scenario is one of success, timeout, connection_error.
Hint 1
Wrap the call api_call_fn(prompt) in a try block, exactly like a real requests.post() call would be.
Hint 2
Use two separate except clauses — one for TimeoutError, one for ConnectionError — each returning its own specific message.
Hint 3
On success (no exception), simply return whatever api_call_fn(prompt) returned.
callllmapi wraps the call to apicallfn(prompt) in a try block, exactly as a real requests.post()-based call would be. Separate except clauses for TimeoutError and ConnectionError return distinct, clear fallback messages instead of letting the exception crash the program — the mock_api stand-in lets all three scenarios (success, timeout, connection failure) be tested deterministically, without any real network access.