减少 Token 消耗 45% 的简单技巧
分享通过移除冗余内容(Defluffer)来优化 LLM 提示词的方法,显著降低 token 消耗和 API 成本。
分享通过移除冗余内容(Defluffer)来优化 LLM 提示词的方法,显著降低 token 消耗和 API 成本。
这是参加「周末挑战:地球日特别版」的投稿。
Fluffer:成人影视行业中帮助别人“做好开工准备”的人。Defluffer:一个简单的脚本,用来移除 prompt 中的“废话”和“填充内容”!它每年或许能减少相当于一百多万棵树所吸收的 CO2(不过大概不能)。
别担心,这篇文章讲的是后者。这是我为地球日挑战提交的一份搞怪作品——但它确实想传达一个严肃的信息,其中的原则也可能带来巨大的环境影响!
我开发了 Defluffer——一款文本长度压缩工具,让你的 prompt 保持简洁!
在 prompt 中每节省一个 token,就意味着在与 LLM 的完整对话中可能节省数百个 token,因为每一步都会加载整个上下文(这是简化后的解释)。
Defluffer 的灵感来自 Caveman——不同之处在于,它使用代码缩小 payload。毕竟,如果为了减少发送给 LLM 的 token 而调用 LLM……这个过程本身又会消耗 token……听起来实在有点傻!
这是一个严肃的项目吗?绝对不是。看在万能之神的分上,千万别把它用于生产环境!
这些原则值得思考吗?绝对值得!
更少的 token = 更少的兆瓦耗电 = 更少的污染和用水,也能降低 GPU 对稀有资源的需求,等等等等。
而且,与订阅服务相比,在使用 API 时,它还能帮你省钱!
理论上,如果你能把这个脚本“完善加固”,并让全世界每一位开发者都使用它,我们每年就能节省超过 60 吉瓦的能源(这些数据是 Gemini“润色”出来的,假设有 4,000 万名开发者使用 AI,每天发送 30 个 prompt,每个 prompt 节省 135 个 token)。
🏡 足够为 5,600 户家庭供电整整一年!
📱 相当于给 39.4 亿部手机充一次电!
🌳 相当于 112 万棵树吸收的 CO2!
这才叫拯救地球!
页面顶部有一个输入框,你可以在里面输入 prompt,看看经过“defluff”处理后能节省多少 token 和单词!
这里有一个演示 prompt,你可以复制粘贴进去试试:
Hello there! I would really appreciate it if you could act as a senior backend developer. I am trying to figure out how to write a python script that connects to the database and retrieves all of the information from the user repository.
Make sure that the results are filtered so that the retry count is greater than or equal to 5, and the active status is strictly equals to true. Due to the fact that the application is currently in the production environment, it is required that you utilize the environment configurations instead of hardcoding the parameters into the functions.
Also, I have a question about the following snippet. Could you please refactor this code without using any external libraries?
` ` `javascript
function calculateMaximum(array) {
if (array === null) return 0;
return Math.max(...array);
}
` ` `
Take into consideration that the output should be formatted as a standard JSON object. If you don't mind, please provide a step by step guide on how to deploy this microservice to the kubernetes cluster at the very end. Thank you so much!
在下方的「impact calculator」标签页中,你还可以看到一些滑块,用来估算每年可能节省的 CO2 和电力。
在「test results」标签页中,你还可以看到使用 Defluffer 处理几个示例 prompt 后,测试集体积缩减的结果!
CodePen 演示,记得向下滚动!!!
核心代码其实非常简单。
困难的部分在于整理需要“压缩”的短语列表(本质上就是一份短语清单,我们会替换或删除其中的短语)。
你可以在 CodePen 中查看代码和替换列表。
不过,下面就是完整的 class!
class Defluffer {
constructor(dictionaries) {
this.phrasesAndLogic = { ...dictionaries.phrases, ...dictionaries.logic };
this.synonyms = dictionaries.synonyms || {};
this.blacklist = new Set(dictionaries.blacklist || []);
}
compress(prompt) {
let text = prompt;
let protectedItems = [];
// 1. Extract and protect code blocks
text = text.replace(/(```
{% endraw %}
[\s\S]*?
{% raw %}
```|`[^`]+`)/g, (match) => {
protectedItems.push(match);
return `PROT${protectedItems.length - 1}PROT`;
});
// 2. Strip multi-word blacklist entries
for (const entry of this.blacklist) {
if (!entry.includes(' ')) continue;
const escaped = entry.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
text = text.replace(new RegExp(`\\b${escaped}\\b`, 'gi'), '');
}
// 3. Phrase and logic collapsing
for (const [phrase, replacement] of Object.entries(this.phrasesAndLogic)) {
if (!phrase) continue;
const escaped = phrase.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`\\b${escaped}\\b`, 'gi');
text = text.replace(regex, () => {
if (!replacement || replacement.trim() === '') return ' ';
protectedItems.push(replacement);
return `PROT${protectedItems.length - 1}PROT`;
});
}
// 4. Tokenize
let tokens = text.split(/(\b[a-zA-Z0-9_'-]+\b)/);
// 5. Apply single-word blacklist and synonyms
tokens = tokens.map(token => {
if (!/^[a-zA-Z0-9_'-]+$/.test(token)) return token;
if (/^PROT\d+PROT$/.test(token)) return token;
const lower = token.toLowerCase();
if (this.blacklist.has(lower)) return '';
if (this.synonyms[lower]) return this.synonyms[lower];
return token;
});
// 6. Rejoin and clean
text = tokens.join('')
.replace(/\s+/g, ' ')
.replace(/\s+([.,?!;:])/g, '$1')
.trim();
// 7. Restore protected items
protectedItems.forEach((item, index) => {
const placeholder = `PROT${index}PROT`;
while (text.includes(placeholder)) {
text = text.replace(placeholder, item);
}
});
// 8. Final cleanup
return text
.replace(/\s+/g, ' ')
.replace(/\s+([.,?!;:])/g, '$1')
.trim();
}
}
使用 Google Gemini 进行 Vibe Coding!
梳理了问题空间和灵感来源。
逐一研究了它提供的方案(其中包括 NLP 库以及其他一些被我否决的东西),最终总结出以下核心原则:空白字符压缩:使用纯正则表达式,把制表符、连续空格等转换为单个空格。短语折叠:通过字典查找短语及其替换内容。废话黑名单:使用 Hash Set 查找并直接删除某些单词(如 a、it 等)。符号逻辑:通过字典查找并替换(将 not 变成 !)。词干提取/同义词:通过字典查找并替换(将 application 变成 app)。
空白字符压缩:使用纯正则表达式,把制表符、连续空格等转换为单个空格。
短语折叠:通过字典查找短语及其替换内容。
废话黑名单:使用 Hash Set 查找并直接删除某些单词(如 a、it 等)。
符号逻辑:通过字典查找并替换(将 not 变成 !)。
词干提取/同义词:通过字典查找并替换(将 application 变成 app)。
让 Gemini 编写代码并创建字典。
让它提供更多字典条目。
后来我放弃了,转而去问 Claude,因为它在消息长度上没那么吝啬。
添加了基础的代码排除机制(我们不想把作为变量使用的 i 删除,所以会让代码保持原样),还添加了关键短语排除机制:将 act as a 替换为 be,但随后还要确保 be 受到保护,避免它在后续处理中被删除。
让 Gemini 编写了一些测试短语。
让 Gemini 添加了一个漂亮的 UI,并在底部加入了一些基础的“等效 CO2 节省量”。
Google Gemini 最佳应用???!???……尽管我不得不使用 Claude,因为 Gemini 就是不肯输出长消息?
我的意思是,我正在要求一个 LLM 编写代码,以减少它自身的 token 使用量,所以想要一条长消息这件事本身有多讽刺,我并不是没意识到。因此从技术角度来看,Gemini 在这里反而比 Claude 更好?哈哈。
部分评论可能只有登录后的访客才能看到。登录即可查看全部评论。
如需采取进一步操作,你可以考虑屏蔽此人和/或举报滥用行为。