HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 14“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Working with LLM APIs and Model Providers
TechLearningPro's Explain path had a versioned prompt and a draft that could not complete a lesson.
Course progress0%
Focus
16 guided sections
Practice signal
Concept-first lesson
Career prep
Foundation builder
AI-Powered Full Stack Development · Lesson 14 · AI and LLM Application Fundamentals
Lesson Overview
TechLearningPro's Explain path had a versioned prompt and a draft that could not complete a lesson. The HTTP call in front of it was still a demo. A 429 from the provider was retried in a tight loop, so one busy enrollment morning multiplied the token bill while learners still saw a spinner. A timeout was retried the same way, and the provider kept generating after the lesson player had given up. A 401 was logged with the Authorization header because the error helper printed response and the request together. Separately, a teammate imported a vendor SDK into the React page "only for localhost," and the fixture key from the test file landed in a bundle review.
This lesson is the server-side client those incidents required. You will call a chat-completions-style HTTP API with fetch, parse the body with Zod, map status codes to typed reasons, retry once only for a short list of conditions, refuse to retry a timeout, and stop a tenant that has spent its daily token ceiling. The prompt renderer from lesson 13 stays the producer of messages. The progress API stays on the quiz path from lesson 12. Provider SDK methods are not the contract. If a vendor publishes a different path, you hide it inside an adapter that still returns the same result type.
No provider account is required to pass the tests. A live base URL is a later binding, done after you read that provider's current HTTP reference.
Detailed Core Concepts
The port is the product contract
Explain needs a function: messages in, draft text or a typed failure out, plus token counts when the provider supplies them. That function is the port. A chat-completions-style adapter is one implementation. A second provider, or a fake, is another. The lesson player, the prompt registry, and progressFromQuiz do not import a vendor package.
SDK convenience methods change names and shapes between major versions. This course does not call them and does not invent stand-ins. The stable surface you code against is HTTP you can read in a test: method, URL, headers, JSON body, status, JSON response. Where this lesson names max_tokens, messages, and choices[0].message.content, it is naming a chat-completions style that many providers document. Confirm those fields on the day you set LLM_BASE_URL. If the current docs use a different cap field or a different path, change the adapter. Leave the port's result type alone.
What the request contains
The body this adapter sends:
model: the id from LLM_MODEL, not a model name hard-coded in the component.
messages: the array explain-v3 already rendered. The client does not rewrite roles.
temperature: 0.2 for Explain, omitted later if that model id rejects the field. An HTTP 400 whose body says the field is unsupported is an adapter fix, not a retry.
max_tokens: the output cap. Some current APIs use a different property for the same idea. Keep the mapping on one line.
The headers:
content-type: application/json
authorization: Bearer plus the key from LLM_API_KEY
The key is not a query parameter. Query parameters leak into access logs. The key is not a default argument. Missing configuration returns missing_config before fetch.
Status codes you will actually handle
Status
Meaning for Explain
Action
200 with a parsed body
Provider produced a completion
Return text or truncated / empty
400
Your body was rejected
invalid_request, no retry
401 or 403
Credential or permission
unauthorized_provider, no retry, page the owner
408
Provider-side request timeout
timeout, no automatic retry
429
Rate limit
One retry if Retry-After is short, else rate_limited
500
Provider fault, request may have been accepted
No automatic retry
503
Provider unavailable, often safe to try once
One retry with a capped wait
Network throw or abort
You did not get a status
timeout or network, no retry on abort
HTTP 500 is the awkward one. The provider may have run the model and failed while writing the response. A silent retry can double-bill. This lesson does not retry 500. A user can click Explain again. That second click is visible and rare. A loop is neither.
Retry-After may be a delay in seconds or an HTTP date. This client honors a delta-seconds value between 0 and 2 inclusive, and otherwise skips the automatic retry so a Retry-After: 120 cannot freeze the request thread. The learner can try later. The UI should say the tutor is busy, not spin for two minutes.
Timeouts are cancellations, not hints
AbortSignal.timeout rejects the fetch with TimeoutError or AbortError, matching lesson 4. When that happens you do not send a second request inside the same click. The first request may still be generating on the provider. Retrying it is how the enrollment-morning bill grew while the spinner was already gone. Record timeout, increment a metric, and return. The player shows the lesson.
Set the timeout from the same budget the product promised, 8 seconds for a section explanation. A batch summary job uses a different client configuration and a queue, not this signal.
Ceilings beat post-hoc surprise
Token usage is the meter that does not show up in CPU graphs until finance forwards the invoice. The adapter estimates a charge before the call: packed input tokens plus maxOutputTokens. If that estimate would carry the tenant over the daily ceiling, return budget_exceeded and do not call fetch. When the response includes usage, record the provider's total_tokens (or the sum of prompt and completion tokens). When it does not, record the estimate. Recording the estimate on failure-to-report avoids a free pass for a provider that omits usage.
The ceiling is per tenant. A global ceiling hides which customer ran away. The ledger in this lesson is in-memory so the tests are obvious. Production puts the same numbers in a store that survives a process restart, or the ceiling resets every time you deploy. The interface below is the one you keep.
Idempotency keys belong on the progress POST, which lesson 10 and lesson 11 already treat as a fact you might retry safely. A generation POST is not idempotent. Sending the same messages twice can produce two drafts and two charges. Do not reuse the progress idempotency key as a provider retry token unless the provider documents that header and you understand whether it suppresses a second generation. This lesson does not send one.
Portability without a lowest-common-denominator mess
The port returns your types. The adapter may:
Rename the output cap field.
Drop temperature for a model id that rejects it.
Read a different environment variable if you run two providers, still from the environment, still never from the client.
Map a provider-specific error JSON into the same reasons. Unknown shapes become invalid_body or http_error, not thrown vendor types in the UI.
The adapter may not:
Accept a tool name that marks a lesson complete. Tools are the next lesson; the rule is already in force.
Log the key while "debugging the 401."
Fall back from a failed provider to a second provider that receives the same excerpt unless that failover is an explicit, budgeted product decision. Silent failover doubles the privacy surface and the chance of a mismatched prompt version.
What you store
Store the draft if the product needs to show it again: tenant, user, lesson version, prompt version, model id, text, and token counts. Mark it non-authoritative. Do not store the Authorization header. Retention of the question text is a privacy decision; the default log line in this lesson stores lengths, not the question. A redaction helper allow-lists fields so a future console.log(request) has to be a deliberate change.
Architecture and Request Flow
flowchart TB
subgraph browser [Browser]
Player[Lesson player]
end
subgraph api [TechLearningPro API]
Auth[Session tenant and lesson ACL]
Prompt[explain-v3 renderer]
Ledger[Tenant token ledger]
Port[Model port]
Progress[Progress service]
end
subgraph data [System of record]
DB[(PostgreSQL)]
end
subgraph provider [Provider]
Http[Chat completions style HTTP]
end
Player -->|explain| Auth
Auth --> Prompt
Prompt --> Ledger
Ledger -->|under ceiling| Port
Ledger -->|over ceiling| Player
Port -->|one POST, optional single retry| Http
Http --> Port
Port -->|draft or typed failure| Player
Player -->|quiz| Progress
Progress --> DB
The ledger sits in front of the port so a ceiling breach spends nothing. The retry, when it happens, is inside the adapter and still counts as the same user click. Progress never observes the provider status.
Step-by-step Implementation
Package path: packages/llm-client/. Strict TypeScript. The tests pass a fake fetch and a fake sleeper so retry waits do not slow the suite.
Step 1: Result types and redacted logs
packages/llm-client/src/types.ts
typescript
exportinterfaceChatMessage{
role:"system"|"user"|"assistant";
content:string;
}
exporttypeClientFailure=
|"missing_config"
|"budget_exceeded"
|"invalid_request"
|"unauthorized_provider"
|"rate_limited"
|"timeout"
|"unavailable"
|"http_error"
|"invalid_body"
|"empty"
|"truncated"
|"network";
exporttypeClientResult=
|{
ok:true;
text:string;
model:string;
promptVersion:string;
promptTokens:number;
completionTokens:number;
}
|{ ok:false; reason: ClientFailure };
exportinterfaceLogRecord{
tenantId:string;
lessonId:string;
promptVersion:string;
model:string;
reason:"ok"| ClientFailure;
status?:number;
durationMs:number;
estimatedTokens:number;
}
/** Allow-list. New fields are added here on purpose, not by spreading the request. */
Call canSpend with the estimate before fetch. Call record with provider usage on success, and with the estimate if the call failed after the provider accepted it (http_error on 500) only when you have evidence the call was billed. This lesson records on success, and records the estimate on truncated because the provider did generate. It does not record on unauthorized_provider or on a ceiling refusal.
A 200 with an HTML body, or a JSON object that uses a different nesting, becomes invalid_body. That is preferable to displaying [object Object] in the tutor panel.
const total = parsed.data.usage?.total_tokens ?? promptTokens + completionTokens;
ledger.record(input.tenantId, total);
returnfinish({
ok:true,
text,
model: parsed.data.model,
promptVersion: config.promptVersion,
promptTokens,
completionTokens,
}, status);
}
Read the retry carefully. retryDelayMs returns null when the status is not retryable, and when Retry-After is longer than two seconds. A null skips the second completeOnce. A timeout on the first attempt returns immediately and never reaches the delay function. promptVersion on a success is config.promptVersion, which the caller sets to explain-v3. The model cannot rename the release.
temperature and max_tokens stay in this file. A provider that documents replacements gets those replacements here, with a comment that cites the doc you read, not a guessed method name.
Step 5: Wire env without importing a key into the browser
The API route, not this package's tests, calls configFromEnv(process.env, "explain-v3"). The browser bundle does not import client.ts. If your bundler pulls server modules into the client, the bug is the import graph, and the symptom is a missing process.env.LLM_API_KEY that someone then "fixes" with NEXT_PUBLIC_LLM_API_KEY. That fix publishes the secret. Keep the import on the server side of the framework boundary you built in the Next.js lesson.
Cleanup: unset any shell export you made for a manual experiment, and do not commit .env. The tests never read a live environment.
Security and Privacy
LLM_API_KEY is read inside configFromEnv from the object the server passes. Tests pass a fixture. Production passes process.env. Nothing writes the key into LogRecord.
toLogRecord returns a new object of known fields. Logging attempt.response or the request init would copy the bearer token into the sink. The 401 incident was that copy.
The ledger key is tenantId from the session, not from the JSON body. A caller who can pick another tenant id can spend that tenant's ceiling or hide their own usage.
The messages still contain the authorized excerpt. The client sends them to the provider, which is a processor. Do not add other learners' rows because the provider "might personalize better."
401 is an operator event. Rotate the key, confirm the server identity, and only then retry a single manual call. Automatic retry of 401 burns nothing useful and spreads the bad credential through more log lines if logging is sloppy.
Least privilege on the provider account: a key that can call the chat endpoint for the chosen model, not a key that can manage billing or read other projects. The database role remains separate.
Generation output is still a draft. A successful 200 does not authorize progressFromQuiz.
Error Handling
Reason
Retry in this click
Learner
Ledger
missing_config
No
Tutor hidden
No charge
budget_exceeded
No
"Explain is paused for today"
No charge
invalid_request
No
Tutor hidden, operator alert
No charge
unauthorized_provider
No
Tutor hidden, operator alert
No charge
rate_limited
Already consumed the one retry, or skipped because Retry-After was long
"Explain is busy"
No charge if both attempts failed before a body
timeout
No
Lesson stays, tutor unavailable
No charge recorded, provider may still bill
unavailable
One attempt already retried
Tutor unavailable
No charge if no success body
truncated
No
Lesson stays, no partial text
Record usage or estimate
http_error
No
Tutor unavailable
No automatic second call
Surface a stable reason to the browser. Do not forward the provider's error JSON. It can contain request echoes. The progress endpoint keeps its own errors: not_passing, constraint violations, idempotent replays. Do not map those through ClientFailure.
If the sleeper's wait is interrupted because the user navigated away, abort. The lab sleeper is a promise. The production route should pass a sleeper that rejects on the request's abort signal so a disconnected client does not hold a retry. Document that hook in the route even if this package's default sleeper is setTimeout.
The 429 test records one sleep, one success, and a single usage charge. Add a case where Retry-After is 120 and assert a single call and rate_limited. Count calls if you change the status list.
Evaluation of the client is mostly contract tests. Quality of the paragraph stays in the prompt eval from lesson 13. Add a dashboard later for timeout rate, 429 rate, budget_exceeded rate, and tokens per tenant. A spike in 400 after a model-id change means the adapter is sending a field that model rejects.
Performance and Cost
The timeout is 8 seconds. The optional retry adds at most 2 seconds of wait plus another 8 seconds. That is the worst case for one click, and it happens only on 429 or 503. It must not happen on every click.
maxOutputTokens of 400 is both a latency cap and a cost cap. The ledger reserves input plus that maximum, which overestimates typical answers. Over-reservation is the conservative ceiling behavior. Reconcile to usage after success so the next call is not charged twice for the same tokens: record stores actual total, and the reservation was only a check. Look at canSpend: it does not increment. Only record increments. A successful call records actuals, not estimate plus actuals.
In-memory ledgers reset on deploy. That is a ceiling bypass. Persist the counter before you turn the ceiling into a customer promise.
Concurrency: two parallel Explain clicks can both pass canSpend and then both record, overshooting by one request. For a daily ceiling that is often acceptable. For a hard monetary stop, decrement a reservation in a transaction in PostgreSQL. Name that race in the design even if the lab map stays process-local.
Caching: still keyed by tenant, lesson version, prompt version, and question hash, and only for non-personalized excerpts. A cache hit should not call the provider and should not double-record tokens.
Illustrative ratio: a retry loop on 429 during an outage can multiply spend by the number of learners clicking Explain. One retry bounds that multiplier at two for a single click, and the ceiling bounds the tenant for the day. Without the ceiling, a bug in the retry predicate removes the bound.
Provider latency dominates. Zod and the ledger are noise. Do not put this client on the progress POST's critical path. The quiz write returns even when the provider is down.
Knowledge Check
1. What problem does this capability solve?
It turns Explain's model call into a bounded server dependency: typed statuses, a single narrow retry, a timeout that does not retry, a redacted log, and a per-tenant token ceiling. The prompt and the progress rules stay where the previous lessons put them.
2. What alternatives exist, and when would you choose each?
A direct fetch adapter fits this course because the HTTP contract stays visible. A vendor SDK fits a team that pins the version and wraps it in the same port, after reading that SDK's current docs. A queue fits jobs longer than the 8-second tutor. Browser-side calls fit a personal experiment and fail the credential review. Retrying every status fits nothing in this product.
3. Which data, identity, and trust boundaries matter?
The key lives in server env. The tenant id on the ledger comes from the session. The provider receives messages that already passed the ACL and the prompt registry. Logs receive the allow-list. PostgreSQL receives progress only from the quiz path.
4. What can fail, and how should the system respond?
400 and 401 fail once and alert operators. 429 and 503 may try once more if the wait is at most two seconds. Timeouts fail once. Ceiling breaches do not call the network. Truncation records usage and shows no partial draft. The lesson page renders in every case.
5. How would you test quality, security, performance, and cost?
Contract tests cover success usage, ceiling refusal, a single 429 retry, no timeout retry, no 400 retry, URL joining, and log redaction. Security review inspects the server import graph for the key. Cost review checks that record uses provider totals and that a persisted ledger replaces the map before launch. Prompt quality stays on the lesson 13 eval, split by promptVersion and model id.
Hands-on Assignment
Lab note. Inject fetch. Use test-key-not-a-secret. Do not print process.env in a test snapshot.
Problem. Replace the demo POST with explainWithProvider, including the ledger and the retry rules.
Tasks.
Implement the client, ledger, schema, and tests above. Fix the 429 sequencing so the assertion counts calls if you prefer that style.
Add the Retry-After: 120 case: one call, rate_limited, zero sleep.
Show a log line for a 401 and show that the fixture key is absent from it.
Draw the sequence for timeout versus 503. Mark which one can spend twice.
Write six control rows: env key, status map, retry predicate, ceiling, log allow-list, progress isolation.
State how you will persist the ledger before the ceiling is a customer-facing promise.
Deliverable. Diagram, tests, control table, and a note on 500 versus 503.
Challenge. Two instances of the API both hold a TokenLedger. Show a spend path that crosses the ceiling. Describe the PostgreSQL update you would use so the check and the reservation commit together. Keep generation itself non-idempotent.
Rubric. Conceptual accuracy and architecture 20%. Working implementation 25%. Security and privacy 20%. Tests and reliability 20%. Documentation of trade-offs 15%.
Common Mistakes
Retrying timeouts. Symptom: the invoice climbs after the UI has already shown a failure. Cause: a generic retry wrapper around fetch. Fix: abort is terminal for that click.
Logging the request init on 401. Symptom: the bearer token appears in the log vendor. Cause: a helper dumped the whole object. Fix: toLogRecord, rotate the key, purge the sink.
Putting the SDK in the client bundle. Symptom: a key or a browser call to the provider. Cause: a shared module imported from React. Fix: server-only module, no NEXT_PUBLIC_ key, rotate if it shipped.
Ceiling checked and then ignored under concurrency. Symptom: a tenant exceeds the plan during a burst. Cause: canSpend and record are not one transaction. Fix: persist a reservation when the promise matters.
Recording the estimate and the usage. Symptom: the ledger runs ahead of the provider dashboard. Cause: both numbers were added. Fix: canSpend only checks; record stores the provider total when present.
Treating the provider POST as idempotent because progress is. Symptom: duplicate drafts and duplicate charges with one idempotency key. Cause: the key was forwarded blindly. Fix: leave generation retries on the narrow status list in this lesson.
Hard-coding a vendor host. Symptom: a test or a fallback calls a real host when env is empty. Cause: a default base URL in source. Fix: missing_config and an injected fetch in tests.
Summary
The Explain provider call is a server-side fetch to a chat-completions-style URL, configured from the environment, parsed with Zod, and wrapped in a port. You retry 429 and 503 at most once, and only when the wait is short. You do not retry timeouts, 400s, or 401s. A tenant ledger refuses work that would cross the daily ceiling, and logs carry an allow-list that omits the key. The prompt version stays explain-v3. The progress write stays on the quiz.
Next Lesson Preview
Structured Outputs, JSON Mode and Function Calling takes the text this client returns and the same HTTP adapter, and demands a schema: an explanation card the UI can trust field by field, and a tool call the server may execute only when the tool is on an allow-list. Completing a lesson is not on that list. /learn/genai and /learn/prompt remain the primers.
The provider's current HTTP reference, read before changing max_tokens, the path, or the auth scheme. This lesson's body is a labeled chat-completions style, not a promise that every host uses it.