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
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
- Python basics. New to Python? Start with Set up Python the modern way.
- About 3 GB of free disk space for the model.
- Know what a token and the context window are: Tokens and context windows (8 minutes).
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.
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" 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.
uv --version 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.
ollama --version 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.
ollama pull llama3.2:3b 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.
brew install openjdk@21 mavensudo apt install openjdk-21-jdk mavenwinget install Microsoft.OpenJDK.21 Apache.Maven S6Check the model answers
ollama run llama3.2:3b "Say hello in five words." Hello there, how are you?
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).
uv init first-llm-call
cd first-llm-call
uv add httpx openai python-dotenv
uv add --dev pytest 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.
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.
# 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 - 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 - Ollama does not check keys. A real provider does: keep this file out of git.line 3
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"),
) load_dotenv()copies.envintoos.environ. Variables already set in your shell or on the server take priority, which is what you want in production.line 6frozen=Truemakes the settings read-only, so nothing changes them by accident.line 9
.venv/
__pycache__/
.env - Never commit
.env: it will hold a real key one day.line 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.
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"]) - The **system** message sets the rules for the whole conversation. Users never see it.line 9
- Low temperature: more predictable answers. Good for explanations and extraction.line 12
- Every OpenAI-compatible API has this one endpoint for chat.line 15
- Local models can take a while for the first call (loading into memory), so give it a generous timeout.line 19
- Turns 4xx and 5xx responses into an exception instead of silently reading an error body.line 21
usagehasprompt_tokens(what you sent) andcompletion_tokens(what came back). That is what you pay for.line 25
uv run raw_call.py 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 Foundwithmodel ... not found- The model name in
.envdoes not match what you pulled. Runollama listand copy the exact name, for examplellama3.2:3b. - It takes 20+ seconds the first time
- Normal: the model is being loaded into memory. Later calls are much faster.
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.
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 max_retries=2: the SDK retries timeouts, 429 (rate limit) and 5xx errors with backoff. Your own code does not have to.line 6- Wrap the call in one function. Every later lab builds on
ask(), and tests can replace it.line 9 resp.usageis the same token count as before, now as an object:usage.prompt_tokens.line 19
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]") <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.5</version>
</parent>
<groupId>dev.algorung</groupId>
<artifactId>first-llm-call</artifactId>
<version>0.1.0</version>
<properties>
<java.version>21</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project> - Spring Boot 3.4 with Java 21. Spring AI 1.0 needs Spring Boot 3.4 or newer.line 8
- The Spring AI BOM keeps every Spring AI module on the same version.line 20
- The Ollama starter. For a hosted API you swap this one dependency and the properties.line 29
spring.ai.ollama.base-url=http://localhost:11434
spring.ai.ollama.chat.options.model=llama3.2:3b
spring.ai.ollama.chat.options.temperature=0.2
spring.main.web-application-type=none - A command-line app: no web server for this lab.line 4
package dev.algorung;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class FirstCall {
public static void main(String[] args) {
SpringApplication.run(FirstCall.class, args);
}
@Bean
CommandLineRunner run(ChatClient.Builder builder) {
return args -> {
ChatClient chat = builder.defaultSystem("You are a concise tutor.").build();
String question = args.length > 0 ? String.join(" ", args) : "Why do databases use indexes?";
ChatResponse resp = chat.prompt().user(question).call().chatResponse();
System.out.println(resp.getResult().getOutput().getText());
var usage = resp.getMetadata().getUsage();
System.out.printf("%n[%d tokens in, %d tokens out]%n", usage.getPromptTokens(), usage.getCompletionTokens());
};
}
} - Spring AI builds a
ChatClient.Builderfrom the properties; you just ask for it.line 17 defaultSystemis the system message for every call made with this client.line 19.call()waits for the whole answer..stream()is the streaming version (next lab).line 21- Token usage, the same numbers as
usagein the Python version.line 23
Java (Spring AI) version of this step:
uv run main.py "Why do databases use indexes?" 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]
mvn -q spring-boot:run -Dspring-boot.run.arguments="Why do databases use indexes?" An index lets the database find matching rows without scanning the whole table... [31 tokens in, 52 tokens out]
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.
# 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 - Output often costs about 4 to 5 times more than input. Long answers are where money goes.line 4
1_000_000: Python lets you write underscores in numbers for readability.line 13
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") - Local model: not in
PRICES, so the cost is 0.line 11 - Multiply by a million calls: this is the number that matters in a design review.line 15
uv run main.py "What is a load balancer?" 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
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.
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}]") - Timeout comes first on purpose:
APITimeoutErroris a subclass ofAPIConnectionError, and Python uses the firstexceptthat matches, so the other order would never reach this branch.line 12 - Server not running or wrong URL. The most common error on day one.line 14
- Wrong model name: Ollama answers 404.line 16
- Only hosted APIs rate-limit. The SDK already retried twice before raising this.line 20
LLM_MODEL=no-such-model uv run main.py "hi" Model 'no-such-model' not found. Run: ollama list
Stuck on this step?
- Windows:
LLM_MODEL=... uv runis not recognised - In PowerShell run
$env:LLM_MODEL="no-such-model"; uv run main.py "hi", thenRemove-Item Env:LLM_MODELafterwards.
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.
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 pytest.approx: compare floats with a tolerance.0.1 + 0.2 == 0.3is False in every language.line 9- A fake server is just a function from request to response.line 17
MockTransportmakes httpx call the function instead of the network.line 24
uv run pytest -q ... [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.
uv run pytest -q && uv run main.py "In one sentence, what is an API?" 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
usagefor 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.
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.
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.
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.