Skip to main content
Glama
jiawei686

tokencompress

by jiawei686

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.


Related MCP server: JSON2TOON MCP Server

安装

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
A
license - permissive license
-
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • A
    license
    A
    quality
    C
    maintenance
    Data compression MCP server with auto-algorithm selection (gzip, brotli, deflate). 7 tools for compress, decompress, analyze, store, retrieve, list, and stats. Achieves 60x compression on docs, 30x on SQL. Lossless round-trip verified. Zero dependencies.
    Last updated
    9
    2
    MIT
  • A
    license
    B
    quality
    D
    maintenance
    Advanced Token-Optimized Object Notation MCP server that compresses JSON with up to 85% token reduction using AI-powered pattern detection, providing lossless compression and decompression through 12 MCP tools.
    Last updated
    12
    9
    MIT
  • F
    license
    -
    quality
    C
    maintenance
    Semantic compression MCP server that reduces document token usage by 60-80% using structured symbolic notation, enabling Claude to efficiently store, retrieve, diff, and summarise documents across PRD, CODE, PAPER, and MEETING domains.
    Last updated

View all related MCP servers

Related MCP Connectors

  • Local-first RAG engine with MCP server for AI agent integration.

  • A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…

  • Hosted MCP server for LLM cost estimation, model comparison, and budget-aware routing.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/jiawei686/tokencompress'

If you have feedback or need assistance with the MCP directory API, please join our Discord server