Advanced⏱ 36 min⚡ 120 XP🧩 5-question quiz

Working with LLM APIs

Call language models like a professional: messages and system prompts, streaming, structured outputs with JSON Schema, tool calling, retries, rate limits, and prompt caching.


In Module 07 (Transformers & LLMs) you saw what happens inside a language model: tokens, attention, next-token prediction, and alignment. This module is about what happens around it: the code that turns a model into a product. Calling a model is easy: one HTTP request, and text comes back. Calling one well, so your app is fast, predictable, affordable, and survives a bad day at your provider, is a craft. This lesson covers the patterns that separate weekend prototypes from software people depend on.

The examples use the widely implemented OpenAI-compatible Python client, which many hosted providers and open-source inference servers (vLLM, SGLang, llama.cpp, Ollama) speak. Anthropic's and Google's SDKs differ in parameter names but have the same shape, and every concept here maps onto them.

The anatomy of a request

A chat request contains a model ID, a list of role-tagged messages, optional tools, and generation settings. The roles are:

  • system (a separate system parameter in some SDKs): standing instructions such as role, constraints, and output format. Treat it as a specification.
  • user: what the human, or your application acting for them, says.
  • assistant: previous model replies, resent so the model sees the conversation.
  • tool: results of tool calls the model requested (covered below).
# pip install openai
import os
from openai import OpenAI

client = OpenAI(
    base_url=os.environ.get("LLM_BASE_URL"),   # None = provider default; or a local server URL
    api_key=os.environ["LLM_API_KEY"],
    max_retries=3,                             # SDK-level retries for transient errors
    timeout=60,                                # never wait forever
)
MODEL = os.environ["LLM_MODEL"]                # keep model IDs in config, not code

response = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": "You are a patient tutor. Answer in at most three sentences."},
        {"role": "user", "content": "Why is the sky blue?"},
    ],
    max_tokens=300,
)
print(response.choices[0].message.content)
print(response.choices[0].finish_reason)   # "stop", "length", "tool_calls", ...
print(response.usage)                      # prompt and completion token counts: your bill

Three habits are visible already. Model IDs live in configuration because you will change them often (the LLMOps lesson in the next module shows how to roll out a model upgrade safely). You always set a timeout. And you always check finish_reason: "length" means the answer was cut off by max_tokens, and silently using a truncated answer is a classic bug.

Parameter names drift between APIs, so check the reference for yours. OpenAI's own API now prefers max_completion_tokens (and requires it for its reasoning models), while most OpenAI-compatible servers still accept max_tokens. Reasoning models also bill their hidden reasoning tokens as output, so usage can report far more completion tokens than the visible answer contains.

Statelessness and its quadratic cost

Chat completion APIs are stateless. The model remembers nothing between calls. To hold a conversation, your app appends each turn to a list and resends it. If a conversation has nn turns of roughly tt tokens each, turn kk sends about k tk\,t input tokens, so the total input over the conversation is

∑k=1nk t  =  t n(n+1)2  ≈  t n22.\sum_{k=1}^{n} k\,t \;=\; \frac{t\,n(n+1)}{2} \;\approx\; \frac{t\,n^2}{2}.

With t=500t = 500 and n=40n = 40, that is about 410,000 input tokens for a conversation whose visible text is only 20,000 tokens. That quadratic growth is why long chats get expensive, why prompt caching (below) matters, and why the context-engineering lesson later in this module exists.

Note: Some providers also offer server-side conversation state (for example, OpenAI's Responses API can continue from a stored previous response). That saves you resending bytes, but the model still processes the whole context on every turn, and that context is still billed, often at cached-token rates. The quadratic shape does not go away; it just moves to the provider's side of the wire.

Generation settings, and what changed

Older guides tell you to tune temperature and top_p for every call. As of 2026 that advice needs care. Many reasoning-capable models manage their own sampling, and some providers ignore or reject sampling parameters on certain models, replacing them with controls such as a reasoning effort setting that trades thinking depth for latency and cost. The durable principle: read the model's documentation for which knobs it accepts, and get determinism from structure (schemas, validation, tests) rather than from temperature=0, which never guaranteed identical outputs anyway because of batching and floating-point non-determinism on the server.

Writing good system prompts

A system prompt is a specification. Good ones state the role, the audience, what to do when information is missing, and the exact output format. Compare "Be helpful" with: "You answer questions about our return policy using only the policy text provided. If the answer is not in the text, say you don't know and suggest contacting support. Reply in plain English under 100 words." The second is testable, and testable prompts are the foundation of the evaluation lesson later in this module.

Streaming

A long answer can take many seconds to generate. Instead of a spinner, stream tokens as they are produced:

stream = client.chat.completions.create(
    model=MODEL,
    messages=[{"role": "user", "content": "Write a haiku about debugging."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
print()

Two latency numbers matter: time to first token (TTFT), dominated by processing the prompt (prefill), and inter-token latency, the decode speed. Streaming does not change total generation time or cost, but users perceive TTFT, so the app feels much faster. Under the hood, most APIs use server-sent events (SSE): a long-lived HTTP response that emits data: lines. Your backend can forward them to the browser.

Streaming has engineering consequences people miss:

  • Errors can arrive mid-stream. A 200 status at the start does not mean success; handle a broken or truncated stream.
  • Structured output and tool arguments arrive in fragments. Accumulate the deltas and parse once the stream ends (or use a tolerant incremental parser, then validate the final object).
  • Moderation and guardrails get harder. If you must check output before showing it, you either buffer (losing the streaming benefit) or check incrementally and be ready to retract.

Structured outputs

Applications need data, not prose: a label, extracted fields, a list of actions. There are three levels of reliability:

ApproachHow it worksGuarantee
Prompt only"Respond with JSON with keys ..."None; models sometimes add prose or miss fields
JSON modeDecoder forced to emit syntactically valid JSONValid JSON, but any shape
Structured outputs (strict JSON Schema)Decoder masks every token that would violate the schemaOutput matches the schema by construction

The third works by constrained decoding. At each step the model produces logits ziz_i over the vocabulary; the server compiles your schema into a grammar (effectively a state machine) whose current state ss defines the set A(s)\mathcal{A}(s) of tokens that may legally come next. Every other logit is set to minus infinity before sampling:

z~i={ziif i∈A(s)−∞otherwisep=softmax(z~)\tilde z_i = \begin{cases} z_i & \text{if } i \in \mathcal{A}(s) \\ -\infty & \text{otherwise} \end{cases} \qquad p = \mathrm{softmax}(\tilde z)

Masked tokens get probability exactly zero, so if the schema says the next thing must be "billing", "bug", or "other", no other token can be chosen. That is why the guarantee is structural, not statistical. The same softmax you met in Module 07 is still doing the choosing; it just picks only among legal tokens.

# pip install openai pydantic
import json
from typing import Literal
from pydantic import BaseModel, field_validator

class Ticket(BaseModel):
    category: Literal["billing", "bug", "feature_request", "other"]
    urgency: int                            # 1 low ... 5 critical
    summary: str

    @field_validator("urgency")
    @classmethod
    def in_range(cls, v: int) -> int:       # a business rule checked in code, not in the schema
        if not 1 <= v <= 5:
            raise ValueError("urgency must be 1-5")
        return v

schema = Ticket.model_json_schema()
schema["additionalProperties"] = False      # strict mode requires a closed object

def classify(message: str) -> Ticket:
    r = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": "Classify the customer support message."},
            {"role": "user", "content": message},
        ],
        response_format={
            "type": "json_schema",
            "json_schema": {"name": "ticket", "schema": schema, "strict": True},
        },
    )
    # Schema-valid by construction, but still validate: rules such as the 1-5 range
    # live in your code, because strict modes support only a subset of JSON Schema.
    return Ticket.model_validate(json.loads(r.choices[0].message.content))

print(classify("I was charged twice this month and need a refund ASAP!"))

Support for strict schemas varies by provider and server, and strict modes usually support only a subset of JSON Schema (for example, some ignore numeric bounds or string patterns, and OpenAI's strict mode requires every property to be listed in required, so optional fields are written as a union with null). Recent SDKs also offer helpers that accept the Pydantic class directly and return a parsed object (in the OpenAI Python SDK, a parse method); they generate the same request under the hood. Whatever the route, keep a validate-and-repair fallback: if validation fails, send the error back ("That was invalid: urgency must be 1-5") and ask for a corrected object, at most once or twice.

Tip: Schema-valid is not the same as correct. A ticket can be perfectly shaped and still mislabeled. Field descriptions in the schema act as instructions, and putting a short reasoning field before the answer field can improve accuracy because the model generates it first. Measure that on your eval set rather than assuming. Format constraints can also cost accuracy: Tam et al. ("Let Me Speak Freely?", 2024) reported that forcing strict formats degraded reasoning on some tasks. A common remedy is to let the model reason freely first (or use a reasoning model), and constrain only the final answer object.

Tool (function) calling

Tool calling is structured output pointed at an action. You describe functions with a name, a description, and a JSON Schema for parameters. When the model decides a tool would help, it replies with a tool call instead of prose. Crucially, the model does not run anything: your code executes the tool and sends the result back, and the model continues.

Rendering diagram…

The diagram shows the two round trips: the first API call returns only a request to use a tool, your application runs the tool (after validating it), and a second call lets the model turn the result into an answer.

import json

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Current weather for a city. Use for any question about present conditions.",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string", "description": "City name, e.g. 'Lisbon'"}},
            "required": ["city"],
            "additionalProperties": False,
        },
        "strict": True,
    },
}]

def get_weather(city: str) -> dict:
    return {"city": city, "temp_c": 14, "conditions": "heavy rain"}   # stub

messages = [{"role": "user", "content": "Should I bike to work in Lisbon today?"}]
r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)
msg = r.choices[0].message
if msg.tool_calls:
    messages.append(msg)                                   # keep the assistant's tool request
    for call in msg.tool_calls:                            # may be several, in parallel
        args = json.loads(call.function.arguments)         # always parse, never string-match
        result = get_weather(**args) if call.function.name == "get_weather" else {"error": "unknown tool"}
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
    r = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)
print(r.choices[0].message.content)

Details that matter in production: the model may request several tool calls at once (run them concurrently, return all results); a failing tool should return an error result rather than crash, so the model can recover; and tool descriptions are prompts, so write them as carefully as the system prompt. Some providers also offer server-side tools (web search, code execution, file search) that run on their infrastructure inside a single API call; convenient, but you give up the chance to inspect each call before it runs. Put the client-side call-observe cycle in a loop and you have an agent, which is the subject of lesson 3, where you will also meet the Model Context Protocol, a standard way to plug tools into any host.

Errors, retries, and timeouts

Networks fail and providers get overloaded. Sort errors into two buckets:

Retry (transient)Don't retry (fix the request)
429 rate limit400 invalid request, context length exceeded
408 / timeouts, connection resets401 / 403 authentication or permission
500, 502, 503, overload errors404 unknown model or endpoint

For transient errors use exponential backoff with jitter: the wait before retry nn (counting from 0) is

dn=min⁡ ⁣(cap,  base⋅2n)⋅U,U∼Uniform(0.5, 1.5)d_n = \min\!\left(\text{cap},\; \text{base}\cdot 2^{n}\right)\cdot U, \qquad U \sim \mathrm{Uniform}(0.5,\,1.5)

(the "full jitter" variant draws UU from Uniform(0,1)\mathrm{Uniform}(0, 1) instead, spreading clients out even more). Without jitter, every client that failed at the same moment retries at the same moment and knocks the server over again (the "thundering herd"). If the server sends a Retry-After header, honor it. This runnable simulation shows how jitter spreads retries out:

import random

def backoff_delays(attempts=5, base=1.0, cap=30.0, jitter=True):
    out = []
    for n in range(attempts):
        d = min(cap, base * 2 ** n)
        out.append(round(d * random.uniform(0.5, 1.5), 2) if jitter else d)
    return out

random.seed(0)
print("no jitter:  ", backoff_delays(jitter=False))      # [1.0, 2.0, 4.0, 8.0, 16.0]
for client_id in range(3):
    print(f"client {client_id}:   ", backoff_delays())   # same shape, different timings

Official SDKs already retry transient errors (the max_retries option above), so prefer configuring them over writing your own loop. Two pitfalls: retries multiply worst-case latency to roughly timeout×(retries+1)\text{timeout}\times(\text{retries}+1) plus the backoff waits, so set both deliberately; and retrying a request that triggered side effects (a tool that sent an email) can duplicate them, so make tools idempotent with request IDs.

Rate limits and throughput

Providers cap requests per minute and tokens per minute (input and output may be counted separately), usually enforced like a token bucket: capacity refills at a steady rate, and each request spends from it. Practical consequences:

  • Limit concurrency with a semaphore or worker pool instead of firing everything at once.
  • Count tokens before sending (providers expose token-counting endpoints or tokenizers) and cap max_tokens on output.
  • Use batch APIs for offline jobs (nightly classification, evaluations). Providers commonly discount them substantially in exchange for results within hours instead of seconds.
  • Route by difficulty: send easy requests to a smaller, cheaper model and hard ones to a frontier model. Module 12 covers routing economics in depth.
import asyncio
from openai import AsyncOpenAI

aclient = AsyncOpenAI(base_url=os.environ.get("LLM_BASE_URL"), api_key=os.environ["LLM_API_KEY"])
limit = asyncio.Semaphore(5)   # at most 5 requests in flight

async def summarize(text: str) -> str:
    async with limit:
        r = await aclient.chat.completions.create(
            model=MODEL, max_tokens=100,
            messages=[{"role": "user", "content": f"Summarize in one line:\n{text}"}])
        return r.choices[0].message.content

# results = asyncio.run(asyncio.gather(*(summarize(d) for d in docs)))  # inside an async main()

Prompt caching

Many requests share a long, identical beginning: a big system prompt, tool definitions, a reference document, the earlier turns of a chat. Re-processing that prefix every time wastes compute. Prompt caching stores the model's internal state (the KV cache from Module 07, lesson 3) for a prefix, so later requests that start with exactly the same tokens skip the prefill for that part. Cached input is billed at a steep discount and TTFT drops sharply. Some providers cache automatically; others require you to mark cache breakpoints; some charge a premium to write the cache. Check your provider's pricing page for the current multipliers and minimum cacheable length.

The one rule that matters: caching is an exact prefix match. Any change, even one character, invalidates everything after it. So:

  1. Order the prompt stable → volatile: tools, then system prompt, then documents, then conversation history, then the new question.
  2. Never put a timestamp, request ID, or user name at the top of the system prompt.
  3. Serialize tools and JSON deterministically (sorted keys, fixed order).
  4. Verify with the usage fields: providers report cached-token counts. If they stay at zero, something early is changing.

A worked example of why it matters: a support bot sends a 5,000-token prefix plus 200 new tokens per request. Without caching, 100,000 requests mean 520 million input tokens at full price. If cached tokens cost one-tenth of normal input (a ratio some providers use; yours may differ), the bill in full-price-equivalent tokens becomes

100,000×200⏟20M uncached  +  0.1×100,000×5,000⏟500M cached  =  70M,\underbrace{100{,}000 \times 200}_{\text{20M uncached}} \;+\; 0.1 \times \underbrace{100{,}000 \times 5{,}000}_{\text{500M cached}} \;=\; 70\text{M},

so the input bill falls from 520 to about 70 million, roughly 87% less, ignoring cache-write premiums and misses. Module 12 (AI Cost Optimization), lesson 4, returns to caching, batching, and routing as a combined cost strategy.

Use the calculator to see how caching, routing, and traffic interact, then try changing the cache hit rate: the savings are only as good as your prefix discipline.

Hands-on exercise

  1. Point the client at any OpenAI-compatible endpoint (a hosted provider, or a local server such as Ollama or vLLM) using environment variables.
  2. Build a command-line chat loop that keeps history, streams replies, prints usage after each turn, and warns when finish_reason == "length".
  3. Implement classify with strict structured outputs. Write ten test messages, including two deliberately ambiguous ones. Record how often the label is wrong even though the JSON is valid.
  4. Add the get_weather tool and a second tool, get_calendar(date). Ask "Should I move my outdoor meeting tomorrow?" and log every tool call.
  5. Make your system prompt about 2,000 tokens long. Send ten requests, then add the current time to the top of the system prompt and send ten more. Compare cached-token counts in usage (if your provider reports them).

Expected outcome: a working streaming chat with tool use, a measured mislabel rate for your classifier, and a concrete demonstration that a changing prefix destroys cache hits.

Key takeaways

  • Chat APIs take role-tagged messages and are stateless; resent history costs tokens on every turn.
  • Always set timeouts, check finish_reason, and keep model IDs in configuration.
  • Streaming improves perceived latency (TTFT) but complicates parsing and moderation.
  • Structured outputs use constrained decoding to guarantee schema-valid JSON; still validate business rules.
  • In tool calling the model requests and your code executes: that boundary is where you enforce safety.
  • Retry only transient errors, with backoff and jitter; make side-effecting tools idempotent.
  • Prompt caching is an exact prefix match: order prompts from stable to volatile.

Next, you will use these building blocks to ground a model in your own documents with retrieval-augmented generation.

Further reading

  • OpenAI API documentation, "Structured Outputs" and "Function calling" guides (platform.openai.com/docs), the reference for the OpenAI-compatible request shape.
  • Anthropic documentation, "Prompt caching" and "Tool use" guides (docs for the Claude API), a clear explanation of prefix caching and tool-call loops.
  • Willard and Louf, "Efficient Guided Generation for Large Language Models" (2023), the finite-state-machine approach behind constrained decoding.
  • Marc Brooker, "Exponential Backoff And Jitter" (AWS Architecture Blog, 2015), a simulation-backed comparison of jitter strategies.

Save your progress and earn XP

Create a free account to take the quiz, track progress and unlock badges.