All Toolsโ€บContext Window Optimizer
๐Ÿ”ง AI Agent Memory ManagementJune 10, 2026โœ… Tests passing

Context Window Optimizer

A CLI tool to optimize the context window for AI agents by dynamically summarizing and compressing prior interactions. It ensures the agent's context fits within a limited token budget without losing essential information.

What It Does

  • Estimates the token count of a given text using a specified tokenizer model.
  • Summarizes text to fit within a specified token budget.
  • Supports input from both text files and raw text strings.
  • Default support for the GPT-2 tokenizer.

Installation

  • Python 3.7+
  • transformers library
  • nltk library
  • pytest for testing

Install the required dependencies using pip:

pip install transformers nltk pytest

Usage

Run the tool from the command line:

python context_window_optimizer.py --input <input_text_or_file> --max_tokens <max_token_count> [--model <model_name>]

Arguments

  • --input: Path to the input text file or raw text.
  • --max_tokens: Maximum token budget.
  • --model: (Optional) Model name for tokenization. Default is gpt2.

Example

Summarize a text file to fit within 50 tokens:

python context_window_optimizer.py --input example.txt --max_tokens 50

Summarize raw text to fit within 30 tokens:

python context_window_optimizer.py --input "This is a long text that needs to be summarized." --max_tokens 30

Source Code

import argparse
import os
from transformers import GPT2Tokenizer
import nltk
from nltk.tokenize import sent_tokenize

nltk.download('punkt')

def estimate_token_count(text, model_name="gpt2"):
    """Estimate the token count of a given text for a specific model."""
    tokenizer = GPT2Tokenizer.from_pretrained(model_name)
    tokens = tokenizer.tokenize(text)
    return len(tokens)

def summarize_text(text, max_tokens, model_name="gpt2"):
    """Summarize the text to fit within the max token limit."""
    sentences = sent_tokenize(text)
    if not sentences:
        return ""

    tokenizer = GPT2Tokenizer.from_pretrained(model_name)
    summarized = []
    current_tokens = 0

    for sentence in sentences:
        sentence_tokens = len(tokenizer.tokenize(sentence))
        if current_tokens + sentence_tokens <= max_tokens:
            summarized.append(sentence)
            current_tokens += sentence_tokens
        else:
            break

    return " ".join(summarized)

def process_input(input_data, max_tokens, model_name):
    """Process the input data and return the summarized context."""
    if os.path.isfile(input_data):
        with open(input_data, 'r', encoding='utf-8') as file:
            text = file.read()
    else:
        text = input_data

    if not text.strip():
        raise ValueError("Input text is empty.")

    return summarize_text(text, max_tokens, model_name)

def main():
    parser = argparse.ArgumentParser(description="Context Window Optimizer")
    parser.add_argument("--input", required=True, help="Path to input text file or raw text.")
    parser.add_argument("--max_tokens", type=int, required=True, help="Maximum token budget.")
    parser.add_argument("--model", default="gpt2", help="Model name for tokenization (default: gpt2).")

    args = parser.parse_args()

    try:
        summarized_context = process_input(args.input, args.max_tokens, args.model)
        print(summarized_context)
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()

Community

Downloads

ยทยทยท

Rate this tool

No ratings yet โ€” be the first!

Details

Tool Name
context_window_optimizer
Category
AI Agent Memory Management
Generated
June 10, 2026
Tests
Passing โœ…
Fix Loops
2

Quick Install

Clone just this tool:

git clone --depth 1 --filter=blob:none --sparse \
  https://github.com/ptulin/autoaiforge.git
cd autoaiforge
git sparse-checkout set generated_tools/2026-06-10/context_window_optimizer
cd generated_tools/2026-06-10/context_window_optimizer
pip install -r requirements.txt 2>/dev/null || true
python context_window_optimizer.py
Context Window Optimizer โ€” AI Tools by AutoAIForge