@jeremysnr/snug-anthropic 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 +9 -0
- package/README.md +61 -0
- package/dist/index.cjs +104 -0
- package/dist/index.d.cts +30 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +79 -0
- package/package.json +45 -0
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,61 @@
|
|
|
1
|
+
# @jeremysnr/snug-anthropic
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@jeremysnr/snug-anthropic)
|
|
4
|
+
[](./LICENSE)
|
|
5
|
+
|
|
6
|
+
Fit Anthropic messages into a token budget. Automatically handles `tool_use`/`tool_result` pairing so you never get a 400 error from an orphaned tool message.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { fitMessages } from '@jeremysnr/snug-anthropic';
|
|
10
|
+
|
|
11
|
+
const { messages } = fitMessages(conversationHistory, {
|
|
12
|
+
budget: 100000,
|
|
13
|
+
reserve: 4096,
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
const response = await client.messages.create({
|
|
17
|
+
model: 'claude-opus-4-5',
|
|
18
|
+
max_tokens: 4096,
|
|
19
|
+
messages,
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Messages are prioritised by recency — older messages are dropped first. `tool_use` and `tool_result` pairs are kept together automatically; if one half doesn't fit, both are dropped.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
npm install @jeremysnr/snug-anthropic
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`@anthropic-ai/sdk` must be installed as a peer dependency.
|
|
32
|
+
|
|
33
|
+
## API
|
|
34
|
+
|
|
35
|
+
### `fitMessages(messages, options)`
|
|
36
|
+
|
|
37
|
+
| Option | Type | Default | Description |
|
|
38
|
+
|--------|------|---------|-------------|
|
|
39
|
+
| `budget` | `number` | — | Token limit |
|
|
40
|
+
| `reserve` | `number` | `0` | Tokens to hold back for the model's reply |
|
|
41
|
+
|
|
42
|
+
**Returns**
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
{
|
|
46
|
+
messages: MessageParam[]; // ready to send
|
|
47
|
+
dropped: MessageParam[]; // what didn't fit
|
|
48
|
+
tokensUsed: number;
|
|
49
|
+
tokensRemaining: number;
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Part of the snug ecosystem
|
|
54
|
+
|
|
55
|
+
- [`@jeremysnr/snug`](https://github.com/JeremySNR/snug) — zero-dependency core primitive
|
|
56
|
+
- [`@jeremysnr/snug-tiktoken`](https://github.com/JeremySNR/snug-tiktoken) — snug with tiktoken, model-agnostic
|
|
57
|
+
- [`@jeremysnr/snug-openai`](https://github.com/JeremySNR/snug-openai) — snug for the OpenAI SDK
|
|
58
|
+
|
|
59
|
+
## Licence
|
|
60
|
+
|
|
61
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
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((block) => {
|
|
32
|
+
if (block["type"] === "text") return String(block["text"] ?? "");
|
|
33
|
+
if (block["type"] === "tool_use") return JSON.stringify(block["input"] ?? "");
|
|
34
|
+
if (block["type"] === "tool_result") {
|
|
35
|
+
const c = block["content"];
|
|
36
|
+
if (typeof c === "string") return c;
|
|
37
|
+
if (Array.isArray(c)) return c.map((b) => String(b["text"] ?? "")).join("");
|
|
38
|
+
}
|
|
39
|
+
return "";
|
|
40
|
+
}).join("");
|
|
41
|
+
}
|
|
42
|
+
return "";
|
|
43
|
+
}
|
|
44
|
+
function getToolUseId(msg) {
|
|
45
|
+
if (msg.role !== "assistant" || !Array.isArray(msg.content)) return void 0;
|
|
46
|
+
const block = msg.content.find((b) => b["type"] === "tool_use");
|
|
47
|
+
return block ? String(block["id"] ?? "") : void 0;
|
|
48
|
+
}
|
|
49
|
+
function getToolResultId(msg) {
|
|
50
|
+
if (msg.role !== "user" || !Array.isArray(msg.content)) return void 0;
|
|
51
|
+
const block = msg.content.find((b) => b["type"] === "tool_result");
|
|
52
|
+
return block ? String(block["tool_use_id"] ?? "") : void 0;
|
|
53
|
+
}
|
|
54
|
+
function fitMessages(messages, options) {
|
|
55
|
+
const enc = (0, import_tiktoken.get_encoding)("cl100k_base");
|
|
56
|
+
const MESSAGE_OVERHEAD = 4;
|
|
57
|
+
try {
|
|
58
|
+
const tokenizer = (text) => enc.encode(text).length;
|
|
59
|
+
const toolUseIndex = /* @__PURE__ */ new Map();
|
|
60
|
+
for (let i = 0; i < messages.length; i++) {
|
|
61
|
+
const id = getToolUseId(messages[i]);
|
|
62
|
+
if (id) toolUseIndex.set(id, i);
|
|
63
|
+
}
|
|
64
|
+
const items = messages.map((msg, i) => {
|
|
65
|
+
const toolResultId = getToolResultId(msg);
|
|
66
|
+
const pairedUseIndex = toolResultId ? toolUseIndex.get(toolResultId) : void 0;
|
|
67
|
+
return {
|
|
68
|
+
id: String(i),
|
|
69
|
+
content: msg,
|
|
70
|
+
tokens: tokenizer(messageToText(msg)) + MESSAGE_OVERHEAD,
|
|
71
|
+
priority: i,
|
|
72
|
+
pairId: toolResultId ? `tool-pair-${toolResultId}` : void 0,
|
|
73
|
+
_pairedUseIndex: pairedUseIndex
|
|
74
|
+
};
|
|
75
|
+
});
|
|
76
|
+
for (const item of items) {
|
|
77
|
+
if (item._pairedUseIndex !== void 0) {
|
|
78
|
+
const useItem = items[item._pairedUseIndex];
|
|
79
|
+
useItem.pairId = item.pairId;
|
|
80
|
+
useItem.priority = item.priority;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const result = (0, import_snug.fit)(
|
|
84
|
+
items.map(({ _pairedUseIndex: _, ...rest }) => rest),
|
|
85
|
+
{
|
|
86
|
+
budget: options.budget,
|
|
87
|
+
reserve: options.reserve,
|
|
88
|
+
suppressApproximationWarning: true
|
|
89
|
+
}
|
|
90
|
+
);
|
|
91
|
+
return {
|
|
92
|
+
messages: result.included.map((i) => i.content),
|
|
93
|
+
tokensUsed: result.tokensUsed,
|
|
94
|
+
tokensRemaining: result.tokensRemaining,
|
|
95
|
+
dropped: result.excluded.map((i) => i.content)
|
|
96
|
+
};
|
|
97
|
+
} finally {
|
|
98
|
+
enc.free();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
102
|
+
0 && (module.exports = {
|
|
103
|
+
fitMessages
|
|
104
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { MessageParam } from '@anthropic-ai/sdk/resources/messages';
|
|
2
|
+
export { MessageParam } from '@anthropic-ai/sdk/resources/messages';
|
|
3
|
+
|
|
4
|
+
interface FitMessagesOptions {
|
|
5
|
+
/** Token budget for the conversation. */
|
|
6
|
+
budget: number;
|
|
7
|
+
/** Tokens to reserve for the model's response. Defaults to 0. */
|
|
8
|
+
reserve?: number;
|
|
9
|
+
}
|
|
10
|
+
interface FitMessagesResult {
|
|
11
|
+
/** Messages that fit, in original order. Pass directly to the Anthropic SDK. */
|
|
12
|
+
messages: MessageParam[];
|
|
13
|
+
tokensUsed: number;
|
|
14
|
+
tokensRemaining: number;
|
|
15
|
+
/** Messages that were dropped. */
|
|
16
|
+
dropped: MessageParam[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Fit an array of Anthropic messages into a token budget.
|
|
20
|
+
*
|
|
21
|
+
* tool_use and tool_result message pairs are automatically linked — if one
|
|
22
|
+
* half doesn't fit, both are dropped, preventing the 400 errors caused by
|
|
23
|
+
* unpaired tool messages.
|
|
24
|
+
*
|
|
25
|
+
* Messages are prioritised by recency. The result is ready to pass directly
|
|
26
|
+
* to client.messages.create.
|
|
27
|
+
*/
|
|
28
|
+
declare function fitMessages(messages: MessageParam[], options: FitMessagesOptions): FitMessagesResult;
|
|
29
|
+
|
|
30
|
+
export { type FitMessagesOptions, type FitMessagesResult, fitMessages };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { MessageParam } from '@anthropic-ai/sdk/resources/messages';
|
|
2
|
+
export { MessageParam } from '@anthropic-ai/sdk/resources/messages';
|
|
3
|
+
|
|
4
|
+
interface FitMessagesOptions {
|
|
5
|
+
/** Token budget for the conversation. */
|
|
6
|
+
budget: number;
|
|
7
|
+
/** Tokens to reserve for the model's response. Defaults to 0. */
|
|
8
|
+
reserve?: number;
|
|
9
|
+
}
|
|
10
|
+
interface FitMessagesResult {
|
|
11
|
+
/** Messages that fit, in original order. Pass directly to the Anthropic SDK. */
|
|
12
|
+
messages: MessageParam[];
|
|
13
|
+
tokensUsed: number;
|
|
14
|
+
tokensRemaining: number;
|
|
15
|
+
/** Messages that were dropped. */
|
|
16
|
+
dropped: MessageParam[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Fit an array of Anthropic messages into a token budget.
|
|
20
|
+
*
|
|
21
|
+
* tool_use and tool_result message pairs are automatically linked — if one
|
|
22
|
+
* half doesn't fit, both are dropped, preventing the 400 errors caused by
|
|
23
|
+
* unpaired tool messages.
|
|
24
|
+
*
|
|
25
|
+
* Messages are prioritised by recency. The result is ready to pass directly
|
|
26
|
+
* to client.messages.create.
|
|
27
|
+
*/
|
|
28
|
+
declare function fitMessages(messages: MessageParam[], options: FitMessagesOptions): FitMessagesResult;
|
|
29
|
+
|
|
30
|
+
export { type FitMessagesOptions, type FitMessagesResult, fitMessages };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { 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((block) => {
|
|
8
|
+
if (block["type"] === "text") return String(block["text"] ?? "");
|
|
9
|
+
if (block["type"] === "tool_use") return JSON.stringify(block["input"] ?? "");
|
|
10
|
+
if (block["type"] === "tool_result") {
|
|
11
|
+
const c = block["content"];
|
|
12
|
+
if (typeof c === "string") return c;
|
|
13
|
+
if (Array.isArray(c)) return c.map((b) => String(b["text"] ?? "")).join("");
|
|
14
|
+
}
|
|
15
|
+
return "";
|
|
16
|
+
}).join("");
|
|
17
|
+
}
|
|
18
|
+
return "";
|
|
19
|
+
}
|
|
20
|
+
function getToolUseId(msg) {
|
|
21
|
+
if (msg.role !== "assistant" || !Array.isArray(msg.content)) return void 0;
|
|
22
|
+
const block = msg.content.find((b) => b["type"] === "tool_use");
|
|
23
|
+
return block ? String(block["id"] ?? "") : void 0;
|
|
24
|
+
}
|
|
25
|
+
function getToolResultId(msg) {
|
|
26
|
+
if (msg.role !== "user" || !Array.isArray(msg.content)) return void 0;
|
|
27
|
+
const block = msg.content.find((b) => b["type"] === "tool_result");
|
|
28
|
+
return block ? String(block["tool_use_id"] ?? "") : void 0;
|
|
29
|
+
}
|
|
30
|
+
function fitMessages(messages, options) {
|
|
31
|
+
const enc = get_encoding("cl100k_base");
|
|
32
|
+
const MESSAGE_OVERHEAD = 4;
|
|
33
|
+
try {
|
|
34
|
+
const tokenizer = (text) => enc.encode(text).length;
|
|
35
|
+
const toolUseIndex = /* @__PURE__ */ new Map();
|
|
36
|
+
for (let i = 0; i < messages.length; i++) {
|
|
37
|
+
const id = getToolUseId(messages[i]);
|
|
38
|
+
if (id) toolUseIndex.set(id, i);
|
|
39
|
+
}
|
|
40
|
+
const items = messages.map((msg, i) => {
|
|
41
|
+
const toolResultId = getToolResultId(msg);
|
|
42
|
+
const pairedUseIndex = toolResultId ? toolUseIndex.get(toolResultId) : void 0;
|
|
43
|
+
return {
|
|
44
|
+
id: String(i),
|
|
45
|
+
content: msg,
|
|
46
|
+
tokens: tokenizer(messageToText(msg)) + MESSAGE_OVERHEAD,
|
|
47
|
+
priority: i,
|
|
48
|
+
pairId: toolResultId ? `tool-pair-${toolResultId}` : void 0,
|
|
49
|
+
_pairedUseIndex: pairedUseIndex
|
|
50
|
+
};
|
|
51
|
+
});
|
|
52
|
+
for (const item of items) {
|
|
53
|
+
if (item._pairedUseIndex !== void 0) {
|
|
54
|
+
const useItem = items[item._pairedUseIndex];
|
|
55
|
+
useItem.pairId = item.pairId;
|
|
56
|
+
useItem.priority = item.priority;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const result = fit(
|
|
60
|
+
items.map(({ _pairedUseIndex: _, ...rest }) => rest),
|
|
61
|
+
{
|
|
62
|
+
budget: options.budget,
|
|
63
|
+
reserve: options.reserve,
|
|
64
|
+
suppressApproximationWarning: true
|
|
65
|
+
}
|
|
66
|
+
);
|
|
67
|
+
return {
|
|
68
|
+
messages: result.included.map((i) => i.content),
|
|
69
|
+
tokensUsed: result.tokensUsed,
|
|
70
|
+
tokensRemaining: result.tokensRemaining,
|
|
71
|
+
dropped: result.excluded.map((i) => i.content)
|
|
72
|
+
};
|
|
73
|
+
} finally {
|
|
74
|
+
enc.free();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
export {
|
|
78
|
+
fitMessages
|
|
79
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@jeremysnr/snug-anthropic",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "snug for the Anthropic SDK. Fit messages into a token budget with automatic tool_use/tool_result pair handling.",
|
|
5
|
+
"keywords": ["llm", "tokens", "context-window", "anthropic", "claude"],
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Jeremy Smith",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/JeremySNR/snug-anthropic.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
|
+
"@anthropic-ai/sdk": ">=0.20.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@anthropic-ai/sdk": "^0.20.0",
|
|
38
|
+
"@types/jest": "^29.5.12",
|
|
39
|
+
"@types/node": "^20.14.0",
|
|
40
|
+
"jest": "^29.7.0",
|
|
41
|
+
"ts-jest": "^29.1.5",
|
|
42
|
+
"tsup": "^8.5.1",
|
|
43
|
+
"typescript": "^5.5.0"
|
|
44
|
+
}
|
|
45
|
+
}
|