Skip to main content

LLM context window management: token budget, compaction strategies, tool result guards

Project description

nodus-context

LLM context window management: token budget, compaction strategies, and tool result guards for AI systems.

Keeps agent conversations within finite LLM context windows without manual message pruning. No required external dependencies — token counting uses a word-count estimate by default; install tiktoken for accurate counts.

Status: v0.1.0 — prepared, not yet published.


Install

pip install nodus-context

# With accurate tiktoken-based token counting:
pip install "nodus-context[tiktoken]"

What it provides

Component Purpose
ContextBudget Token budget with utilization tracking and overflow detection
ContextMessage Normalized message (role, content, token count)
ContextWindow Message list with budget enforcement and compaction
DropToolInternalsStrategy Remove intermediate tool calls, keep final pairs
SummarizeStrategy Keep head + tail, replace middle with a summary message
estimate_tokens / count_tokens Word-estimate or tiktoken-accurate counting

Quick start

from nodus_context import ContextWindow, ContextBudget, ROLE_USER, ROLE_ASSISTANT

budget = ContextBudget(max_tokens=8192)
window = ContextWindow(budget=budget)

window.add(ROLE_USER, "What is the capital of France?")
window.add(ROLE_ASSISTANT, "The capital of France is Paris.")

messages = window.messages()   # list of ContextMessage
print(f"Using {budget.used}/{budget.max_tokens} tokens")

ContextBudget

from nodus_context import ContextBudget

budget = ContextBudget(max_tokens=4096, reserve_tokens=512)
budget.add(150)                # record token usage
budget.utilization             # float 0.0–1.0
budget.available               # tokens remaining (respects reserve)
budget.is_over_budget          # True if used > max_tokens
budget.reset()

ContextWindow

from nodus_context import ContextWindow, ContextBudget, DropToolInternalsStrategy

window = ContextWindow(
    budget=ContextBudget(max_tokens=8192),
    compaction_strategy=DropToolInternalsStrategy(),
    compaction_threshold=0.85,   # compact when 85% full
)

window.add(role, content)         # adds message, tracks tokens
window.add_raw(context_message)   # add pre-built ContextMessage
window.messages()                 # current message list
window.compact()                  # trigger compaction manually
window.guard_tool_results(n=2)    # keep only the last n tool result pairs
window.token_count                # current total
window.message_count

Compaction runs automatically when utilization >= compaction_threshold.


Compaction strategies

DropToolInternalsStrategy

Removes intermediate tool_use / tool_result pairs, keeping only the final n pairs. Reduces context without losing the outcome.

from nodus_context import DropToolInternalsStrategy
strategy = DropToolInternalsStrategy(keep_last_n_pairs=1)

SummarizeStrategy

Keeps the first head_count and last tail_count messages; replaces everything in between with a single summary message.

from nodus_context import SummarizeStrategy
strategy = SummarizeStrategy(
    head_count=2,
    tail_count=4,
    summary_fn=lambda msgs: "Summary of intermediate steps.",
)

summary_fn can call an LLM — any callable that takes a list of ContextMessage and returns a string.


Token counting

from nodus_context import estimate_tokens, count_tokens

estimate_tokens("Hello, world!")   # fast word-count estimate (no dep)
count_tokens("Hello, world!")      # tiktoken if installed, else estimate

Install nodus-context[tiktoken] for accurate counts.


Role constants

from nodus_context import (
    ROLE_USER, ROLE_ASSISTANT, ROLE_SYSTEM,
    ROLE_TOOL_USE, ROLE_TOOL_RESULT, ROLE_THINKING,
)

Design

  • No required dependencies. Token estimation uses ~4 chars per token heuristic. Accurate counting requires tiktoken (optional extra).
  • Protocol-based strategies. Any callable satisfying CompactionStrategy works — no inheritance needed.

Development

pip install -e ".[dev]"
pytest tests/ -q

License

MIT — see LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

nodus_context-0.1.0.tar.gz (11.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

nodus_context-0.1.0-py3-none-any.whl (9.8 kB view details)

Uploaded Python 3

File details

Details for the file nodus_context-0.1.0.tar.gz.

File metadata

  • Download URL: nodus_context-0.1.0.tar.gz
  • Upload date:
  • Size: 11.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for nodus_context-0.1.0.tar.gz
Algorithm Hash digest
SHA256 f7f3807694b814e3608b1f93379f0c00384550c9c2da502fea11332ddbcb9298
MD5 016d554bf49048dccdf210766a403d5f
BLAKE2b-256 32c0066989be2b05a71d2ac2a03ab73654d121e45b80b868bbdfdfe108a613a3

See more details on using hashes here.

File details

Details for the file nodus_context-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: nodus_context-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 9.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for nodus_context-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8606c79e3ec7e147b1cb26b411b0904a52d7542325e453e91ff408cbe6970042
MD5 0eaf3408f320bdeb24877e729fbacc04
BLAKE2b-256 318a61a88ce5079106166a8809ce41a99bf4ea890a0b9d975199fe4c423a7dc5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page