Search RU
Tasks / AI / LLM / Context budget for the model
Statement medium

Context budget for the model

`fit_context(messages, max_tokens, count_tokens)` builds the context for the
model.

`messages` is a list of dicts `{"role": ..., "content": ...}`. If the first
element is `system`, it is mandatory and always kept. The remaining messages are
taken from the end: the newest ones first.

Rules:

- an empty list gives an empty list;
- `system` is always first and never dropped;
- if `system` alone does not fit the budget, raise `ContextTooLong`;
- the other messages are added while `max_tokens` allows;
- when space runs out, the older message is dropped and the newer ones stay;
- the kept messages keep their original order.

Write tests with a simple `count_tokens = len(content)`.

aicontexttokens
test_solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

What matters more when trimming: the system rules or the latest user message?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts