PromptisePromptise
PlatformSoonEnterprise
DocsGitHub
Talk to usGet started
Promptise - AI Framework LogoPromptise

The full-stack framework for agentic systems. Build with the framework. Run it on the platform. Launch it with our engineers.

pip install promptise

[01] Product

  • Framework
  • Platform (coming soon)
  • Enterprise
  • How it works
  • Contact

[02] Framework

  • The Agent
  • The Interface
  • The Harness

[03] Resources

  • Documentation
  • GitHub
  • Why Promptise
  • Use cases
  • Roadmap
  • Guides
  • Learning Paths
  • Questions

[04] Company

  • About
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Subprocessors

© 2026 Promptise by Manser Ventures. All rights reserved.

hello@promptise.com
← Guides> Tools and the Model Context Protocol (MCP)

Context Engineering for AI Agents: Context Window Management

Context engineering for AI agents: decide what the model sees on each step, return less from tools, and keep long runs small without losing the question.

Level
Intermediate
Reading time
26 min
Published
Oct 10, 2026
Last updated
Oct 24, 2026
Tested with
Promptise 1.9.0
By
Promptise Team
  • Context Engineering
  • Cost Control
  • Model Context Protocol (MCP)
Contents · 11 sections↓
  1. 01What is context engineering for AI agents?
  2. 02How do you manage the context window of an AI agent?
  3. 03How does context grow in a long agent run?
  4. 04What you need
  5. 05How to apply context engineering to a long agent run, step by step
  6. 06What happens when the model reads all ten logs at once?
  7. 07How to budget the starting context with the ContextEngine
  8. 08Context engineering best practices
  9. 09Common context engineering mistakes
  10. 10Frequently asked questions
  11. 11Where to go next

Context engineering for AI agents decides what the model sees on each step of a run: what stays, what gets cut, and what the agent fetches only when it needs it. Done well, a long run stays small and the question stays in view until the last step. Done badly, every model call resends every tool result so far, and you pay for all of it again on each step. This guide explains how an agent's context grows, then builds an agent that investigates an incident across ten service logs with Promptise Foundry. You'll meter every model call, see where the tokens go, and shrink the context step by step. The code runs on Promptise Foundry 1.9.0 with gpt-5-mini, and the outputs come from real runs.

[01]

What is context engineering for AI agents?

Context engineering is deciding what goes into the model's context on each step of an agent run, and in what form. The context is everything one model call receives: the instructions, the task, the chat history, every tool call and result so far, and any retrieved data. Prompt engineering is about the wording of one prompt. Context engineering is about that whole working set as it changes over a long run.

In an agent, most of the context is tool results. So most context engineering is tool design: what each tool returns, and how much. The rest is choosing where each kind of content lives and how the run stays bounded as results pile up.


[02]

How do you manage the context window of an AI agent?

Keep three kinds of content apart:

  • Rules and facts the agent needs on every step go in the system prompt, which is sent on every call.

  • Bulk data stays behind tools that return only what the step needs. Return a summary instead of a whole file, and add a second tool to drill into details.

  • The run itself needs a way to stay bounded as tool results pile up.

With Promptise Foundry the first two are yours to write, and the third is built in:

Pythonfinal.py
1
2
3
4
5
6
7
8
9
10
11
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"logs": StdioServerSpec(command=sys.executable, args=["lean_server.py"])},
        instructions=INSTRUCTIONS,
    )
    meter = TokenMeter(watch="the number of ERROR lines per service")
    try:
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": QUESTION}]},
            config={"callbacks": [meter]},
        )

On the incident in this guide, that setup reads all ten logs and answers every part of the question with about 15,000 input tokens. The same agent reading raw log files with nothing trimmed needs about twenty times as many. With automatic compaction over raw files it needs about forty times as many, because compaction cuts each older log short and the model reads it again. The steps below show each of those runs and why they behave the way they do.


[03]

How does context grow in a long agent run?

Every step of a tool loop is one model call. Without any management, each call sends the instructions, the question, and every tool call and result so far, so the input grows with each step. Promptise Foundry has two mechanisms that change what gets sent:

Rendering diagram…

  • Compaction inside the tool loop. The default agent pattern, ReAct, runs its loop with context_scope="auto". Until there are six tool results, the model sees the full transcript. From then on it sees a compact view: your instructions and any system messages you passed, the current question, its most recent step, and a "facts already gathered" ledger with one line per earlier tool call. Results longer than 2,000 characters are cut to an excerpt that tells the model how to get the full result again, and a result the model fetches again stays in full. Compaction only changes what the model sees: a call it repeats runs the tool again. agent_pattern="managed" uses that compact view from the first step, and build_agent(context_compaction=...) turns it off or moves the threshold. The Context Lifecycle guide and the Context scope reference describe both.

  • The ContextEngine, before the loop. build_agent(context_engine=...) assembles the instructions, chat history and memory into a token budget, and trims the least important parts first. It assembles once per call to the agent, before any tool runs. What its budget leaves after the instructions and tool definitions also caps the compacted tool loop. The Context Engine docs list its layers.

What survives compaction matters more than how much it saves. This is what the model receives before and after the switch:

In the prompt

Before compaction

After compaction

Your instructions

Yes

Yes

The current question, as a dict or a HumanMessage

Yes

Yes, the latest one

System messages you pass in

Yes

Yes

Earlier turns of a chat

Yes

A short note: the last six messages, 400 characters each

Tool results

Every call and result

The last step's results; older ones once each in the ledger, cut to 2,000 characters unless the model fetched them twice

A tool call the model repeats

Runs the tool

Runs the tool; reusing the earlier result is opt-in

Side by side, the full transcript the model receives with fewer than 6 tool results and the compact view it receives with 6 or more, where earlier turns become a short note and older tool results move into a facts already gathered ledger cut to 2,000 characters.
FigureWhat the model receives before and after compaction

[04]

What you need

  • Python 3.10 or newer.

  • Promptise Foundry 1.9.0 or newer from PyPI. tiktoken, which the ContextEngine uses to count tokens exactly for OpenAI models, comes with it.

  • An OpenAI API key. This guide uses gpt-5-mini; other providers work by changing the model string, as listed in Models & Providers.

>_Terminal
pip install "promptise>=1.9.0"
export OPENAI_API_KEY="sk-..."

[05]

How to apply context engineering to a long agent run, step by step

The job: an incident hit checkout between 14:00 and 14:30. The agent reads the logs of ten services and reports the ERROR count per service, the total, the first ERROR, and the root cause. Ten logs of about 5,500 tokens each are enough to show every problem a long run has.

Step 01

Create the incident logs

make_logs.py writes the ten logs, 140 normal lines per service plus the incident, and prints the right answer so you can check every run against it:

Pythonmake_logs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""Write ten service logs for a checkout incident into logs/, and print the right answer."""
import random
from pathlib import Path

random.seed(7)  # the same logs on every run
SERVICES = ["auth", "billing", "gateway", "inventory", "notifications",
            "orders", "payments", "search", "shipping", "users"]

# The incident: inventory's database pool runs out, and the failures spread upstream.
INCIDENT = {
    "inventory": [("14:07:41.204", "db pool exhausted (max=20, waiting=31) request_id=r-4be19a")]
    + [(f"14:0{8 + i // 3}:{10 + i * 7:02d}.{100 + i:03d}",
        f"db pool exhausted (max=20, waiting={30 + i}) request_id=r-{i:02x}c27d") for i in range(6)],
    "orders": [(f"14:08:{12 + i * 9:02d}.{300 + i:03d}",
                f"inventory reserve/stock lookup failed: HTTP 500 request_id=r-c27d1{i}") for i in range(5)],
    "gateway": [(f"14:08:{20 + i * 9:02d}.{500 + i:03d}",
                 f"POST /checkout 502 upstream=orders request_id=r-c27d1{i}") for i in range(4)],
    "payments": [(f"14:09:{5 + i * 20:02d}.{700 + i:03d}",
                  f"payment intent cancelled: order creation failed request_id=r-a{i}") for i in range(2)],
}

out = Path("logs")
out.mkdir(exist_ok=True)
errors = {}
for service in SERVICES:
    lines = []
    for n in range(140):  # 140 normal requests, one every 12 seconds from 14:00
        ts = f"2026-10-09T14:{n * 12 // 60:02d}:{n * 12 % 60:02d}.{random.randint(0, 999):03d}Z"
        item, latency, request = random.randint(1000, 9999), random.randint(3, 90), random.getrandbits(24)
        lines.append((ts, "INFO", f"{service} GET /api/items/{item} 200 OK latency_ms={latency} request_id=r-{request:06x}"))
    for clock, message in INCIDENT.get(service, []):
        lines.append((f"2026-10-09T{clock}Z", "ERROR", f"{service} {message}"))
    lines.sort()
    (out / f"{service}.log").write_text("".join(f"{ts} {level} {text}\n" for ts, level, text in lines))
    count = sum(1 for _, level, _ in lines if level == "ERROR")
    if count:
        errors[service] = count

first = min((line.split()[0], path.stem) for path in out.glob("*.log")
            for line in path.read_text().splitlines() if line.split()[1] == "ERROR")
print("files:", len(SERVICES), "| bytes:", sum(p.stat().st_size for p in out.glob("*.log")))
print("ERROR lines per service:", errors)
print("total ERROR lines:", sum(errors.values()))
print("first ERROR:", first[1], first[0][11:23])
>_Terminal
python make_logs.py
Output
files: 10 | bytes: 140724
ERROR lines per service: {'gateway': 4, 'inventory': 7, 'orders': 5, 'payments': 2}
total ERROR lines: 18
first ERROR: inventory 14:07:41.204
Step 02

Give the agent the logs as a tool

The tools live in a small MCP server. read_log returns a whole file, the way a first version of a tool usually does:

Pythonlogs_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from pathlib import Path

from promptise.mcp.server import MCPServer

server = MCPServer("logs")
LOG_DIR = Path(__file__).parent / "logs"


def services() -> list[str]:
    return sorted(p.stem for p in LOG_DIR.glob("*.log"))


@server.tool()
async def list_logs() -> list[str]:
    """List the services that have a log file for the incident window."""
    return services()


@server.tool()
async def read_log(service: str) -> str:
    """Return the full log file of one service, every line.

    Args:
        service: A service name from list_logs, for example "orders".
    """
    if service not in services():
        return f"No log for service {service!r}. Call list_logs for valid names."
    return (LOG_DIR / f"{service}.log").read_text()


if __name__ == "__main__":
    server.run()

How big is one result? The ContextEngine's token counter answers that without calling a model:

Pythoncount_tokens.py
1
2
3
4
5
6
7
8
"""How big is each tool result? Count before you send it."""
from pathlib import Path

from promptise import ContextEngine

engine = ContextEngine(model="openai:gpt-5-mini")
for path in sorted(Path("logs").glob("*.log"))[:3]:
    print(f"{path.name:<16} {engine.count_tokens(path.read_text()):>6,} tokens")
Output
auth.log          5,517 tokens
billing.log       5,526 tokens
gateway.log       5,669 tokens

About 5,500 tokens per file, 55,000 for all ten. If MCP servers are new to you, How to Connect MCP Servers to Your AI Agent in Python explains this file line by line.

Step 03

Meter every model call

You can't manage what you don't measure. This LangChain callback records, for each model call, how many messages went in, whether the compaction ledger was among them, whether a phrase you choose was still visible, and the token usage the provider reported. Its table() method prints one row per call and a total:

Pythonmeter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""Record what the model saw and what it cost, one row per model call."""

from langchain_core.callbacks import AsyncCallbackHandler

LEDGER_MARKER = "Facts already gathered"


class TokenMeter(AsyncCallbackHandler):
    def __init__(self, watch: str | None = None):
        self.watch = watch  # a phrase to look for in what the model sees
        self.calls: list[dict] = []

    async def on_chat_model_start(self, serialized, messages, **kwargs):
        sent = messages[0]
        text = "\n".join(str(m.content) for m in sent)
        self.calls.append(
            {
                "messages": len(sent),
                "tool_results": sum(1 for m in sent if m.type == "tool"),
                "ledger": LEDGER_MARKER in text,
                "watch_seen": bool(self.watch) and self.watch in text,
            }
        )

    async def on_llm_end(self, response, **kwargs):
        message = response.generations[0][0].message
        usage = message.usage_metadata or {}
        self.calls[-1].update(
            input=usage.get("input_tokens", 0),
            cached=(usage.get("input_token_details") or {}).get("cache_read", 0),
            output=usage.get("output_tokens", 0),
            wants=", ".join(
                tc["name"] + "".join(f" {v}" for v in tc["args"].values()) for tc in message.tool_calls
            )
            or "final answer",
        )

    def table(self) -> str:
        rows = ["call msgs tool msgs ledger   input  cached output  next"]
        for i, c in enumerate(self.calls, 1):
            rows.append(
                f"{i:>4} {c['messages']:>4} {c['tool_results']:>9} {('yes' if c['ledger'] else 'no'):>6} "
                f"{c.get('input', 0):>7,} {c.get('cached', 0):>7,} {c.get('output', 0):>6,}  {c.get('wants', '')[:40]}"
                + (f"  [watch: {'seen' if c['watch_seen'] else 'MISSING'}]" if self.watch else "")
            )
        i = sum(c.get("input", 0) for c in self.calls)
        ca = sum(c.get("cached", 0) for c in self.calls)
        o = sum(c.get("output", 0) for c in self.calls)
        cost = (i - ca) * 0.25e-6 + ca * 0.025e-6 + o * 2e-6
        rows.append(f"total: {len(self.calls)} model calls, {i:,} input ({ca:,} cached) + {o:,} output tokens = ${cost:.4f}")
        return "\n".join(rows)

The total is priced at OpenAI's list price for gpt-5-mini: $0.25 per million input tokens, $0.025 per million cached input tokens and $2.00 per million output tokens. You pass the meter to any run with config={"callbacks": [meter]}. For tracing in production, Promptise's own observability records tokens per call too; the meter is here because it also shows what the model was sent.

Step 04

Run the investigation with the default agent

The script asks the question, watches for the phrase "the number of ERROR lines per service" from it, and can build the agent four ways. The instructions ask for one service per step, so the run is long enough to watch it grow:

Pythoninvestigate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Investigate an incident across ten service logs, and meter every model call.

    python investigate.py            # the default agent
    python investigate.py managed    # agent_pattern="managed"
    python investigate.py full       # no compaction: the whole transcript every call
    python investigate.py engine     # the default agent with a ContextEngine
    python investigate.py default lean_server.py   # the same agent with smaller tool results
"""

import asyncio
import sys

from promptise import ContextEngine, build_agent
from promptise.config import StdioServerSpec
from promptise.engine import GraphIterationLimitError

from meter import TokenMeter

INSTRUCTIONS = (
    "You are an SRE assistant. Answer from the logs only. "
    "Work through the logs one service at a time: call one tool for one service, "
    "look at the result, then go to the next. Never ask about two services in one step."
)
QUESTION = (
    "We had an incident on 2026-10-09 between 14:00 and 14:30. Read every service log. "
    "Then tell me: (1) the number of ERROR lines per service, (2) the total, "
    "(3) which service logged the first ERROR and its exact timestamp, "
    "and (4) the root cause in one sentence."
)
SERVER_FILE = sys.argv[2] if len(sys.argv) > 2 else "logs_server.py"
SERVER = StdioServerSpec(command=sys.executable, args=[SERVER_FILE])


async def main(mode: str) -> None:
    options = {
        "full": {"context_compaction": False},
        "engine": {"context_engine": ContextEngine(model="openai:gpt-5-mini")},
        "managed": {"agent_pattern": "managed"},
    }.get(mode, {})

    agent = await build_agent(
        model="openai:gpt-5-mini", servers={"logs": SERVER}, instructions=INSTRUCTIONS, **options
    )
    meter = TokenMeter(watch="the number of ERROR lines per service")
    try:
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": QUESTION}]},
            config={"callbacks": [meter]},
        )
        answer = result["messages"][-1].content
    except GraphIterationLimitError as exc:
        # The run hit its step limit before the model answered.
        answer = f"no answer: {exc}"
    finally:
        await agent.shutdown()
    print(meter.table())
    print("\n>>>", answer)


asyncio.run(main(sys.argv[1] if len(sys.argv) > 1 else "default"))
>_Terminal
python investigate.py
Output
call msgs tool msgs ledger   input  cached output  next
   1    2         0     no     291       0     83  list_logs  [watch: seen]
   2    4         1     no     345       0     23  read_log auth  [watch: seen]
   3    6         2     no   5,890       0    151  read_log billing  [watch: seen]
   4    8         3     no  11,444   5,760     17  read_log gateway  [watch: seen]
   5   10         4     no  17,141  11,264     17  read_log inventory  [watch: seen]
   6   12         5     no  22,927  17,024     17  read_log notifications  [watch: seen]
   7    5         1    yes   9,479       0    343  read_log auth  [watch: seen]
   8    5         1    yes  14,924       0    151  read_log billing  [watch: seen]
   9    5         1    yes  19,601       0    279  read_log gateway  [watch: seen]
  10    5         1    yes  24,544       0    151  read_log orders  [watch: seen]
  11    5         1    yes  24,567       0    343  read_log inventory  [watch: seen]
  12    5         1    yes  30,419       0    279  read_log notifications  [watch: seen]
  13    5         1    yes  34,911   5,632    215  read_log orders  [watch: seen]
  14    5         1    yes  39,903       0    279  read_log payments  [watch: seen]
  15    5         1    yes  39,788       0    151  read_log search  [watch: seen]
  16    5         1    yes  40,593       0    343  read_log payments  [watch: seen]
  17    5         1    yes  46,260  39,552    407  read_log search  [watch: seen]
  18    5         1    yes  50,852  39,424     17  read_log shipping  [watch: seen]
  19    5         1    yes  50,853       0    215  read_log users  [watch: seen]
  20    5         1    yes  51,722       0    151  read_log shipping  [watch: seen]
  21    5         1    yes  57,276  50,688    727  read_log users  [watch: seen]
  22    5         1    yes  61,935  50,688  1,202  final answer  [watch: seen]
total: 22 model calls, 655,665 input (220,032 cached) + 5,561 output tokens = $0.1255

>>> Summary from logs (2026-10-09 14:00–14:30):

1) ERROR lines per service
- auth: 0
- billing: 0
- gateway: 4
- inventory: 7
- notifications: 0
- orders: 5
- payments: 2
- search: 0
- shipping: 0
- users: 0

2) Total ERROR lines: 18

3) First ERROR recorded: inventory at 2026-10-09T14:07:41.204Z

4) Root cause (one sentence): The inventory service exhausted its DB connection pool (db pool exhausted) causing HTTP 500s on inventory lookups, which cascaded into order reservation failures and upstream 502s/cancelled payment intents.

Read it row by row. Each log added about 5,600 input tokens to every later call. After six tool results, list_logs and five logs, compaction switched on at call 7. The message count dropped from 12 to 5: the instructions, the question, the last tool call, its result, and the ledger. The question stayed in view, [watch: seen] on every row. The trouble is the ledger. It cuts each older result to its first 2,000 characters and ends it with a note: [shortened: the first 2,000 of … characters are shown above. Only if you need the rest, call read_log once more with the same arguments (several in one step if you need them together); a result you fetch again is kept in full]. In these logs the ERROR lines start after 14:07, well past the first 2,000 characters.

So the model did what the note says. From call 7 on it read every log a second time, alternating between a log it had already read and the next new one. Each re-read ran the tool again: compaction changes what the model sees, not what a call does. A result fetched twice stays in full in the ledger, so the compacted view grew back to every log in full, and call 22 sent 61,935 tokens. The answer is right, but the run sent 655,665 input tokens. The instructions made it worse, because they forbid asking for two services in one step.

python investigate.py managed behaves the same way. The managed pattern compacts from the first step, so it starts re-reading at call 4 and ends with a similar total. The lesson is the same for both: on whole files, the cut to 2,000 characters decides the cost.

The run answered at call 22. The default ReAct loop allows 25 model calls (build_agent(max_agent_iterations=...)). A run that reaches the limit before the model answers raises GraphIterationLimitError from promptise.engine. investigate.py catches it and prints the message, so the meter's table still shows where the tokens went.

Re-reading a file that can't change is wasted work for the server, so you can opt in to reuse: with build_agent(context_compaction=ContextCompaction(reuse_results=["read_log"])), a repeated read_log call gets the earlier result once the loop compacts, and trace_tools prints ↺ Reusing an earlier result for tool: read_log for it. The model is sent the same text, though. Reuse saves tool runs, not context. List only tools whose results can't change during a run, never a status or health check.

Step 05

Compare it with the full transcript

To see what compaction should be saving, run the same agent with compaction turned off. That's one argument, build_agent(context_compaction=False), which investigate.py full passes:

>_Terminal
python investigate.py full
Output
call msgs tool msgs ledger   input  cached output  next
   1    2         0     no     291       0     83  list_logs  [watch: seen]
   2    4         1     no     345       0     87  read_log auth  [watch: seen]
   3    6         2     no   5,890   5,632    215  read_log billing  [watch: seen]
   …
  10   20         9     no  45,360  39,680     17  read_log shipping  [watch: seen]
  11   22        10     no  50,907  45,184     17  read_log users  [watch: seen]
  12   24        11     no  56,462  50,816  1,430  final answer  [watch: seen]
total: 12 model calls, 313,279 input (276,864 cached) + 1,951 output tokens = $0.0199

>>> Summary from the logs (2026-10-09 14:00–14:30):

1) ERROR count per service
- auth: 0
- billing: 0
- gateway: 4
- inventory: 7
- notifications: 0
- orders: 5
- payments: 2
- search: 0
- shipping: 0
- users: 0

2) Total ERROR lines: 18

3) First ERROR (service and exact timestamp):
- inventory — 2026-10-09T14:07:41.204Z ("ERROR inventory db pool exhausted (max=20, waiting=31) request_id=r-4be19a")

4) Root cause (one sentence, per logs):
- The inventory service's database connection pool was exhausted (db pool exhausted messages), causing inventory to return HTTP 500s which cascaded into orders lookup failures, gateway 502s on checkout, and subsequent payment/order cancellations.

Every log was read once and every part of the answer is right. The price is growth: the last call sent 56,462 tokens, and the run sent 313,279 in total, because every result rides along on every later call. That's still half of what the compacted run in step 4 sent.

One thing kept the bill low here. The cached column shows input the provider served from its prompt cache: a full transcript only ever appends, so each call starts with the previous call's exact text. At list price without the cache, the same run costs about $0.082. Cache hits vary from run to run, and they don't help the context window: with a hundred logs instead of ten, this design simply stops fitting.

Step 06

Make the tools return less

The cheapest token is the one a tool never returns. The agent doesn't need 140 lines of 200 OK to count errors; it needs the counts and the error lines. So summarize where the data lives, and give the model a second tool to drill in when it needs detail:

Pythonlean_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from collections import Counter
from pathlib import Path

from promptise.mcp.server import MCPServer

server = MCPServer("logs")
LOG_DIR = Path(__file__).parent / "logs"


def services() -> list[str]:
    return sorted(p.stem for p in LOG_DIR.glob("*.log"))


def lines_of(service: str) -> list[str]:
    return (LOG_DIR / f"{service}.log").read_text().splitlines()


@server.tool()
async def list_logs() -> list[str]:
    """List the services that have a log file for the incident window."""
    return services()


@server.tool()
async def log_summary(service: str) -> dict:
    """Summarize one service's log: line counts per level, time range, and every ERROR line.

    Args:
        service: A service name from list_logs, for example "orders".
    """
    if service not in services():
        return {"error": f"No log for service {service!r}. Call list_logs for valid names."}
    lines = lines_of(service)
    return {
        "service": service,
        "lines": len(lines),
        "levels": dict(Counter(line.split()[1] for line in lines)),
        "from": lines[0].split()[0],
        "to": lines[-1].split()[0],
        "errors": [line for line in lines if line.split()[1] == "ERROR"],
    }


@server.tool()
async def search_log(service: str, text: str, limit: int = 20) -> list[str]:
    """Return up to `limit` lines of one service's log that contain `text`, such as a request ID.

    Args:
        service: A service name from list_logs.
        text: Text to look for, for example "r-4be19a" or "WARN".
        limit: The most lines to return.
    """
    if service not in services():
        return [f"No log for service {service!r}. Call list_logs for valid names."]
    return [line for line in lines_of(service) if text in line][:limit]


if __name__ == "__main__":
    server.run()

The counting now happens in code, which counts correctly every time, and the limit on search_log keeps a drill-down from flooding the context. Same default agent, smaller tools:

>_Terminal
python investigate.py default lean_server.py
Output
call msgs tool msgs ledger   input  cached output  next
   1    2         0     no     384       0     83  list_logs  [watch: seen]
   2    4         1     no     438       0     87  log_summary auth  [watch: seen]
   …
   6   12         5     no   1,233       0     17  log_summary notifications  [watch: seen]
   7    5         1    yes   1,324       0    279  log_summary orders  [watch: seen]
   8    5         1    yes   1,587       0     17  log_summary orders  [watch: seen]
   …
  12    5         1    yes   1,889       0     17  log_summary users  [watch: seen]
  13    5         1    yes   1,968       0    946  final answer  [watch: seen]
total: 13 model calls, 16,237 input (1,408 cached) + 2,136 output tokens = $0.0080

>>> 1) ERROR lines per service
- auth: 0
- billing: 0
- gateway: 4
- inventory: 7
- notifications: 0
- orders: 5
- payments: 2
- search: 0
- shipping: 0
- users: 0

2) Total ERROR lines: 18

3) First ERROR: inventory at 2026-10-09T14:07:41.204Z

4) Root cause (one sentence):
Inventory service database pool exhaustion (db pool exhausted, max=20) beginning at 2026-10-09T14:07:41.204Z caused inventory to return HTTP 500s, which led to orders' inventory lookup failures and cascaded into gateway 502s and payment cancellations.

The input fell from 313,279 to 16,237 tokens, about nineteen times less, and about forty times less than the compacted run over whole files. The agent got through all ten services with the question in view at every call, and the answer is right. It asked for the orders summary twice, and the repeat ran the tool again. Each summary is far below the 2,000-character cut, so the ledger carries every error line in full: small tool results are what make compaction work. With summaries, the run costs about the same with compaction or without it, and python investigate.py full lean_server.py shows that. The tool design decides the cost.

Step 07

Put the facts that must survive into the instructions

Put the rules and facts the agent needs at its last step into instructions, because they are sent on every call, before and after compaction. Here that's who the report is for and what shape it takes:

Pythonfinal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""The same long run, set up to keep what matters."""

import asyncio
import sys

from promptise import build_agent
from promptise.config import StdioServerSpec

from meter import TokenMeter

# Rules and facts the agent needs on every step live in the instructions.
INSTRUCTIONS = """\
You are an SRE assistant. Answer from the logs only.
Work through the logs one service at a time: call one tool for one service,
look at the result, then go to the next. Never ask about two services in one step.

Facts for every report:
- Incident commander: Priya Raman. Address the report to her by name.
- Answer exactly the numbered parts the user asks for. No mitigation advice.
"""
QUESTION = (
    "We had an incident on 2026-10-09 between 14:00 and 14:30. Read every service log. "
    "Then tell me: (1) the number of ERROR lines per service, (2) the total, "
    "(3) which service logged the first ERROR and its exact timestamp, "
    "and (4) the root cause in one sentence."
)


async def main() -> None:
    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={"logs": StdioServerSpec(command=sys.executable, args=["lean_server.py"])},
        instructions=INSTRUCTIONS,
    )
    meter = TokenMeter(watch="the number of ERROR lines per service")
    try:
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": QUESTION}]},
            config={"callbacks": [meter]},
        )
        print(meter.table())
        print("\n>>>", result["messages"][-1].content)
    finally:
        await agent.shutdown()


asyncio.run(main())
>_Terminal
python final.py
Output
call msgs tool msgs ledger   input  cached output  next
   1    2         0     no     420       0     83  list_logs  [watch: seen]
   2    4         1     no     474       0    215  log_summary auth  [watch: seen]
   3    6         2     no     568       0     17  log_summary billing  [watch: seen]
   4    8         3     no     662       0     17  log_summary gateway  [watch: seen]
   5   10         4     no     897       0     17  log_summary inventory  [watch: seen]
   6   12         5     no   1,269       0     17  log_summary notifications  [watch: seen]
   7    5         1    yes   1,360       0     17  log_summary orders  [watch: seen]
   8    5         1    yes   1,623       0     17  log_summary payments  [watch: seen]
   9    5         1    yes   1,769       0    215  log_summary search  [watch: seen]
  10    5         1    yes   1,847       0    279  log_summary shipping  [watch: seen]
  11    5         1    yes   1,925       0    599  log_summary users  [watch: seen]
  12    5         1    yes   2,004       0  1,063  final answer  [watch: seen]
total: 12 model calls, 14,818 input (0 cached) + 2,556 output tokens = $0.0088

>>> Priya Raman,

1) Number of ERROR lines per service:
- auth: 0
- billing: 0
- gateway: 4
- inventory: 7
- notifications: 0
- orders: 5
- payments: 2
- search: 0
- shipping: 0
- users: 0

2) Total: 18

3) First ERROR and timestamp: inventory at 2026-10-09T14:07:41.204Z

4) Root cause (one sentence): Inventory service's database connection pool exhaustion ("db pool exhausted") caused inventory to return HTTP 500 errors, which led to orders reserve/stock lookup failures, upstream 502s at the gateway, and subsequent payment cancellations.

After compaction the model gets five messages, and the question is one of them on every call. The answer matches the right answer from step 1 line by line, and the report is addressed to the incident commander from the instructions. The whole run cost under a cent. Each call stayed between 420 and 2,004 input tokens, so a run over a hundred services would still fit comfortably.


[06]

What happens when the model reads all ten logs at once?

Models often ask for several tools in one step. investigate_parallel.py is investigate.py with one instruction changed, so the model may batch its calls:

Pythoninvestigate_parallel.py
INSTRUCTIONS = (
    "You are an SRE assistant. Answer from the logs only. "
    "Read each service's log with read_log, one service per call."
)

gpt-5-mini then asked for all ten logs in its second call. Here's the default agent, then the full transcript:

Output
call msgs tool msgs ledger   input  cached output  next
   1    2         0     no     268       0    147  list_logs  [watch: seen]
   2    4         1     no     322       0    159  read_log auth, read_log billing, read_lo  [watch: seen]
   3   14        10    yes  56,409       0  1,436  final answer  [watch: seen]
total: 3 model calls, 56,999 input (0 cached) + 1,742 output tokens = $0.0177
Output
call msgs tool msgs ledger   input  cached output  next
   1    2         0     no     268       0     83  list_logs  [watch: seen]
   2    4         1     no     322       0    165  read_log auth, read_log billing, read_lo  [watch: seen]
   3   15        11     no  56,351       0  1,563  final answer  [watch: seen]
total: 3 model calls, 56,941 input (0 cached) + 1,811 output tokens = $0.0179

With eleven results in one step, the compacted call and the full transcript are about the same size: 56,409 tokens against 56,351. The ten results are the last step, so they appear once, and the ledger holds only list_logs. Both runs answered every part correctly. Batching cuts the number of calls, but it puts every result into one call, so the size of each result matters even more.


[07]

How to budget the starting context with the ContextEngine

The ContextEngine solves a different problem: a chat whose history keeps growing. Before each call it counts the instructions, history, memory and question with tiktoken, and when they exceed the budget it drops the least important parts first, oldest conversation turns before anything else. This example uses a tiny window so trimming shows on a short history:

Pythonengine_budget.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Budget the context an agent starts with: instructions, chat history and the new question."""

import asyncio

from langchain_core.callbacks import AsyncCallbackHandler
from promptise import ContextEngine, build_agent


class ShowPrompt(AsyncCallbackHandler):
    """Print every message the model receives on its first call."""

    def __init__(self):
        self.done = False

    async def on_chat_model_start(self, serialized, messages, **kwargs):
        if not self.done:
            self.done = True
            for m in messages[0]:
                print(f"  {m.type:<6} {str(m.content)[:60]}")


# Six earlier turns of a chat about the incident.
history = []
for service in ["auth", "billing", "gateway", "inventory", "notifications", "orders"]:
    history.append({"role": "user", "content": f"Summarize the {service} log."})
    history.append(
        {"role": "assistant", "content": f"The {service} log has 140 INFO lines. " + "Nothing unusual. " * 40}
    )


async def main() -> None:
    default = ContextEngine(model="openai:gpt-5-mini")
    print(f"default for gpt-5-mini: window {default.window:,}, budget {default.budget:,}")

    # A deliberately tiny window, so trimming happens on a short example.
    engine = ContextEngine(model="openai:gpt-5-mini", model_context_window=800, response_reserve=300)
    engine.add_layer("runbook", priority=7, required=True, content="Incident commander: Priya Raman.")

    agent = await build_agent(
        model="openai:gpt-5-mini",
        servers={},
        instructions="You are an SRE assistant. Be brief.",
        context_engine=engine,
    )
    try:
        print("the model sees:")
        result = await agent.ainvoke(
            {"messages": history + [{"role": "user", "content": "Which services have we covered so far?"}]},
            config={"callbacks": [ShowPrompt()]},
        )
        report = engine.last_report
        print(f"budget {report.budget}, used {report.total_tokens} ({report.utilization:.0%}), trimmed {report.trimmed_layers}")
        for layer in report.layers:
            print(f"  {layer['name']:<13} priority {layer['priority']:>2}  {layer['tokens']:>4} tokens  trimmed={layer['trimmed']}")
        print(">>>", result["messages"][-1].content)
    finally:
        await agent.shutdown()


asyncio.run(main())
Output
default for gpt-5-mini: window 400,000, budget 272,000
the model sees:
  system Incident commander: Priya Raman.
  system You are an SRE assistant. Be brief.
  human  Summarize the inventory log.
  ai     The inventory log has 140 INFO lines. Nothing unusual. Nothi
  human  Summarize the notifications log.
  ai     The notifications log has 140 INFO lines. Nothing unusual. N
  human  Summarize the orders log.
  ai     The orders log has 140 INFO lines. Nothing unusual. Nothing 
  human  Which services have we covered so far?
budget 500, used 445 (89%), trimmed ['conversation']
  identity      priority 10    10 tokens  trimmed=False
  user_message  priority 10     8 tokens  trimmed=False
  runbook       priority  7     7 tokens  trimmed=False
  conversation  priority  1   420 tokens  trimmed=True
>>> Covered: inventory, notifications, and orders — each log showed ~140 INFO lines with no anomalies.

The budget is the window minus response_reserve. The three oldest exchanges were dropped as whole user and assistant pairs, and the new question stayed. The runbook layer marked required=True reached the model, and the instructions were sent once. last_report says exactly what happened. The agent now believes only three services were covered, which is what trimming means: dropped turns are gone, not summarized.

The first line shows the default for gpt-5-mini: a 400,000-token window, with the budget capped at the model's 272,000-token input limit. That's far above anything the investigation sends, so adding a default ContextEngine to it changes nothing (python investigate.py engine shows this). Pass model_context_window when you want it to budget for less.

A window of 800 tokens minus a response reserve of 300 leaves a budget of 500, of which 445 were used, and the report shows the identity, user_message and runbook layers kept while the priority 1 conversation layer was trimmed by dropping the three oldest exchanges.
FigureThe ContextEngine fits its layers into the budget and trims the conversation first

For chats stored through a conversation store, there's a simpler cap: build_agent(conversation_max_messages=N) keeps only the newest N messages of each session when it saves them.


[08]

Context engineering best practices

  • Measure before you tune. Count a tool result with ContextEngine.count_tokens and meter real runs. The numbers decide where the work is. In this guide it was entirely in the tool results.

  • Return less from tools. Summarize, filter and count where the data lives, in code. Return the error lines, not the file. Add a drill-down tool with a limit for the cases where the model needs detail.

  • Use the system prompt for what must always hold. Output format, who the report is for, hard rules, the facts the last step depends on. It's sent on every call, twelve times in the final.py run above, so keep it short. System messages you pass in and the current question survive compaction too, but instructions are the place for anything the last step depends on.

  • Put everything large or occasional behind tools. Logs, runbooks, past incidents and documentation belong behind a search or lookup tool, the way RAG turns documents into a search tool. The model fetches the slice it needs, when it needs it.

  • Write the summaries yourself. Promptise doesn't ask a model to summarize the run. The ledger cuts long results to their first 2,000 characters, earlier chat turns become a short clipped note, and the ContextEngine drops whole turns. If a summary matters, produce it in the tool, as log_summary does.

  • Keep one long job per question. In a chat, a compacted turn sees the earlier conversation only as a note of its last six messages, cut to 400 characters each. Run long investigations as their own ainvoke call, and bring the result back into the chat afterwards.


[09]

Common context engineering mistakes

  • Tools that return whole files. After six tool results, older results longer than 2,000 characters are cut to an excerpt, and the model has to call the tool again to see the rest. That's why the default agent in step 4 read every log twice. Make the tools return less. If the model really needs whole results, raise the cut with context_compaction=ContextCompaction(keep_result_chars=...) from promptise.engine, or turn compaction off with context_compaction=False. ContextCompaction(max_result_chars=...) caps every new result as it arrives, with a marker that gives its full length and asks for narrower arguments. It helps when a tool can return less, not when the model needs the whole file.

  • Not catching the step limit. When an iteration limit stops a tool loop before the model answered, ainvoke raises GraphIterationLimitError from promptise.engine, with the limit and the pending_tools whose results the model never saw. The default ReAct loop and the managed pattern allow 25 model calls; build_agent(max_agent_iterations=...) changes that. Catch it wherever a long run can reach the limit, as investigate.py does.

  • Expecting repeated calls to be free. A repeated call runs the tool. That's right for a status or a health check, and wasted work for a file that doesn't change during the run. ContextCompaction(reuse_results=[...]) answers repeats of the tools you list from the earlier result once the loop compacts. It saves tool runs, not tokens.

  • Relying on earlier chat turns in a long run. With chat history in the input, as agent.chat() builds it, a compacted call sees the last six earlier messages, 400 characters each, and then the current question. Facts a long run needs from earlier turns belong in instructions or behind a tool.

  • Expecting a model-written summary. Compaction and the ContextEngine are deterministic: they cut and drop, so what's cut is gone from that call. That costs no extra model calls, and it means the quality of what's kept depends on your tools.

  • Counting on the ContextEngine to bound a tool loop. Its default budget for gpt-5-mini is 272,000 tokens, the model's input limit, so it only bounds a tool loop that gets very long. Pass model_context_window when you want a smaller budget.


[10]

Frequently asked questions

What is context engineering for AI agents?

Deciding what goes into the model's context on each step of an agent run: instructions, the task, history, tool results and retrieved data, and in what form. Prompt engineering is about the wording of one prompt; context engineering is about the whole working set as it changes over a long run. In practice most of it is tool design: what each tool returns, and how much.

What is context compaction?

Replacing a long transcript with a shorter view before the next model call. Promptise's default agent does it automatically after six tool results. It keeps the instructions and any system messages, the current question, the latest step and a ledger with one entry per earlier tool call, with long results cut to 2,000 characters. Other systems summarize the history with a model instead. Either way, check what the compacted view still contains, because that's all the model knows. Context compaction for AI agents compares trimming and summarizing on one transcript.

Does a bigger context window solve the problem?

Not on its own. The full-transcript run in step 5 peaked at 56,462 tokens, well inside gpt-5-mini's window, and answered correctly. But it sent 313,279 input tokens to do work that took about 15,000 with smaller tool results. Every token in the window is paid for on every call, and the growth doesn't stop at ten files.

How do I reduce the token usage of an AI agent?

Meter each model call first, then shrink the largest input. For agents that's almost always tool results: return summaries and counts instead of raw data, cap list sizes, and add a drill-down tool. Keep the system prompt short, since it's resent every call. Prompt caching lowers the price of repeated prefixes, but not the size of the context.

Should I summarize conversation history?

When a chat outgrows its budget, something has to give: either old turns are dropped, as the ContextEngine and conversation_max_messages do, or they're summarized. Promptise doesn't summarize history with a model; inside a long tool loop, earlier turns become a short note of the last six messages. If older turns matter, keep the facts they produced in a tool or in the instructions, rather than relying on the turns themselves.


[11]

Where to go next

  • Context Compaction for AI Agents: Trim vs Summarize: what each strategy keeps, and how to write a summary that keeps file paths.

  • Tool Result Too Large? Keep an AI Agent's Context Small: cap and page large tool results.

  • Context Engine: layers, priorities, budgets and the assembly report.

  • Context Lifecycle Management: the full, scoped and ledger modes and the managed pattern.

  • Engine nodes: Context scope: every PromptNode option, including context_scope and auto_ledger_after.

  • Reasoning Patterns: the built-in agent patterns and when each one fits.

  • Context System for prompts: context providers that inject user, environment and error context into prompts.

  • Observability: record tokens and latency for every call in production.

  • How to Connect MCP Servers to Your AI Agent in Python: the agent and server basics this guide builds on.

  • OpenAPI to MCP: Turn Any REST API into an MCP Server: generated tools are a common source of oversized results, and a good place to apply these rules.

Contents

  1. 01What is context engineering for AI agents?
  2. 02How do you manage the context window of an AI agent?
  3. 03How does context grow in a long agent run?
  4. 04What you need
  5. 05How to apply context engineering to a long agent run, step by step
  6. 06What happens when the model reads all ten logs at once?
  7. 07How to budget the starting context with the ContextEngine
  8. 08Context engineering best practices
  9. 09Common context engineering mistakes
  10. 10Frequently asked questions
  11. 11Where to go next

Learning paths

Want more structure? Paths put guides in order, like a short course.

See the paths →

> Tools and the Model Context Protocol (MCP)

Related guides

All guides in this topic →
  • // 01Intermediate · 18 minHow to Deploy an AI Agent with Docker (2026 Guide)Deploy an AI agent with Docker: a Dockerfile, env vars and secrets, health checks, graceful shutdown, and docker compose with the agent's MCP server.
  • // 02Intermediate · 9 minLLM Supply Chain Security: Models, Packages, Data and ToolsLLM supply chain security as a checklist: inventory models, data and tools, pin and verify hashes, load safe formats, check provenance and plan fallbacks.
  • // 03Intermediate · 14 minLLM Tool Rate Limiting: Per-Client Limits for MCP ServersRate limit LLM tool calls per client, tenant and tool on a Python MCP server: a real load test, the error the agent sees, and how to retry it.
  • // 04Intermediate · 19 minMCP Long-Running Tasks: Background Jobs in PythonRun slow MCP tools as background jobs in Python: submit, poll progress, retry failures and cancel, with a real agent, real runs and honest limits.
  • // 05Intermediate · 20 minMCP Server Monitoring: Prometheus, OpenTelemetry and LogsMonitor an MCP server in Python: Prometheus metrics, JSON logs, OpenTelemetry traces and alerts that show which tools are slow, failing or abused.
  • // 06Intermediate · 24 minBest AI Agent Frameworks (2026): Python Options ComparedThe best AI agent frameworks in 2026 by use case: LangGraph, Pydantic AI, OpenAI Agents SDK, CrewAI, Google ADK and more, with the same agent in nine.

Keep going.

Browse every guide by topic and level, or follow a learning path that puts them in order.

All guidesLearning paths