Skip to content
Back to Insights

Generative AI Learning Series: Part 13 - Demystifying Prompts, Tokens, Context Windows, Temperature, and Hallucinations

Master the essential inner mechanics of Large Language Models, including prompt engineering, tokenization, context windows, temperature scaling, and hallucinations.

Vikram K
Vikram K
Senior Software Engineer

Part 13 of the Generative AI Series

Welcome back! In Part 12, we learned how Large Language Models (LLMs) are trained and how they generate responses one word at a time. But learning how an LLM is built is only half the story. To use AI effectively, you also need to understand the underlying mechanics that influence every single conversation you have with ChatGPT, Gemini, or Claude. Let’s dive into the essential vocabulary of the AI era.

Every AI hallucination, creative outburst, or “forgotten” instruction can be traced directly back to how the model processes tokens within its context window and the temperature settings guiding its predictions.


1. The Prompt: Talking to AI

Imagine walking into a restaurant. If you simply say to the waiter, “Food,” they will look confused. But if you say, “I’d like one vegetarian masala dosa with coconut chutney,” they immediately understand your request.

The quality of your request dictates the quality of the response. Exactly the same thing happens with AI. A prompt is the instruction, question, or input that you provide to an AI model. Everything you type into a chatbot is a prompt (e.g., “Explain Machine Learning”, “Summarize this PDF”).

1.1 Why Prompts Matter: Bad vs. Good

Imagine asking two teachers the same question.

  • Student 1: “Explain.”
  • Student 2: “Explain Machine Learning to a Class 8 student using cricket examples.”

Student 2 will receive a vastly better explanation because the request is clearer. AI behaves similarly. The more context you provide, the easier it is for the model to generate a response that matches your expectations.

Prompt Quality Example Why it works (or doesn't)
Bad Prompt Write about AI. Too vague; no audience, length, or purpose specified.
Better Prompt Write a beginner-friendly blog explaining AI using real-life analogies. AI now knows the audience, tone, and style.
Excellent Prompt Act as a senior AI educator. Write a beginner-friendly article explaining Machine Learning for college students. Use simple English, diagrams, and a summary. The destination is crystal clear. It provides a role, format, and specific deliverables.

Interactive Simulation: The Prompt Upgrader

Simulation: How AI Sees Your Prompt

Click the buttons below to see how prompt quality drastically changes the AI's internal target logic and final output.

Your Input: Write about AI.
AI Output:

Artificial Intelligence is a branch of computer science. It is used in many things today like computers and robots. It was invented a long time ago...


2. Tokens: The Language of LLMs

In previous chapters, we briefly mentioned tokens. Let’s look closer. A token is the basic unit of text that an LLM processes. Humans read words. AI reads tokens.

2.1 Why Not Words?

Different languages have long words, short words, punctuation, emojis, and numbers. Instead of treating every word as a single rigid unit, LLMs break text into flexible pieces. This is highly efficient for the underlying math.

Example Sentence: Artificial Intelligence is amazing.

A tokenizer might break this into five tokens conceptually: Artificial | Intelligence | is | amazing | .

However, another model’s tokenizer might split it into even smaller fragments: Artific | ial | Intelligence | is | amaz | ing

The Furniture Analogy: Imagine shipping a large wardrobe. Instead of transporting it whole, you disassemble it into manageable pieces, and reassemble it at the destination. Tokens work similarly—AI processes manageable textual pieces rather than full sentences at once.

2.2 The Token Limit

Every LLM has a maximum number of tokens it can process in a single interaction. This is called the token limit (or maximum context length). If you exceed this limit, the AI can no longer process the request.

Interactive Simulation: The Tokenizer

Simulation: Real-Time Token Splitting

Type a sentence below to see how an AI breaks human language down into token fragments (represented by different colors).

Tokens Generated: 7

3. The Context Window: The AI’s Working Memory

Closely related to tokens is the Context Window. The context window is the amount of recent information the model can consider while generating a response. Think of it as the model’s working memory for your current conversation.

The Notebook Analogy: Imagine solving a complex math problem. You keep notes in a 10-page notebook. Eventually, you run out of space. To write more, you have to erase the oldest pages. The context window works in a similar way. If a conversation gets too long, the earliest messages “fall out” of the window, and the AI forgets them.

This directly relates to Cognitive Load Theory. The Context Window acts as the AI’s Working Memory. If you pack the prompt with too much extraneous information (Extraneous Load), the AI struggles to process the actual task (Germane Load). When the Working Memory fills up, older data doesn’t go to Long-Term Memory—it is simply permanently dropped.

3.1 Context Window vs. Long-Term Memory

Feature Context Window (Working Memory) Long-Term Memory
Duration Temporary (Only lasts for the current chat session) Persistent (If enabled by the app, e.g., ChatGPT Memories)
Scope Used only during one active conversation Can persist across entirely different conversations
Limitation Strictly limited by token capacity (e.g., 128k tokens) Managed separately by external databases or RAG

Interactive Simulation: Sliding Context Window

Simulation: The "Forgetting" Mechanism

This AI has a tiny context window limit of 3 messages. Add messages to the chat and watch what happens to the oldest information when the limit is exceeded.

Active Context Window (Max 3)
Forgotten Data (Fallen Out)

4. Temperature: How Creative Should the AI Be?

This is one of the most fascinating backend settings of an LLM. Temperature controls how predictable or creative the model’s generated responses are. It doesn’t change what the model knows; it changes how adventurous it is when choosing the next token.

The Chef Analogy:

  1. Chef A (Low Temperature): Always follows the recipe exactly. Consistent, safe, and highly predictable.
  2. Chef C (High Temperature): Experiments with entirely new flavor combinations. Highly creative, diverse, but sometimes erratic.

(Important Note: Turning up the temperature does not make the AI smarter. It just flattens the probability curve, making the AI more willing to pick less obvious words!)

4.1 Temperature Use Cases

Use Case Recommended Temperature Expected Output
Writing Production Code / Legal Docs Low (0.0 - 0.3) Highly consistent, factual, predictable.
Drafting Emails / Articles Medium (0.4 - 0.7) Balanced between standard phrasing and engaging flow.
Brainstorming / Poetry / Storytelling High (0.8 - 1.2+) Highly diverse, creative, and unique.

Interactive Simulation: The Temperature Dial

Simulation: Next Token Selection via Temperature

Prompt: "The developer sat down and started to write..."

Strict (0.0) Creative (1.0+)
Temperature Level: 0.0

AI Completion:
The developer sat down and started to write code.
Backend Token Probabilities:

5. Hallucinations: Confident but Incorrect

This is a critical concept to grasp for everyday AI use. A hallucination occurs when an AI model generates information that sounds highly convincing but is factually incorrect, fabricated, or unsupported.

If you ask an AI, “Who won the FIFA World Cup in 1890?” a well-behaved model will state the tournament didn’t exist then. However, a hallucinating model might confidently declare: “England won the FIFA World Cup in 1890 in a thrilling match.”

5.1 Why Do Hallucinations Happen?

Remember how LLMs work: they are mathematical engines predicting the most likely next token. They do not have an internal “truth-checker” verifying statements against a real-world database. If a prompt is ambiguous or asks about a topic outside the model’s knowledge base, the model will simply stitch together plausible-sounding tokens that structurally look like a correct answer.

5.2 How to Reduce Hallucinations:

  • Prompt Specificity: Ask clear, specific questions.
  • Request Citations: Ask the AI to cite its sources or base its answer only on provided text.
  • Chain of Thought: Break complex questions into smaller, logical steps (“Think step-by-step”).
  • Human-in-the-Loop: Always verify high-stakes information (medical, legal, financial) independently.

Interactive Simulation: Anatomy of a Hallucination

Simulation: Plausibility vs. Truth

Observe how the LLM generates a response based on Statistical Plausibility rather than Truth when tricked.

User Prompt: "Tell me about the famous 17th-century astronaut, Sir Thomas Galileo."
(Note: This person/event never existed)

6. Putting Everything Together: The Lifecycle of a Prompt

When you type a message to ChatGPT, all these concepts happen in a fraction of a second. Here is the complete lifecycle of a single prompt happening inside a Transformer Neural Network.

Interactive Simulation: The AI Engine Room

Simulation: Step-by-Step AI Engine Room

1. Input
2. Tokenization
3. Context Assembly
4. Transformer Math
5. Decoding (Temp)

Step 1: The User Prompt

User types: "Explain AI simply."

The raw text string is captured by the application interface. At this stage, it is just human-readable character data. Neural networks cannot do math on raw letters, so this text must be translated into a numerical format.


7. Common Misconceptions

✕ Misconception
Tokens are exactly the same as words.
✓ Reality
Tokens can be whole words, syllables, or even single punctuation marks depending on the tokenizer.
✕ Misconception
A larger context window makes the AI smarter.
✓ Reality
It allows the AI to read longer documents at once, but it doesn't automatically improve its underlying reasoning abilities.
✕ Misconception
If the AI sounds confident, it must be correct.
✓ Reality
LLMs are designed to sound fluent and authoritative. They can confidently lie to you (hallucinate). Always verify important facts!

8. Summary Glossary Table

Concept Simple Meaning
Prompt The instruction or question you give the AI.
Token The basic building block (sub-word fragment) processed by the model.
Context Window The amount of recent conversation history the model holds in its active working memory.
Token Limit The absolute maximum number of tokens the context window can hold at once.
Temperature A setting controlling how predictable (low temp) or wildly creative (high temp) the AI is.
Hallucination A confident but entirely incorrect or fabricated AI response.

Did You Know?

  1. Tokens cost money!When you use a commercial AI API (like OpenAI or Anthropic), you are billed per 1,000 tokens processed, not per word or per hour.
  2. The Context Window is growing fast! In 2022, a standard context window was 4,096 tokens (about 3,000 words). By 2024, models like Gemini 1.5 Pro supported up to 2 million tokens—enough to upload entire books and codebases at once!

9. Beginner FAQs

1. If I upload a PDF, does it use up my Context Window?

Yes. Every single word and punctuation mark in that PDF is converted to tokens and placed into the context window. If the PDF is longer than the token limit, the AI will either reject it or "forget" the beginning of the document.

2.Can I set the Temperature to 0 to prevent hallucinations?

No. Setting the temperature to 0 makes the AI completely deterministic (it will always give you the same answer to the same prompt). It reduces *some* wild hallucinations, but if the AI fundamentally lacks the factual data, it will still confidently hallucinate a deterministic, incorrect answer.


10. What’s Next?

Now that you understand the mechanics of Large Language Models—from their Transformer engines to tokens, temperature, and context windows—it’s time to explore the amazing ecosystem built around them.

In Part 14, we will look at the heavyweights. We will compare the world’s most influential Generative AI models, including ChatGPT, Gemini, Claude, Llama, Midjourney, and more. You’ll learn who built them, what their strengths are, and which model is best suited for your specific daily tasks.

Key Takeaways

  • The quality of your request (prompt) strictly dictates the quality of the AI's response.
  • Tokens are sub-word pieces that AI processes, not whole human words.
  • The Context Window is the AI's limited working memory; older conversation data 'falls out'.
  • Temperature is a backend setting controlling whether the AI acts predictable (low) or highly creative (high).
  • Hallucinations happen because AI predicts plausible next words without a built-in 'truth-checker'.

Vikram K

Senior Software Engineer

Part of the Xpergia team helping enterprises transform through practical AI implementation.

Explore other Articles

Technical

From RAG to Agents: Building a Grounded Assistant on Amazon Bedrock

How we built the assistant on this site – retrieval that keeps it honest, a relevance floor that makes it refuse, and one real tool call that turns a conversation into a booked meeting.

July 21, 2026 9 min read
Saurabh Mehrotra Director at Xpergia
Read more
Technical

Model Context Protocol in the Enterprise: What It Solves, and What It Doesn't

MCP standardises how agents reach your tools and data, which removes a real integration tax. It does not solve permissions, auditability, or knowing which tools an agent should have.

August 1, 2026 7 min read
Saurabh Mehrotra Director at Xpergia
Read more
Technical

Optimising Neo4J Bulk Import

Lessons from loading billion-node graphs – trading off speed, cost, and data quality. If you've worked with Neo4J's bulk import tool on anything beyond a toy dataset, you'll know that the defaults don't cut it.

February 3, 2023 9 min read
Saurabh Mehrotra Director at Xpergia
Read more
Technical

Generative AI Learning Series: Part 1 - Introduction to Artificial Intelligence

Learn what Artificial Intelligence is, why it became necessary, and how it evolved into Generative AI. Welcome to the first installment of our comprehensive series on Generative AI.

August 13, 2026 10 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 2 - Evolution of Artificial Intelligence

Trace the 70-year timeline that led to modern Artificial Intelligence and Generative AI. In Part 1, we established what AI is, cleared up common misconceptions, and defined where Generative AI fits into the grand hierarchy.

August 14, 2026 12 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 3 - Understanding Machine Learning

Discover how Machine Learning transforms computing by learning patterns from data, exploring its workflow, paradigms, and interactive simulations. In Part 2, we explored how AI evolved from relying on rigid, handwritten rules (Symbolic AI) to systems that can adapt.

August 18, 2026 12 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 4 - Neural Networks Explained

Discover how human biology inspired Deep Learning, and explore the mathematical magic behind artificial neurons and deep networks. In Part 3, we saw how Machine Learning shifted the paradigm from explicitly writing rules to teaching computers via examples.

August 19, 2026 14 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 5 - Demystifying the Magic: How Neural Networks Actually Learn

Understand the core mechanics of how modern AI systems actually improve themselves. Imagine giving the same math exam to two students. Student A scores 35/100, while Student B scores 95/100. Student B didn't become better overnight.

August 20, 2026 12 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 6 - Why Traditional Neural Networks Were Not Enough

Understand the limitations of early neural networks when dealing with memory, context, and sequential data. So far, we’ve learned how a neural network works. It can identify cats in images, predict house prices, classify spam emails, and recognize handwritten digits.

August 21, 2026 11 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 7 - Recurrent Neural Networks (RNNs)

Discover how AI learned to remember the past with Recurrent Neural Networks, unlocking the power of sequential data. "Traditional Neural Networks could recognize patterns, but they had no memory.

August 22, 2026 11 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 8 - Long Short-Term Memory (LSTM): Teaching AI What to Remember

Learn how to teach AI what to remember and what to forget using Long Short-Term Memory networks. Welcome back to our Generative AI series! In Part 7, we explored how Recurrent Neural Networks (RNNs) gave AI the gift of memory.

August 24, 2026 13 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 9 - Transformers: The Breakthrough That Changed AI Forever

Discover the Transformer architecture, the attention mechanism, and how parallel processing laid the foundation for ChatGPT and modern Generative AI. Welcome back! In [Part 8], we saw how LSTMs gave AI a "smart memory," allowing it to remember important details and forget irrelevant ones.

August 25, 2026 15 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 10 - The Complete Transformer Architecture Explained Simply

Discover the inner workings of the Transformer architecture, including Positional Encoding, Encoders, Decoders, and Multi-Head Attention. Welcome back to our beginner-to-advanced Generative AI series!

August 26, 2026 15 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 11 - Birth of Generative AI: The Moment AI Started Creating

Discover how Artificial Intelligence transitioned from analyzing data to creating completely new content, and where Generative AI fits in the technology landscape.

August 27, 2026 16 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 12 - Large Language Models (LLMs): The Technology Behind ChatGPT, Gemini, and Claude

Understand the core technology powering modern AI assistants, how they learn, and how they generate text. If the Transformer architecture we discussed in Part 10 is the "engine," then a Large Language Model (LLM) is the complete vehicle.

August 28, 2026 14 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 14 - Popular Generative AI Models: Understanding What Makes Each Unique

Explore the Generative AI landscape and understand the unique strengths of models like ChatGPT, Gemini, Claude, Midjourney, and more. By this point in the blog series, you've learned: Now it's time to meet the actual AI models that are shaping today's world.

September 1, 2026 12 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 15 - Practical Real-World Applications (Part 1)

Discover how Generative AI is transforming healthcare, education, software development, marketing, and everyday life. So far in this series, we've learned what AI is, how it evolved, and the mechanics behind Machine Learning, Deep Learning, Neural Networks, Transformers, and Large Language Models.

September 2, 2026 11 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 16 - Practical Real-World Applications (Part 2)

Explore how AI is becoming a universal digital assistant across various professional domains, from lawyers to scientists. In the previous part, we explored how Generative AI is transforming Healthcare, Education, Software Development, Marketing, Customer Support, Finance, Agriculture, Manufacturing,…

September 3, 2026 10 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 17 - Prompt Engineering: The Art and Science of Communicating Effectively with AI

Master the most critical skill in the AI era by learning how to craft clear, structured, and effective prompts to get the best possible results from Large Language Models.

September 4, 2026 12 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 18 - AI Agents: From Answering Questions to Completing Tasks

Discover the evolution from basic chatbots to autonomous AI Agents that can plan, reason, use tools, and execute complex workflows. So far in this series, we've explored Artificial Intelligence, Machine Learning, Deep Learning, Transformers, Large Language Models, and Prompt Engineering.

September 7, 2026 12 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 19 - Challenges and Limitations of Generative AI: Risks, Responsibilities, and Ethical Questions

Explore the risks, ethical challenges, and responsibilities associated with Generative AI, from hallucinations and deepfakes to data privacy. So far, this blog series has focused primarily on the extraordinary capabilities of Generative AI.

September 8, 2026 15 min read
Vikram K Senior Software Engineer
Read more
Technical

Generative AI Learning Series: Part 20 - The Future of Generative AI

Explore where AI is heading and what it means for humanity by diving into Multimodal AI, AGI, ASI, and the future workplace. We have now reached the final part of this series. So far, we've explored: Now let's look ahead. What might AI become over the next decade and beyond?

September 9, 2026 16 min read
Vikram K Senior Software Engineer
Read more
Strategy

What Enterprise AI Agents Actually Are (And What They Aren't)

Everyone is selling AI agents. Very little of what's being sold is an agent. Here's the distinction that decides whether your project delivers or quietly stalls.

July 14, 2026 8 min read
Saurabh Mehrotra Director at Xpergia
Read more
Strategy

Agentic Workflow Automation: Where Agents Beat RPA, and Where They Don't

Rule-based automation is cheaper, faster and more reliable than an AI agent – right up to the point where the input varies. A practical framework for deciding which half of your process belongs to which.

July 28, 2026 7 min read
Saurabh Mehrotra Director at Xpergia
Read more