Sign in Start free

AI engineeringFree course

LLM Fundamentals for Engineers

How large language models work and how to build with them: tokens and cost, generation and sampling, the API, production prompts, structured output and tool calls, embeddings and RAG, evaluation, security (OWASP LLM Top 10 2026) and production operations, on one project.

  • Level Junior → Expert
  • Time 318 min
  • Modules 10
  • Exercises 35 with worked solutions
  • Includes Lab, 5-question quiz, references

What you'll learn

  • Explain tokens, context windows, sampling and how models generate text
  • Call model APIs robustly with retries, limits and cost control
  • Write production prompts and get validated structured output and tool calls
  • Ground answers with embeddings and retrieval (RAG)
  • Evaluate quality and defend against prompt injection and data leakage

Each lesson is tagged Junior, Mid or Expert, so you can start where you are. Finish with the lab and the quiz; a score of 4 out of 5 marks the course complete in this browser.

The lessons below are in English for now, because they quote technical names, commands and log fields. An Arabic version is planned.

Course map

Each module moves from fundamentals to applied work to an expert challenge. Exercises have worked solutions: try first, then open the solution. 10 modules · 35 exercises · ~5.3 hours

  1. 0Start here: what an LLM is and how applications use itJuniorMidExpert30 min · 3 exercises
  2. 1Tokens, context windows and costJuniorMidExpert33 min · 4 exercises
  3. 2How a model generates textJuniorMidExpert35 min · 4 exercises
  4. 3The API in practice: messages, streaming, errors and limitsJuniorMidExpert26 min · 3 exercises
  5. 4Prompt engineering for productionJuniorMidExpert33 min · 4 exercises
  6. 5Structured output and tool callingJuniorMidExpert32 min · 3 exercises
  7. 6Embeddings and retrieval-augmented generation (RAG)JuniorMidExpert33 min · 4 exercises
  8. 7Evaluating LLM applicationsJuniorMidExpert32 min · 4 exercises
  9. 8Security, privacy and responsible useJuniorMidExpert32 min · 4 exercises
  10. 9Production: models, cost, latency and operations; cheat sheet and assessmentJuniorMidExpert32 min · 2 exercises

No prior experience is needed. Module 0 covers the architecture, installation and configuration, and sets up the project you extend in every module. Each command is labelled with its impact (read-only, changes files, changes the system, uses the network). Work on a computer or virtual machine you control.

0

Start here: what an LLM is and how applications use it

Goal: Place LLMs within AI, understand what they can and cannot do, see the parts of an LLM application, and set up the lab.

30 min

Concepts: where large language models come from

Large language models sit at the end of a chain: artificial intelligence, machine learning, deep learning, generative AI, and finally LLMs, transformer networks trained on vast text to predict the next token. A model is built in stages: pre-training on large data produces a base model that knows a lot but does not follow instructions; instruction tuning teaches it to respond to requests; preference tuning (reinforcement learning from human or AI feedback) shapes helpfulness and safety. What you call through an API is the result of all three.

Knowing how models are made explains their behaviour: they are fluent because they learned language patterns, they hallucinate because they predict plausible text rather than look facts up, and their knowledge stops at a training cutoff. Application design follows directly: give models facts and tools, and check what matters.

Artificial intelligencemachines doing tasks that need intelligenceMachine learningsystems that learn patterns from dataDeep learningmany-layer neural networksGenerative AImodels that create text, images, audio, codeLarge language modelstransformers trained on vast text to predict tokens
Dataweb, books, codePre-trainingpredict the next tokenBase modelknows, does not followInstruction tuningexamples of good answersPreference tuningRLHF / RLAIF, safetyDeployed modelAPI, chat, agents
Base modelraw next-tokenpredictorInstruct / chatfollows instructionsReasoning modelthinks beforeansweringMultimodaltext + images, audioEmbedding modeltext → vector,no generationOpen-weightdownload andself-host
Good atlanguage: write, summarise, translatepatterns: classify, extractreasoning over what is in contextWeak atfacts after the training cutoffexact arithmetic, countingknowing what it does not knowThereforegive it the facts (context, RAG)give it tools (calculators, APIs)check outputs that matter

Quick check: Why does an LLM sometimes state wrong facts confidently?

Exercise 1Junior

Which model type would you use to (a) search policy documents by meaning, (b) answer customers, (c) plan a multi-step investigation?

Worked solution

(a) an embedding model; (b) an instruct/chat model; (c) a reasoning model, or an instruct model inside an agent loop.

A next-token predictor trained on a vast amount of text

A large language model (LLM) is a neural network trained to predict the next piece of text (token) given the text so far. Trained on trillions of tokens and then tuned to follow instructions, it can answer questions, summarise, translate, write code, extract data and call tools.

LLMs let software handle language: customer questions, documents, emails and logs, which rule-based code handles poorly. They are also probabilistic: the same question can produce different answers, and a fluent answer can be wrong. Engineering with LLMs is mostly about controlling those two facts.

Artificial intelligencesystems that perform tasks needing intelligenceMachine learninglearn patterns from dataDeep learningmany-layer neural networksGenerative AIcreate text, images, audio, codeLarge language modelspredict the next token
ModelsAnthropic ClaudeAnthropic ClaudeOpenAIOpenAIGoogle GeminiGoogle GeminiOpen weightsLlamaLlamaMistral AIMistral AIHugging FaceHugging FaceRun locallyOllamaOllamavLLMvLLMCloudAmazon BedrockAmazon BedrockAzure AI FoundryAzure AI FoundryVertex AIVertex AIBuildPythonPythonPydanticPydanticNumPyNumPyRetrievepgvectorpgvectorQdrantQdrantChromaChromaEvaluatepromptfoopromptfooRagasRagasObserveLangfuseLangfuseOpenTelemetryOpenTelemetryArize PhoenixArize PhoenixThe LLM landscape: hosted models, open-weight models, platforms and the tools around them.
LLMs are good atLLMs are unreliable atSo you…
language: summarise, classify, extract, rewriteexact facts they were not givenprovide the facts in the prompt (RAG, tools)
following clear instructions and formatsarithmetic and long exact procedureslet code do maths and validation
writing and explaining codeknowing events after their training datagive current data through tools
many languages, including Arabicconsistency across runslower temperature, schemas, evals

Quick check: A model confidently cites a refund policy your company does not have. What is this called?

Anatomy of an LLM application

Your code is in charge. It gathers the right data, builds the prompt, calls the model through an API, checks the output, and decides what to show or do. The model is one component, not the whole system.

UserquestionYour appauth, history, dataPromptinstructions + contextLLM APIgenerateChecksschema, safety, costAnswershown or acted on
Customersweb and WhatsAppNEWAssistant servicePython APIPythonNEWPrompt builderLLM provider APIRouter + cacheToken budgetSchema validationTool: get_shipmentVector indexPolicy documentsEval suiteCI gateGuardrailsTracing + costHuman agentStage 0: customers ask the assistant service; it will grow module by module.
shell
python3 -m venv .venv && source .venv/bin/activate
pip install anthropic openai numpy jsonschema
export ANTHROPIC_API_KEY=…   # from the provider console; never commit it

Your first API call

python · first_call.py (Anthropic Messages API)
import anthropic

client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY from the environment
response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=400,
    temperature=0.2,
    system="You are Rimal Logistics' shipment assistant. Answer only from the context.",
    messages=[{"role": "user", "content": "Where is shipment RL-1001?"}],
)
print(response.content[0].text)
print(response.usage.input_tokens, response.usage.output_tokens, response.stop_reason)
1
Client reads the key from the environment.
2
Model ID: pick per task; newer and larger is not always better.
3
Hard limit on the answer length (and the cost).
4
Low temperature for factual, repeatable answers.
5
System prompt: the rules; messages: the conversation.
6
Usage and stop reason: log them for cost and truncation checks.
Example output (no context given, so the model correctly refuses to invent a status)
I don't have tracking data for RL-1001 in this conversation. If you share the tracking details, or connect me to the tracking system, I can tell you its status.
31 46 end_turn
python · the same call with OpenAI's Responses API
from openai import OpenAI

client = OpenAI()                       # reads OPENAI_API_KEY
response = client.responses.create(
    model="gpt-6.2-sol",
    instructions="You are Rimal Logistics' shipment assistant. Answer only from the context.",
    input="Where is shipment RL-1001?",
    max_output_tokens=400,
)
print(response.output_text)
1
Model ID (GPT-6.2 Sol).
2
instructions ≈ system prompt; input = the user message.

Exercise 11Junior

The example answer did not invent a status. Which line made that likely, and what would you add so it can answer?

Worked solution

The system prompt says to answer only from the context, and no context was given. Add the shipment record to the prompt (module 4) or give the model a tool that looks it up (module 5).

Exercise 12Junior

Name two things your code should log for every model call, and why.

Worked solution

Input and output tokens (cost and context growth) and the stop reason (max_tokens means the answer was cut off). Also the model ID and prompt version, so you can explain any answer later.

Tools in this course

Anthropic ClaudePlatform

Claude models (Opus, Sonnet, Haiku) through the Messages API.

Use it for: assistants, agents, coding, long documents

Integrates with: AWS Bedrock, Google Vertex AI, MCP

OpenAIPlatform

GPT models through the Responses API.

Use it for: assistants, agents, multimodal apps

Integrates with: Azure AI Foundry

Google GeminiPlatform

Gemini models through the Gemini API and Vertex AI.

Use it for: multimodal and Google Cloud apps

Integrates with: Vertex AI

Hugging FaceArtifacts

Hub for open-weight models, datasets and libraries.

Use it for: finding and running open models

Integrates with: transformers, vLLM

OllamaRuntime

Runs open-weight models locally with one command.

Use it for: offline labs, private data

Integrates with: OpenAI-compatible API

Project step 0

The shipment assistant

Goal: Rimal Logistics wants an assistant that answers shipment and policy questions accurately in English and Arabic, hands over to a human when unsure, and costs a predictable amount. You will build it module by module.

1

Tokens, context windows and cost

Goal: Understand tokenisation, train a small tokenizer, budget the context window, and estimate cost.

33 min

Free account Create a free account or sign in to continue this course.

2

How a model generates text

Goal: Follow text through embeddings, attention and sampling, and understand training stages and why models hallucinate.

35 min

Free account Create a free account or sign in to continue this course.

3

The API in practice: messages, streaming, errors and limits

Goal: Use conversation messages correctly, stream responses, handle errors and rate limits, and choose models and parameters.

26 min

Free account Create a free account or sign in to continue this course.

4

Prompt engineering for production

Goal: Write clear, structured prompts with context, rules, format and examples, render them safely, and improve them systematically.

33 min

Free account Create a free account or sign in to continue this course.

5

Structured output and tool calling

Goal: Get reliable JSON from a model, validate it, and let the model request your functions through tool calls.

32 min

Free account Create a free account or sign in to continue this course.

6

Embeddings and retrieval-augmented generation (RAG)

Goal: Represent text as vectors, retrieve the most relevant policy chunks, and ground answers in them with citations.

33 min

Free account Create a free account or sign in to continue this course.

7

Evaluating LLM applications

Goal: Measure quality with golden datasets and automatic checks, compare prompt versions, and gate releases in CI.

32 min

Free account Create a free account or sign in to continue this course.

8

Security, privacy and responsible use

Goal: Recognise the main LLM application risks, defend against prompt injection and data leakage, and handle output and cost safely.

32 min

Free account Create a free account or sign in to continue this course.

9

Production: models, cost, latency and operations; cheat sheet and assessment

Goal: Choose models deliberately, control cost and latency, operate the assistant, and prove the skills on a new use case.

32 min

Free account Create a free account or sign in to continue this course.

Quick reference (the cheat-sheet lessons and the PDF content)
1

What happens inside a request

Junior

An LLM predicts the next token from everything in its context. It has no memory between calls unless you send the history again.

One request to a model: everything the model knows about your task must fit in the context windowSystem promptrole, rules, formatTools / schemaswhat it may callRetrieved contextdocs, records (RAG)Conversationprevious turnsUser messagethe taskModelnext-token predictioninput tokens (billed, limited by the context window)output tokens
2

Core concepts in one table

Junior
ConceptWhat it means for you
TokenA chunk of text (about ¾ of an English word; Arabic often uses more tokens per word). Pricing and limits are in tokens
Context windowMaximum input + output tokens per call. Long contexts cost more and can dilute attention
Temperature / samplingHigher = more varied output. Use low values for extraction and classification
Pre-training vs fine-tuningGeneral knowledge from huge corpora vs adapting behaviour with your examples
Knowledge cutoffThe model does not know later events: give it current facts in the prompt or through tools
HallucinationFluent but wrong output. Reduce with grounding (RAG), citations and verification
Reasoning / extended thinkingThe model spends extra tokens working through a problem before answering: better on hard tasks, slower and costlier
EmbeddingA vector that represents meaning; used for search and clustering, not generation
Tool use (function calling)The model returns a structured request; your code runs the tool and sends back the result
3

A prompt structure that survives production

JuniorMid
text · system prompt template
You are a security triage assistant for Rimal Logistics.

<task>
Classify the alert and recommend the next step.
</task>

<rules>
- Use only the alert and context below. If something is
  missing, say what is missing; do not guess.
- Severity is one of: low, medium, high, critical.
- Never include secrets or personal data in the output.
</rules>

<context>{retrieved_runbook_sections}</context>
<alert>{alert_json}</alert>

<examples>{two_labelled_examples}</examples>

Return JSON that matches the schema you were given.

Why it works

  • Clear role and task at the top
  • Rules stated as positive instructions plus a fallback ("say what is missing")
  • Untrusted data fenced in tags and treated as data
  • A few diverse examples beat long explanations
  • Explicit output contract: schema, not prose
  • Version prompts in Git like code
4

Structured output and tool calls

Mid
python · structured output (pseudo-SDK)
schema = {
  "type": "object",
  "properties": {
    "severity": {"enum": ["low", "medium", "high", "critical"]},
    "technique": {"type": "string", "pattern": "^T\\d{4}"},
    "next_step": {"type": "string", "maxLength": 300}
  },
  "required": ["severity", "next_step"],
  "additionalProperties": False}

resp = client.generate(model=MODEL, system=SYSTEM,
        messages=[{"role": "user", "content": alert}],
        response_schema=schema, temperature=0)
result = validate(resp.json, schema)   # always validate
Your appModelTool (your code)prompt + tool schemastool_call: lookup_ip(203.0.113.5)run with app permissionsresulttool_resultfinal answer
5

Choosing a model

Mid
FactorAskTrade-off
CapabilityDoes it pass your eval set, not a public leaderboard?Bigger models: better reasoning, higher cost and latency
LatencyWhat is the time to first token and total time at p95?Small models or streaming for chat UX
CostTokens per task × price × volume per month?Caching, shorter prompts, routing easy tasks to small models
Context and modalityLong documents, images, audio?Long context is not free: retrieval is often cheaper
DeploymentAPI, cloud-hosted, or open-weight on your own GPUs?Data residency and control vs operating effort
Data and termsIs input used for training? Retention? Region?Check contract terms; enterprise tiers differ
6

Evaluate before you ship

MidExpert

Without an eval set every prompt change is a guess. Re-run it on each change, like unit tests.

Collect50–200 real casesLabelexpected outcomeMetricsexact, rubric, LLM-judgeBaselinecurrent prompt/modelChange one thingprompt, model, RAGGateno regression → ship
7

Cost and latency levers

Mid

Cheaper

  • Prompt caching for long, repeated prefixes (system prompt, documents)
  • Route simple tasks to a small model
  • Batch APIs for offline jobs
  • Trim context: retrieve the top passages, not whole documents
  • Cap max_tokens and ask for concise output

Faster

  • Stream tokens to the user
  • Parallelize independent calls
  • Smaller model for the first draft, larger only when needed
  • Cache final answers for repeated questions
  • Keep tool round-trips few
8

Failure modes and mitigations

MidExpert
FailureMitigation
Hallucinated facts or citationsGround with retrieval; require quotes from sources; verify links and numbers in code
Prompt injection from documents, web pages or emailTreat retrieved text as data; limit tool permissions; human approval for actions
Inconsistent output formatSchema-constrained output plus validation and retry
Sensitive data leakageRedact before sending; data-classification rules; no secrets in prompts
Silent quality drift after a model updatePin model versions; run the eval set before switching
Over-trust by usersShow sources and confidence; keep a human in the loop for high-impact decisions
Next steps Ground answers in your own data with Retrieval-Augmented Generation (RAG), then let models act with Agentic AI Systems.

Key terms

Token
The unit models read and write: a word, word piece or character.
Context window
Maximum tokens per call, including the answer.
Temperature
Sampling setting: low is focused, high is varied.
Structured output
Model output constrained to and validated against a JSON Schema.
RAG
Retrieval-augmented generation: fetch relevant text and answer from it with citations.
Prompt injection
Text that tries to override the application's instructions.

Hands-on lab

Free account Create a free account or sign in to continue this course.

Knowledge check

Answer all five questions, then check your answers. Each answer comes with a short explanation.

1Why can the same prompt give different answers?
2What usually costs more per token?
3Best way to give a model your current policies?
4Which defence actually limits prompt injection damage?
5What should run on every prompt or model change?

Further reading

Put it into practice