@sema-agent/core
Version:
Stateless, task-oriented AI agent core
44 lines (43 loc) • 1.36 kB
JavaScript
function asList(models) {
return Array.isArray(models) ? models : Object.values(models);
}
function costOf(m) {
if (!m.cost) {
return Number.POSITIVE_INFINITY;
}
return (m.cost.input ?? 0) + (m.cost.output ?? 0);
}
function matches(m, c) {
for (const need of c.needs ?? []) {
if (need === "vision" && !m.input?.includes("image"))
return false;
if (need === "reasoning" && !m.reasoning)
return false;
}
if (c.minContext != null && (m.contextTokens ?? m.contextWindow ?? 0) < c.minContext) {
return false;
}
if (c.tier != null && m.params?.tier !== c.tier) {
return false;
}
return true;
}
export function selectModel(models, criteria = {}) {
const candidates = asList(models).filter((m) => matches(m, criteria));
if (candidates.length === 0) {
return undefined;
}
const premium = criteria.prefer === "premium";
return candidates.reduce((best, m) => {
const c = costOf(m);
const b = costOf(best);
return premium ? (c > b ? m : best) : c < b ? m : best;
});
}
export function selectModelOrThrow(models, criteria = {}) {
const m = selectModel(models, criteria);
if (!m) {
throw new Error(`selectModel: no model in the catalog matches ${JSON.stringify(criteria)}`);
}
return m;
}