Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. LLM Fundamentals

What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps

A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.

Chaand Sheikh

·27 November 2026LLM Fundamentals

What you will learn

  • Explain the next-token loop that every LLM strength and weakness comes from
  • List the language tasks a model does well and the four things it cannot do alone
  • See with tiktoken why a model guesses when it counts letters
  • Match each limitation to the engineering fix: RAG, tools, history, evals or validation

Before you start

  • Basic Python

Before you build anything on top of a large language model (LLM), you need an honest line around it: where it is strong, and where it will let you down. Both sides come from one simple idea. Once you have that idea, you can decide in a minute whether a task fits a model, or needs help from your code.

Three messages, three kinds of work

A support team wants an AI to answer customer messages. Here are three that came in:

  • Please reply politely to this angry email.
  • What is my order balance today?
  • What is 17% of 4,862?

All three look like simple questions, but they are very different kinds of work. The first is pure language. The second needs a fact the model has never seen. The third needs an exact sum.

A good picture to hold on to: the model is a brilliant intern who read the whole library last year. Fast, fluent, and sometimes confidently wrong.

The one idea behind everything

An LLM reads text, predicts the next piece, adds it, and predicts again. That's the whole loop.

The next-token loop 1 Text in "the sky is" 2 Tokens small pieces 3 Guess next e.g. blue? clear? 4 Add it "the sky is blue" repeat: guess again from the longer text It predicts what sounds right. It does not look anything up or check anything.
The candidates in step 3 are examples to show the idea, not real model output.

A token is a chunk of text, often a word or part of a word. The model picks the piece that best fits the patterns it learned, then guesses again. Keep this loop in your head, because every strength and every weakness below comes from it.

What it does well

Every strength is a language task, working with words and patterns:

  • Draft: write a polite reply to a customer email.
  • Summarise: shrink a long ticket into three lines.
  • Extract: pull the order number and the date out of a message.
  • Classify: label a message as billing, delivery or complaint.
  • Translate: turn an English answer into Spanish.
  • Write code: a small function from a plain description.

That's the intern's home ground.

What it cannot do alone

The intern can't check your bank balance unless you hand over the statement. Four gaps:

  1. Fresh facts. A model has a training cut-off date. It knows nothing after it, like last week's news, or your order balance today.
  2. Exact maths. It can slip on big sums, and on counting letters.
  3. Memory. Each call starts blank, unless you send the earlier messages again.
  4. Hallucination. It can state a wrong answer in a very confident voice. This is the dangerous one, because it sounds right.

None of these is a bug. They all follow from predicting the next token.

Why it slips: it sees tokens, not letters

Here's a tiny script that shows how text is cut up before the model reads it. It uses tiktoken, which runs offline with no API key. For each text it encodes the token ids, decodes each id back into its piece, and prints them.

import tiktoken

encoder = tiktoken.get_encoding("cl100k_base")

for text in ["strawberry", "123456789", "How many r in strawberry?"]:
    token_ids = encoder.encode(text)
    pieces = [encoder.decode([token_id]) for token_id in token_ids]
    print(f"{text!r} -> {len(token_ids)} tokens: {pieces}")
'strawberry' -> 3 tokens: ['str', 'aw', 'berry']
'123456789' -> 3 tokens: ['123', '456', '789']
'How many r in strawberry?' -> 6 tokens: ['How', ' many', ' r', ' in', ' strawberry', '?']

Look at the first line. The model never sees the letters s, t, r, a, w, b, e, r, r, y. It sees three pieces: str, aw and berry. So when you ask how many r's are in strawberry, the answer is a guess, not a count. The same goes for the number: it arrives as three chunks of three digits, not as nine digits, which is one reason big sums slip.

Notice the leading spaces too: ' many' and ' strawberry' are pieces with the space built in. For how tokens turn into a context window and a bill, see LLM Tokens, Context Windows and Cost.

The engineer's fix table

We don't replace the intern. We give the intern the right tools. Each gap has a standard fix that lives in your code:

LimitationFixWhat the fix does
Old knowledgeRAGFetch fresh documents and put them in the prompt
Exact mathsToolsLet the model call a calculator or run code
No memoryConversation historySend the earlier messages with each call
Wrong answersEvals and checksMeasure how often answers are right, and check what the model says
Messy outputValidationForce a shape and reject anything else

The model supplies the language. Your code supplies the facts, the sums, the memory and the checks. Each row has its own article: the RAG pipeline, tool use, validating output with Pydantic and evals.

A three-question checklist

Before you build on a model, ask:

  1. Is it a language task? Drafting, summarising, extracting and classifying are a good fit.
  2. Can a wrong answer be caught? By a rule, a test, or a second source.
  3. Who checks it? A person or a check in code, before the answer matters.

Run the three support messages through it. The angry email is a language task, and a person can read the draft before it goes out: a good fit. The order balance is a fact the model doesn't have: it needs your database, through RAG or a tool. The 17% question is exact maths: hand it to a calculator tool.

Common mistakes

  • Trusting a fluent answer because it sounds sure. Confidence is part of the output style, not a sign of truth.
  • Asking the model for live data (balances, stock, today's prices) with nothing in the prompt. It can only guess.
  • Letting it do arithmetic or counting that matters. Use a tool.
  • Expecting it to remember the last call. Send the history yourself.
  • Shipping without a check. If nobody can catch a wrong answer, the task isn't ready for a model.

Quick recap

IdeaIn one line
The loopRead text, predict the next token, add it, repeat
Strong atDrafting, summarising, extracting, classifying, translating, code
Weak atFresh facts, exact maths, memory, guaranteed truth
Why letters slip"strawberry" is 3 tokens: str, aw, berry
The fixesRAG, tools, history, evals, validation

Try it yourself

  1. Edit the list in the script with your own text (your name, a long number, a product code) and run it. Which ones split in surprising places?
  2. Write five tasks from your own job and mark each one: language task or not?
  3. For each risky task, pick a row from the fix table.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 4 of 79

Previous
LLM Tokens, Context Windows and Cost: What One Question Really Costs
Next post
Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Related posts

The AI Stack in One Picture: Six Layers Every AI Product Is Built From

Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.

Tokenization: What an LLM Actually Sees When You Type

A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.

LLM Tokens, Context Windows and Cost: What One Question Really Costs

Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.

Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply

An LLM replies with a string. Pydantic turns that string into a typed object or a clear error. Validate a User, generate its JSON Schema, then follow one customer e-mail through a Ticket model where the first reply says refund, fails the check, and the retry fits.

On this page

  • Three messages, three kinds of work
  • The one idea behind everything
  • What it does well
  • What it cannot do alone
  • Why it slips: it sees tokens, not letters
  • The engineer's fix table
  • A three-question checklist
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.