Fit OpenAI chat messages into a token budget. Pass the result directly to client.chat.completions.create.
import { fitMessages } from '@jeremysnr/snug-openai';
const { messages } = fitMessages(conversationHistory, {
model: 'gpt-4o',
budget: 8192,
reserve: 1024,
});
const response = await client.chat.completions.create({ model: 'gpt-4o', messages });System messages are always kept. Other messages are prioritised by recency, so older messages are dropped first when the budget is tight.
npm install @jeremysnr/snug-openai
openai must be installed as a peer dependency.
| Option | Type | Default | Description |
|---|---|---|---|
budget |
number |
(required) | Token limit |
reserve |
number |
0 |
Tokens to hold back for the model's reply |
model |
TiktokenModel |
cl100k_base encoding |
Selects the tiktoken encoding. gpt-4o and newer use o200k_base, so pass the model you will call. |
Returns
{
messages: ChatCompletionMessageParam[]; // ready to send
dropped: ChatCompletionMessageParam[]; // what didn't fit
tokensUsed: number;
tokensRemaining: number;
}tiktoken encoders are WASM objects and are slow to construct, so this package caches one per model and keeps it for the life of the process. Call freeEncoders() to release that memory; the next fitMessages() recreates encoders as needed.
Each message is counted as the tiktoken length of its text content plus four tokens for OpenAI's per-message role and delimiter framing. That is the figure from OpenAI's cookbook and is close enough for budgeting, but the exact overhead varies slightly by model, and non-text content (images, tool call arguments) is not counted. Keep a reserve that covers the difference.
@jeremysnr/snug, zero-dependency core primitive@jeremysnr/snug-tiktoken, snug with tiktoken for OpenAI encodings@jeremysnr/snug-anthropic, snug for the Anthropic SDK
MIT