This is the first hands-on lesson of the AI Engineer learning path. By the end you will have a small command-line tool that answers questions about a text file, and a log that shows exactly what each answer cost in tokens and time. Everything runs on your own computer with a free, open-weights model, so you need no account and no API key.

What you’ll learn

  • How a program talks to a language model, and what comes back.
  • What tokens, the context window and temperature mean in practice.
  • How to measure latency and token usage, the two numbers that drive cost.
  • How to compare two models on the same task with evidence.

Prerequisites: basic Python (functions, dictionaries, reading files) and a terminal. About 8 GB of RAM is enough for the small models used here.

1. Set up a local model

We’ll use Ollama, which runs open-weights models locally and serves them through a simple HTTP API on your machine.

  1. Install Ollama from its website and start it.
  2. Download two small models to compare later. Any two small instruction-tuned models will do; pick ones that fit your RAM, for example:
ollama pull <small-model-a>
ollama pull <small-model-b>
ollama list          # shows the models you have and their sizes
  1. Install the one Python package we need:
pip install requests

Ollama listens on http://localhost:11434. Nothing leaves your machine.

2. Your first call

A chat model takes a list of messages, each with a role (system, user or assistant) and some content, and returns the next assistant message. Save this as ask.py:

import requests

OLLAMA = "http://localhost:11434/api/chat"

def ask(model: str, question: str, context: str = "", temperature: float = 0.2) -> dict:
    messages = [
        {"role": "system", "content": "Answer using only the provided text. If the text doesn't contain the answer, say so."},
        {"role": "user", "content": f"Text:\n{context}\n\nQuestion: {question}"},
    ]
    r = requests.post(OLLAMA, json={
        "model": model,
        "messages": messages,
        "stream": False,
        "options": {"temperature": temperature},
    }, timeout=300)
    r.raise_for_status()
    return r.json()

if __name__ == "__main__":
    reply = ask("<small-model-a>", "What is this text about?", "Paris is the capital of France.")
    print(reply["message"]["content"])

Run it with python ask.py. The response is JSON. Besides the answer in message.content, Ollama reports usage fields, including:

Field Meaning
prompt_eval_count Tokens in your input (the prompt)
eval_count Tokens the model generated
total_duration Total time for the request, in nanoseconds

3. Tokens, context and temperature

Tokens are the units models read and write: pieces of words, punctuation and spaces. Hosted APIs charge per token (usually a different price for input and output), and generation time grows with the number of output tokens. That is why the usage fields matter.

The context window is the maximum number of tokens a model can consider at once: your instructions, the text you provide and its answer combined. If your file is longer than the window, it won’t fit; later stages of the path cover retrieval, which solves this properly.

Temperature controls randomness. Low values (around 0 to 0.3) make answers more repeatable, which is what you want for extraction and question answering. Higher values give more varied wording, which is useful for brainstorming.

4. Measure every call

Engineering starts with measurement. Extend ask.py so that every call is logged: add the code below to the file, and replace the old if __name__ == "__main__": block with the new one at the end.

import csv, sys, time, pathlib

def logged_ask(model: str, question: str, context: str) -> str:
    start = time.perf_counter()
    reply = ask(model, question, context)
    wall = time.perf_counter() - start
    row = {
        "model": model,
        "question": question,
        "input_tokens": reply.get("prompt_eval_count"),
        "output_tokens": reply.get("eval_count"),
        "seconds": round(wall, 2),
        "answer": reply["message"]["content"].strip().replace("\n", " ")[:200],
    }
    log = pathlib.Path("calls.csv")
    new = not log.exists()
    with log.open("a", newline="") as f:
        w = csv.DictWriter(f, fieldnames=row.keys())
        if new:
            w.writeheader()
        w.writerow(row)
    return row["answer"]

if __name__ == "__main__":
    model, path, question = sys.argv[1], sys.argv[2], sys.argv[3]
    text = pathlib.Path(path).read_text()
    print(logged_ask(model, question, text))

Usage: python ask.py <model> notes.txt "What are the three main points?"

If you later switch to a hosted API, add a cost column: input tokens times the input price, plus output tokens times the output price, using the provider’s published per-token rates.

5. Compare two models on your task

Leaderboards rank models on someone else’s tasks. Your task is the one that matters.

  1. Pick a text file you know well, such as meeting notes, an article or documentation.
  2. Write five questions with answers you can check, including one the text doesn’t answer.
  3. Run all five questions against both models.
  4. Open calls.csv and score each answer as correct, partly correct or wrong. Did each model admit when the answer wasn’t in the text?

Now you have evidence: accuracy on your questions, average latency and token counts for each model. Often a smaller model is good enough, and much faster.

Project checklist

  • ask.py answers questions about any text file.
  • Every call is logged with model, tokens and time.
  • Five test questions, including one unanswerable, scored for two models.
  • A short note: which model would you choose for this task, and why?

Keep this project. In Stage 2 you’ll turn free-text answers into structured output that code can check automatically, and your five questions will become the start of a proper evaluation set.

Next: Stage 2, prompts, structured output and your first evaluation.

Prepared with AI assistance and reviewed by an editor before publication. Editorial & AI policy.