jiawei686

tokencompress

Community jiawei686
Updated

🔐 Local, zero-cloud token & text compression for LLM prompts and logs. Offline rules + optional local Ollama semantic + lossless gzip. MCP / HTTP / CLI / library. 中文友好。

tokencompress

本地、零云依赖的 token / 文本压缩工具包。把冗长 prompt、日志、长文压短,省 token、省钱、不联网

  • 纯 Python,无强制依赖(可选 tiktoken 做精确 GPT 计数)
  • 四种形态随便挑:MCP 服务 / HTTP API / CLI / 当库导入
  • 离线规则压缩 + 可选本地 Ollama 语义压缩 + gzip 无损打包
  • 智能自动压缩:短输入原样放行,代码块/URL/JSON 自动豁免,只压正文

License: MIT

English

tokencompress is a local, zero-cloud token & text compression toolkit for LLM prompts, context windows, and log/transport volume.

  • 🔒 100% local — no API keys, no network calls. Rules & lossless run fully offline; semantic mode only talks to a local Ollama.
  • 🧩 Four interfaces — MCP server, HTTP API, CLI, and importable Python library.
  • 🌏 Bilingual — first-class Chinese + English filler/stop-word removal and phrase abbreviation.
  • 🤖 Smart auto-compress — short inputs pass through untouched; code blocks, URLs, and JSON are auto-exempt; only prose gets compressed.
  • 📦 Lossless mode — gzip + base64 packing for logs/transport, fully reversible.

Keywords: token compression, prompt compression, LLM context, local-first, privacy, MCP, CLI, Chinese NLP, text compression, Ollama.

安装

cd tokcompress
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt

没有自带 venv。按上面“安装”步骤建 .venv 即可;或 pip install . 后直接用系统 python3

最简单的用法

1) 当库导入(推荐给写代码的人)

from tokencompress import compress, auto_compress, measure

# 手动压
r = compress("你的长文本……", method="rules")
print(r["compressed"])            # 压缩后的文本
print(r["metrics"]["token_ratio"])  # 0.71 表示省了约 29% token

# 智能自动压:短的不动,长的才压
out = auto_compress("你的长文本……")["compressed"]

2) 命令行(CLI)

# 压一段文字
python -m tokencompress compress "你的长文本……"

# 从管道读(最常用)
cat long_prompt.txt | python -m tokencompress autocompress -

# 只算 token 数
python -m tokencompress measure "你的长文本……"

3) tca 包装脚本(一行管道,最简)

# 压缩剪贴板
pbpaste | ./bin/tca

# 压缩文件
cat long_prompt.txt | ./bin/tca

# 自定义触发阈值(token 数,低于此值原样放行)
echo "很长的文本……" | ./bin/tca --threshold 300

可选:把下面这行加进 ~/.zshrc,之后任意位置都能用 tca

alias tca="$HOME/path/to/tokencompress/bin/tca"   # 替换成你的实际路径

4) HTTP 服务(给别的程序调用)

python -m tokencompress serve --port 8787
curl -s -X POST localhost:8787/compress \
  -H 'Content-Type: application/json' \
  -d '{"text":"你的长文本……","method":"rules"}'

端点:/health /strategies /backends /measure /compress /decompress /autocompress

5) 接入 WorkBuddy(MCP)

examples/mcp_config.json 的内容加进 ~/.workbuddy/mcp.jsonmcpServers,重启 WorkBuddy 后,对话里就能直接让模型调用 compress_text / auto_compress_text 等工具。

压缩方法

method 说明 是否可逆 依赖
rules 离线规则流水线:去空白/去重/去填充词/短语缩写 否(有损但语义保留)
semantic 本地 Ollama 模型做语义压缩 本机 Ollama
both 先 rules 再语义 本机 Ollama(无则回退 rules)
lossless gzip + base64 打包,用于日志/传输

rules 流水线顺序:whitespace → dedup → filler → abbreviate → truncate可用 compress(text, strategies_list=[...]) 指定只跑其中几步。

真实压缩率(本机实测)

案例 1:中英混合 prompt(method=rules

输入:“我们需要因为时间成本的原因去写一个用于短视频生成的提示词,for example 我们可以这样描述:given a topic,in order to 让模型生成一段画面。actually 要注意避免图像畸变这个问题,basically 这个细节很重要,also 要让画面保持稳定。”

指标 压缩前 压缩后 比率
tokens(离线估算) 128 92 0.719
bytes 301 261 0.867

命中的规则:filler(去掉 actually/basically/also)、abbreviate(for example→e.g.、in order to→to)

输出:“我们需要因为时间成本的原因去写一个用于短视频生成的提示词,e.g. 我们可以这样描述:given a topic,to 让模型生成一段画面。 要注意避免图像畸变这个问题, 这个细节很重要, 要让画面保持稳定”

案例 2:重复日志(method=lossless

输入:50 行相同的 INFO ... worker-7 processed batch id=8821 items=64 ok

指标 压缩前 压缩后 比率
bytes 3050 144 0.047

可逆:解压后与原文逐字节一致 ✓(适合日志归档/网络传输)

案例 3:智能自动压缩(auto_compress)

  • 短输入(≤ 500 token,可配 --threshold):原样放行,绝不误伤指令
  • 长输入(上面案例 1 重复 6 遍):自动压缩,token_ratio ≈ 0.717
  • 代码块( ```)、URL、文件路径、JSON 行:永远不压

常见问题

token 数是怎么算的? 离线估算:CJK ≈ 1 token/字符,拉丁文 ≈ 1 token/4 字符。装了 tiktokenmeasure(text, model="gpt-4o") 可拿到精确 GPT 计数。

会把我数据发到云端吗? 不会。rules / lossless 完全本地。semantic 只连本机http://localhost:11434(Ollama),不联网、不经过任何第三方。

装了 Ollama 怎么启用语义压缩? 拉一个小模型(如 qwen2.5:3b),list_backends()会显示 ollama: available。之后 compress(text, method="semantic") 即可。

文件结构

tokcompress/
├── tokencompress/        # 包本体
│   ├── __init__.py       # 导出 compress / measure / decompress / auto_compress ...
│   ├── core.py           # 统一入口
│   ├── strategies.py     # 规则流水线 + 无损打包 + 语义压缩
│   ├── tokenizer.py      # token 估算 / 后端探测
│   ├── cli.py            # 命令行
│   ├── http_server.py    # HTTP API
│   └── mcp_server.py     # MCP 服务
├── bin/tca               # 一键自动压缩包装脚本
├── examples/             # mcp_config.json / usage.md
└── requirements.txt

MCP Server · Populars

MCP Server · New

    asdecided

    AsDecided

    Native deterministic requirements-as-code engine and read-only MCP server.

    Community asdecided
    Mapika

    portview

    See what's on your ports, then act on it. Diagnostic-first port viewer for Linux, MacOS and Windows.

    Community Mapika
    sandeepbazar

    🛡️ ocm-mcp-server

    An MCP server that lets AI agents operate a multi-cluster Kubernetes fleet through an Open Cluster Management hub, with policy, approval, and audit between the model and your clusters.

    Community sandeepbazar
    raintree-technology

    HIG Doctor

    Apple HIG reference and cross-framework UI audit tooling for agents.

    wgt19861219

    Godot MCP Enhanced

    Enhanced MCP server for Godot 4.5-4.7: 33 tools / 199 actions, 3-layer architecture (headless + editor + game bridge), secure sandbox, recording & frame-verify, cross-version CI.

    Community wgt19861219