billion-context 0.1.75-pr.487.306 → 0.1.75-pr.489.309
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/dist/index.js +90 -12
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -50705,7 +50705,7 @@ function summaryPayload(protocol, model, system, content) {
|
|
|
50705
50705
|
if (protocol === "openai") {
|
|
50706
50706
|
return { model, max_tokens: MAX_SUMMARY_OUTPUT_TOKENS, messages: [{ role: "system", content: system }, { role: "user", content }], stream: false };
|
|
50707
50707
|
}
|
|
50708
|
-
return { model, max_output_tokens: MAX_SUMMARY_OUTPUT_TOKENS, instructions: system, input: [{ role: "user", content }], stream: false };
|
|
50708
|
+
return { model, max_output_tokens: MAX_SUMMARY_OUTPUT_TOKENS, instructions: system, input: [{ role: "user", content }], stream: false, store: false };
|
|
50709
50709
|
}
|
|
50710
50710
|
function extractSummaryText(protocol, json) {
|
|
50711
50711
|
if (protocol === "anthropic") {
|
|
@@ -50771,7 +50771,7 @@ TASK: The conversation segment below (messages ${startRef}\u2013${endRef}) must
|
|
|
50771
50771
|
var ABORTED_FAILURE = { kind: "aborted", detail: "the client disconnected during preflight compression" };
|
|
50772
50772
|
async function preflightCompress(deps, messages) {
|
|
50773
50773
|
const limit = deps.config.modelContextLimit;
|
|
50774
|
-
const result = { compressedRanges: 0, savedTokens: 0, payloadEstimate: estimateCoreMessages(messages) };
|
|
50774
|
+
const result = { compressedRanges: 0, savedTokens: 0, payloadEstimate: estimateCoreMessages(messages) + (deps.imageFloor ?? 0) };
|
|
50775
50775
|
if (limit <= 0) return result;
|
|
50776
50776
|
const budget = Math.max(MIN_CHUNK_TOKENS, Math.floor(limit * CHUNK_FRACTION));
|
|
50777
50777
|
const minChars = deps.config.compress.minCompressRange;
|
|
@@ -50791,8 +50791,8 @@ async function preflightCompress(deps, messages) {
|
|
|
50791
50791
|
renderTags: "text-only"
|
|
50792
50792
|
});
|
|
50793
50793
|
deps.session.state = turn.state;
|
|
50794
|
-
currentTokens = Math.max(deps.session.stats.lastInputTokens, estimateCoreMessages(turn.messages));
|
|
50795
|
-
result.payloadEstimate = estimateCoreMessages(turn.messages);
|
|
50794
|
+
currentTokens = Math.max(deps.session.stats.lastInputTokens, estimateCoreMessages(turn.messages) + (deps.imageFloor ?? 0));
|
|
50795
|
+
result.payloadEstimate = estimateCoreMessages(turn.messages) + (deps.imageFloor ?? 0);
|
|
50796
50796
|
if (startTokens < 0) startTokens = currentTokens;
|
|
50797
50797
|
if (currentTokens < limit) break;
|
|
50798
50798
|
const ranges = viableRanges(turn.nudge?.compressibleRanges ?? []);
|
|
@@ -50878,6 +50878,78 @@ async function preflightCompress(deps, messages) {
|
|
|
50878
50878
|
return result;
|
|
50879
50879
|
}
|
|
50880
50880
|
|
|
50881
|
+
// src/image-tokens.ts
|
|
50882
|
+
var REMOTE_IMAGE_TOKENS = 4096;
|
|
50883
|
+
function imageTokenCap() {
|
|
50884
|
+
const v2 = Number(process.env.BILI_IMAGE_TOKEN_CAP ?? "");
|
|
50885
|
+
return Number.isInteger(v2) && v2 > 0 ? v2 : 0;
|
|
50886
|
+
}
|
|
50887
|
+
function applyCap(cost) {
|
|
50888
|
+
const cap = imageTokenCap();
|
|
50889
|
+
return cap > 0 ? Math.min(cost, cap) : cost;
|
|
50890
|
+
}
|
|
50891
|
+
function costForUrl(url) {
|
|
50892
|
+
if (url.startsWith("data:")) {
|
|
50893
|
+
const i = url.indexOf("base64,");
|
|
50894
|
+
if (i >= 0) return applyCap(Math.ceil((url.length - i - "base64,".length) / 4));
|
|
50895
|
+
}
|
|
50896
|
+
return applyCap(REMOTE_IMAGE_TOKENS);
|
|
50897
|
+
}
|
|
50898
|
+
function isObj(v2) {
|
|
50899
|
+
return typeof v2 === "object" && v2 !== null;
|
|
50900
|
+
}
|
|
50901
|
+
function urlOf(v2) {
|
|
50902
|
+
if (typeof v2 === "string") return v2;
|
|
50903
|
+
if (isObj(v2) && typeof v2.url === "string") return v2.url;
|
|
50904
|
+
return void 0;
|
|
50905
|
+
}
|
|
50906
|
+
function imageTokensInParsedBody(protocol, body) {
|
|
50907
|
+
if (!isObj(body)) return 0;
|
|
50908
|
+
let total = 0;
|
|
50909
|
+
if (protocol === "responses") {
|
|
50910
|
+
const input = body.input;
|
|
50911
|
+
if (!Array.isArray(input)) return 0;
|
|
50912
|
+
for (const item of input) {
|
|
50913
|
+
if (!isObj(item) || !Array.isArray(item.content)) continue;
|
|
50914
|
+
for (const part of item.content) {
|
|
50915
|
+
if (!isObj(part) || part.type !== "input_image") continue;
|
|
50916
|
+
const url = urlOf(part.image_url);
|
|
50917
|
+
if (url) total += costForUrl(url);
|
|
50918
|
+
}
|
|
50919
|
+
}
|
|
50920
|
+
return total;
|
|
50921
|
+
}
|
|
50922
|
+
const messages = body.messages;
|
|
50923
|
+
if (!Array.isArray(messages)) return 0;
|
|
50924
|
+
for (const m2 of messages) {
|
|
50925
|
+
if (!isObj(m2) || !Array.isArray(m2.content)) continue;
|
|
50926
|
+
for (const part of m2.content) {
|
|
50927
|
+
if (!isObj(part)) continue;
|
|
50928
|
+
if (protocol === "openai") {
|
|
50929
|
+
if (part.type !== "image_url") continue;
|
|
50930
|
+
const url = urlOf(part.image_url);
|
|
50931
|
+
if (url) total += costForUrl(url);
|
|
50932
|
+
} else {
|
|
50933
|
+
if (part.type !== "image") continue;
|
|
50934
|
+
const src = part.source;
|
|
50935
|
+
if (isObj(src) && src.type === "base64" && typeof src.data === "string") total += applyCap(Math.ceil(src.data.length / 4));
|
|
50936
|
+
else if (isObj(src) && src.type === "url" && typeof src.url === "string") total += costForUrl(src.url);
|
|
50937
|
+
}
|
|
50938
|
+
}
|
|
50939
|
+
}
|
|
50940
|
+
return total;
|
|
50941
|
+
}
|
|
50942
|
+
function imageTokensInRawBody(protocol, raw) {
|
|
50943
|
+
const s3 = typeof raw === "string" ? raw : raw.toString("utf8");
|
|
50944
|
+
const probe = protocol === "responses" ? s3.includes("input_image") : protocol === "openai" ? s3.includes("image_url") : s3.includes('"type":"image"') || s3.includes('"type": "image"');
|
|
50945
|
+
if (!probe) return 0;
|
|
50946
|
+
try {
|
|
50947
|
+
return imageTokensInParsedBody(protocol, JSON.parse(s3));
|
|
50948
|
+
} catch {
|
|
50949
|
+
return 0;
|
|
50950
|
+
}
|
|
50951
|
+
}
|
|
50952
|
+
|
|
50881
50953
|
// src/web/index.ts
|
|
50882
50954
|
import { readFileSync as readFileSync3 } from "fs";
|
|
50883
50955
|
import { dirname as dirname4, join as join3 } from "path";
|
|
@@ -57235,7 +57307,7 @@ function emergencyNudge(nudge, escalationPct = EMERGENCY_NUDGE_ESCALATION_PCT) {
|
|
|
57235
57307
|
function clampOutgoingOutput(rebuilt, field, ctx, sessionId, log2) {
|
|
57236
57308
|
const raw = rebuilt[field];
|
|
57237
57309
|
if (typeof raw !== "number") return;
|
|
57238
|
-
const inputEstimate = estimateInputTokens(ctx.processedMessages, ctx.systemText, ctx.tools, ctx.lastInputTokens);
|
|
57310
|
+
const inputEstimate = estimateInputTokens(ctx.processedMessages, ctx.systemText, ctx.tools, ctx.lastInputTokens) + ctx.imageTokens;
|
|
57239
57311
|
const capped = clampOutputBudget(raw, inputEstimate, ctx.nativeWindow);
|
|
57240
57312
|
if (capped !== void 0) {
|
|
57241
57313
|
rebuilt[field] = capped;
|
|
@@ -57300,7 +57372,7 @@ function prepareOpenai(parsed, req, opts, core, config, prompts, log2, session,
|
|
|
57300
57372
|
processedMessages = [];
|
|
57301
57373
|
}
|
|
57302
57374
|
const rebuilt = { ...parsed, messages: rebuiltMessages, tools: toolsOut };
|
|
57303
|
-
clampOutgoingOutput(rebuilt, typeof parsed.max_completion_tokens === "number" ? "max_completion_tokens" : "max_tokens", { systemText: openaiSystemText, tools: toolsOut, processedMessages, lastInputTokens: session.stats.lastInputTokens, nativeWindow }, sessionId, log2);
|
|
57375
|
+
clampOutgoingOutput(rebuilt, typeof parsed.max_completion_tokens === "number" ? "max_completion_tokens" : "max_tokens", { systemText: openaiSystemText, tools: toolsOut, processedMessages, lastInputTokens: session.stats.lastInputTokens, nativeWindow, imageTokens: imageTokensInParsedBody("openai", rebuilt) }, sessionId, log2);
|
|
57304
57376
|
delete rebuilt.prompt_cache_retention;
|
|
57305
57377
|
if (stream2 && rebuilt.stream_options === void 0) {
|
|
57306
57378
|
rebuilt.stream_options = { include_usage: true };
|
|
@@ -57418,7 +57490,7 @@ function prepareResponses(parsed, req, opts, core, config, prompts, log2, sessio
|
|
|
57418
57490
|
}
|
|
57419
57491
|
const rebuilt = { ...parsed, input: rebuiltInput, tools: toolsOut };
|
|
57420
57492
|
if (!isCompactionTrigger) {
|
|
57421
|
-
clampOutgoingOutput(rebuilt, "max_output_tokens", { systemText: (responsesProjection?.systemParts ?? []).join("\n"), tools: toolsOut, processedMessages, lastInputTokens: session.stats.lastInputTokens, nativeWindow }, sessionId, log2);
|
|
57493
|
+
clampOutgoingOutput(rebuilt, "max_output_tokens", { systemText: (responsesProjection?.systemParts ?? []).join("\n"), tools: toolsOut, processedMessages, lastInputTokens: session.stats.lastInputTokens, nativeWindow, imageTokens: imageTokensInParsedBody("responses", rebuilt) }, sessionId, log2);
|
|
57422
57494
|
}
|
|
57423
57495
|
const promptCacheKey = resolvePromptCacheKey(
|
|
57424
57496
|
rebuilt.prompt_cache_key,
|
|
@@ -57643,11 +57715,13 @@ function isPreflightFailFast(outcome) {
|
|
|
57643
57715
|
async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, core, config, model, route, affinity, log2, instanceId) {
|
|
57644
57716
|
const session = prepared.session;
|
|
57645
57717
|
const limit = config.modelContextLimit;
|
|
57646
|
-
const
|
|
57718
|
+
const imageTokens = imageTokensInRawBody(prepared.protocol, prepared.body);
|
|
57719
|
+
const payloadEstimate = estimateCoreMessages(prepared.processedMessages) + imageTokens;
|
|
57647
57720
|
const tokenCount = Math.max(session.stats.lastInputTokens, payloadEstimate);
|
|
57648
57721
|
if (limit <= 0 || !model || tokenCount < limit) return prepared;
|
|
57649
57722
|
const failFast = (status2, detail, retryable) => {
|
|
57650
|
-
const
|
|
57723
|
+
const imageNote = imageTokens >= limit ? ` Images alone account for ~${imageTokens} tokens (\u2265 window ${limit}); compression cannot remove them \u2014 shrink or remove the images, or raise the window.` : "";
|
|
57724
|
+
const message = `context ~${tokenCount} tokens exceeds the model window ${limit} (model=${model}) and preflight compression could not bring it under: ${detail}.` + imageNote + ` The over-window payload was NOT forwarded.`;
|
|
57651
57725
|
log2("error", `[${session.id}] preflight fail-fast ${status2} (retryable=${retryable}): ${message}`);
|
|
57652
57726
|
return { failFast: true, status: status2, message, retryable, respond: !res.writableEnded };
|
|
57653
57727
|
};
|
|
@@ -57677,7 +57751,8 @@ async function preflightCompressIfNeeded(prepared, runPrepare, req, res, opts, c
|
|
|
57677
57751
|
model,
|
|
57678
57752
|
proxyUrl,
|
|
57679
57753
|
signal: clientAbort.signal,
|
|
57680
|
-
log: log2
|
|
57754
|
+
log: log2,
|
|
57755
|
+
imageFloor: imageTokens
|
|
57681
57756
|
},
|
|
57682
57757
|
prepared.originalMessages
|
|
57683
57758
|
);
|
|
@@ -57846,9 +57921,12 @@ ${hdrText}
|
|
|
57846
57921
|
const info = inspectContextOverflow(upstream.status, errBody.toString("utf8"));
|
|
57847
57922
|
if (info.isOverflow) {
|
|
57848
57923
|
let reqModel;
|
|
57924
|
+
let rejectedImageTokens = 0;
|
|
57849
57925
|
try {
|
|
57850
57926
|
const rawBody = typeof prepared.body === "string" ? prepared.body : prepared.body.toString("utf8");
|
|
57851
|
-
|
|
57927
|
+
const parsedBody = JSON.parse(rawBody);
|
|
57928
|
+
reqModel = typeof parsedBody.model === "string" ? parsedBody.model : void 0;
|
|
57929
|
+
rejectedImageTokens = imageTokensInParsedBody(prepared.protocol, parsedBody);
|
|
57852
57930
|
} catch {
|
|
57853
57931
|
reqModel = void 0;
|
|
57854
57932
|
}
|
|
@@ -57860,7 +57938,7 @@ ${hdrText}
|
|
|
57860
57938
|
s3.metadata.learnedContextLimits = learnedMap;
|
|
57861
57939
|
log2("warn", `[${s3.id}] upstream context overflow \u2014 learned real window ${info.window} for ${reqModel ?? "(unknown model)"} (was ${prev ?? "unset"}); arming emergency shrink`);
|
|
57862
57940
|
} else {
|
|
57863
|
-
const payloadEstimate = estimateCoreMessages(prepared.processedMessages);
|
|
57941
|
+
const payloadEstimate = estimateCoreMessages(prepared.processedMessages) + rejectedImageTokens;
|
|
57864
57942
|
const prev = (reqModel ? learnedMap[reqModel] : void 0) ?? s3.metadata.learnedContextLimit;
|
|
57865
57943
|
if (payloadEstimate >= 1e3 && (prev === void 0 || payloadEstimate < prev)) {
|
|
57866
57944
|
if (reqModel) learnedMap[reqModel] = payloadEstimate;
|