Skip to content

About

snug for the OpenAI SDK. Fit chat messages into a token budget.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

@jeremysnr/snug-openai

npm license

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.

Install

npm install @jeremysnr/snug-openai

openai must be installed as a peer dependency.

API

fitMessages(messages, options)

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;
}

freeEncoders()

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.

How counts are made

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.

Part of the snug ecosystem

Licence

MIT

About

snug for the OpenAI SDK. Fit chat messages into a token budget.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages