Skip to content

Module 02 · Lesson 2.4

Context Design: What the Agent Needs at Each Step

40 minUpdated 18 Nov 2026Part of Agent Design and Instruction Engineering · AI Agent Development
On this page
  1. What you will learn
  2. What is context in an AI agent?
  3. What to include and what to leave out of the context
  4. How to trim or summarise a long conversation history
  5. What the Quillfeather agent needs at each step
  6. Build the context for one step in Python
  7. Conclusion and your next step
  8. Common errors and fixes
  9. Validation checklist
  10. Hands-on exercise
  11. Knowledge check
  12. Frequently asked questions
  13. References

Think of a helper at a busy desk. If the desk holds only the papers for today's job, they work fast and make fewer mistakes. If it is buried under old letters, other people's files and a stranger's passport, they slow down, get confused and might leak something private.

An AI agent has a desk too. What you put on it is called context, and you choose it at every step. This lesson shows how to decide what the agent needs, what to leave out and how to filter it in code. Most of it needs no coding. One short Python example at the end builds the context for one step.

What you will learn

  • Explain context, context window and tokens in plain words.
  • Choose what an agent needs to see at each step of a task.
  • Keep secrets, other people's data and unneeded personal details out of the context.
  • Run a short Python script that filters an order record and trims a message history.

Before you start

What is context in an AI agent?

An AI agent is a program that uses an AI model to decide its own next step. A model is the AI part that reads text and writes text. It does not remember anything by itself. It only knows what you show it each time you ask.

Everything the model can read when it decides its next step is called its context. Picture the papers on someone's desk. They can only use what is on the desk right now.

Context
All the text the model can read for one step: the instructions, the conversation so far, tool results and anything else you add.
Context window
The size limit of the context. It is the size of the desk. If you pile on too much, something has to go.
Token
A small piece of text, such as a short word or part of a longer word. Models count text in tokens, not in words. A short word is often one token, and a long word is often several.

Tokens matter for three reasons. They fill the context window. They drive cost, because most providers charge by the token. And they affect speed, because more text takes longer to read. Limits and prices change often, so always check your provider's current page. The blog post Understanding Context Windows and Token Limits goes deeper.

What to include and what to leave out of the context

More context is not always better. Extra text costs money, slows the agent down and can distract it. Aim for the smallest context that lets the agent do this step well.

Include: what this step needs

  • The instructions: the agent's role, rules and output format. You wrote these in the previous lessons.
  • The current question: what the customer asked just now.
  • Tool results for this step: for example, the status and delivery date from lookup_order.
  • One or two examples: only if the agent often gets the format wrong without them.

Leave out: what the step does not need

  • Secrets: API keys, passwords and other login details. A model never needs them. Your code uses them, not the model.
  • Other customers' data: the agent for one customer must not see another customer's orders.
  • Personal details the step does not need: to explain an order status, the agent does not need a phone number or a home address.
  • Old messages that no longer matter: a greeting from 40 messages ago helps nobody.

Share the minimum

Data minimisation is a simple privacy idea: share the minimum. Give the model only the data it needs for this step, and nothing more. It is like showing a delivery driver the street address, but not your bank statement.

How to trim or summarise a long conversation history

A conversation history is the list of earlier messages. It grows with every turn. If you send all of it every time, you eventually hit the context window, and you pay for old text again and again.

There are two simple ways to keep it short.

MethodHow it worksGood forWatch out for
Keep the last N messagesSend only the most recent messages, for example the last six.Short tasks where recent turns matter most.An important fact from early on, such as the order number, may be dropped. Keep key facts separately.
Summarise older messagesReplace old messages with a short note, such as "Customer asked about order QF-1042; it is dispatched".Long conversations with facts worth keeping.A summary can lose details or add mistakes. Check it, and keep important facts in plain fields.
Many agents combine both: key facts in fields, a short summary of the past, and the last few messages word for word.

A summary is usually written by the model itself, which means it costs a little too. Start with the simple "last N" method. Add summaries only when you see real problems.

What the Quillfeather agent needs at each step

Context is chosen per step, not once for the whole agent. Here is the Quillfeather Cycles order agent from earlier lessons, answering "Where is my order QF-1042?". Each step gets a different desk.

StepIncludeLeave out
1. Understand the questionInstructions, the customer's latest message, the last few messages.Order records, since no lookup has happened yet.
2. Look up the order (lookup_order)The order number from the customer. Your code runs the tool.The model never needs the database login. Your code holds it.
3. Write the replyInstructions, the question, and the order's number, status and estimated delivery date.Name, email, phone and address. The reply does not need them.
4. Handle a return request (request_return)The order number and status. The rule that staff must approve.Payment details and other orders. A person approves the return.
The same order record shows up at several steps, but each step sees only its own slice.

Notice what happens in step 3. The database holds the customer's name, email and address. The reply only needs three facts. Your code does the cutting.

Filtering happens before the model sees anything
  1. Full record

    Name, email, phone, address, status, date

  2. Your code filters

    Keep only the fields this step needs

  3. Trimmed history

    Last N messages

  4. Model context

    Instructions plus the small slice

The model only sees the box on the right. Everything else stays in your code and your database.

Build the context for one step in Python

The script below builds the context for step 3. It takes a full order record, keeps three fields and keeps only the last three messages. It does not call any AI model, so it runs offline. All the personal data is made up.

Pythonbuild_context.py
order = {
    "order_id": "QF-1042",
    "customer_name": "Alex Example",
    "email": "alex@example.com",
    "phone": "555-0100",
    "address": "1 Sample Street, Exampletown",
    "status": "dispatched",
    "estimated_delivery": "2026-11-18",
}
history = [
    "customer: Hi",
    "agent: Hello! How can I help?",
    "customer: Where is order QF-1042?",
    "agent: Let me check that for you.",
    "customer: Thanks, and when will it arrive?",
]
NEEDED_FIELDS = ["order_id", "status", "estimated_delivery"]
LAST_N = 3


def build_context(order, history):
    small_order = {key: order[key] for key in NEEDED_FIELDS}
    return {"order": small_order, "recent_messages": history[-LAST_N:]}


context = build_context(order, history)
print(context["order"])
for message in context["recent_messages"]:
    print(message)
print("has email:", "email" in context["order"])

Runs offline with Python 3.10 or later, standard library only. Save it and run python build_context.py.

What each part does

  • order = {...} is a dictionary, a set of labelled values. It stands for the full record from the database, including name, email, phone and address.
  • history = [...] is a list of earlier messages, oldest first.
  • NEEDED_FIELDS names the only fields step 3 may see. This is data minimisation written as a list. Changing the step means changing this list.
  • LAST_N = 3 says how many recent messages to keep.
  • {key: order[key] for key in NEEDED_FIELDS} builds a new, smaller dictionary. Only the listed keys are copied. Everything else is left behind.
  • history[-LAST_N:] takes the last three items of the list. The minus sign counts from the end.
  • The last print shows that the email is not in the result.
OutputCaptured from a real run
{'order_id': 'QF-1042', 'status': 'dispatched', 'estimated_delivery': '2026-11-18'}
customer: Where is order QF-1042?
agent: Let me check that for you.
customer: Thanks, and when will it arrive?
has email: False

Only this small result would go to the model. The name, email, phone and address never leave your code. The greeting messages are gone too.

Conclusion and your next step

Context is the desk the model works at. Put on it the instructions, the question and the facts this step needs. Leave off secrets, other people's data, unneeded personal details and old clutter. Do the filtering in code, before the model reads anything.

Your next step: pick one step of an agent you have in mind and write down what it includes and leaves out, like the Quillfeather table above. Then continue to Exercise: Write and test an agent specification, where you combine the objective, instructions, plan and context rules into one specification.

For more background, read How to Prevent AI Hallucinations in Code Generation, which shows why giving a model the right facts matters, or look up any new word in the Glossary of AI Engineering and Agent Terms.

Common errors and how to fix them

The agent repeats a customer's email or phone number in a reply.

Why it happens: The whole database record was put into the context, including fields the step does not need.

Fix: Filter the record in code with an allow-list of fields before building the context.

The agent forgets the order number halfway through a long chat.

Why it happens: Old messages were cut off, and the number only lived in one of them.

Fix: Store key facts in separate fields and add them to every context. Do not rely on old messages.

Costs and response times keep growing during a conversation.

Why it happens: The full history is sent again on every step, so the token count keeps rising.

Fix: Keep only the last N messages, or replace old ones with a short summary.

A secret such as an API key appears in a log or a reply.

Why it happens: The key was placed in the instructions or the tool output that the model reads.

Fix: Keep secrets in your code or in environment settings. The model should never see them.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Design the context for a library helper

A town library has an agent that helps members renew books. Write a per-step table for three steps, and change build_context.py so that it builds the context for the reply step of this agent.

You will need

  • A loan record with these fields: member_name, member_email, member_phone, book_title, due_date, renewals_used, is_reserved.
  • A history of eight messages.
  • Steps: understand the request, check the loan, write the reply.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Ask what the reply must say. A new due date, or a reason for refusing.
  • The reply needs to know whether the book is reserved and how many renewals are used.
  • Change NEEDED_FIELDS and LAST_N. The rest of the code can stay the same.
Show a model answer

A strong answer keeps these fields for the reply step: book_title, due_date, renewals_used and is_reserved. These are enough to say whether a renewal is allowed and what the due date is. It drops member_name, member_email and member_phone, because the reply can say "your book" without them. The script sets NEEDED_FIELDS to those four names and LAST_N to 4. In the table, step 1 includes the instructions and the last messages but no loan record, step 2 includes the member's request and the lookup input but no secrets, and step 3 includes the slimmed loan record. Each step leaves out data it does not use.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Which data should the order agent see when it writes a status reply?
    Show the answer and explanation

    Answer: B. The reply only needs those three facts, so sharing the minimum is both safer and cheaper. The full record is tempting because more facts feel safer, but each extra field raises the risk of a leak. The password is never needed by the model, because your code makes the lookup.

  2. 2.What is the best place to hide the customer's email from the model?
    Show the answer and explanation

    Answer: B. If the email is never in the context, the model cannot repeat it. An instruction feels like protection, but the model has already read the email and may still repeat it. Deleting it from the reply afterwards only catches the exact text you expect.

  3. 3.A conversation has 80 messages. What is a sensible way to handle it?
    Show the answer and explanation

    Answer: B. This keeps what matters and drops the clutter, which saves tokens and cost. Sending everything feels safe, but it grows cost and may overflow the context window. The first message is usually a greeting or an early request that may no longer matter.

Frequently asked questions

What is a context window in simple words?

It is the limit on how much text a model can read for one step. Think of a desk: only so many papers fit on it. The text includes your instructions, the conversation and tool results. Different models have different limits, so check your provider's current documentation.

What is a token?

A token is a small piece of text that a model reads and counts. A short word is often one token, and a long or unusual word may be split into several. Tokens decide how much fits in the context window, and most providers charge by the token.

Why shouldn't I put everything into the context?

More text costs more money, slows the answer and can distract the model from what matters. It also raises privacy risk, because anything in the context can show up in a reply. Give the model what this step needs and nothing else.

How do I keep private data away from an AI model?

Filter the data in your own code before you build the context. Use a short list of allowed fields and drop the rest. Never put passwords or API keys in the context. Also check what your provider does with data you send, and follow your company's rules.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.