llmtrim

repository·main·Indexed 41 days ago

https://github.com/fkiene/llmtrim

A static, deterministic LLM prompt and payload compressor that reduces input tokens by 30-90% without extra model calls. It functions as a local proxy for tools like Claude Code and Cursor, or as a library via llmtrim-core (Rust), @llmtrim/js (TypeScript), and UniFFI bindings for Python, Ruby, Swift, and Kotlin. It includes a system-tray dashboard (llmtrim-tray) and supports Model Context Protocol (MCP) as a server.

Tokens
48.4K
Snippets
127
Records
226
Agent score
54%

What's inside llmtrim

  1. Overview of llmtrim-tray

    main

    The llmtrim-tray is a system-tray / menu-bar application that provides a visual dashboard of llmtrim's compression savings. It displays aggregate savings, a per-agent breakdown (e.g., Claude Code, Codex, Gemini), and savings trends via a popover window.

    Supported Platforms:

    • macOS
    • Windows
    • Linux (X11/Wayland via WebKitGTK and AppIndicator).

    Linux Runtime Dependencies:

    • libwebkit2gtk-4.1
    • libayatana-appindicator3
  2. Use llmtrim-core in other languages

    main

    The llmtrim-core engine is written in Rust but is available for other languages:

    • Python, Ruby, Swift, Kotlin: Available via UniFFI through the llmtrim-uniffi package.
    • JavaScript / TypeScript: Available via WebAssembly as the @llmtrim/js npm package (see llmtrim-wasm).
    • CLI: Use the llmtrim crate for a drop-in compressing proxy.
  3. Use llmtrim-uniffi for in-process compression

    main

    The llmtrim-uniffi package provides UniFFI bindings over llmtrim-core, allowing you to perform LLM request compression natively within your application's process. Unlike the llmtrim proxy which intercepts network traffic via HTTPS_PROXY, these bindings require you to explicitly call compress() on your request body and then send the resulting JSON using your own HTTP client.

    Use this approach when:

    • You are running in sandboxed or serverless environments where setting a process-wide HTTPS_PROXY is difficult.
    • You use certificate-pinned clients that reject MITM (Man-in-the-Middle) CA certificates.
    • You want to avoid the latency of an extra network hop or the complexity of running a sidecar process.
  4. Understand llmtrim-core compression presets

    main

    The engine uses different workload presets to determine how to compress various parts of an LLM request. You can select these via DenseConfig or let the engine auto-route them based on the request structure.

    Available Presets

    • auto: (Default) Shape-routed; picks the best strategy based on the request structure.
    • aggressive: High compression ratio.
    • agent: Optimized for agentic workflows.
    • code: Optimized for source code (reduces bodies to signatures).
    • rag: Optimized for Retrieval Augmented Generation (ranking/dropping context chunks).
    • safe: Uses only lossless compression stages.

    What is compressed

    • Tool output: Folds noise in build logs, diffs, and JSON.
    • Long context: Ranks and keeps relevant chunks; drops the rest.
    • Source code: Reduces function bodies to signatures (supports 14 languages).
    • Tool schemas: Trims descriptions and drops unused tools.
    • JSON / record arrays: Re-encodes to compact tables (TOON/CSV) or samples large arrays.
    • Model reply: Requests terser output from the model.
  5. Understand llmtrim compression modes and quality gating

    main

    llmtrim uses a quality-gated approach to compression, meaning it only applies lossy cuts if the model's answer quality is maintained.

    Key modes include:

    • auto: The default mode. It is quality-gated to ensure high-quality responses.
    • aggressive: Accepts more lossy cuts, provided the quality gate still holds.
    • safe: A preset for users who require a byte-faithful round-trip (no lossy information reduction).

    Note: While 'lossless' stages preserve the information the model reads (e.g., via abbreviation legends), the engine does not transform the model's response back to its original form.

  6. Compare llmtrim compression strategies

    main

    llmtrim differs from other tools by compressing both input and output while leaving the cached prefix untouched to maintain prompt cache stability. It scores based on whether the answer survives the cut rather than just tokens removed.

    Input Compression Comparison:

    • llmtrim auto: ~25% reduction, ~5ms overhead, high quality.
    • llmtrim aggressive: ~28% reduction, ~5ms overhead, high quality.
    • Headroom: ~24% reduction, ~0.9s overhead (ML-based).
    • leanctx / LLMLingua-2: 52-81% reduction, ~6s overhead, significantly lower quality.
    • entroly: 80-89% reduction, <1ms overhead, significantly lower quality.

    Output Compression Comparison:

    • llmtrim output_terse: ~69% reduction, ~19 tokens overhead.
    • caveman: ~80% reduction, ~949 tokens overhead (due to large system prompt).
  7. Data contract for llmtrim-tray dashboard

    main

    The tray application consumes data via a specific contract designed to protect privacy. The AgentAggregate type and dashboard queries are designed to drop sensitive columns such as project paths and session_name.

    Key data points provided to the UI include:

    • % saved: The gross savings percentage (the primary metric).
    • bill_micros: The billing amount, provided as an i64 in microseconds (divide by 1e6 for standard currency units).
    • trend: An array of data points used to draw an SVG-path sparkline.
    • has_savings_data: A boolean flag to handle pre-meter NULLs (if false, the UI should show — instead of 0%).
  8. Understand the llmtrim Tray App architecture

    main

    The llmtrim-tray is a system-tray (menu-bar) desktop application built with Tauri v2 and a Vite + TS web frontend. It provides a visual dashboard of compression metrics per LLM agent (e.g., Claude Code, Gemini).

    Key Architectural Principles:

    • Read-Only Access: The tray app is strictly a read-only consumer of the llmtrim-ledger. It uses SQLITE_OPEN_READ_ONLY to ensure it never takes an exclusive lock or interferes with the llmtrim-cli proxy, which is the sole writer of the ledger.
    • Decoupled Data Layer: All aggregation logic and data mapping reside in the llmtrim-ledger crate. The tray app is a thin wrapper that calls these functions via Tauri commands.
    • Security-First Design:
      • The AgentAggregate type is structurally designed to prevent leaking sensitive information like project paths or session_name to the webview.
      • The Tauri configuration uses a strict Capability Allowlist and Content Security Policy (CSP), specifically setting connect-src 'none' to prevent unauthorized network access.
    • Platform Support: Phase 1 focuses on macOS and Windows. Linux support is deferred due to desktop environment tray complexities.
  9. How llmtrim compression works

    main

    llmtrim acts as a local proxy that intercepts LLM API traffic. It identifies 'waste' in requests (like repetitive build logs or massive JSON arrays) and trims them before forwarding the request to the provider (OpenAI, Anthropic, etc.).

    Key Principles

    • Safety First: Compression cannot raise your bill or break a request. If a compressed body is rejected by the provider, the original is resent. Each stage is re-measured with the provider's real tokenizer.
    • Zero Data Leakage: Everything runs locally on your machine. Prompts never touch the llmtrim servers; only anonymous token counts are used.
    • Compatibility: Works with any tool that honors HTTPS_PROXY (Claude Code, Cursor, Aider, etc.). Note: GitHub Copilot is not supported due to certificate pinning.
    • Preservation: Existing prompt-cache prefixes (cache_control) are left untouched. Lines prefixed with LLMTRIM_KEEP: are preserved even during windowing.
  10. Security posture of llmtrim-tray

    main

    The llmtrim-tray is designed with a strict security model to protect user privacy:

    • Data Minimization: The Tauri IPC contract only carries aggregate numbers. It explicitly excludes sensitive metadata such as project, session_name, mcp_server, or tool_name.
    • Error Masking: Errors passed to the webview are stripped of filesystem paths; full error details are sent only to stderr.
    • Sandboxing: The Content Security Policy (CSP) sets connect-src 'none'. The capability allowlist excludes shell, fs, http, updater, and clipboard.
    • Read-Only Access: The application opens the ledger in read-only mode.
  11. Install llmtrim as a library

    main

    You can use the llmtrim engine directly in your applications without a proxy. Compression runs in-process and does not require extra model calls.

    # Rust
    cargo add llmtrim-core
    
    # Python
    pip install llmtrim
    
    # Ruby
    gem install llmtrim
    
    # Kotlin
    implementation("io.github.fkiene:llmtrim:0.13.7")
    
    # Swift
    SwiftPM fkiene/llmtrim-swift ≥ 0.1.8
    
    # JS / TS
    @llmtrim/js (WASM)
  12. Use llmtrim as an MCP server

    main

    You can expose the llmtrim engine to a Model Context Protocol (MCP) client. Running llmtrim mcp starts an MCP server over stdin/stdout providing three tools:

    • llmtrim_compress
    • llmtrim_compress_text
    • llmtrim_stats

    Registration:

    • To register with Claude Code: llmtrim mcp install
    • To get the configuration for other clients: llmtrim mcp install --print
    llmtrim mcp install
    # or
    llmtrim mcp install --print