Skip to content

Commit 532e191

Browse files
committed
clamp stream max tokens to context window
1 parent 4712bea commit 532e191

1 file changed

Lines changed: 168 additions & 0 deletions

File tree

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
import type { StreamFn } from "@earendil-works/pi-agent-core";
2+
import type { ProviderRuntimeModel } from "../../plugins/provider-runtime-model.types.js";
3+
import { log } from "./logger.js";
4+
5+
const STREAM_INPUT_CHARS_PER_TOKEN_ESTIMATE = 4;
6+
const STREAM_INPUT_TOKEN_SAFETY_MARGIN = 1.2;
7+
const MIN_CONTEXT_REMAINING_OUTPUT_TOKENS = 1;
8+
9+
type StreamContext = Parameters<StreamFn>[1];
10+
type StreamModel = Parameters<StreamFn>[0];
11+
type ContextWindowLikeModel = {
12+
contextTokens?: unknown;
13+
contextWindow?: unknown;
14+
maxTokens?: unknown;
15+
};
16+
17+
function normalizePositiveInt(value: unknown): number | undefined {
18+
if (typeof value !== "number" || !Number.isFinite(value)) {
19+
return undefined;
20+
}
21+
const int = Math.floor(value);
22+
return int > 0 ? int : undefined;
23+
}
24+
25+
function estimateSerializableChars(value: unknown): number {
26+
if (typeof value === "string") {
27+
return value.length;
28+
}
29+
if (value === undefined || value === null) {
30+
return 0;
31+
}
32+
try {
33+
const serialized = JSON.stringify(value);
34+
return typeof serialized === "string" ? serialized.length : 0;
35+
} catch {
36+
return 256;
37+
}
38+
}
39+
40+
function estimateContentBlockChars(block: unknown): number {
41+
if (!block || typeof block !== "object") {
42+
return estimateSerializableChars(block);
43+
}
44+
const typed = block as {
45+
type?: unknown;
46+
text?: unknown;
47+
thinking?: unknown;
48+
name?: unknown;
49+
arguments?: unknown;
50+
};
51+
if (typed.type === "text" && typeof typed.text === "string") {
52+
return typed.text.length;
53+
}
54+
if (typed.type === "thinking" && typeof typed.thinking === "string") {
55+
return typed.thinking.length;
56+
}
57+
if (typed.type === "toolCall") {
58+
return (
59+
(typeof typed.name === "string" ? typed.name.length : 0) +
60+
estimateSerializableChars(typed.arguments)
61+
);
62+
}
63+
if (typed.type === "image") {
64+
return 8_000;
65+
}
66+
return estimateSerializableChars(block);
67+
}
68+
69+
function estimateContentChars(content: unknown): number {
70+
if (typeof content === "string") {
71+
return content.length;
72+
}
73+
if (!Array.isArray(content)) {
74+
return estimateSerializableChars(content);
75+
}
76+
return content.reduce((sum, block) => sum + estimateContentBlockChars(block), 0);
77+
}
78+
79+
function estimateMessageChars(message: unknown): number {
80+
if (!message || typeof message !== "object") {
81+
return 0;
82+
}
83+
const record = message as { content?: unknown };
84+
const contentChars = estimateContentChars(record.content);
85+
return contentChars > 0 ? contentChars : estimateSerializableChars(message);
86+
}
87+
88+
function estimateStreamInputTokens(context: StreamContext): number {
89+
const ctx = context as {
90+
messages?: unknown;
91+
systemPrompt?: unknown;
92+
tools?: unknown;
93+
};
94+
let chars = typeof ctx.systemPrompt === "string" ? ctx.systemPrompt.length : 0;
95+
if (Array.isArray(ctx.messages)) {
96+
chars += ctx.messages.reduce((sum, message) => sum + estimateMessageChars(message), 0);
97+
}
98+
if (Array.isArray(ctx.tools) && ctx.tools.length > 0) {
99+
chars += estimateSerializableChars(ctx.tools);
100+
}
101+
return Math.max(
102+
0,
103+
Math.ceil((chars / STREAM_INPUT_CHARS_PER_TOKEN_ESTIMATE) * STREAM_INPUT_TOKEN_SAFETY_MARGIN),
104+
);
105+
}
106+
107+
function resolveContextWindowTokens(
108+
callModel: StreamModel,
109+
configuredModel?: ProviderRuntimeModel,
110+
): number | undefined {
111+
const callModelRecord = callModel as ContextWindowLikeModel;
112+
return (
113+
normalizePositiveInt(callModelRecord.contextTokens) ??
114+
normalizePositiveInt(configuredModel?.contextTokens) ??
115+
normalizePositiveInt(callModelRecord.contextWindow) ??
116+
normalizePositiveInt(configuredModel?.contextWindow)
117+
);
118+
}
119+
120+
function resolveModelMaxTokens(
121+
callModel: StreamModel,
122+
configuredModel?: ProviderRuntimeModel,
123+
): number | undefined {
124+
const callModelRecord = callModel as ContextWindowLikeModel;
125+
return (
126+
normalizePositiveInt(callModelRecord.maxTokens) ??
127+
normalizePositiveInt(configuredModel?.maxTokens)
128+
);
129+
}
130+
131+
export function clampMaxTokensToContextWindow(params: {
132+
maxTokens: number | undefined;
133+
callModel: StreamModel;
134+
configuredModel?: ProviderRuntimeModel;
135+
context: StreamContext;
136+
}): number | undefined {
137+
if (params.maxTokens === undefined || params.maxTokens <= 0) {
138+
return params.maxTokens;
139+
}
140+
const contextWindowTokens = resolveContextWindowTokens(params.callModel, params.configuredModel);
141+
if (contextWindowTokens === undefined) {
142+
return params.maxTokens;
143+
}
144+
const inputTokens = estimateStreamInputTokens(params.context);
145+
const remainingTokens = contextWindowTokens - inputTokens;
146+
if (remainingTokens >= params.maxTokens) {
147+
return params.maxTokens;
148+
}
149+
const clamped = Math.max(MIN_CONTEXT_REMAINING_OUTPUT_TOKENS, remainingTokens);
150+
log.debug(
151+
`clamping maxTokens to remaining context window: requested=${params.maxTokens} ` +
152+
`clamped=${clamped} inputTokens=${inputTokens} contextWindow=${contextWindowTokens}`,
153+
);
154+
return clamped;
155+
}
156+
157+
export function clampModelMaxTokensToContextWindow(params: {
158+
callModel: StreamModel;
159+
configuredModel?: ProviderRuntimeModel;
160+
context: StreamContext;
161+
}): number | undefined {
162+
return clampMaxTokensToContextWindow({
163+
maxTokens: resolveModelMaxTokens(params.callModel, params.configuredModel),
164+
callModel: params.callModel,
165+
configuredModel: params.configuredModel,
166+
context: params.context,
167+
});
168+
}

0 commit comments

Comments
 (0)