Skip to content
C

Robust LLM API Wrapper

Mediumpython

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).

Input (stdin)

Output

Run your code to see output here...