@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
222 lines (221 loc) • 8.73 kB
JavaScript
import { bedrockModelIdForLookup } from "./bedrockIdentifiers.js";
import { getProviderRules } from "../providers/rules/registry.js";
function requireLimitsSection(key, value) {
if (value === undefined) {
throw new Error(`Provider rules file "limits.json" has no ${key}`);
}
return value;
}
/**
* Token Limit Constants for NeuroLink
*
* Centralized token configuration to replace magic numbers throughout the codebase.
* Includes model-specific token limits, use-case optimized limits, and provider constraints.
*
* @fileoverview Token constants for AI model interactions
* @author NeuroLink Team
* @version 1.0.0
*/
/**
* Standard token limit categories
* General-purpose token limits for different use cases
*/
export const TOKEN_LIMITS = {
/** Conservative limits (reliable across all models) */
CONSERVATIVE: 4096, // 4K - Safe for all providers
/** Standard limits (most modern models) */
STANDARD: 8192, // 8K - Modern model standard
/** High-capacity limits (premium models) */
HIGH_CAPACITY: 16384, // 16K - High-capacity models
/** Large context windows (specialized models) */
LARGE_CONTEXT: 100000, // 100K - Large context models
/** Ultra-large context windows (latest models) */
ULTRA_LARGE_CONTEXT: 200000, // 200K - Ultra-large context
/** Maximum context for any model */
MAXIMUM_CONTEXT: 2097152, // 2M - Theoretical maximum
};
/**
* Use-case specific token limits
* Optimized token limits for different application scenarios
*/
export const USE_CASE_TOKENS = {
/** Quick evaluation tasks */
EVALUATION: 500, // 500 - Keep evaluation fast
/** Analysis operations */
ANALYSIS: 800, // 800 - Analysis operations
/** Summary generation */
SUMMARY: 1000, // 1K - Summary generation
/** Documentation generation */
DOCUMENTATION: 12000, // 12K - Documentation generation
/** Code generation */
CODE_GENERATION: 4000, // 4K - Code generation tasks
/** Creative writing */
CREATIVE_WRITING: 6000, // 6K - Creative writing tasks
/** Translation tasks */
TRANSLATION: 2000, // 2K - Translation tasks
/** Conversation responses */
CONVERSATION: 2048, // 2K - Conversation responses
/** Technical explanations */
TECHNICAL_EXPLANATION: 3000, // 3K - Technical explanations
/** Research tasks */
RESEARCH: 8000, // 8K - Research and analysis
};
/**
* Provider-specific token limits
* Safe output token limits for each AI provider, from the
* `outputTokenLimits` section of `src/lib/providers/rules/limits.json`.
*/
const OUTPUT_TOKEN_LIMITS = requireLimitsSection("outputTokenLimits", getProviderRules("limits").outputTokenLimits);
export const PROVIDER_TOKEN_LIMITS = {
...OUTPUT_TOKEN_LIMITS.tables,
DEFAULT: OUTPUT_TOKEN_LIMITS.default,
};
/**
* Context window sizes for different models
* Maximum input token limits (separate from output limits)
*/
export const CONTEXT_WINDOWS = {
/** Small context models */
SMALL: 4096, // 4K - Small context
/** Medium context models */
MEDIUM: 32768, // 32K - Medium context
/** Large context models */
LARGE: 128000, // 128K - Large context
/** Ultra-large context models */
ULTRA_LARGE: 1048576, // 1M - Ultra-large context
/** Maximum theoretical context */
MAXIMUM: 2097152, // 2M - Maximum context
};
/**
* Model-specific token limits with input/output breakdown
* For models that require explicit input and output token limits; from the
* `modelTokenLimits` section of `src/lib/providers/rules/limits.json`.
*/
export const MODEL_TOKEN_LIMITS = requireLimitsSection("modelTokenLimits", getProviderRules("limits").modelTokenLimits);
/**
* Token estimation utilities
* Rough estimates for token counting without full tokenization
*/
export const TOKEN_ESTIMATION = {
/** Average characters per token (English) */
CHARS_PER_TOKEN: 4, // 4 chars - English average
/** Average words per token */
WORDS_PER_TOKEN: 0.75, // 0.75 words - English average
/** Code characters per token (more compact) */
CODE_CHARS_PER_TOKEN: 3, // 3 chars - Code is more compact
/** Safety margin for token estimates */
SAFETY_MARGIN: 0.8, // 80% - Safety margin for estimates
};
/**
* Token utility functions
*/
export const TokenUtils = {
/**
* Get safe token limit for a specific provider and model
* @param provider - Provider name
* @param model - Model name (optional)
* @returns Safe token limit for the provider/model
*/
getProviderTokenLimit: (provider, model) => {
const normalizedProvider = provider.toLowerCase().replace(/[-_]/g, "");
const tableName = OUTPUT_TOKEN_LIMITS.providerTables[normalizedProvider];
const providerLimits = tableName === undefined
? undefined
: OUTPUT_TOKEN_LIMITS.tables[tableName];
if (providerLimits === undefined) {
return PROVIDER_TOKEN_LIMITS.DEFAULT;
}
if (model && providerLimits[model]) {
return providerLimits[model];
}
if (model &&
OUTPUT_TOKEN_LIMITS.inferenceProfileTables?.includes(tableName)) {
const lookupModel = bedrockModelIdForLookup(model);
if (lookupModel !== undefined) {
return TokenUtils.getProviderTokenLimit(provider, lookupModel);
}
}
return providerLimits.default || PROVIDER_TOKEN_LIMITS.DEFAULT;
},
/**
* Get token limit for specific use case
* @param useCase - Use case type
* @returns Appropriate token limit
*/
getUseCaseTokenLimit: (useCase) => {
return USE_CASE_TOKENS[useCase] || TOKEN_LIMITS.STANDARD;
},
/**
* Estimate token count from text
* @param text - Input text
* @param isCode - Whether the text is code (more compact tokenization)
* @returns Estimated token count
*/
estimateTokenCount: (text, isCode = false) => {
const charsPerToken = isCode
? TOKEN_ESTIMATION.CODE_CHARS_PER_TOKEN
: TOKEN_ESTIMATION.CHARS_PER_TOKEN;
const estimatedTokens = Math.ceil(text.length / charsPerToken);
// Apply safety margin
return Math.ceil(estimatedTokens / TOKEN_ESTIMATION.SAFETY_MARGIN);
},
/**
* Check if text exceeds token limit
* @param text - Input text
* @param limit - Token limit to check against
* @param isCode - Whether the text is code
* @returns True if text exceeds limit
*/
exceedsTokenLimit: (text, limit, isCode = false) => {
const estimatedTokens = TokenUtils.estimateTokenCount(text, isCode);
return estimatedTokens > limit;
},
/**
* Get appropriate token limit category
* @param estimatedTokens - Estimated token count
* @returns Token limit category
*/
getTokenLimitCategory: (estimatedTokens) => {
if (estimatedTokens <= TOKEN_LIMITS.CONSERVATIVE) {
return "CONSERVATIVE";
}
if (estimatedTokens <= TOKEN_LIMITS.STANDARD) {
return "STANDARD";
}
if (estimatedTokens <= TOKEN_LIMITS.HIGH_CAPACITY) {
return "HIGH_CAPACITY";
}
if (estimatedTokens <= TOKEN_LIMITS.LARGE_CONTEXT) {
return "LARGE_CONTEXT";
}
return "ULTRA_LARGE_CONTEXT";
},
/**
* Truncate text to fit within token limit
* @param text - Input text
* @param tokenLimit - Maximum tokens allowed
* @param isCode - Whether the text is code
* @returns Truncated text
*/
truncateToTokenLimit: (text, tokenLimit, isCode = false) => {
const charsPerToken = isCode
? TOKEN_ESTIMATION.CODE_CHARS_PER_TOKEN
: TOKEN_ESTIMATION.CHARS_PER_TOKEN;
// Apply safety margin
const maxChars = Math.floor(tokenLimit * charsPerToken * TOKEN_ESTIMATION.SAFETY_MARGIN);
if (text.length <= maxChars) {
return text;
}
// Truncate and add ellipsis
return text.substring(0, maxChars - 3) + "...";
},
};
// Legacy compatibility exports from existing constants
export const DEFAULT_MAX_TOKENS = TOKEN_LIMITS.STANDARD;
export const DEFAULT_EVALUATION_MAX_TOKENS = USE_CASE_TOKENS.EVALUATION;
export const DEFAULT_ANALYSIS_MAX_TOKENS = USE_CASE_TOKENS.ANALYSIS;
export const DEFAULT_DOCUMENTATION_MAX_TOKENS = USE_CASE_TOKENS.DOCUMENTATION;
// Provider-specific safe defaults (from existing PROVIDER_MAX_TOKENS)
export const ANTHROPIC_SAFE = PROVIDER_TOKEN_LIMITS.ANTHROPIC.default;
export const OPENAI_STANDARD = PROVIDER_TOKEN_LIMITS.OPENAI.default;
export const GOOGLE_STANDARD = PROVIDER_TOKEN_LIMITS.GOOGLE_AI.default;