Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 25 min · revision 2

Lab: Trim a Conversation to Fit a Budget

Build and test a Python function that assembles a chat request from a system prompt, past turns and ranked passages under a fixed token budget: fixed parts first, passages best first, history newest first in whole turns, a summary of what was dropped, and a final recount with a real tokenizer.

Contentsand lesson path

What you will learn

  • Allocate a context budget across instructions, history, retrieved content and output, and enforce it in code.
  • Choose a strategy for long inputs (truncation, summarization or retrieval) and explain its quality trade-off, including position effects.

01. Goal and setup

In this lab you write assemble(), the function at the heart of this skill's practice project. It takes a system prompt, the conversation so far, a new question and a list of retrieved passages with relevance scores, and returns a request that fits a token budget, as counted by the tokenizer you use:

  • the system prompt, the new question and the output reserve are never cut;
  • passages are added best first, up to their own cap;
  • history is added newest first, in whole turns, in the room that is left;
  • dropped turns are replaced by a short summary;
  • the finished request is counted again, and the count is returned with it.

You will test it on a short, a medium and a very long conversation. Everything runs locally: tiktoken is the tokenizer, and a simple function stands in for the model that would write summaries, so no API key is needed. You need Python 3.12 or later and network access for the first install. The lab was tested with tiktoken 0.14 and pytest 9.2.

Terminal
mkdir budget-chat && cd budget-chat
python3 -m venv .venv          # Python 3.12 or later; Windows: py -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install tiktoken pytest
python -c "import tiktoken, pytest; print(tiktoken.__version__, pytest.__version__)"
Expected output (your versions may be newer)
0.14.0 9.2.0
Folder layout at the end of the lab
budget-chat/
├── .venv/
├── tokens.py          counting helpers (step 1)
├── assemble.py        the request builder (steps 2 to 4)
├── demo.py            three conversations of different lengths (step 4)
├── test_assemble.py   tests that prove the limit holds (step 5)
└── check_*.py         small scripts that print what each step built

02. Step 1: Count tokens the way the request will

Every decision in the builder rests on counting, so start with three helpers. A message costs its text plus a few tokens for the role markers and separators that the chat format adds around it. OpenAI documents about three per message for its format; the code rounds up to four, and you would calibrate the number against the usage your provider reports. truncate_to_tokens will cap the summary later.

tokens.py
import tiktoken

ENCODING = tiktoken.get_encoding('o200k_base')
# Chat formats wrap each message in role markers and separators. OpenAI documents
# about 3 tokens per message for its format; we round up and check against usage.
MESSAGE_OVERHEAD = 4


def count_text(text: str) -> int:
    return len(ENCODING.encode(text))


def count_message(message: dict[str, str]) -> int:
    return count_text(message['content']) + MESSAGE_OVERHEAD


def truncate_to_tokens(text: str, limit: int) -> str:
    ids = ENCODING.encode(text)
    return text if len(ids) <= limit else ENCODING.decode(ids[:limit])
check_tokens.py
from tokens import count_message, count_text, truncate_to_tokens

print(count_text('Where is my parcel?'))
print(count_message({'role': 'user', 'content': 'Where is my parcel?'}))
print(truncate_to_tokens('Your parcel left the depot at 07:40 this morning.', 6))
Terminal
python check_tokens.py
Expected output
5
9
Your parcel left the depot at

The question is 5 tokens of text and 9 as a message. Truncation works on token ids and decodes the first six back into text, which is why it cuts at a word boundary here; with other text it can cut inside a word.

03. Step 2: Describe the request and its budget

Start assemble.py with the data types. Budget.total covers input and output together, so input_limit is what remains after the output reserve, which will be sent as the max output tokens setting. Passages go into the user turn as labelled documents placed before the question; the next lesson explains why that order helps. The system prompt is passed separately, as Anthropic's API expects; for an API that wants it as the first message, prepend it when you send.

assemble.py · part 1
from collections.abc import Callable
from dataclasses import dataclass

from tokens import MESSAGE_OVERHEAD, count_message, count_text, truncate_to_tokens

Message = dict[str, str]
Summariser = Callable[[list[Message]], str]
SUMMARY_LABEL = '\n\nSummary of earlier turns:\n'


class BudgetError(ValueError):
    """The parts that may not be cut do not fit the budget."""


@dataclass(frozen=True)
class Passage:
    source: str
    text: str
    score: float  # higher means more relevant


@dataclass(frozen=True)
class Budget:
    total: int  # input plus output, per request
    output_reserve: int  # sent as max_tokens
    retrieved_cap: int  # most tokens that passages may use
    summary_cap: int = 200  # most tokens for the summary of dropped turns

    @property
    def input_limit(self) -> int:
        return self.total - self.output_reserve


@dataclass
class Request:
    system: str
    messages: list[Message]
    max_tokens: int
    input_tokens: int
    turns_kept: int
    turns_dropped: int
    passages_kept: list[str]


def format_passages(passages: list[Passage]) -> str:
    return ''.join(f'<doc source="{p.source}">\n{p.text}\n</doc>\n' for p in passages)


def build_user_content(passages: list[Passage], question: str) -> str:
    if not passages:
        return question
    return f'{format_passages(passages)}\nQuestion: {question}'


def count_request(system: str, messages: list[Message]) -> int:
    system_cost = count_text(system) + MESSAGE_OVERHEAD
    return system_cost + sum(count_message(m) for m in messages)
check_request.py
from assemble import Budget, Passage, build_user_content, count_request

doc = Passage('warranty.md', 'Kettles carry a two-year warranty.', 0.93)
content = build_user_content([doc], 'Is my kettle covered?')
print(content)
print(count_request('Be brief.', [{'role': 'user', 'content': content}]))
print(Budget(total=3_000, output_reserve=600, retrieved_cap=700).input_limit)
Terminal
python check_request.py
Expected output
<doc source="warranty.md">
Kettles carry a two-year warranty.
</doc>

Question: Is my kettle covered?
38
2400

The request costs 38 tokens: the system prompt and one user message holding the document and the question, each with its overhead. With a 3,000-token budget and a 600-token reserve, 2,400 tokens are left for input.

04. Step 3: Choose passages and turns

Add three functions to the end of assemble.py. select_passages sorts by score and stops at the first passage that does not fit, so a weak passage can never take the place of a stronger one. group_turns pairs each user message with the reply that follows it, so a turn is kept or dropped as a whole. newest_that_fit counts how many of the newest turns fit; it stops at the first turn that is too big rather than skipping it, because a history with a hole in the middle reads as a different conversation.

assemble.py · part 2
def select_passages(passages: list[Passage], room: int) -> list[Passage]:
    """Best first; stop at the first passage that does not fit."""
    chosen: list[Passage] = []
    used = 0
    for passage in sorted(passages, key=lambda p: p.score, reverse=True):
        cost = count_text(format_passages([passage]))
        if used + cost > room:
            break  # a weaker passage never takes the place of a stronger one
        chosen.append(passage)
        used += cost
    return chosen


def group_turns(history: list[Message]) -> list[list[Message]]:
    """A turn is a user message plus the assistant reply that follows it."""
    turns: list[list[Message]] = []
    for message in history:
        if message['role'] == 'user' or not turns:
            turns.append([message])
        else:
            turns[-1].append(message)
    return turns


def newest_that_fit(turns: list[list[Message]], room: int) -> int:
    used = kept = 0
    for turn in reversed(turns):
        cost = sum(count_message(m) for m in turn)
        if used + cost > room:
            break  # never skip a turn: the kept history must be contiguous
        used += cost
        kept += 1
    return kept
check_select.py
from assemble import Passage, group_turns, newest_that_fit, select_passages
from tokens import count_message

history = [
    {'role': 'user', 'content': 'Hi, my kettle leaks.'},
    {'role': 'assistant', 'content': 'Sorry! Is it the lid or the base?'},
    {'role': 'user', 'content': 'The base.'},
    {'role': 'assistant', 'content': 'Thanks. Please send a photo.'},
    {'role': 'user', 'content': 'Sent.'},
    {'role': 'assistant', 'content': 'A replacement is on its way.'},
]
turns = group_turns(history)
print(len(turns), 'turns costing', [sum(count_message(m) for m in t) for t in turns])
print('newest turns that fit in 40 tokens:', newest_that_fit(turns, 40))

passages = [
    Passage('a.md', 'kettle ' * 50, 0.2),
    Passage('b.md', 'kettle ' * 100, 0.9),
    Passage('c.md', 'kettle ' * 20, 0.5),
]
print([p.source for p in select_passages(passages, 150)])
Terminal
python check_select.py
Expected output
3 turns costing [24, 18, 17]
newest turns that fit in 40 tokens: 2
['b.md', 'c.md']

The two newest turns cost 18 + 17 = 35 tokens, and the oldest would take the total to 59, over the 40 allowed. For the passages, b.md (score 0.9, 112 tokens) and c.md (0.5, 32 tokens) fit in 150; a.md would need 62 more.

05. Step 4: Assemble within the budget

Now the function itself, at the end of assemble.py. It works in four stages, marked by the comments:

  1. Count the fixed parts and raise BudgetError if they alone exceed the input limit. Cutting the instructions or the question would produce a request that answers something else.
  2. Add passages up to the smaller of their cap and the room left.
  3. Fit the newest turns into what remains. If some turns must go and a summariser was given, reserve summary_cap tokens for the summary first.
  4. Build the real request and count it again. Tokens can merge where two texts are joined, so the sum of the parts is not always the count of the whole. If the request is over the limit, drop one more turn and try again.
assemble.py · part 3
def assemble(
    system: str,
    history: list[Message],
    question: str,
    passages: list[Passage],
    budget: Budget,
    summarise: Summariser | None = None,
) -> Request:
    # 1. The parts we never cut: instructions, the new question, the output reserve.
    fixed = count_request(system, [{'role': 'user', 'content': question}])
    if fixed > budget.input_limit:
        raise BudgetError(f'fixed parts need {fixed}; limit {budget.input_limit}')

    # 2. Retrieved passages, best first, up to their cap.
    room = budget.input_limit - fixed
    chosen = select_passages(passages, min(budget.retrieved_cap, room))
    content = build_user_content(chosen, question)

    # 3. History, newest turns first, in whatever room is left.
    with_passages = count_request(system, [{'role': 'user', 'content': content}])
    room = budget.input_limit - with_passages
    turns = group_turns(history)
    kept = newest_that_fit(turns, room)
    if kept < len(turns) and summarise is not None:
        kept = newest_that_fit(turns, room - budget.summary_cap)

    # 4. Recount the real request; joins can add a token or two, so drop more if needed.
    while True:
        dropped = turns[: len(turns) - kept]
        final_system = system
        if dropped and summarise is not None:
            summary = summarise([m for turn in dropped for m in turn])
            limit = budget.summary_cap - count_text(SUMMARY_LABEL)
            final_system += SUMMARY_LABEL + truncate_to_tokens(summary, limit)
        messages = [m for turn in turns[len(turns) - kept :] for m in turn]
        messages.append({'role': 'user', 'content': content})
        used = count_request(final_system, messages)
        if used <= budget.input_limit:
            break
        if kept == 0:
            raise BudgetError(f'request needs {used}; limit {budget.input_limit}')
        kept -= 1

    return Request(
        system=final_system,
        messages=messages,
        max_tokens=budget.output_reserve,
        input_tokens=used,
        turns_kept=kept,
        turns_dropped=len(turns) - kept,
        passages_kept=[p.source for p in chosen],
    )

Create demo.py with a help-centre system prompt, five ranked passages, a generator of conversations of any length and a stand-in summariser that keeps the first sentence of each dropped user message. The budget is deliberately small, 3,000 tokens, so the effects show at once.

demo.py
from assemble import Budget, Message, Passage, assemble

SYSTEM = 'You are the support assistant for Kettle & Co. Answer from the documents.'
PASSAGES = [
    Passage('warranty.md', 'Kettles carry a two-year warranty. ' * 30, 0.93),
    Passage('damage.md', 'Report damage within 14 days with a photo. ' * 15, 0.71),
    Passage('refunds.md', 'Refunds reach your card in 5 to 10 days. ' * 12, 0.64),
    Passage('delivery.md', 'Standard delivery takes 2 to 4 working days. ' * 20, 0.52),
    Passage('careers.md', 'We are hiring in Leeds and Hanoi. ' * 10, 0.05),
]
BUDGET = Budget(total=3_000, output_reserve=600, retrieved_cap=700, summary_cap=200)


def conversation(turns: int) -> list[Message]:
    history: list[Message] = []
    for i in range(1, turns + 1):
        order = 48000 + i
        history.append({'role': 'user', 'content': f'Order #{order} came late. '
                        'The box was dented. Can I get the delivery fee back?'})
        history.append({'role': 'assistant', 'content': f'Sorry about order #{order}. '
                        'I have refunded the delivery fee; allow 5 to 10 days.'})
    return history


def first_sentences(messages: list[Message]) -> str:
    """Stand-in summariser: the first sentence of each user message."""
    return '\n'.join('- ' + m['content'].split('. ')[0] for m in messages
                     if m['role'] == 'user')


if __name__ == '__main__':
    print(f'input limit: {BUDGET.input_limit} tokens')
    for name, turns in [('short', 3), ('medium', 40), ('very long', 400)]:
        request = assemble(SYSTEM, conversation(turns), 'Is my kettle still under '
                           'warranty?', PASSAGES, BUDGET, summarise=first_sentences)
        print(f'{name:<10} kept {request.turns_kept:>2} turns, dropped '
              f'{request.turns_dropped:>3}, input {request.input_tokens} tokens')
    print('passages:', ', '.join(request.passages_kept))
    print(request.system.splitlines()[2:5])
Terminal
python demo.py
Expected output
input limit: 2400 tokens
short      kept  3 turns, dropped   0, input 797 tokens
medium     kept 30 turns, dropped  10, input 2258 tokens
very long  kept 30 turns, dropped 370, input 2373 tokens
passages: warranty.md, damage.md, refunds.md
['Summary of earlier turns:', '- Order #48001 came late', '- Order #48002 came late']

The short conversation is kept whole. The medium one loses its 10 oldest turns, which are replaced by the summary in the last line. The very long one keeps the same 30 recent turns: however long the conversation grows, the request stays under 2,400 input tokens, so its cost and latency stay flat. Only three passages make it in: together they use 611 of the 700-token cap, delivery.md would need 231 more, and the loop stops there, so careers.md is never even considered.

The summary is placed in the system prompt here for simplicity. It is built from user text, so in production keep it clearly labelled as a record of the conversation, not as instructions; the AI security skill returns to this.

06. Step 5: Prove the limit with tests

A budget only helps if it always holds. The tests below check the limit for conversations from 0 to 5,000 turns, recount each request independently, and pin down the behaviours you designed: short histories survive whole, the newest turn and the question survive, passages follow the ranking, and impossible budgets raise an error.

test_assemble.py
import pytest

from assemble import Budget, BudgetError, assemble, count_request
from demo import BUDGET, PASSAGES, SYSTEM, conversation, first_sentences

QUESTION = 'Is my kettle still under warranty?'


@pytest.mark.parametrize('turns', [0, 3, 40, 400, 5_000])
def test_request_never_exceeds_the_input_limit(turns):
    request = assemble(SYSTEM, conversation(turns), QUESTION, PASSAGES, BUDGET,
                       summarise=first_sentences)
    assert request.input_tokens <= BUDGET.input_limit
    # Recount independently: the reported number must be the real one.
    assert count_request(request.system, request.messages) == request.input_tokens
    assert request.max_tokens == BUDGET.output_reserve


def test_short_conversation_is_kept_whole():
    request = assemble(SYSTEM, conversation(3), QUESTION, PASSAGES, BUDGET)
    assert request.turns_dropped == 0
    assert 'Summary of earlier turns' not in request.system


def test_newest_turn_survives_and_question_comes_last():
    history = conversation(400)
    request = assemble(SYSTEM, history, QUESTION, PASSAGES, BUDGET)
    assert request.messages[-3:-1] == history[-2:]
    assert request.messages[-1]['content'].endswith(QUESTION)
    assert request.messages[0]['role'] == 'user'


def test_passages_follow_the_ranking_and_the_cap():
    request = assemble(SYSTEM, [], QUESTION, PASSAGES, BUDGET)
    assert request.passages_kept == ['warranty.md', 'damage.md', 'refunds.md']


def test_fixed_parts_that_do_not_fit_raise():
    tiny = Budget(total=500, output_reserve=490, retrieved_cap=0)
    with pytest.raises(BudgetError):
        assemble(SYSTEM, [], QUESTION, PASSAGES, tiny)
Terminal
python -m pytest -q
Illustrative output (the test count is exact; your timing will differ)
.........                                                                [100%]
9 passed in 1.09s

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

Inside assemble()

Three questions about design choices in the lab code.

Q1. Why does newest_that_fit stop at the first turn that does not fit, instead of skipping it and trying older, shorter turns?
Q2. What does assemble() do when the system prompt and the new question alone are larger than the input limit?
Q3. Why does stage 4 count the finished request again instead of trusting the sum of the parts counted earlier?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch task

Finish the first half of the practice project by making the builder realistic:

  1. Replace first_sentences with a model-written summary. Ask for at most 150 tokens that keep order numbers, names and decisions, set the output limit to match, and store the summary so it is extended, not rewritten, as more turns drop off. Without an API key yet, keep the stand-in and come back after the next skill.
  2. Support tool calls: let group_turns keep a tool call and its result in the same turn, and replace tool results older than five turns with a one-line note.
  3. Count the three demo conversations with your provider's counting endpoint or from the usage of real calls, compare them with tiktoken, and adjust MESSAGE_OVERHEAD or add a safety margin until the budget holds for your model.
  4. Add a test with one passage larger than the whole passage cap, and decide whether to skip it or truncate it.

10. Review prompt

Without looking back, write the four stages of assemble() in order, with the rule each one applies and what happens when it runs out of room. Then explain why the summary needs its own cap, why turns are dropped whole and from the oldest end, and which test you would write first if a colleague changed MESSAGE_OVERHEAD to zero.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check