@sema-agent/core
Version:
Stateless, task-oriented AI agent core
277 lines (276 loc) • 13.4 kB
JavaScript
import { headerListEntries, lockHeader, takeHeaderSpellings } from "./request-params.js";
import { describeRejectedValue } from "../core/tool-search-setting.js";
import { capabilityOf } from "./model-capability.js";
import { MIN_THINKING_TOKENS, RESPONSES_APIS, THINKING_LEVELS, budgetCapSkipsThinking, completionsFormatOf, declaredEffortLevels, declaredOffSpelling, judgeThinkingLevel, mintEffortWireValue, offSpelling, reasoningBudgetShare, reasoningRequestCarried, resolveEffort, sanitizeEffortLevels, } from "./reasoning.js";
export function lowestReasoningSeat(model) {
return offSpelling(model).spelled ? "off" : "low";
}
export function engineSeatTier(model, tier) {
return tier !== "off" && capabilityOf(model, "reasoning") === "unknown" ? undefined : tier;
}
const BETA_EFFORT = "effort-2025-11-24";
const BETA_CONTEXT_MANAGEMENT = "context-management-2025-06-27";
const BETA_INTERLEAVED_THINKING = "interleaved-thinking-2025-05-14";
const CAP_BLIND = MIN_THINKING_TOKENS * 2;
function saidOf(tier, wrote) {
if (wrote.tierKey)
return tier;
if (wrote.switched)
return tier === "off" ? "off" : "on";
return "provider_default";
}
function refuseInput(field, sentence) {
const e = new Error(`applyReasoningToRequest: ${sentence}`);
e.code = "config.invalid_argument";
e.detail = { field };
throw e;
}
function refuseBody(field, why, value) {
return refuseInput(field, `${field} ${why} (got ${describeRejectedValue(value)})`);
}
const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
function mergeInto(body, key, members) {
const held = body[key];
if (held !== undefined && !isPlainObject(held))
refuseBody(`body.${key}`, "must be an object when present (the thinking keys are written into it)", held);
body[key] = { ...(held ?? {}), ...members };
}
const isThinkingEdit = (edit) => isPlainObject(edit) && typeof edit.type === "string" && edit.type.startsWith("clear_thinking_");
const OWNED_MEMBERS = {
completions: ["reasoning_effort", "thinking", "reasoning", "enable_thinking", "chat_template_kwargs.enable_thinking"],
responses: ["reasoning.effort"],
messages: ["thinking", "output_config.effort", "context_management.edits"],
};
function refuseOwnedMembers(lane, body) {
for (const path of OWNED_MEMBERS[lane]) {
const [head, member] = path.split(".");
const outer = body[head];
let value = outer;
if (member !== undefined)
value = isPlainObject(outer) ? outer[member] : undefined;
if (path === "context_management.edits")
value = Array.isArray(value) ? value.find(isThinkingEdit) : undefined;
if (value !== undefined)
refuseBody(`body.${path}`, "is written by the applier from the requested tier and may not be supplied in the body", value);
}
}
const wroteNothing = { effort: undefined, switched: false };
function withEffort(body, effort, supportsEffort) {
if (!supportsEffort || effort === undefined)
return wroteNothing;
body.reasoning_effort = effort;
return { effort, switched: false };
}
function switchedWith(body, key, members) {
mergeInto(body, key, members);
return { effort: undefined, switched: true };
}
function putSwitch(body, key, value) {
body[key] = value;
return { effort: undefined, switched: true };
}
const COMPLETIONS_DIALECT = {
openai: {
off: (body, model) => {
const spelling = declaredOffSpelling(model);
return spelling === undefined ? wroteNothing : withEffort(body, spelling, true);
},
on: withEffort,
},
openrouter: {
off: (body) => putSwitch(body, "reasoning", { enabled: false }),
on: (body, effort) => {
putSwitch(body, "reasoning", effort === undefined ? {} : { effort });
return { effort, switched: true };
},
},
deepseek: {
off: (body) => putSwitch(body, "thinking", { type: "disabled" }),
on: (body, effort, supportsEffort) => {
putSwitch(body, "thinking", { type: "enabled" });
return { effort: withEffort(body, effort, supportsEffort).effort, switched: true };
},
},
together: {
off: (body) => putSwitch(body, "reasoning", { enabled: false }),
on: (body, effort, supportsEffort) => {
putSwitch(body, "reasoning", { enabled: true });
return { effort: withEffort(body, effort, supportsEffort).effort, switched: true };
},
},
qwen: { off: (body) => putSwitch(body, "enable_thinking", false), on: (body) => putSwitch(body, "enable_thinking", true) },
zai: { off: (body) => putSwitch(body, "enable_thinking", false), on: (body) => putSwitch(body, "enable_thinking", true) },
"qwen-chat-template": {
off: (body) => switchedWith(body, "chat_template_kwargs", { enable_thinking: false }),
on: (body) => switchedWith(body, "chat_template_kwargs", { enable_thinking: true }),
},
};
function applyCompletions(input, level, body) {
const { model } = input;
const compat = (model.compat ?? {});
const format = completionsFormatOf(compat);
const dialect = COMPLETIONS_DIALECT[format];
let tier = "off";
let wrote = wroteNothing;
if (level === "off") {
if (offSpelling(model, input.api).spelled)
wrote = dialect.off(body, model);
}
else if (reasoningRequestCarried(model, level, input.withheld)) {
const mint = mintEffortWireValue(level, model, compat.reasoningEffortLevels);
tier = mint.resolution.effective;
wrote = dialect.on(body, mint.wireValue, compat.supportsReasoningEffort ?? true);
}
const said = saidOf(tier, { tierKey: wrote.effort !== undefined, switched: wrote.switched });
return { body, headers: {}, effort: wrote.effort, carried: { said, format } };
}
function applyResponses(input, level, body) {
const { model } = input;
const compat = (model.compat ?? {});
let tier = "off";
let effort;
if (level === "off") {
effort = offSpelling(model, input.api).spelled ? declaredOffSpelling(model) : undefined;
}
else if (compat.supportsReasoningEffort !== false && reasoningRequestCarried(model, level, input.withheld)) {
const mint = mintEffortWireValue(level, model, compat.reasoningEffortLevels);
tier = mint.resolution.effective;
effort = mint.wireValue;
}
if (effort !== undefined)
mergeInto(body, "reasoning", { effort });
return { body, headers: {}, effort, carried: { said: saidOf(tier, { tierKey: effort !== undefined, switched: false }), format: "responses" } };
}
function thinkingBudget(maxTokens, share, fixed, hardCap) {
const max = hardCap ? maxTokens : Math.max(maxTokens, MIN_THINKING_TOKENS * 2);
const want = fixed ?? Math.floor(max * share);
const budget = Math.min(Math.max(MIN_THINKING_TOKENS, want), max - 1);
return { max, budget };
}
function applyMessages(input, level, body) {
const { model } = input;
const compat = (model.compat ?? {});
const declaredEffort = declaredEffortLevels(compat.effortLevels);
let tier = "off";
let thinkingOn = false;
let budgetIsTier = false;
if (reasoningRequestCarried(model, level, input.withheld)) {
tier = level;
if (compat.thinkingMode === "adaptive") {
body.thinking = { type: "adaptive" };
thinkingOn = true;
}
else {
if (body.max_tokens === undefined || body.max_tokens === null) {
refuseInput("body.max_tokens", "the Messages budget form needs a body.max_tokens (it sizes the thinking budget)");
}
const maxTokens = body.max_tokens;
const hardCap = input.budget?.capIsHard ?? true;
if (!budgetCapSkipsThinking(maxTokens, hardCap)) {
const share = input.budget?.share ?? reasoningBudgetShare(level);
const { max, budget } = thinkingBudget(maxTokens, share, input.budget?.tokens, hardCap);
if (!Number.isFinite(Number(max)) || !Number.isFinite(budget)) {
const shown = (value) => (typeof value === "string" ? JSON.stringify(value) : String(value));
refuseInput(!Number.isFinite(Number(max)) ? "body.max_tokens" : input.budget?.tokens !== undefined ? "budget.tokens" : "budget.share", `the Messages budget form cannot size a thinking budget from body.max_tokens ${shown(body.max_tokens)}, ` +
`budget.share ${shown(share)}, budget.tokens ${shown(input.budget?.tokens)} (cap ${shown(max)}, budget ${shown(budget)}); each must read as a finite number`);
}
body.max_tokens = max;
body.thinking = { type: "enabled", budget_tokens: budget };
thinkingOn = true;
budgetIsTier = input.budget?.share === undefined && input.budget?.tokens === undefined;
}
}
if (thinkingOn)
delete body.temperature;
}
else if (level === "off" && offSpelling(model, input.api).spelled) {
body.thinking = { type: "disabled" };
}
const betas = [];
let effort;
if (declaredEffort !== undefined && reasoningRequestCarried(model, level, input.withheld)) {
const tiers = [...new Set(sanitizeEffortLevels(declaredEffort).map((t) => (t === "minimal" ? "low" : t)))];
tier = resolveEffort(level, tiers).effective;
effort = tier;
mergeInto(body, "output_config", { effort });
betas.push(BETA_EFFORT);
}
if (compat.contextManagement && thinkingOn) {
const held = body.context_management;
const edits = isPlainObject(held) ? held.edits : undefined;
if (edits !== undefined && !Array.isArray(edits))
refuseBody("body.context_management.edits", "must be an array when present (the thinking edit is written into it)", edits);
mergeInto(body, "context_management", { edits: [{ type: "clear_thinking_20251015", keep: "all" }, ...(edits ?? [])] });
betas.push(BETA_CONTEXT_MANAGEMENT);
}
if (compat.interleavedThinking)
betas.push(BETA_INTERLEAVED_THINKING);
const said = saidOf(tier, { tierKey: effort !== undefined || budgetIsTier, switched: body.thinking !== undefined });
return { body, headers: betas.length > 0 ? { "anthropic-beta": betas.join(",") } : {}, effort, carried: { said, format: declaredEffort !== undefined ? "effort" : "budget" } };
}
export function applyReasoningToRequest(input) {
const level = judgeThinkingLevel(input.level, "applyReasoningToRequest.level");
const lane = input.api === "anthropic-messages" ? "messages" : RESPONSES_APIS.has(input.api) ? "responses" : "completions";
refuseOwnedMembers(lane, input.body);
const body = { ...input.body };
if (lane === "messages")
return applyMessages(input, level, body);
if (lane === "responses")
return applyResponses(input, level, body);
return applyCompletions(input, level, body);
}
export function resolutionOf(requested, carried, endpoint) {
const effective = carried.said;
return {
requested,
effective,
graded: effective !== "off" && THINKING_LEVELS.includes(effective),
clamped: effective !== requested,
format: carried.format,
endpoint,
...(effective === "provider_default" ? { dropped: true } : {}),
};
}
export function resolveReasoning(requested, model, facts) {
judgeThinkingLevel(requested, "resolveReasoning.requested");
const api = model.api ?? "unknown";
const { carried } = applyReasoningToRequest({
api,
model,
level: requested,
body: { max_tokens: facts?.outputCapTokens ?? CAP_BLIND },
budget: { capIsHard: facts?.hardOutputCap ?? false },
});
return resolutionOf(requested, carried, api);
}
export function thinkingBudgetFollowsCap(model, level, tried) {
if (level === undefined)
return false;
const { body } = applyReasoningToRequest({ api: model.api ?? "unknown", model, level, body: { max_tokens: CAP_BLIND }, budget: { capIsHard: false }, ...(tried ? { withheld: [] } : {}) });
return isPlainObject(body.thinking) && body.thinking.budget_tokens !== undefined;
}
export function reasoningEffortLevelsOf(model) {
const api = model.api ?? "unknown";
const honored = THINKING_LEVELS.filter((t) => {
if (t === "off")
return false;
const applied = applyReasoningToRequest({ api, model, level: t, body: { max_tokens: CAP_BLIND }, budget: { capIsHard: false } });
return applied.effort !== undefined && applied.carried.said === t;
});
return honored.length > 0 ? honored : undefined;
}
export function mergeReasoningHeaders(headers, patch) {
for (const [name, value] of Object.entries(patch)) {
const lower = name.toLowerCase();
if (lower !== "anthropic-beta") {
lockHeader(headers, lower, value);
continue;
}
const present = takeHeaderSpellings(headers, lower).flatMap((held) => headerListEntries(held));
for (const beta of headerListEntries(value)) {
if (!present.includes(beta))
present.push(beta);
}
headers[lower] = present.join(",");
}
}