UNPKG

@juspay/neurolink

Version:

The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002

382 lines (381 loc) • 17.4 kB
import { AIProviderName } from "../constants/enums.js"; import { API_KEY_FORMATS } from "../utils/providerConfig.js"; import { getDefaultModel } from "../providers/rules/fallbackModel.js"; import { getProviderRules } from "../providers/rules/registry.js"; import { getCatalogJsonEntries, getDecideCatalogEntries, catalogCredentialsKey, catalogEnvVar, } from "../providers/catalog/loader.js"; import { DEFAULT_INFERENCE_KINDS } from "../types/index.js"; /** * Hand-maintained provider identity, credentials, defaults, and runtime * behavior classification for every provider EXCEPT the JSON-catalog * providers derived by buildCatalogDescriptors() below. The data lives in * src/lib/providers/rules/descriptors.json; this turns each entry into a * runtime descriptor (API key pattern compiled, default model resolved). */ const PROVIDER_NAMES = new Set(Object.values(AIProviderName)); function descriptorFromJson(entry) { const { name, defaultModel, defaultModelFrom, apiKeyFormat, notes: _notes, ...rest } = entry; if (!PROVIDER_NAMES.has(name)) { throw new Error(`descriptors.json names "${name}", which is not an AIProviderName`); } const pattern = apiKeyFormat === undefined ? undefined : API_KEY_FORMATS[apiKeyFormat]; if (apiKeyFormat !== undefined && pattern === undefined) { throw new Error(`descriptors.json: ${name} names apiKeyFormat "${apiKeyFormat}", which credentials.json does not define`); } return { ...rest, name: name, defaultModel: defaultModelFrom === undefined ? (defaultModel ?? "") : getDefaultModel(defaultModelFrom), ...(pattern === undefined ? {} : { apiKeyFormatPattern: pattern }), }; } const descriptorEntries = getProviderRules("descriptors").descriptors; if (descriptorEntries === undefined) { throw new Error('Provider rules file "descriptors.json" has no descriptors'); } const HAND_DESCRIPTORS = descriptorEntries.map(descriptorFromJson); const TRAIT_LISTS = getProviderRules("descriptors").traitLists ?? {}; /** * Builds a ProviderDescriptor for every JSON-catalog provider. Every field * is derived from the catalog JSON (src/lib/providers/catalog/<id>.json), * never hand-typed. * * defaultModel prefers models.registryDefaultModel over models.default — * only mistral sets registryDefaultModel today (its long-shipped descriptor's * defaultModel was MISTRAL_LARGE_LATEST, while models.default is the smaller * mistral-small-2506 the OpenAI-compat runtime path actually defaults to via * MISTRAL_MODEL); every other provider's registryDefaultModel is absent, so * `?? entry.models.default` is a no-op for them. * * timeouts and autoSelectPriority are included only when the JSON sets * them — today only mistral does, preserving its pre-migration hand-typed * values. */ function buildCatalogDescriptor(entry) { // Cloudflare is the only catalog provider whose wire config is a // baseURLTemplate + extra credential (accountId) rather than a plain // baseURL env var — mirrors loader.ts's buildCatalogEntries() // computedBaseURL.envVar formula exactly. Duplicated intentionally, the // same way loader.ts itself duplicates toCamelCase from // tools/codegen-catalog.ts (src/ must not import from tools/). const fallbacks = entry.wire.apiKeyFallbackEnvVars?.length ? { fallbacks: [...entry.wire.apiKeyFallbackEnvVars] } : {}; const envVars = entry.wire.baseURLTemplate ? { apiKey: catalogEnvVar(entry, "apiKey"), ...fallbacks, extraRequired: [ `${entry.id.toUpperCase().replace(/-/g, "_")}_${(entry.wire.extraCredentials?.[0] ?? "accountId") .replace(/([A-Z])/g, "_$1") .toUpperCase()}`, ], model: catalogEnvVar(entry, "model"), } : { apiKey: catalogEnvVar(entry, "apiKey"), ...fallbacks, baseURL: catalogEnvVar(entry, "baseURL"), model: catalogEnvVar(entry, "model"), }; return { name: entry.id, aliases: entry.aliases, credentialsKey: catalogCredentialsKey(entry), envVars, // Every catalog provider runs on the shared Chat Completions base. wire: "openai-chat", defaultModel: entry.models.registryDefaultModel ?? entry.models.default, // "none" (not an invented literal — it's the union's own // no-tool-support member, the same one // REPLICATE/VOYAGE/JINA/STABILITY/IDEOGRAM/RECRAFT use above) is // mancer's branch; "model-dependent" is huggingface's (matches // ProviderDescriptor.toolSupport's own union member, same value // Ollama's hand descriptor already uses). toolSupport: entry.capabilities.tools === "model-dependent" ? "model-dependent" : entry.capabilities.tools ? "native" : "none", localRuntime: false, healthCheck: "env-only", setupUrl: entry.setup.url, ...(entry.setup.apiKeyFormat ? { apiKeyFormatPattern: new RegExp(entry.setup.apiKeyFormat) } : {}), ...(entry.timeouts ? { timeouts: entry.timeouts } : {}), ...(entry.autoSelectPriority !== undefined ? { autoSelectPriority: entry.autoSelectPriority } : {}), }; } /** * Builds the ProviderDescriptor of a JSON `decide` provider. It serves only * `decide`, so it declares no auto-select, preference or health-sweep rank: * those feed generation fallback chains a text-less provider must never join. */ export function buildDecideDescriptor(entry) { const fallbacks = entry.wire.apiKeyFallbackEnvVars?.length ? { fallbacks: [...entry.wire.apiKeyFallbackEnvVars] } : {}; return { name: entry.id, aliases: entry.aliases, credentialsKey: catalogCredentialsKey(entry), envVars: { apiKey: catalogEnvVar(entry, "apiKey"), ...fallbacks, baseURL: catalogEnvVar(entry, "baseURL"), // A key is useless without an endpoint when the provider has no built-in one. ...(entry.decide.baseURLRequired ? { extraRequired: [catalogEnvVar(entry, "baseURL")] } : {}), model: catalogEnvVar(entry, "model"), }, defaultModel: entry.models.default, inferenceKinds: ["decide"], decideOrder: entry.decide.order, ...(entry.decide.ambientKeyGuard ? { ambientKeyGuard: { baseURLEnvVars: [...entry.decide.ambientKeyGuard.baseURLEnvVars], trustedOrigins: [...entry.decide.ambientKeyGuard.trustedOrigins], ...(entry.decide.ambientKeyGuard.credentialBaseURLs ? { credentialBaseURLs: entry.decide.ambientKeyGuard.credentialBaseURLs.map((credentialField) => ({ ...credentialField })), } : {}), }, } : {}), toolSupport: "none", localRuntime: false, healthCheck: "env-only", setupUrl: entry.setup.url, ...(entry.setup.apiKeyFormat ? { apiKeyFormatPattern: new RegExp(entry.setup.apiKeyFormat) } : {}), ...(entry.timeouts ? { timeouts: { ...entry.timeouts } } : {}), ...(entry.decisionLimits ? { decisionLimits: entry.decisionLimits } : {}), }; } function buildCatalogDescriptors() { return [ ...getCatalogJsonEntries().map(buildCatalogDescriptor), ...getDecideCatalogEntries().map(buildDecideDescriptor), ]; } /** * Single source of truth for provider identity, credentials, defaults, and * runtime behavior classification — the hand-maintained providers plus the * JSON-catalog providers derived above. */ export const PROVIDER_DESCRIPTORS = [ ...HAND_DESCRIPTORS, ...buildCatalogDescriptors(), ]; /** O(1) canonical-name → descriptor lookup. */ export const PROVIDER_DESCRIPTORS_BY_NAME = new Map(PROVIDER_DESCRIPTORS.map((d) => [d.name, d])); /** * O(1) alias → canonical-name lookup, covering both `aliases` and each * descriptor's own lowercased `name`. Replaces the O(n) linear scan in * ProviderFactory.normalizeProviderName(). */ export const PROVIDER_ALIAS_INDEX = new Map(PROVIDER_DESCRIPTORS.flatMap((d) => [ [d.name.toLowerCase(), d.name], ...d.aliases.map((alias) => [alias.toLowerCase(), d.name]), ])); /** A built-in descriptor by name or alias, case-insensitive. */ export function findBuiltInDescriptor(name) { if (!name) { return undefined; } const canonical = PROVIDER_ALIAS_INDEX.get(name.toLowerCase()); return canonical === undefined ? undefined : PROVIDER_DESCRIPTORS_BY_NAME.get(canonical); } /** Whether the provider's descriptor lists this named hook. */ export function descriptorHasHook(name, hook) { return findBuiltInDescriptor(name)?.hooks?.includes(hook) === true; } /** Whether descriptors.json puts the provider in this label list. */ export function inProviderTraitList(name, list) { const canonical = findBuiltInDescriptor(name)?.name ?? name; return TRAIT_LISTS[list]?.includes(canonical) === true; } const servesDecide = (descriptor) => (descriptor.inferenceKinds ?? DEFAULT_INFERENCE_KINDS).includes("decide"); /** * Throws unless every descriptor that serves `decide` has its own finite * `decideOrder`. The order is the precedence of resolveDefaultDecisionProvider(), * so a missing or repeated number would make that choice depend on array position. */ export function assertUniqueDecideOrder(descriptors) { const owners = new Map(); for (const descriptor of descriptors.filter(servesDecide)) { const order = descriptor.decideOrder; if (order === undefined || !Number.isFinite(order)) { throw new Error(`decision provider "${descriptor.name}" has no usable decideOrder`); } const clash = owners.get(order); if (clash !== undefined) { throw new Error(`decideOrder ${order} is used by both "${clash}" and "${descriptor.name}"`); } owners.set(order, descriptor.name); } } /** The descriptors that serve `decide`, lowest `decideOrder` first. */ export function orderDecisionProviders(descriptors) { const rank = (d) => d.decideOrder ?? Number.MAX_SAFE_INTEGER; return descriptors.filter(servesDecide).sort((a, b) => rank(a) - rank(b)); } assertUniqueDecideOrder(PROVIDER_DESCRIPTORS); /** * Providers that serve the `decide` inference type, derived from each * descriptor's `inferenceKinds` and sorted by `decideOrder`, lowest first. A * provider that declares nothing is a text provider, so it is not here. */ export const DECISION_PROVIDERS = orderDecisionProviders(PROVIDER_DESCRIPTORS); /** * The scheme, host and port of a base URL, lower-cased and without the default * port, or undefined when the text is not an http(s) URL. The path, query and a * trailing slash do not matter, and userinfo is not part of an origin, so * `https://api.openai.com@evil.test/v1` reads as `https://evil.test`. */ function originOf(text) { try { const url = new URL(text.trim()); return url.protocol === "http:" || url.protocol === "https:" ? url.origin : undefined; } catch { return undefined; } } /** * Whether the guard lets a key found in the environment stand. It does not * when a listed base-URL variable, or a listed credentials field, is set to * something other than a trusted origin; an unparseable value is untrusted, a * blank or absent one is unset. A credentials field that is not text cannot be * read as a URL, so it is untrusted too. */ function ambientKeyTrusted(guard, credentials) { const trusted = new Set(guard.trustedOrigins .map(originOf) .filter((origin) => origin !== undefined)); const standsFor = (value) => { if (value === undefined || value === null) { return true; } if (typeof value !== "string") { return false; } if (value.trim() === "") { return true; } const origin = originOf(value); return origin !== undefined && trusted.has(origin); }; const slices = credentials; return (guard.baseURLEnvVars.every((name) => standsFor(process.env[name])) && (guard.credentialBaseURLs ?? []).every(({ key, field }) => standsFor(slices?.[key]?.[field]))); } /** * Whether a decision provider is fully configured: its key and every * extraRequired variable are set, each either in the environment or in * `credentials` — the same config a caller passes to * `new NeuroLink({ credentials })` or per call. Whitespace counts as unset. * * A key found only in the environment does not count while the descriptor's * `ambientKeyGuard` finds that it belongs to something else, unless the host * routed the provider on purpose with its own base-URL variable or a * `credentials` base URL. A key in `credentials` always counts. */ function isDecisionProviderConfigured(descriptor, credentials) { const isSet = (value) => typeof value === "string" && value.trim() !== ""; const inEnv = (name) => name !== undefined && isSet(process.env[name]); const slice = descriptor.credentialsKey ? credentials?.[descriptor.credentialsKey] : undefined; const routedOnPurpose = inEnv(descriptor.envVars.baseURL) || isSet(slice?.baseURL); const envKeyStands = descriptor.ambientKeyGuard === undefined || routedOnPurpose || ambientKeyTrusted(descriptor.ambientKeyGuard, credentials); // `gatewayApiKey` is TypeSafe's config form of AI_GATEWAY_API_KEY. const hasKey = (envKeyStands && [descriptor.envVars.apiKey, ...(descriptor.envVars.fallbacks ?? [])].some(inEnv)) || isSet(slice?.apiKey) || isSet(slice?.gatewayApiKey); // A required base URL can also come from credentials.<key>.baseURL, and any // other required value the descriptor maps to a field of that slice. const hasRequired = (descriptor.envVars.extraRequired ?? []).every((name) => { const field = descriptor.envVars.extraRequiredCredentialFields?.[name]; return (inEnv(name) || (name === descriptor.envVars.baseURL && isSet(slice?.baseURL)) || (field !== undefined && isSet(slice?.[field]))); }); return hasKey && hasRequired; } /** * The decision provider to use when a caller names none: the first * DECISION_PROVIDERS entry that is fully configured, from the environment or * from `credentials`. * * This is where "if somebody configures it, we start using it" is * implemented. Returns undefined when none is configured, which every * internal consumer treats as "carry on exactly as before". */ export function resolveDefaultDecisionProvider(credentials) { return DECISION_PROVIDERS.find((descriptor) => isDecisionProviderConfigured(descriptor, credentials))?.name; } /** * Names of the decision providers that accept images, or, with `video` or * `audio`, the ones that accept that too: a hint that names a provider which * would refuse the same request is worse than none. */ export function listMediaDecisionProviders(needs) { return DECISION_PROVIDERS.filter((descriptor) => { const media = descriptor.decisionLimits?.media; return (media !== undefined && (!needs?.video || media.video) && (!needs?.audio || media.audio !== undefined)); }).map((descriptor) => descriptor.name); } /** "a", "a or b", "a, b or c". */ function listOr(items) { return items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} or ${items[items.length - 1]}`; } /** * The variables that would configure each decision provider, one clause per * provider in precedence order, e.g. "TYPESAFE_API_KEY or AI_GATEWAY_API_KEY * for typesafe, or LAYA_API_KEY and LAYA_BASE_URL for laya". Derived from * DECISION_PROVIDERS so a new decision provider appears in every "nothing is * configured" message without anyone editing one. */ export function describeDecisionProviderKeys() { return DECISION_PROVIDERS.map((descriptor) => { const keys = [ descriptor.envVars.apiKey, ...(descriptor.envVars.fallbacks ?? []), ].filter((name) => typeof name === "string" && name !== ""); const required = descriptor.envVars.extraRequired ?? []; const guard = descriptor.ambientKeyGuard; const unlessRouted = descriptor.envVars.baseURL ? `, unless ${descriptor.envVars.baseURL} is set` : ""; const named = guard ? [ ...guard.baseURLEnvVars, ...(guard.credentialBaseURLs ?? []).map(({ key, field }) => `credentials.${key}.${field}`), ] : []; const caveat = guard ? ` (ignored while ${listOr(named)} names a host outside ${listOr(guard.trustedOrigins)}${unlessRouted})` : ""; return `${[keys.join(" or "), ...required].join(" and ")} for ${descriptor.name}${caveat}`; }).join(", or "); }