Skip to content

Courses / GenAI & LLM / Module 2

Module 2: LLM APIs and local models: chat, streaming, tool calling, model gateways

12 h · theory 4 · hands-on 5 · project 2 · revision 1

You will be able to

  • Call hosted and local models through one OpenAI-compatible client and a gateway (LiteLLM)
  • Stream tokens to a UI and handle timeouts, retries and rate limits
  • Implement a tool-calling loop by hand
  • Track tokens and cost per request

Capstone increment: Capstone /chat endpoint with streaming, a provider switch (Ollama local / hosted API) and per-request cost logging.

Job-description skills: LLM APIs, Ollama, Function calling, Cost and token optimization · Lab tools: ollama, openai, litellm, fastapi, httpx

1. One interface for every model

Almost every provider, and local servers like Ollama and vLLM, now accept the same OpenAI-style chat request: a list of messages with roles (system, user, assistant, tool), a model name, and sampling settings. Write your code against that shape once.

A model gateway such as LiteLLM sits between your code and the providers. It maps one request format to many providers, holds the keys, and gives you retries, fallbacks, budgets and cost logs in one place. Switching from a hosted model to a local one becomes a config change.

Keep the model name, base URL and prices in configuration, never in code. You will change models more often than you expect: prices drop, new models ship, and some customers will require that no data leaves their network.

App code/chat, /extractClientOpenAI-compatibleGatewayLiteLLM: keys, routingPoliciestimeout, retry, fallbackCost logtokens × priceHosted APIfrontier modelHosted APIcheaper modelOllamalocal, no data leavesYour code talks to one interface…and the gateway decides where the request goesprimaryfallbackdev / private
Switching provider becomes a config change, not a rewrite. Retries and cost logging live in one place.
In production: Ollama serves an OpenAI-compatible API at http://localhost:11434/v1. Point the same client at it with a dummy key and your code runs fully offline: ideal for development, tests and private data.

2. Streaming: perceived speed is real speed

A non-streaming call returns nothing until the whole answer is generated. With stream=True the server sends server-sent events: one small JSON chunk per few tokens, ending with data: [DONE]. Users judge speed by time to first token, not total time.

Measure both. Time to first token is dominated by queueing and processing the prompt (long prompts are slower to start); total time is dominated by the number of output tokens. That is why shorter outputs are the cheapest latency win.

Streaming complicates two things: you only know token usage at the end (ask for it with stream_options or count it yourself), and you can't validate structured output until it's complete. Stream to humans; don't stream JSON that code will parse.

3. Timeouts, retries and rate limits

Hosted APIs limit requests and tokens per minute. Exceed the limit and you get HTTP 429. Transient 5xx errors and timeouts happen too. Every call needs a timeout, a bounded number of retries, and a backoff between them.

Use exponential backoff with jitter: wait roughly 0.5 s, 1 s, 2 s, 4 s, each multiplied by a random factor. The randomness stops all your workers retrying at the same instant. Respect Retry-After when the server sends it. Never retry 400-class errors other than 429: the request itself is wrong.

Run the simulator below. Watch how instant retries multiply the load on an already overloaded provider, and how backoff trades a little latency for far fewer wasted calls.

Rate limits and retriesA burst of requests hits a provider that accepts a fixed number per second. Pick how your client retries a 429.

Succeeded 60 · failed 60 · attempts sent 120 (1.0× the real requests) · latency p50 0.3 s, p95 0.3 s

Bars: attempts sent per second (first 60 s). Dashed line: the rate limit. Red bars are wasted attempts that get a 429.

Guided experiments
  1. 120 requests over 3 s at 20/s with no retry. How many fail? This is what users see when a launch-day burst hits.
  2. Switch to “Retry immediately”. Successes rise, but look at the attempts sent and the red bars. Why does retrying instantly make the overload worse (the thundering herd)?
  3. Switch to backoff with jitter. Compare attempts sent and p95 latency. What did you trade for fewer failures?
  4. Set max retries to 0 and 10 with backoff. Where would you put the limit for a user waiting on a chat reply, and for a nightly batch job?
Common misconception: “More retries make the system more reliable.” Past a point they make outages worse: each failing request becomes several, and the provider stays overloaded longer.

4. Tool calling by hand

You describe functions to the model with a JSON Schema. Instead of answering, the model can reply with tool_calls: a function name and arguments as a JSON string. Your code runs the function, appends a message with role tool and the matching tool_call_id, and calls the model again. The model never executes anything itself.

Write this loop yourself once before you use a framework. You'll see that the arguments can be invalid JSON or name a tool that doesn't exist, that you must cap the number of steps, and that tool errors should go back to the model as messages rather than crash the loop. Module 7 and the Agentic AI course build on exactly this loop.

5. Counting tokens and money

Every response includes usage: prompt tokens and completion tokens. Log them per request with the model name, and compute cost from a price table in config. Output tokens typically cost 3-5 times more than input tokens.

Add the cost to your logs from day one. When a manager asks what one processed document costs, or why last month's bill doubled, you should be able to answer with a query, not an estimate. Prices change often, so date your price table and check it monthly.

Tip: Track cost per business unit (per document, per conversation), not just per call. One document may take several calls once you add retries and validation.

Hands-on: coding window

The coding window and the full VS Code lab are available after you sign in.

Sign in to code

Labs

Lab 2.1: Same code, three models

Install Ollama and pull a small model (for example a 3B instruct model). Using the openai Python client, send the same question to Ollama and to one hosted model by changing only base_url and model. Then route both through a LiteLLM config.

Expected: One script, three runs (Ollama direct, hosted direct, via LiteLLM), with answer, latency and token usage printed for each.

Lab 2.2: Streaming /chat endpoint (capstone increment)

Add POST /chat to the capstone that streams tokens to the client with FastAPI’s StreamingResponse, reads provider and model from config, sets a 30 s timeout, retries 429 and 5xx with backoff, and logs tokens and cost per request.

Expected: curl -N shows tokens arriving progressively; a log line per request includes model, tokens in/out, latency and cost; a test covers the retry logic with a mocked 429.

Lab 2.3: Break the tool loop

Extend the tool-calling starter with a second tool. Make the model request an unknown tool and malformed arguments. Handle both by returning an error message to the model, and stop after 5 steps.

Expected: The loop never raises; the transcript shows the error message sent to the model and a final answer or a clean stop.

Go deeper

Videos

Further reading

  • Docs Tool use with Claude · Anthropic docs. The exact message format for tool definitions, tool_use blocks and tool_result blocks.
  • Docs Function calling · OpenAI API docs. The same idea in OpenAI's API, useful for seeing what every provider has in common.
  • Docs Ollama API · Ollama docs. The local model server's REST API: chat, streaming and tool calls without a cloud account.
  • Docs LiteLLM documentation · LiteLLM. One client and an optional proxy for 100+ providers; the gateway pattern from this module.
  • Docs Using server-sent events · MDN Web Docs. The streaming format most LLM APIs use, from the browser's side.

GitHub repositories

  • openai/openai-python: The README sections on streaming, retries and timeouts; the client options apply to any OpenAI-compatible server.
  • BerriAI/litellm: The proxy config docs: model_list, fallbacks and budgets. Copy the pattern for the capstone gateway.
  • ollama/ollama: docs/openai.md for the compatible endpoints, and the Modelfile docs for setting a default system prompt.
  • anthropics/claude-cookbooks: The tool_use folder: complete tool-calling examples, including error handling.

Checkpoint quiz

1. Your streaming chat feels slow, but total generation time is fine. Which metric should you measure first?
2. A provider returns HTTP 400 for a request. What should the retry logic do?
3. Why add random jitter to exponential backoff?
4. In tool calling, who executes the function?
5. What does a model gateway like LiteLLM give you?

Interview questions

  1. Design the retry and timeout policy for an LLM call inside a user-facing chat endpoint. What changes for a nightly batch job?
  2. How would you switch the capstone from a hosted model to a local one without changing application code?
  3. Explain the tool-calling message flow. What can go wrong at each step?
  4. Why should you avoid streaming output that another program will parse?
  5. How would you work out the cost of processing one document end to end?

Ask the professor

Sign in to ask questions about this module.

Discussion

Community discussion appears here once giscus is configured (see README).