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
- 0Start here: what an LLM is and how applications use itJuniorMidExpert30 min · 3 exercises
- 1Tokens, context windows and costJuniorMidExpert33 min · 4 exercises
- 2How a model generates textJuniorMidExpert35 min · 4 exercises
- 3The API in practice: messages, streaming, errors and limitsJuniorMidExpert26 min · 3 exercises
- 4Prompt engineering for productionJuniorMidExpert33 min · 4 exercises
- 5Structured output and tool callingJuniorMidExpert32 min · 3 exercises
- 6Embeddings and retrieval-augmented generation (RAG)JuniorMidExpert33 min · 4 exercises
- 7Evaluating LLM applicationsJuniorMidExpert32 min · 4 exercises
- 8Security, privacy and responsible useJuniorMidExpert32 min · 4 exercises
- 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.
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.
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.
Quick check: Why does an LLM sometimes state wrong facts confidently?
Fluency is not retrieval.
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.
| LLMs are good at | LLMs are unreliable at | So you… |
|---|---|---|
| language: summarise, classify, extract, rewrite | exact facts they were not given | provide the facts in the prompt (RAG, tools) |
| following clear instructions and formats | arithmetic and long exact procedures | let code do maths and validation |
| writing and explaining code | knowing events after their training data | give current data through tools |
| many languages, including Arabic | consistency across runs | lower temperature, schemas, evals |
Quick check: A model confidently cites a refund policy your company does not have. What is this called?
The model produced plausible but unsupported text; grounding and evaluation reduce it.
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.
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# run an open-weight model locally, no API key
ollama pull llama3.3
ollama run llama3.3 "Summarise: shipment RL-1001 is delayed at customs"Keep API keys in environment variables or a secret manager, give each app its own key, set spending limits in the provider console, and rotate keys that leak (see the DevSecOps course).
Your first API call
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)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
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)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
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
GPT models through the Responses API.
Use it for: assistants, agents, multimodal apps
Integrates with: Azure AI Foundry
Gemini models through the Gemini API and Vertex AI.
Use it for: multimodal and Google Cloud apps
Integrates with: Vertex AI
Hub for open-weight models, datasets and libraries.
Use it for: finding and running open models
Integrates with: transformers, vLLM
Runs open-weight models locally with one command.
Use it for: offline labs, private data
Integrates with: OpenAI-compatible API
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.
Tokens, context windows and cost
Goal: Understand tokenisation, train a small tokenizer, budget the context window, and estimate cost.
Free account Create a free account or sign in to continue this course.
How a model generates text
Goal: Follow text through embeddings, attention and sampling, and understand training stages and why models hallucinate.
Free account Create a free account or sign in to continue this course.
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.
Free account Create a free account or sign in to continue this course.
Prompt engineering for production
Goal: Write clear, structured prompts with context, rules, format and examples, render them safely, and improve them systematically.
Free account Create a free account or sign in to continue this course.
Structured output and tool calling
Goal: Get reliable JSON from a model, validate it, and let the model request your functions through tool calls.
Free account Create a free account or sign in to continue this course.
Embeddings and retrieval-augmented generation (RAG)
Goal: Represent text as vectors, retrieve the most relevant policy chunks, and ground answers in them with citations.
Free account Create a free account or sign in to continue this course.
Evaluating LLM applications
Goal: Measure quality with golden datasets and automatic checks, compare prompt versions, and gate releases in CI.
Free account Create a free account or sign in to continue this course.
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.
Free account Create a free account or sign in to continue this course.
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.
Free account Create a free account or sign in to continue this course.
Quick reference (the cheat-sheet lessons and the PDF content)
What happens inside a request
An LLM predicts the next token from everything in its context. It has no memory between calls unless you send the history again.
Core concepts in one table
| Concept | What it means for you |
|---|---|
| Token | A chunk of text (about ¾ of an English word; Arabic often uses more tokens per word). Pricing and limits are in tokens |
| Context window | Maximum input + output tokens per call. Long contexts cost more and can dilute attention |
| Temperature / sampling | Higher = more varied output. Use low values for extraction and classification |
| Pre-training vs fine-tuning | General knowledge from huge corpora vs adapting behaviour with your examples |
| Knowledge cutoff | The model does not know later events: give it current facts in the prompt or through tools |
| Hallucination | Fluent but wrong output. Reduce with grounding (RAG), citations and verification |
| Reasoning / extended thinking | The model spends extra tokens working through a problem before answering: better on hard tasks, slower and costlier |
| Embedding | A 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 |
A prompt structure that survives production
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
Structured output and tool calls
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 validateChoosing a model
| Factor | Ask | Trade-off |
|---|---|---|
| Capability | Does it pass your eval set, not a public leaderboard? | Bigger models: better reasoning, higher cost and latency |
| Latency | What is the time to first token and total time at p95? | Small models or streaming for chat UX |
| Cost | Tokens per task × price × volume per month? | Caching, shorter prompts, routing easy tasks to small models |
| Context and modality | Long documents, images, audio? | Long context is not free: retrieval is often cheaper |
| Deployment | API, cloud-hosted, or open-weight on your own GPUs? | Data residency and control vs operating effort |
| Data and terms | Is input used for training? Retention? Region? | Check contract terms; enterprise tiers differ |
Evaluate before you ship
Without an eval set every prompt change is a guess. Re-run it on each change, like unit tests.
Cost and latency levers
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_tokensand 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
Failure modes and mitigations
| Failure | Mitigation |
|---|---|
| Hallucinated facts or citations | Ground with retrieval; require quotes from sources; verify links and numbers in code |
| Prompt injection from documents, web pages or email | Treat retrieved text as data; limit tool permissions; human approval for actions |
| Inconsistent output format | Schema-constrained output plus validation and retry |
| Sensitive data leakage | Redact before sending; data-classification rules; no secrets in prompts |
| Silent quality drift after a model update | Pin model versions; run the eval set before switching |
| Over-trust by users | Show sources and confidence; keep a human in the loop for high-impact decisions |
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.
Further reading
- Anthropic documentation docs.claude.com
- OpenAI API documentation platform.openai.com
- OWASP GenAI Security Project genai.owasp.org
- NIST AI Risk Management Framework nist.gov
- OpenTelemetry GenAI semantic conventions opentelemetry.io