Practical & Responsible AI
- 1. Foundations of AI
- 2. NLP
- 3. How LLMs work
- 4. Working with LLMs
- 5. Building AI systems
- 6. Practical & responsible AI
Choosing a model
There is no single "best" model. Choose by the needs of the task:
| Criterion | Questions to ask |
|---|---|
| Quality | How well does it do on my test cases, not just public benchmarks? |
| Cost | Price per million input/output tokens, or hardware cost if self-hosted |
| Latency | Does a user wait for it (needs fast responses) or does it run in a batch? |
| Context window | How much text must fit in a single request? |
| Privacy & location | May the data leave my organisation or country? Is the data used for training? |
| Capabilities | Tool calling, structured output, vision, languages, reasoning mode |
| Licence | Can I use it commercially? Are there usage restrictions? |
Open-weight vs closed models
| Closed / proprietary (API) | Open-weight | |
|---|---|---|
| Examples | GPT (OpenAI), Claude (Anthropic), Gemini (Google) | Llama (Meta), Mistral, Qwen (Alibaba), Gemma (Google), DeepSeek, gpt-oss (OpenAI) |
| Access | Through the provider's API or app | Download the weights and run them anywhere |
| Strengths | Usually the most capable; no hardware to manage; quick to start | Data stays local; full control; no per-token fees; can be fine-tuned; works offline |
| Weaknesses | Data leaves your network; per-token cost; model versions can change or be retired | You need the hardware and operations skills; largest models need expensive GPUs |
Running models locally
| Tool | What it is | Best for |
|---|---|---|
| Ollama | Command-line tool and local server that downloads and runs quantised models | The easiest start on a laptop or workstation; local REST API |
| llama.cpp | C/C++ inference engine (uses the GGUF format) that runs on CPU and GPU | Maximum control and efficiency on consumer hardware |
| LM Studio | Desktop app with a chat UI and local server | Trying models without the command line |
| vLLM | High-throughput serving engine for GPUs | Serving many users on a server |
| Hugging Face Transformers | Python library for loading and running models | Research, fine-tuning, experiments |
A minimal example with Ollama:
# Download and chat with a model in the terminal
ollama pull llama3.1:8b
ollama run llama3.1:8b "Explain what a context window is in two sentences."
# Ollama also serves a local REST API on port 11434
curl http://localhost:11434/api/chat -d '{
"model": "llama3.1:8b",
"messages": [{"role": "user", "content": "What is RAG?"}],
"stream": false
}'
How much memory does a model need?
The weights must fit in GPU memory (VRAM), or in system RAM for CPU or Apple-silicon unified-memory inference. A good first estimate:
\( \text{memory for weights} \approx \text{number of parameters} \times \text{bytes per parameter} \)
Then add roughly 10–30% for the KV cache and runtime overhead; more for long contexts.
| Model size | FP32 (4 bytes) | FP16 / BF16 (2 bytes) | 8-bit (1 byte) | 4-bit (~0.5 byte) |
|---|---|---|---|---|
| 8B | 32 GB | 16 GB | 8 GB | ~4–5 GB |
| 13B | 52 GB | 26 GB | 13 GB | ~7–8 GB |
| 70B | 280 GB | 140 GB | 70 GB | ~35–40 GB |
Quantization
Quantization stores weights with fewer bits, for example 4-bit integers instead of 16-bit floating-point numbers. Groups of weights share a scale factor so the original values can be approximately reconstructed during computation. The model becomes 2–4× smaller and often faster, with a small loss in quality.
| Precision | Typical quality impact | Common formats |
|---|---|---|
| 16-bit (FP16 / BF16) | Reference quality (how most models are released) | Safetensors |
| 8-bit | Usually very close to 16-bit | GGUF Q8_0, bitsandbytes int8 |
| ~4–5-bit | Small, usually acceptable drop; the popular sweet spot for local use | GGUF Q4_K_M / Q5_K_M, GPTQ, AWQ |
| 2–3-bit | Noticeable degradation, especially for smaller models | GGUF Q2_K, Q3_K |
A useful rule: a larger model at 4-bit often beats a smaller model at 16-bit that uses the same memory.
Cost
Hosted APIs charge per token, with separate prices for input and output, usually quoted per million tokens:
\( \text{cost} = \dfrac{\text{input tokens}}{10^6}\times p_{\text{in}} + \dfrac{\text{output tokens}}{10^6}\times p_{\text{out}} \)
Worked example (hypothetical prices: $3 per million input tokens, $15 per million output tokens). A document assistant handles 10,000 requests a day, each with 2,000 input tokens and 500 output tokens:
| Tokens per day | Cost per day | |
|---|---|---|
| Input | 10,000 × 2,000 = 20 million | 20 × $3 = $60 |
| Output | 10,000 × 500 = 5 million | 5 × $15 = $75 |
| Total | $135 per day (~$4,000 per month) |
Ways to reduce cost:
- Use a smaller model for simple steps (routing, classification, extraction).
- Prompt caching for repeated long prefixes (system prompts, documents).
- Batch APIs for work that does not need an immediate answer; major providers offer them at about half price.
- Shorter context: retrieve fewer, better chunks; summarise long histories.
- Limit output length and ask for concise formats.
- For steady, high volume, compare with self-hosting an open-weight model, including the cost of hardware and staff time.
Latency & throughput
| Metric | Meaning |
|---|---|
| Time to first token (TTFT) | Delay before the first word appears. Grows with input length (prefill). |
| Output speed | Tokens generated per second after that (decode). |
| Total latency | \(\text{TTFT} + \text{output tokens} \div \text{output speed}\) |
| Throughput | Total tokens per second a server produces across all users. |
AI security
LLM applications have new kinds of vulnerabilities, because instructions and data travel through the same channel: text. The OWASP Top 10 for LLM Applications (2025) lists the main risks:
| # | Risk | In short |
|---|---|---|
| LLM01 | Prompt injection | Input that overrides the developer's instructions |
| LLM02 | Sensitive information disclosure | The model reveals personal data, secrets or confidential content |
| LLM03 | Supply chain | Compromised models, datasets, plug-ins or packages |
| LLM04 | Data and model poisoning | Manipulated training or fine-tuning data |
| LLM05 | Improper output handling | Model output used unchecked (e.g. run as code or SQL, rendered as HTML) |
| LLM06 | Excessive agency | Too many permissions or too much autonomy for an agent |
| LLM07 | System prompt leakage | Secrets or logic exposed through the system prompt |
| LLM08 | Vector and embedding weaknesses | Attacks on RAG stores, e.g. leaking data across users |
| LLM09 | Misinformation | Hallucinated or misleading output that people trust |
| LLM10 | Unbounded consumption | Uncontrolled usage leading to cost blow-ups or denial of service |
Prompt injection
- Direct injection: the user types instructions to bypass rules ("ignore previous instructions…", "jailbreaks").
- Indirect injection: instructions hidden in a web page, email, PDF, code comment or tool result that the AI processes.
There is currently no complete technical fix, so defence is about limiting the damage. Be especially careful when one system combines all three of: access to private data, exposure to untrusted content, and the ability to communicate externally (Simon Willison calls this the "lethal trifecta").
- Give tools the least privilege they need; prefer read-only.
- Require human confirmation for sensitive or irreversible actions.
- Treat all model output as untrusted input: validate, escape and sandbox it.
- Separate and label untrusted content; never put secrets in prompts.
- Monitor and rate-limit usage.
Privacy & data protection
- Know where data goes. With a hosted API, prompts are sent to the provider. Read the terms: is data stored, for how long, in which region, and is it used for training? Business and API terms often differ from free consumer apps.
- Do not paste secrets (passwords, API keys, personal or classified data) into tools that are not approved for that data.
- Minimise and redact personal data before sending it; keep only what is needed.
- GDPR applies to personal data processed with AI in the EU: you need a legal basis, transparency, data-subject rights and, for high-risk processing, a data protection impact assessment (DPIA).
- Local models keep data on your own hardware, which is often the simplest answer for sensitive data.
Bias & fairness
Models learn from human-written data and absorb its biases: stereotypes about gender, ethnicity, age or nationality; over-representation of English and Western viewpoints; and historical patterns of discrimination. This matters most when AI influences decisions about people (hiring, lending, healthcare, policing).
| Source of bias | Mitigation |
|---|---|
| Unrepresentative training data | Test on data that represents all affected groups; measure differences in outcomes |
| Biased historical labels | Review the labelling process; don't simply replicate past decisions |
| Prompt or deployment context | Avoid using sensitive attributes unless necessary; audit outputs regularly |
| Automation bias (people over-trusting AI) | Keep humans meaningfully in the loop for important decisions; explain limitations |
Regulation & governance
The EU AI Act (Regulation (EU) 2024/1689) is the first comprehensive AI law. It entered into force on 1 August 2024 and applies in phases: prohibited practices from 2 February 2025, obligations for general-purpose AI models from 2 August 2025, and most remaining rules from 2026–2027. Some deadlines have been proposed for adjustment, so check the official text for current dates. It regulates by risk level:
Other important frameworks:
- NIST AI Risk Management Framework (USA, voluntary): four functions, Govern, Map, Measure, Manage.
- ISO/IEC 42001:2023: an international standard for an AI management system, certifiable like ISO 27001.
- Organisation policies: which tools are approved, what data may be used with them, and who reviews AI output.
A practical checklist
| Before you build | Before you launch | After you launch |
|---|---|---|
| Is AI the right tool, or would a rule or a query do? | Test set passes on real examples | Monitor quality, cost and latency |
| What data is involved, and where may it go? | Prompt-injection and misuse tests done | Collect user feedback and failure cases |
| What happens when the AI is wrong? | Tool permissions minimised; human approval for risky actions | Re-run evaluations when models or prompts change |
| Which regulations apply? | Users told they are interacting with AI | Review logs for misuse and drift |
Key terms
- Open-weight modelA model whose trained weights can be downloaded and run.
- VRAMGPU memory; the main limit on which models you can run.
- QuantizationStoring weights with fewer bits to save memory.
- GGUFFile format for quantised models used by llama.cpp and Ollama.
- TTFTTime to first token: how long before the answer starts.
- Prompt injectionMalicious instructions hidden in input that hijack the model.
- Excessive agencyAn AI given more permissions or autonomy than it needs.
- EU AI ActEU regulation that sets duties for AI according to risk level.
Common misconceptions
| Misconception | Reality |
|---|---|
| "Local models are always worse." | Good open-weight models are strong on many everyday tasks, and they can be the right choice for privacy and cost even when a hosted model is somewhat stronger. |
| "You need a data centre to run an LLM." | 4-bit 7–8B models run on a laptop with 8–16 GB of memory. |
| "A good system prompt prevents prompt injection." | Instructions help but can be bypassed. Limit permissions and validate actions. |
| "The API price is the full cost." | Development, evaluation, monitoring and human review usually cost more than the tokens. |
Back to the start: AI content hub.
References
Security, risk & regulation
- OWASP Top 10 for LLM Applications
- K. Greshake et al. (2023). Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection.
- The lethal trifecta for AI agents — Simon Willison
- EU AI Act, Regulation (EU) 2024/1689 (official text) and EU AI Act explorer
- NIST AI Risk Management Framework
- ISO/IEC 42001:2023 AI management systems
Running & optimising models
- Ollama and llama.cpp on GitHub
- Hugging Face: Quantization overview
- T. Dettmers et al. (2022). LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale.
- E. Frantar et al. (2022). GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers.
- W. Kwon et al. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention (vLLM).
- Artificial Analysis (independent comparisons of model quality, price and speed)
Books
- AI Engineering: Building Applications with Foundation Models — Chip Huyen (O'Reilly, 2025)
- The Alignment Problem — Brian Christian (W. W. Norton, 2020)
- Weapons of Math Destruction — Cathy O'Neil (Crown, 2016)
- Co-Intelligence: Living and Working with AI — Ethan Mollick (Portfolio, 2024)
Some other interesting things to know:
- Visit my pages on Machine learning & Deep learning
- Visit my website on Data engineering
- Visit my website on Data, Big Data, Data-modeling, Datawarehouse, SQL, cloud-compute.