@sema-agent/core
Version:
Stateless, task-oriented AI agent core
162 lines (161 loc) • 5.5 kB
JavaScript
import { isCredentialHeaderName, namesASecret } from "../core/secret-env.js";
import { isPlainRecord } from "../core/mods/kernel/receive.js";
import { BrainError } from "./errors.js";
export const OPENAI_RESERVED = new Set([
"model",
"messages",
"stream",
"stream_options",
"tools",
"temperature",
"max_tokens",
"stop",
"reasoning_effort",
"thinking",
"reasoning",
"enable_thinking",
"chat_template_kwargs",
]);
export const ANTHROPIC_RESERVED = new Set([
"model",
"messages",
"system",
"stream",
"tools",
"temperature",
"max_tokens",
"thinking",
"output_config",
"context_management",
"speed",
]);
export const RESPONSES_RESERVED = new Set([
"model",
"input",
"stream",
"instructions",
"tools",
"temperature",
"max_output_tokens",
"reasoning",
"store",
"previous_response_id",
"conversation",
]);
const NO_KEYS = Object.freeze([]);
const extraBodyKind = (v) => (v === null ? "null" : Array.isArray(v) ? "an array" : typeof v === "object" ? "an object that is not plain (a class instance, a Map, …)" : `a ${typeof v}`);
export function judgeExtraBody(extraBody, modelId) {
if (extraBody === undefined)
return { entries: undefined };
const whose = `Model.extraBody of model ${JSON.stringify(modelId)}`;
if (!isPlainRecord(extraBody)) {
return {
refused: {
code: "config.invalid_argument",
field: "Model.extraBody",
sentence: `${whose} is ${extraBodyKind(extraBody)} — it must be a plain object of request-body keys, or absent; any other value is refused rather than spread into the request body as numbered keys or left out without a word. Write a plain object, or remove it.`,
},
};
}
const entries = Object.entries(extraBody);
if (entries.some(([k]) => k === "max_completion_tokens")) {
return {
refused: {
code: "config.extra_body_output_cap",
sentence: `${whose} supplies "max_completion_tokens" — an output-cap spelling the engine owns: it writes the per-request cap ` +
`itself, so a cap is never taken from extraBody. Set it via limits.maxOutputTokens (per request) or Model.maxTokens; ` +
`on the OpenAI wire Model.compat.maxTokensField picks the spelling.`,
},
};
}
return { entries };
}
export function applyExtraBody(body, model, reserved) {
const verdict = judgeExtraBody(model.extraBody, model.id);
if (verdict.refused !== undefined)
throw new BrainError("invalid_request", `${verdict.refused.code}: ${verdict.refused.sentence}`);
if (verdict.entries === undefined)
return { body, dropped: NO_KEYS };
const passthrough = {};
const dropped = [];
for (const [k, v] of verdict.entries) {
if (reserved.has(k))
dropped.push(k);
else
passthrough[k] = v;
}
return { body: { ...passthrough, ...body }, dropped: dropped.length === 0 ? NO_KEYS : dropped };
}
export function lockHeader(headers, lowerName, value) {
for (const k of Object.keys(headers)) {
if (k !== lowerName && k.toLowerCase() === lowerName)
delete headers[k];
}
headers[lowerName] = value;
}
export function takeHeaderSpellings(headers, lowerName) {
const values = [];
for (const k of Object.keys(headers)) {
if (k.toLowerCase() === lowerName) {
values.push(headers[k]);
delete headers[k];
}
}
return values;
}
export function headerListEntries(value) {
return typeof value === "string" ? value.split(",").map((entry) => entry.trim()).filter((entry) => entry !== "") : [];
}
export function headerBagOnce(bag) {
return bag === undefined ? undefined : { ...bag };
}
export function mergeHeaders(...bags) {
const out = {};
const spellingByFold = new Map();
for (const bag of bags) {
if (!bag)
continue;
for (const [name, value] of Object.entries(bag)) {
const fold = name.toLowerCase();
if (isCredentialHeaderName(name)) {
out[name] = value;
continue;
}
const prior = spellingByFold.get(fold);
if (prior !== undefined && prior !== name)
delete out[prior];
spellingByFold.set(fold, name);
out[name] = value;
}
}
return out;
}
export function declaredRequestValues(bags, stated, key) {
const out = new Set();
for (const bag of bags)
for (const value of Object.values(bag ?? {}))
if (typeof value === "string" && value !== "")
out.add(value);
for (const value of stated)
if (value !== undefined && value !== "")
out.add(value);
if (key !== undefined && namesASecret(key))
out.add(key);
return [...out];
}
export const OUTPUT_CAP_KEYS = {
openai: ["max_tokens", "max_completion_tokens"],
anthropic: ["max_tokens"],
responses: ["max_output_tokens"],
};
export function effectiveOutputCap(body, keys) {
let smallest;
for (const key of keys) {
const raw = body[key];
if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0)
continue;
if (smallest === undefined || raw < smallest)
smallest = raw;
}
return smallest;
}