UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

114 lines (113 loc) • 5.47 kB
import { outputCapReportOf } from "../core/terminal-cause.js"; export const FLOOR_OUTPUT_TOKENS = 3000; const CONTEXT_HEADROOM_TOKENS = 1000; const CONTEXT_OVERFLOW_RE = /^input length and `max_tokens` exceed context limit: (\d+) \+ (\d+) > (\d+)(?!\w|[.,]\d|\s\d|[+\-*/])/; const CONTEXT_OVERFLOW_PREFIX = "input length and `max_tokens` exceed context limit:"; function providerDiagnostic(body) { const trimmed = body.trim(); if (!trimmed.startsWith("{")) return undefined; let parsed; try { parsed = JSON.parse(trimmed); } catch { return undefined; } if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined; const err = parsed.error; if (typeof err !== "object" || err === null || Array.isArray(err)) return undefined; const message = err.message; return typeof message === "string" ? message : undefined; } function reportFrom(diagnostic) { const message = diagnostic.trimStart(); const m = CONTEXT_OVERFLOW_RE.exec(message); if (m === null) return undefined; if (message.slice(m[0].length).includes(CONTEXT_OVERFLOW_PREFIX)) return undefined; const [, rawInput, rawMax, rawLimit] = m; if (rawInput === undefined || rawMax === undefined || rawLimit === undefined) return undefined; const inputTokens = Number.parseInt(rawInput, 10); const maxTokens = Number.parseInt(rawMax, 10); const contextLimit = Number.parseInt(rawLimit, 10); if (!Number.isSafeInteger(inputTokens) || !Number.isSafeInteger(maxTokens) || !Number.isSafeInteger(contextLimit)) { return undefined; } if (inputTokens <= contextLimit - maxTokens) return undefined; return { inputTokens, maxTokens, contextLimit }; } export function parseContextOverflow(status, body) { if (status !== 400) return undefined; const diagnostic = providerDiagnostic(body); return diagnostic === undefined ? undefined : reportFrom(diagnostic); } const REQUESTED_TOKENS_OVERFLOW_RE = /^This model's maximum context length is (\d+) tokens\. However, you requested (\d+) tokens \((\d+) in the messages, (\d+) in the completion\)/; const REQUESTED_TOKENS_OVERFLOW_PREFIX = "This model's maximum context length is "; export function parseRequestedTokensOverflow(status, body) { if (status !== 400) return undefined; const message = providerDiagnostic(body)?.trimStart(); if (message === undefined) return undefined; const m = REQUESTED_TOKENS_OVERFLOW_RE.exec(message); if (m === null || message.slice(m[0].length).includes(REQUESTED_TOKENS_OVERFLOW_PREFIX)) return undefined; const [limit, total, input, output] = [m[1], m[2], m[3], m[4]].map((n) => Number.parseInt(n ?? "", 10)); return contextOverflowReportOf({ inputTokens: input, maxTokens: output, contextLimit: limit }, total); } export function contextOverflowReportOf(v, total) { if (typeof v !== "object" || v === null) return undefined; const { inputTokens, maxTokens, contextLimit } = v; const exact = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0; if (!exact(inputTokens) || !exact(maxTokens) || !exact(contextLimit)) return undefined; if (total !== undefined && (!Number.isSafeInteger(total) || total - inputTokens !== maxTokens)) return undefined; return inputTokens > contextLimit - maxTokens ? { inputTokens, maxTokens, contextLimit } : undefined; } export function outputCapLoweredDetail(from, to) { return `output limit lowered from ${from} to ${to} tokens, retrying`; } export function planOutputCapAdjustment(report, otherCapsInEffect = []) { const available = Math.max(0, report.contextLimit - report.inputTokens - CONTEXT_HEADROOM_TOKENS); if (available < FLOOR_OUTPUT_TOKENS) return { outcome: "below_floor", available }; const current = Math.min(report.maxTokens, ...otherCapsInEffect.filter((c) => c !== undefined)); if (available >= current) return { outcome: "no_progress", available, current }; return { outcome: "adjust", maxOutputTokens: available, current }; } const OUTPUT_CAP_ABOVE_MODEL_MAX_RE = /^max_tokens: (\d+) > (\d+), which is the maximum allowed number of output tokens\b/; function outputCapSentenceOf(status, body) { if (status !== 400) return undefined; const diagnostic = providerDiagnostic(body)?.trimStart(); if (diagnostic === undefined) return undefined; const m = OUTPUT_CAP_ABOVE_MODEL_MAX_RE.exec(diagnostic); if (m === null || diagnostic.slice(m[0].length).includes("which is the maximum allowed number of output tokens")) return undefined; return m; } export const MEDIA_ITEMS_REFUSED_SENTENCE = "Request rejected as unprocessable by the model (too many or oversized images, or unsupported parameters)"; export function mediaItemsRefusalOf(status, body) { if (status !== 400) return false; return providerDiagnostic(body)?.includes(MEDIA_ITEMS_REFUSED_SENTENCE) === true; } export function outputCapRefusalOf(status, body) { const m = outputCapSentenceOf(status, body); if (m === undefined) return undefined; const [, rawRequested, rawAllowed] = m; const report = outputCapReportOf({ requested: Number.parseInt(rawRequested ?? "", 10), allowed: Number.parseInt(rawAllowed ?? "", 10) }); return report !== undefined ? { report } : {}; }