Talk to an LLM from code
Debug the unreliable LLM API call
Page 5 advances one concrete command-line LLM summarizer: explain the decision, run the code, inspect failure, measure evidence, and keep only what is ready to ship.
Before you start
Why this matters
Without running code, predict the output of this page's example and name the intermediate value that would prove your prediction. Then write one sentence answering: “What could look successful while actually being wrong?” For this stage, focus on unreliable LLM API call. Keep the prediction nearby; comparing it with the real output is the first debugging exercise, not a quiz about syntax.
1Learn the idea
Read
Build focus
Break the artifact on purpose. The most important failure family is missing keys, timeouts, rate limits, malformed JSON, empty choices, and prompt text accidentally appearing in logs. Reproduce one failure with the smallest possible input, inspect the intermediate values, and fix the boundary or algorithm rather than catching every exception. Retrying deterministic bad input only repeats the same mistake; a retry is justified only for a transient dependency.
The artifact's user-facing goal is specific: send one system message and one user message through an HTTP-shaped client and return a bounded one-sentence summary. Its accepted input is a non-empty text string, model name, timeout, and API key loaded from the environment. Those statements are intentionally narrower than “build an AI system.” Narrow scope lets us inspect every input and expected result, and it prevents a toy result from being presented as a production claim. This example demonstrates a controlled failure or defensive branch and prints the reason instead of crashing mysteriously.
Read
Run the example
Save this as lesson.js and run node lesson.js. It uses only the language standard library, so the example is reproducible offline.
async function retry(call){for(let n=0;n<3;n++){try{return await call()}catch(e){if(e.status!==429||n===2)throw e;}}}
let n=0; retry(async()=>{if(n++<1)throw Object.assign(new Error('rate'),{status:429});return 'ok'}).then(console.log);
Expected output: ok after one simulated 429. Exact floating-point formatting may vary slightly, but the asserted behavior must not. Read the output as evidence about this stage, not merely proof that the interpreter started.
Read
Debug the stage
Separate request construction, transport, and response parsing. Test each with a fake transport before contacting a provider. For a malformed response, print the status and safe structural fields, never the API key or full prompt. Retry only explicit transient statuses such as 429, cap attempts, and preserve the final error. A missing choices array is a contract failure, not an empty successful summary.
At the debugging stage, save the smallest failing fixture beside the expected result. Change one cause at a time and rerun the exact command printed above; that makes the repair reviewable and keeps this chapter's progressive artifact reproducible.
Read
Evaluate before continuing
Run a fixed set of short prompts through the fake contract and, when credentials are intentionally available, through the real adapter. Measure latency, retries, output length, and whether the one-sentence constraint holds. Save expected properties rather than exact prose because model wording can vary. Contract tests must remain deterministic and runnable offline.
For this debugging page, preserve the fixture and result as evidence for the next page. Label observations separately from conclusions: a passing assertion establishes the behavior it names, while broader usefulness requires the chapter's full evaluation set and stated operating limits.
Continue learning · glossary & guides
- [ ] Can I reproduce the failure with one minimal input?
- [ ] Did I fix the first broken invariant instead of masking the exception?
- [ ] Does a neighboring valid case still pass?
- [ ] Can every network behavior be tested through the fake transport?