AI Engineering Β· Build lab 1 of 14

Your first LLM call: raw HTTP, the SDK, and Spring AI

Call a language model from code three ways: a raw HTTP request so you see exactly what goes over the wire, the official SDK, and Spring AI. Then make it switchable between a free local model and a paid API, read token usage, estimate cost, and handle the errors you will actually hit.

⏱ 40 minBeginnerπŸ’Έ Free (local model)7 stepsPython + Java

Python 3.12uvOllamallama3.2:3bhttpxopenai SDKSpring Boot 3 + Spring AI (optional)

Overview video

1 / 6

0 of 7 steps done

What you will build

A small command-line program that sends a question to a language model and prints the answer, the token usage and an estimated cost.

It talks to a local model through Ollama by default, so it is free and private. Changing three lines in .env points the same code at a hosted API instead. You will write the call first as a raw HTTP request, then with the SDK, so you know exactly what the SDK does for you.

Before you start

Setup

S1Install uv (the Python project tool)

uv installs Python for you, creates the virtual environment and manages packages. One tool instead of pyenv + venv + pip.

Run
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
You should see
everything's installed!

S2Check uv works

The export PATH=... line makes uv work in this terminal right away. New terminal windows find it on their own (the installer added it to your shell settings). On Windows, open a new terminal after installing.

Run
uv --version
You should see
uv 0.x.y

S3Install Ollama (runs models on your machine)

Download it from ollama.com/download and open it once. It runs a small server on port 11434 that speaks the same chat API as the hosted providers.

Run
ollama --version
You should see
ollama version is 0.x.y

S4Pull a small model (llama3.2:3b, about 2 GB)

A 3-billion-parameter model runs on most laptops, including ones without a GPU. Answers are slower and simpler than a frontier model, which is fine for learning: the code is identical.

Run
ollama pull llama3.2:3b
You should see
pulling manifest
...
success

S5Java only (optional): JDK 21 and Maven

Only if you want the Spring AI version (switch to Java at the top of the steps). Put the Java files from step 4 in a folder of their own.

Run
brew install openjdk@21 maven

S6Check the model answers

Run
ollama run llama3.2:3b "Say hello in five words."
You should seeyour text will differ: the model writes it
Hello there, how are you?
1

Create the project

A fresh project with its own Python and three packages.

uv init creates a folder with pyproject.toml (the project file, like package.json or pom.xml). uv add installs packages into the project's own virtual environment and records them, so anyone can recreate it with uv sync.

We add httpx (HTTP client), openai (the SDK, which also works with Ollama and many other providers) and python-dotenv (reads settings from .env).

Run
uv init first-llm-call
cd first-llm-call
uv add httpx openai python-dotenv
uv add --dev pytest
You should see
Initialized project `first-llm-call` at `.../first-llm-call`
Resolved 20 packages in 410ms
Installed 18 packages in 35ms
 + httpx==0.28.1
 + openai==1.x.x
 + python-dotenv==1.x.x
 ...
Stuck on this step?
uv: command not found
Run export PATH="$HOME/.local/bin:$PATH" (macOS and Linux), or open a new terminal so the installer's PATH change applies.
2

Settings in one place

Model, URL and key come from `.env`, never from the code.

Every LLM app needs three settings: where the API is, which model, and the key. Keeping them in .env means the same code runs locally for free and against a paid API in production, and the key never ends up in git.

.env
# Local model through Ollama (free). Ollama ignores the key, but the SDK needs a value.
LLM_BASE_URL=http://localhost:11434/v1
LLM_API_KEY=ollama
LLM_MODEL=llama3.2:3b

# A hosted API instead: change these three lines, nothing else.
# LLM_BASE_URL=https://api.your-provider.com/v1
# LLM_API_KEY=sk-...
# LLM_MODEL=the-model-name
  1. Ollama serves an OpenAI-compatible API under /v1. Most providers and servers (vLLM, LM Studio, many cloud APIs) use the same request shape.line 2
  2. Ollama does not check keys. A real provider does: keep this file out of git.line 3
config.py
import os
from dataclasses import dataclass

from dotenv import load_dotenv

load_dotenv()  # read .env into environment variables (real env vars win)


@dataclass(frozen=True)
class Settings:
    base_url: str
    api_key: str
    model: str


def settings() -> Settings:
    return Settings(
        base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
        api_key=os.environ.get("LLM_API_KEY", "ollama"),
        model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
    )
  1. load_dotenv() copies .env into os.environ. Variables already set in your shell or on the server take priority, which is what you want in production.line 6
  2. frozen=True makes the settings read-only, so nothing changes them by accident.line 9
.gitignore
.venv/
__pycache__/
.env
  1. Never commit .env: it will hold a real key one day.line 3
Why this way? Hard-coding the model name and URL is the most common reason a demo cannot move to production. One settings function is all it takes.
3

The raw HTTP request

See exactly what an LLM API call is: one POST with JSON in and JSON out.

Before any SDK, send the request yourself. The body has the model and a list of messages, each with a role (system, user or assistant) and content. The reply has the answer in choices[0].message.content and the token counts in usage.

raw_call.py
import httpx

from config import settings

s = settings()
body = {
    "model": s.model,
    "messages": [
        {"role": "system", "content": "You are a concise tutor. Answer in at most two sentences."},
        {"role": "user", "content": "What is a hash map?"},
    ],
    "temperature": 0.2,
}

resp = httpx.post(
    f"{s.base_url}/chat/completions",
    headers={"Authorization": f"Bearer {s.api_key}"},
    json=body,
    timeout=60,
)
resp.raise_for_status()
data = resp.json()

print(data["choices"][0]["message"]["content"])
print("usage:", data["usage"])
  1. The **system** message sets the rules for the whole conversation. Users never see it.line 9
  2. Low temperature: more predictable answers. Good for explanations and extraction.line 12
  3. Every OpenAI-compatible API has this one endpoint for chat.line 15
  4. Local models can take a while for the first call (loading into memory), so give it a generous timeout.line 19
  5. Turns 4xx and 5xx responses into an exception instead of silently reading an error body.line 21
  6. usage has prompt_tokens (what you sent) and completion_tokens (what came back). That is what you pay for.line 25
Run
uv run raw_call.py
You should seeyour text will differ: the model writes it
A hash map (also known as a hash table) is a data structure that stores key-value pairs, where each key is unique and maps to a specific value. It uses a hash function to quickly look up and retrieve values based on their corresponding keys.
usage: {'prompt_tokens': 44, 'completion_tokens': 52, 'total_tokens': 96}
Stuck on this step?
httpx.ConnectError: [Errno 61] Connection refused
Ollama is not running. Open the Ollama app (or run ollama serve) and try again.
404 Not Found with model ... not found
The model name in .env does not match what you pulled. Run ollama list and copy the exact name, for example llama3.2:3b.
It takes 20+ seconds the first time
Normal: the model is being loaded into memory. Later calls are much faster.
4

The same call with the SDK

Let the SDK build the request, parse the reply, retry and time out for you.

The SDK sends exactly the request you just wrote by hand. What it adds: typed responses, automatic retries on temporary errors, timeouts, and streaming. Pointing base_url at Ollama is all it takes to use it with a local model.

llm.py
from openai import OpenAI

from config import settings

_s = settings()
client = OpenAI(base_url=_s.base_url, api_key=_s.api_key, timeout=60, max_retries=2)


def ask(question: str, system: str = "You are a concise tutor.", temperature: float = 0.2):
    """Send one question, return (answer, usage)."""
    resp = client.chat.completions.create(
        model=_s.model,
        messages=[
            {"role": "system", "content": system},
            {"role": "user", "content": question},
        ],
        temperature=temperature,
    )
    return resp.choices[0].message.content, resp.usage
  1. max_retries=2: the SDK retries timeouts, 429 (rate limit) and 5xx errors with backoff. Your own code does not have to.line 6
  2. Wrap the call in one function. Every later lab builds on ask(), and tests can replace it.line 9
  3. resp.usage is the same token count as before, now as an object: usage.prompt_tokens.line 19
main.py
import sys

from llm import ask

question = " ".join(sys.argv[1:]) or "Explain recursion to a new programmer."
answer, usage = ask(question)
print(answer)
print(f"\n[{usage.prompt_tokens} tokens in, {usage.completion_tokens} tokens out]")
Run
uv run main.py "Why do databases use indexes?"
You should seeyour text will differ: the model writes it
Databases use indexes to improve query performance by:

1. **Reducing the number of disk I/O operations**: Indexes allow the database to quickly locate data without having to scan the entire table.
...

[37 tokens in, 185 tokens out]
5

Estimate the cost of every call

Turn token counts into money, the habit that keeps LLM features affordable.

Providers price input and output tokens separately, per million tokens, and output usually costs several times more. A local model costs nothing per call, but you still want the habit: the same code goes to production.

The prices below are examples, not any provider's real prices. Put your provider's numbers in PRICES.

cost.py
# Example prices in US dollars per 1 million tokens. Replace with your provider's prices.
PRICES = {
    "small-model": {"input": 0.15, "output": 0.60},
    "frontier-model": {"input": 3.00, "output": 15.00},
}


def estimate_cost(prompt_tokens: int, completion_tokens: int, model: str) -> float:
    """Dollar cost of one call. Unknown models (like a local one) cost 0."""
    p = PRICES.get(model)
    if p is None:
        return 0.0
    return (prompt_tokens * p["input"] + completion_tokens * p["output"]) / 1_000_000
  1. Output often costs about 4 to 5 times more than input. Long answers are where money goes.line 4
  2. 1_000_000: Python lets you write underscores in numbers for readability.line 13
main.py 7 new or changed lines
import sys

from config import settings
from cost import estimate_cost
from llm import ask

question = " ".join(sys.argv[1:]) or "Explain recursion to a new programmer."
answer, usage = ask(question)
print(answer)

cost = estimate_cost(usage.prompt_tokens, usage.completion_tokens, settings().model)
print(f"\n[{usage.prompt_tokens} in, {usage.completion_tokens} out, about ${cost:.6f}]")
for model in ("small-model", "frontier-model"):
    c = estimate_cost(usage.prompt_tokens, usage.completion_tokens, model)
    print(f"  on {model}: ${c:.6f} per call, ${c * 1_000_000:,.0f} per million calls")
  1. Local model: not in PRICES, so the cost is 0.line 11
  2. Multiply by a million calls: this is the number that matters in a design review.line 15
Run
uv run main.py "What is a load balancer?"
You should seeyour text will differ: the model writes it
A load balancer spreads incoming requests across several servers...

[30 in, 48 out, about $0.000000]
  on small-model: $0.000033 per call, $33 per million calls
  on frontier-model: $0.000810 per call, $810 per million calls
6

Handle the errors you will actually hit

Clear messages instead of stack traces when the server is down, slow, or the model name is wrong.

The SDK already retries temporary failures. What is left is telling the user what went wrong. The SDK raises specific exception classes, so you can catch each case and say something useful.

main.py 13 new or changed lines
import sys

import openai

from config import settings
from cost import estimate_cost
from llm import ask

question = " ".join(sys.argv[1:]) or "Explain recursion to a new programmer."
try:
    answer, usage = ask(question)
except openai.APITimeoutError:
    sys.exit("The model took too long. Try a shorter question or a smaller model.")
except openai.APIConnectionError:
    sys.exit("Cannot reach the model server. Is Ollama running? (open the app or run: ollama serve)")
except openai.NotFoundError:
    sys.exit(f"Model '{settings().model}' not found. Run: ollama list")
except openai.AuthenticationError:
    sys.exit("The API key was rejected. Check LLM_API_KEY in .env")
except openai.RateLimitError:
    sys.exit("Rate limited by the provider. Wait a moment and try again.")

print(answer)
cost = estimate_cost(usage.prompt_tokens, usage.completion_tokens, settings().model)
print(f"\n[{usage.prompt_tokens} in, {usage.completion_tokens} out, about ${cost:.6f}]")
  1. Timeout comes first on purpose: APITimeoutError is a subclass of APIConnectionError, and Python uses the first except that matches, so the other order would never reach this branch.line 12
  2. Server not running or wrong URL. The most common error on day one.line 14
  3. Wrong model name: Ollama answers 404.line 16
  4. Only hosted APIs rate-limit. The SDK already retried twice before raising this.line 20
Run
LLM_MODEL=no-such-model uv run main.py "hi"
You should see
Model 'no-such-model' not found. Run: ollama list
Stuck on this step?
Windows: LLM_MODEL=... uv run is not recognised
In PowerShell run $env:LLM_MODEL="no-such-model"; uv run main.py "hi", then Remove-Item Env:LLM_MODEL afterwards.
7

Test it without a model

Unit tests that run in milliseconds, with no server and no cost.

Tests should not call a real model: it is slow, costs money and gives different words each time. Test your own logic (the cost maths) directly, and test the HTTP handling against a fake server with httpx.MockTransport.

test_basics.py
import httpx
import pytest

from cost import estimate_cost


def test_cost_small_model():
    # 1,000 in and 500 out at $0.15 and $0.60 per million
    assert estimate_cost(1000, 500, "small-model") == pytest.approx(0.00045)


def test_unknown_model_is_free():
    assert estimate_cost(10_000, 10_000, "llama-on-my-laptop") == 0.0


def test_parse_reply_from_fake_server():
    def fake_server(request: httpx.Request) -> httpx.Response:
        assert request.url.path.endswith("/chat/completions")
        return httpx.Response(200, json={
            "choices": [{"message": {"role": "assistant", "content": "Hi!"}}],
            "usage": {"prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7},
        })

    client = httpx.Client(transport=httpx.MockTransport(fake_server), base_url="http://test/v1")
    data = client.post("/chat/completions", json={"model": "m", "messages": []}).json()
    assert data["choices"][0]["message"]["content"] == "Hi!"
    assert data["usage"]["total_tokens"] == 7
  1. pytest.approx: compare floats with a tolerance. 0.1 + 0.2 == 0.3 is False in every language.line 9
  2. A fake server is just a function from request to response.line 17
  3. MockTransport makes httpx call the function instead of the network.line 24
Run
uv run pytest -q
You should see
...                                                     [100%]
3 passed in 0.12s

Check it works

Two checks: the tests pass, and the program answers a real question through your local model with token counts and cost lines.

Test
uv run pytest -q && uv run main.py "In one sentence, what is an API?"
You should see
3 passed in 0.12s
An API is a set of rules that lets one program ask another for data or actions.

[29 in, 19 out, about $0.000000]

Troubleshooting

Answers are very slow (more than 30 seconds)

Your machine is running the model on the CPU. Use a smaller model (ollama pull llama3.2:1b and set LLM_MODEL=llama3.2:1b), close other heavy apps, and keep questions short.

The answer is cut off mid-sentence

The reply hit the output limit. Pass max_tokens=500 to create() and check resp.choices[0].finish_reason: length means it was cut.

ModuleNotFoundError: No module named 'openai'

You ran python main.py outside the project environment. Use uv run main.py, which always uses the project's packages.

It works locally but a hosted API says 401

The key is wrong or not loaded. Print settings().base_url (never print the key) to confirm .env was read, and check there are no quotes or spaces around the key.

What changes in production

  • Never put keys in code or in the browser. Calls go from your server to the provider; the browser talks only to your server.
  • Set a timeout and a retry budget on every call. A model call can take seconds; without limits one slow provider stalls your whole service.
  • Log usage for every call with the user and feature. Cost surprises come from a few users or one feature with long prompts.
  • Keep the provider behind one function (ask() here). Swapping or adding a provider, or a fallback when one is down, then touches one file.

Interview angle

β€œWalk me through what happens when your app calls an LLM API.”

My server sends one HTTPS POST to the chat completions endpoint with the model name and the message list: a system message with the rules, then the user turn. The provider tokenizes it, runs the model and returns JSON with the answer and the token usage. I wrap it in one function with a timeout, a couple of retries for 429 and 5xx, and I log the usage so I can attribute cost. Settings come from the environment, so the same code runs against a local model in development and a hosted one in production.

Clean up

Keep the project: the next lab builds on config.py and llm.py. To free disk space later, remove the model.

Run
ollama rm llama3.2:3b

Practice

No model needed: these run in your browser and check your answer.

Cost of a whole conversation

Each turn of a chat sends the whole history again. Write conversation_cost(turns, price_in, price_out) where turns is a list of (prompt_tokens, completion_tokens) per call and prices are dollars per million tokens. Return the total in dollars.

Exercise
def conversation_cost(turns, price_in, price_out):
    # turns: [(prompt_tokens, completion_tokens), ...]
    total = 0.0
    # your code here
    return total


print(conversation_cost([(100, 50), (200, 40)], 1.0, 4.0))
Hint

Sum prompt tokens times the input price and completion tokens times the output price, then divide by 1,000,000.

Build the message list

Write build_messages(system, history, question). history is a list of (user_text, assistant_text) pairs from earlier turns. Return the list of message dicts in the order the API expects: the system message, then each pair as a user and an assistant message, then the new question as a user message.

Exercise
def build_messages(system, history, question):
    messages = []
    # your code here
    return messages


print(build_messages("Be brief.", [("Hi", "Hello!")], "What is DNS?"))
Hint

Start with the system dict, loop over the pairs appending a user dict then an assistant dict, and finish with the question.

The full project

Every file from this lab, as it is after the last step.

Download Python project (.zip) Download Java project (.zip)