@jeremysnr/snug-openai 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jeremy Smith
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # @jeremysnr/snug-openai
2
+
3
+ [![npm](https://img.shields.io/npm/v/@jeremysnr/snug-openai)](https://www.npmjs.com/package/@jeremysnr/snug-openai)
4
+ [![license](https://img.shields.io/npm/l/@jeremysnr/snug-openai)](./LICENSE)
5
+
6
+ Fit OpenAI chat messages into a token budget. Pass the result directly to `client.chat.completions.create`.
7
+
8
+ ```ts
9
+ import { fitMessages } from '@jeremysnr/snug-openai';
10
+
11
+ const { messages } = fitMessages(conversationHistory, {
12
+ model: 'gpt-4o',
13
+ budget: 8192,
14
+ reserve: 1024,
15
+ });
16
+
17
+ const response = await client.chat.completions.create({ model: 'gpt-4o', messages });
18
+ ```
19
+
20
+ System messages are always kept. Other messages are prioritised by recency — older messages are dropped first when the budget is tight.
21
+
22
+ ## Install
23
+
24
+ ```
25
+ npm install @jeremysnr/snug-openai
26
+ ```
27
+
28
+ `openai` must be installed as a peer dependency.
29
+
30
+ ## API
31
+
32
+ ### `fitMessages(messages, options)`
33
+
34
+ | Option | Type | Default | Description |
35
+ |--------|------|---------|-------------|
36
+ | `budget` | `number` | — | Token limit |
37
+ | `reserve` | `number` | `0` | Tokens to hold back for the model's reply |
38
+ | `model` | `TiktokenModel` | `'gpt-4o'` | Used to select the tiktoken encoding |
39
+
40
+ **Returns**
41
+
42
+ ```ts
43
+ {
44
+ messages: ChatCompletionMessageParam[]; // ready to send
45
+ dropped: ChatCompletionMessageParam[]; // what didn't fit
46
+ tokensUsed: number;
47
+ tokensRemaining: number;
48
+ }
49
+ ```
50
+
51
+ ## Part of the snug ecosystem
52
+
53
+ - [`@jeremysnr/snug`](https://github.com/JeremySNR/snug) — zero-dependency core primitive
54
+ - [`@jeremysnr/snug-tiktoken`](https://github.com/JeremySNR/snug-tiktoken) — snug with tiktoken, model-agnostic
55
+ - [`@jeremysnr/snug-anthropic`](https://github.com/JeremySNR/snug-anthropic) — snug for the Anthropic SDK
56
+
57
+ ## Licence
58
+
59
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ fitMessages: () => fitMessages
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+ var import_tiktoken = require("tiktoken");
27
+ var import_snug = require("@jeremysnr/snug");
28
+ function messageToText(msg) {
29
+ if (typeof msg.content === "string") return msg.content;
30
+ if (Array.isArray(msg.content)) {
31
+ return msg.content.map((part) => "text" in part ? part.text : "").join("");
32
+ }
33
+ return "";
34
+ }
35
+ function fitMessages(messages, options) {
36
+ const enc = options.model ? (0, import_tiktoken.encoding_for_model)(options.model) : (0, import_tiktoken.get_encoding)("cl100k_base");
37
+ const MESSAGE_OVERHEAD = 4;
38
+ try {
39
+ const tokenizer = (text) => enc.encode(text).length;
40
+ const items = messages.map((msg, i) => ({
41
+ id: String(i),
42
+ content: msg,
43
+ tokens: tokenizer(messageToText(msg)) + MESSAGE_OVERHEAD,
44
+ // system = highest priority; others prioritised by recency
45
+ priority: msg.role === "system" ? 1e4 : i
46
+ }));
47
+ const result = (0, import_snug.fit)(items, {
48
+ budget: options.budget,
49
+ reserve: options.reserve,
50
+ suppressApproximationWarning: true
51
+ });
52
+ return {
53
+ messages: result.included.map((i) => i.content),
54
+ tokensUsed: result.tokensUsed,
55
+ tokensRemaining: result.tokensRemaining,
56
+ dropped: result.excluded.map((i) => i.content)
57
+ };
58
+ } finally {
59
+ enc.free();
60
+ }
61
+ }
62
+ // Annotate the CommonJS export names for ESM import in node:
63
+ 0 && (module.exports = {
64
+ fitMessages
65
+ });
@@ -0,0 +1,33 @@
1
+ import { TiktokenModel } from 'tiktoken';
2
+ import { ChatCompletionMessageParam } from 'openai/resources/chat/completions';
3
+ export { ChatCompletionMessageParam } from 'openai/resources/chat/completions';
4
+
5
+ interface FitMessagesOptions {
6
+ /** Token budget for the conversation. */
7
+ budget: number;
8
+ /** Tokens to reserve for the model's response. Defaults to 0. */
9
+ reserve?: number;
10
+ /**
11
+ * OpenAI model name — used to select the correct tiktoken encoding.
12
+ * Defaults to gpt-4o.
13
+ */
14
+ model?: TiktokenModel;
15
+ }
16
+ interface FitMessagesResult {
17
+ /** Messages that fit, in original order. Pass directly to the OpenAI SDK. */
18
+ messages: ChatCompletionMessageParam[];
19
+ tokensUsed: number;
20
+ tokensRemaining: number;
21
+ /** Messages that were dropped. */
22
+ dropped: ChatCompletionMessageParam[];
23
+ }
24
+ /**
25
+ * Fit an array of OpenAI chat messages into a token budget.
26
+ *
27
+ * System messages are always highest priority. Other messages are prioritised
28
+ * by recency — newer messages are kept over older ones when the budget is tight.
29
+ * The result is ready to pass directly to client.chat.completions.create.
30
+ */
31
+ declare function fitMessages(messages: ChatCompletionMessageParam[], options: FitMessagesOptions): FitMessagesResult;
32
+
33
+ export { type FitMessagesOptions, type FitMessagesResult, fitMessages };
@@ -0,0 +1,33 @@
1
+ import { TiktokenModel } from 'tiktoken';
2
+ import { ChatCompletionMessageParam } from 'openai/resources/chat/completions';
3
+ export { ChatCompletionMessageParam } from 'openai/resources/chat/completions';
4
+
5
+ interface FitMessagesOptions {
6
+ /** Token budget for the conversation. */
7
+ budget: number;
8
+ /** Tokens to reserve for the model's response. Defaults to 0. */
9
+ reserve?: number;
10
+ /**
11
+ * OpenAI model name — used to select the correct tiktoken encoding.
12
+ * Defaults to gpt-4o.
13
+ */
14
+ model?: TiktokenModel;
15
+ }
16
+ interface FitMessagesResult {
17
+ /** Messages that fit, in original order. Pass directly to the OpenAI SDK. */
18
+ messages: ChatCompletionMessageParam[];
19
+ tokensUsed: number;
20
+ tokensRemaining: number;
21
+ /** Messages that were dropped. */
22
+ dropped: ChatCompletionMessageParam[];
23
+ }
24
+ /**
25
+ * Fit an array of OpenAI chat messages into a token budget.
26
+ *
27
+ * System messages are always highest priority. Other messages are prioritised
28
+ * by recency — newer messages are kept over older ones when the budget is tight.
29
+ * The result is ready to pass directly to client.chat.completions.create.
30
+ */
31
+ declare function fitMessages(messages: ChatCompletionMessageParam[], options: FitMessagesOptions): FitMessagesResult;
32
+
33
+ export { type FitMessagesOptions, type FitMessagesResult, fitMessages };
package/dist/index.js ADDED
@@ -0,0 +1,40 @@
1
+ // src/index.ts
2
+ import { encoding_for_model, get_encoding } from "tiktoken";
3
+ import { fit } from "@jeremysnr/snug";
4
+ function messageToText(msg) {
5
+ if (typeof msg.content === "string") return msg.content;
6
+ if (Array.isArray(msg.content)) {
7
+ return msg.content.map((part) => "text" in part ? part.text : "").join("");
8
+ }
9
+ return "";
10
+ }
11
+ function fitMessages(messages, options) {
12
+ const enc = options.model ? encoding_for_model(options.model) : get_encoding("cl100k_base");
13
+ const MESSAGE_OVERHEAD = 4;
14
+ try {
15
+ const tokenizer = (text) => enc.encode(text).length;
16
+ const items = messages.map((msg, i) => ({
17
+ id: String(i),
18
+ content: msg,
19
+ tokens: tokenizer(messageToText(msg)) + MESSAGE_OVERHEAD,
20
+ // system = highest priority; others prioritised by recency
21
+ priority: msg.role === "system" ? 1e4 : i
22
+ }));
23
+ const result = fit(items, {
24
+ budget: options.budget,
25
+ reserve: options.reserve,
26
+ suppressApproximationWarning: true
27
+ });
28
+ return {
29
+ messages: result.included.map((i) => i.content),
30
+ tokensUsed: result.tokensUsed,
31
+ tokensRemaining: result.tokensRemaining,
32
+ dropped: result.excluded.map((i) => i.content)
33
+ };
34
+ } finally {
35
+ enc.free();
36
+ }
37
+ }
38
+ export {
39
+ fitMessages
40
+ };
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@jeremysnr/snug-openai",
3
+ "version": "0.1.0",
4
+ "description": "snug for the OpenAI SDK. Fit chat messages into a token budget, ready to pass to client.chat.completions.create.",
5
+ "keywords": ["llm", "tokens", "context-window", "openai", "gpt"],
6
+ "license": "MIT",
7
+ "author": "Jeremy Smith",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/JeremySNR/snug-openai.git"
11
+ },
12
+ "type": "module",
13
+ "main": "./dist/index.cjs",
14
+ "module": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "require": "./dist/index.cjs"
21
+ }
22
+ },
23
+ "files": ["dist"],
24
+ "scripts": {
25
+ "build": "tsup",
26
+ "test": "node node_modules/jest/bin/jest.js",
27
+ "prepublishOnly": "npm run build"
28
+ },
29
+ "dependencies": {
30
+ "@jeremysnr/snug": "^0.1.0",
31
+ "tiktoken": "^1.0.22"
32
+ },
33
+ "peerDependencies": {
34
+ "openai": ">=4.0.0"
35
+ },
36
+ "devDependencies": {
37
+ "@types/jest": "^29.5.12",
38
+ "@types/node": "^20.14.0",
39
+ "jest": "^29.7.0",
40
+ "openai": "^4.0.0",
41
+ "ts-jest": "^29.1.5",
42
+ "tsup": "^8.5.1",
43
+ "typescript": "^5.5.0"
44
+ }
45
+ }