Skip to Content
Working with LLM APIsA developer application sends a JSON request through an HTTPS API to a hosted language model and receives text and usage metadata. Three learning goals: send a request, shape the context, build a reliable application.APPLIED AI FOR DEVELOPERS · PART 3Working withLLM APIsIn Part 2, we looked inside the model.Now we connect it to an application. Send a requestHTTP, authentication and JSON. Shape the contextInstructions and conversation history. Build for reliabilityValidate, measure and handle failures. YOUR APPLICATIONExplain this code…Prompt + instructionsModel + output limit{ "model": "…","input": "…","store": false }Response LLM PROVIDERAPI endpointLanguage model Inference → output tokensText + usage metadata REQUESTHTTPSPOST /responses RESPONSEJSON TODAY'S ROUTERequest → response → context → reliable application
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com1 / 16
Recap: From Inside the Model to Your ApplicationPart 2 recap: tokens become embedding vectors; causal attention, position and MLPs build context across decoder blocks; vocabulary scores become next-token probabilities; generation appends a token and repeats with fixed weights. Context is finite and fluent output needs verification. Part 3 connects this mechanism to an application through an API.APPLIED AI FOR DEVELOPERS · PART 3Recap:From Inside the Model to Your ApplicationPart 2 opened the black box. Four ideas explain what happens behind an LLM API. 1Tokens → vectors2Layers build context3Predict the next token4Append and repeatbank→Token IDs map to learnedembedding vectors.Causal attention + positionMLP + residual pathsRepeat across decoder blocks.Each position uses its past.brightnewunclearVocabulary scores → probabilities.Illustrative distribution.The future of AI isbrightChoose a token; predict again.Inference keeps weights fixed.Context is finite.Your app selects the history and evidence to include.Fluent does not mean verified.Ground important claims and validate the result.PART 3Your application→LLM API→this mechanism→ useful, checked output
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com2 / 16
What Is an LLM API?Your application calls a hosted API over HTTPS. The API service handles authentication, request validation, model routing and usage accounting. The language model runs inference and returns generated output through the API. The API is the interface; the model supplies the learned capabilities.APPLIED AI FOR DEVELOPERS · PART 3What Is anLLM API?A programmable interface that lets your application use a language model over the network. YOUR APPLICATION You own the workflowUser interface + app logic HTTP clientPrompt, instructions, model ID API SERVICEThe contract around inference AuthenticationRequest validation Model routingLimits + usageEndpoint + schema + operational rules LANGUAGE MODELThe learned capability Runs inference on your input REQUESTHTTPS + JSON RESPONSEText + usage API = interface + serviceHow you access and operate the capability. Model = learned parameters + inferenceWhat generates the output from your context. A chat product adds a ready-made user interface. An API lets you build your own.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com3 / 16
The Anatomy of an API RequestFive parts of an OpenAI Responses API request: HTTPS endpoint and POST method; Authorization header with a runtime API key; model selection; user input; and output and storage controls. Matching numbered labels connect the explanations to a JSON request example. No real key is included.APPLIED AI FOR DEVELOPERS · PART 3The Anatomy of anAPI RequestOne HTTPS request combines a destination, credentials and a structured JSON body. 1DestinationPOST starts a generation request.Use the provider's HTTPS endpoint.2AuthenticationThe header carries your API key.Supply it at runtime; never hard-code it.3ModelChoose the capability to call.The model must be accessible to your key.4InputSend the user's prompt or input items.Add instructions and context when needed.5ControlsBound output; choose storage behavior.Supported options depend on the model.HTTP REQUEST · OPENAI RESPONSES API1POST https://api.openai.com/v1/responses2Authorization: Bearer RUNTIME_KEYContent-Type: application/json{3"model": "gpt-5.4-mini",4"input": "Explain an API in 3 sentences.",5"max_output_tokens": 400,"store": false}NEXT: SEND ITEnter a temporary key and prompt on slide 5 — then inspect the response.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com4 / 16

APPLIED AI FOR DEVELOPERS · PART 3

Your First LLM API Call LIVE DEMO

01 CONNECT TO OPENAI
02 WRITE YOUR REQUEST
POST /v1/responses → JSON → text
The model's response appears here.

Input tokens: — · Output tokens: — · Time: —

Direct browser → OpenAI. No proxy. CORS has not been checked.

Key stays in this page's runtime only; Clear removes it and aborts the request. Browser tools and page scripts can access it. Use a temporary key and revoke it afterwards. Prompt is sent to OpenAI; store:false does not guarantee zero data retention.

WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com5 / 16
Understanding the API ResponseA simplified raw Responses API JSON object with three highlighted areas: completion status, generated text inside message output content, and input/output token usage. Extract text by item type, check incomplete responses and refusals, and distinguish server token accounting from browser elapsed time. All example values are illustrative.APPLIED AI FOR DEVELOPERS · PART 3Understanding theAPI ResponseThe response is a structured result — generated text is only one part of it. RESPONSE BODY · SIMPLIFIED JSON{ "status": "completed", "output": [{ "type": "message", "content": [{ "type": "output_text", "text": "An API lets apps communicate." }] }], "usage": { "input_tokens": 24, "output_tokens": 38 }}1231Check the outcomeRead status before trusting the result.Handle incomplete output, refusals and errors.2Extract the generated textoutput[] → message → content[] → output_textCollect matching text parts; render them as text.Do not assume output[0] is always a message.3Read actual token usageInput: 24 tokens Output: 38 tokensElapsed time is measured separately by the browser.RAW REST ≠ SDK HELPERThe SDK's output_text helper collects text; raw fetch returns typed output items.Illustrative JSON and token counts; not a measured demo response.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com6 / 16
Instructions and Conversation ContextInstructions define application behavior. Input supplies the user question and relevant context. A JSON example separates top-level instructions from input messages containing user and assistant history. Retrieved documents are untrusted data, and important results need validation.APPLIED AI FOR DEVELOPERS · PART 3Instructions andConversation ContextTell the model how to behave — and supply the information it needs for this request. 01 · INSTRUCTIONSDefine application behavior.Task, audience, constraints and format.Keep guidance explicit and consistent. 02 · INPUT + CONTEXTSupply the question and evidence.Current user messageRelevant earlier user / assistant turnsDocuments or tool results, when neededYour app decides what to include. RESPONSES API · REQUEST BODY EXCERPT{ "instructions": "Explain APIs clearly. Be concise.", "input": [ { "role": "user", "content": "What is an API?" }, { "role": "assistant", "content": "An API lets applications communicate." }, { "role": "user", "content": "Now give me a GET request example." } ]}KEEP THE BOUNDARYRetrieved text is untrusted data. Keep secrets out of prompts.Instructions guide behavior; validate important outputs in your application.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com7 / 16
Controlling Model BehaviorChoose a suitable model, bound output, and understand temperature: low values favor likely tokens with less variation; high values allow more varied choices. Temperature is an API parameter only for supporting models and configurations. Lower temperature does not guarantee identical answers. Define acceptance criteria, evaluate representative cases and validate important results.APPLIED AI FOR DEVELOPERS · PART 3ControllingModel BehaviorUse the controls your model supports — then measure whether the result meets your needs.123Choose the capabilityMODELTask-appropriate modelMatch model strengths to your task.Compare quality, latency and cost.Evaluate on representative examples.Bound the outputmax_output_tokensSet an explicit upper limit.Request a schema when supported.Validate the returned structure.A token limit may truncate the answer.TemperatureAPI parameter: temperatureLow · e.g. 0.2Favors likely tokens; less variation.High · e.g. 0.8More varied token choices.Only where supported by the modeland its selected configuration.EXPECT VARIATIONLower temperature does not promise identical answers.API BODY EXCERPT{ "temperature": 0.2 }Not a truth or quality control.Check support; omit if unsupported. Slide 5 does not set it yet.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com8 / 16
Multi-Turn ConversationsA concrete second request resends instructions, the first user question, the assistant answer and the new user question. A colored JSON excerpt matches the conversation shown on the left. This illustrates application-managed context; provider state is another supported approach. The live demo sends independent requests.APPLIED AI FOR DEVELOPERS · PART 3Multi-TurnConversationsFor the follow-up, your app sends the earlier exchange together with the new question. THE CONVERSATION USER · FIRST QUESTIONWhat is an API? ASSISTANT · FIRST ANSWERAn API lets applicationscommunicate. USER · FOLLOW-UPNow show me a GETrequest example. The next call receives all three messages.No automatic memory is assumed. SECOND REQUEST · BODY EXCERPT{ "instructions": "Explain APIs clearly. Be concise.", "input": [ { "role": "user", "content": "What is an API?" }, { "role": "assistant", "content": "An API lets applications communicate." }, { "role": "user", "content": "Now show me a GET request example." } ]}ANOTHER OPTIONUse supported provider state, e.g. previous_response_id; resend needed instructions.Check retention and context growth. Slide 5 still sends independent requests.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com9 / 16
Streaming ResponsesIllustrative timelines compare full output shown at completion with streaming text deltas rendered as they arrive. Streaming improves perceived responsiveness, not necessarily total time. Set stream true, parse server-sent events, join deltas and handle completion, cancellation and errors. Network chunks are not event boundaries. Slide 5 remains non-streaming.APPLIED AI FOR DEVELOPERS · PART 3StreamingResponsesShow text as it arrives, instead of waiting for the entire response to finish. SAME TASK · TWO WAYS TO DISPLAY THE OUTPUT NON-STREAMINGRequestWaiting for completion…An API lets apps communicate. STREAMINGAn APIlets appscommunicate.Completed + final usage↑ First visible text↑ CompletionIllustrative timing only. Earlier visible output does not guarantee a shorter total generation time.01 · REQUEST{ "stream": true }Enable streaming in the JSON body.02 · READ + RENDERParse SSE events; append text deltas.Network chunks ≠ complete events.03 · FINISH SAFELYHandle completion and errors.Support cancellation; render as text.OUR LIVE DEMOSlide 5 uses a non-streaming request. Streaming requires additional event-handling code.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com10 / 16
Tokens, Latency and CostTokens, latency and cost. Different models have different input and output rates; the same token usage can have different costs. Output is usually more expensive per token, but long input can cost more in total. Sum token count times applicable rate across categories. Compare total cost per task with quality and latency. Token counts, cached input and reasoning affect accounting. Chart proportions are illustrative.APPLIED AI FOR DEVELOPERS · PART 3Tokens, Latencyand CostMeasure the whole request: how much it uses, how long it takes and what it costs.01 · TOKENSCount input and outputINPUTInstructionsHistoryPromptOUTPUTGenerated tokensRead usage metadata from the API.Tokens are not the same as words.02 · LATENCYFollow the elapsed timeNetwork → input processing→ model work → output transferStreaming: first text ≠ completion.Demo time: browser wall-clock duration.03 · COSTDifferent models, different pricesSame token usage ≠ same cost.Each model has its own input / output rates.Output usually costs more per token.But long input can cost more in total.Cached input has separate rates.Cost = token count × applicable rateSum categories; use current model pricing.TOTAL COST MATTERSInput cost + output cost; divide token counts by 1M when using per-million rates.COMPARE PER TASKQuality + latency + total costToken counts can vary by model. Cached input and reasoning affect accounting; demo timing is not a billing quote.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com11 / 16
Handling Errors and LimitsDiagnose errors before retrying. Invalid requests, model access and authentication need configuration fixes. Rate-limit errors may warrant bounded exponential backoff with jitter, but quota errors need account action. Service errors may be temporary. A timeout has an unknown completion outcome. Browser fetch failures can arise from network, CORS or browser policy. Never expose keys in logs or errors.APPLIED AI FOR DEVELOPERS · PART 3HandlingErrors and LimitsClassify the failure first. A retry only helps when the cause is temporary. SIGNALWHAT TO CHECKAPPLICATION ACTION400 / 404Request, parameters, endpoint or model accessFix the request or configuration.401 / 403Key validity, project permissions and accessFix credentials / access; avoid blind retries.429Rate limit or exhausted quota? Read the error.Rate limit: backoff. Quota: account action.5xxTemporary provider-side failureUse bounded retries with backoff + jitter.TIMEOUTThe request may still have completedCancel locally; check outcome before repeating.BROWSER FETCH FAILED?Network, CORS or browser policy may block the call.JavaScript cannot always distinguish these causes.RETRY POLICY · ILLUSTRATIVEWait → longer wait → stop after a bounded limitAdd jitter; respect provider retry guidance and deadlines.SAFE FAILUREShow useful messages. Never log API keys. Keep request IDs for diagnosis.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com12 / 16
Choosing the Right ModelDefine task requirements, test candidate models on the same representative examples and compare quality, latency and total cost per successful task. A conceptual comparison matrix uses placeholders rather than benchmark claims. First satisfy quality and operational constraints, then optimize cost and speed. Model access and supported features depend on the account and provider.APPLIED AI FOR DEVELOPERS · PART 3Choosing theRight ModelChoose for your task — using measured results, rather than the model name alone. 01 · DEFINE THE REQUIREMENTSWhat must the model deliver?Quality and acceptable failure rateResponse-time targetBudget per completed taskOutput format and tool supportPrivacy and deployment constraints02 · TEST CANDIDATES ON THE SAME TASKSInclude normal inputs, hard cases and expected failures.CandidateQualityLatencyCost / taskModel AMeasureMeasureMeasureModel BMeasureMeasureMeasureModel CMeasureMeasureMeasureTemplate only — no invented scores or universal model ranking.03 · CHOOSEMeet the quality threshold first; then optimize total cost and response time.CHECK BEFORE DEPLOYINGModel access + parameter support + limits→ re-evaluate when things change
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com13 / 16
Different API ProvidersThree access patterns: direct hosted APIs such as OpenAI, Anthropic and Google; cloud platforms such as Microsoft Azure and Amazon Bedrock; and self-hosted model serving. Compare authentication, schemas, streaming, tools, structured output, retention and usage accounting. Similar HTTP interfaces do not imply identical behavior.APPLIED AI FOR DEVELOPERS · PART 3DifferentAPI ProvidersThe request travels over HTTP — but the service contract and operating model can differ.01 · DIRECT HOSTED API02 · CLOUD PLATFORM03 · SELF-HOSTEDCall the provider directly.Examples: OpenAI, Anthropic, GoogleProvider manages model serving.Use its credentials, schema and billing.Use a cloud access layer.Microsoft Azure · Amazon BedrockCloud identity and deployment options.Model availability and endpoints vary.Operate the serving stack.Your infrastructure + a model serverOwn hardware, scaling and monitoring.Check model license and capabilities.CHECK BEFORE SWITCHINGAuthentication + schemasStreaming + tools + output formatsRetention + usage accountingKEY IDEAA similar HTTP interface does not guarantee identical behavior. Test your integration.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com14 / 16
Building a Simple LLM ApplicationBuild a code explainer: a user submits a snippet through the interface; the backend validates input, adds instructions and calls the model with server-held credentials; the response is validated and displayed. Production adds access control, timeouts, budget limits, monitoring and evaluations. The slide 5 browser-key demo is a temporary teaching setup.APPLIED AI FOR DEVELOPERS · PART 3Building a SimpleLLM ApplicationExample: a code explainer that turns a submitted snippet into a clear explanation.01 · USER INTERFACEconst total = items.reduce( (sum, x) => sum + x, 0);Collect the code snippet.Show loading, answer or error.Render generated text safely.02 · YOUR BACKENDValidate input + add instructionsChoose model + bound outputCall the provider with server-held keyCheck the response before returning itOwn the workflow and operational controls.03 · LLM PROVIDERInstructions + snippet→ inference → explanationGenerate the explanation.Return output + usage metadata.Your app validates important results.BEFORE PRODUCTIONAccess + input limitsTimeouts + budgetsLogs without secretsQuality evaluationsTEACHING DEMOSlide 5 uses a temporary browser key. A production app keeps credentials on the server.YOUR EXERCISEBuild the code explainer; test useful answers, invalid input and provider failures.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com15 / 16
Key Takeaways and What's NextFour takeaways: understand the API contract, design instructions and context, measure quality latency and cost, and build for failure. Next lesson, Part 4: Prompting and Structured Output, covering system prompts, few-shot prompting, JSON outputs, schemas and reliable prompt design.APPLIED AI FOR DEVELOPERS · PART 3Key Takeaways& What's NextOne request is easy. A reliable application needs engineering.01Understand the contractEndpoint, authentication and JSON.Read typed output; handle completion.02Design the contextGive clear instructions and relevant history.Treat retrieved content as untrusted data.03Measure the systemCompare quality, latency and cost per task.Model prices and supported controls differ.04Build for failureValidate output and protect credentials.Handle limits, errors and uncertain outcomes.NEXT · PART 4Prompting & Structured OutputSystem prompts · few-shot prompting · JSON outputs · schemas · reliable prompt designTAKE IT WITH YOUStart with one useful task. Define success. Test the failures as well as the happy path.
WORKING WITH LLM APIs · 2026Dr. Jürgen Nützel, www.deenovum.com16 / 16

Arrow keys: navigate · Home / End: first / last slide · Download PDF: saved edition of all 16 slides · Live demo on slide 5 is interactive in the web edition only.