Skip to content

Types Reference

All TypeScript interfaces exported by ai-armor.

Import

ts
import type {
  ArmorConfig,
  ArmorContext,
  ArmorInstance,
  ArmorLog,
  ArmorRequest,
  BudgetConfig,
  CacheConfig,
  ExactCacheConfig,
  FallbackConfig,
  FallbackResult,
  LoggingConfig,
  RateLimitConfig,
  RateLimitResult,
  RateLimitRule,
  RoutingConfig,
  SafetyCheckResult,
  SafetyConfig,
  SemanticCacheConfig,
  StorageAdapter,
} from 'ai-armor'

ArmorConfig

Top-level configuration object passed to createArmor(). All fields are optional -- only configure the features you need.

ts
interface ArmorConfig {
  rateLimit?: RateLimitConfig
  budget?: BudgetConfig
  fallback?: FallbackConfig
  cache?: CacheConfig
  routing?: RoutingConfig
  safety?: SafetyConfig
  logging?: LoggingConfig
}
FieldTypeDescription
rateLimitRateLimitConfigRate limiting configuration
budgetBudgetConfigCost tracking and budget configuration
fallbackFallbackConfigFallback chain configuration
cacheCacheConfigResponse caching configuration
routingRoutingConfigModel alias routing configuration
safetySafetyConfigSafety guardrails configuration
loggingLoggingConfigLogging and observability configuration

RateLimitConfig

Configuration for rate limiting.

ts
interface RateLimitConfig {
  strategy: 'sliding-window'
  rules: RateLimitRule[]
  store?: 'memory' | 'redis' | StorageAdapter
  keyResolver?: (ctx: ArmorContext, ruleKey: string) => string
  onLimited?: (ctx: ArmorContext) => void
}
FieldTypeRequiredDescription
strategy'sliding-window'YesRate limiting algorithm. Currently 'sliding-window' is fully implemented.
rulesRateLimitRule[]YesArray of rate limit rules. All rules must pass for a request to be allowed.
store'memory' | 'redis' | StorageAdapterNoStorage backend. Default: in-memory. Pass a StorageAdapter for shared state across instances.
keyResolver(ctx: ArmorContext, ruleKey: string) => stringNoCustom function to resolve rate limit keys from context. Overrides default key resolution.
onLimited(ctx: ArmorContext) => voidNoCallback fired synchronously when a request is rate limited.

RateLimitRule

A single rate limit rule defining a dimension, limit, and time window.

ts
interface RateLimitRule {
  key: 'user' | 'ip' | 'apiKey' | (string & {})
  limit: number
  window: string
}
FieldTypeDescription
key'user' | 'ip' | 'apiKey' | stringDimension to rate limit by. Built-in keys resolve from ArmorContext fields. Custom strings resolve from ctx[key].
limitnumberMaximum number of requests allowed within the window.
windowstringTime window duration. Format: number + unit (s for seconds, m for minutes, h for hours, d for days). Examples: '30s', '1m', '1h', '24h', '1d'.

RateLimitResult

Result returned by armor.checkRateLimit().

ts
interface RateLimitResult {
  allowed: boolean
  remaining: number
  resetAt: number
}
FieldTypeDescription
allowedbooleantrue if the request is within all rate limits.
remainingnumberNumber of requests remaining before the most restrictive rule is hit.
resetAtnumberUnix timestamp (milliseconds) when the earliest rate limit window resets. 0 if no rate limit is configured.

BudgetConfig

Configuration for cost tracking and budget enforcement.

ts
interface BudgetConfig {
  daily?: number
  monthly?: number
  perUser?: number
  perUserMonthly?: number
  onExceeded: 'block' | 'warn' | 'downgrade-model'
  downgradeMap?: Record<string, string>
  store?: 'memory' | 'redis' | StorageAdapter
  onWarned?: (ctx: ArmorContext, budget: {
    daily: number
    monthly: number
    perUserDaily?: number
    perUserMonthly?: number
  }) => void
  onUnknownModel?: (model: string) => void
}
FieldTypeRequiredDescription
dailynumberNoMaximum daily spend in USD. Resets at midnight (server local time).
monthlynumberNoMaximum monthly spend in USD. Resets on the 1st of each month.
perUsernumberNoMaximum daily spend per user in USD. Requires ctx.userId to be set.
perUserMonthlynumberNoMaximum monthly spend per user in USD. Requires ctx.userId to be set.
onExceeded'block' | 'warn' | 'downgrade-model'YesAction to take when a budget limit is exceeded.
downgradeMapRecord<string, string>NoMaps expensive models to cheaper alternatives. Used when onExceeded is 'downgrade-model'.
store'memory' | 'redis' | StorageAdapterNoStorage backend for cost data. Default: in-memory.
onWarnedfunctionNoCallback fired when onExceeded is 'warn' and a budget is exceeded. Receives current spend totals including perUserMonthly.
onUnknownModel(model: string) => voidNoCallback fired when a model is not found in the pricing table.

FallbackConfig

Configuration for fallback chains.

ts
interface FallbackConfig {
  chains: Record<string, string[]>
  timeout?: number
  retries?: number
  backoff?: 'exponential' | 'linear'
  healthCheck?: boolean
}
FieldTypeRequiredDescription
chainsRecord<string, string[]>YesMaps primary model to ordered list of fallback models.
timeoutnumberNoRequest timeout in milliseconds before triggering fallback.
retriesnumberNoNumber of retries per model before moving to next in chain.
backoff'exponential' | 'linear'NoBackoff strategy between retries.
healthCheckbooleanNoEnable passive health checking for automatic recovery.

CacheConfig

Configuration for response caching. This is a union type -- use strategy: 'exact' for exact-match caching or strategy: 'semantic' for embedding-based similarity caching.

ts
type CacheConfig = ExactCacheConfig | SemanticCacheConfig

ExactCacheConfig

ts
interface ExactCacheConfig {
  enabled: boolean
  strategy: 'exact'
  ttl: number
  maxSize?: number
  keyFn?: (request: ArmorRequest) => string
}
FieldTypeRequiredDescription
enabledbooleanYesEnable or disable caching.
strategy'exact'YesExact-match cache strategy.
ttlnumberYesTime-to-live for cache entries, in seconds.
maxSizenumberNoMaximum number of cache entries. When exceeded, LRU entries are evicted.
keyFn(request: ArmorRequest) => stringNoCustom function to generate cache keys. Default serializes model + messages + temperature + tools.

SemanticCacheConfig

ts
interface SemanticCacheConfig {
  enabled: boolean
  strategy: 'semantic'
  ttl: number
  maxSize?: number
  embeddingFn: (text: string) => Promise<number[]>
  similarityThreshold?: number
  keyFn?: (request: ArmorRequest) => string
}
FieldTypeRequiredDescription
enabledbooleanYesEnable or disable caching.
strategy'semantic'YesSemantic similarity cache strategy.
ttlnumberYesTime-to-live for cache entries, in seconds.
maxSizenumberNoMaximum number of cache entries. When exceeded, LRU entries are evicted.
embeddingFn(text: string) => Promise<number[]>YesFunction that returns an embedding vector for the given text. Used for similarity comparison.
similarityThresholdnumberNoMinimum cosine similarity (0-1) to consider a cache hit. Default: 0.92.
keyFn(request: ArmorRequest) => stringNoCustom function to generate cache keys. Default serializes model + messages + temperature + tools.

RoutingConfig

Configuration for model alias routing.

ts
interface RoutingConfig {
  aliases: Record<string, string>
}
FieldTypeRequiredDescription
aliasesRecord<string, string>YesMaps alias names to real model names. Example: { fast: 'gpt-4o-mini', best: 'claude-opus-4-20250514' }

SafetyConfig

Configuration for safety guardrails.

ts
interface SafetyConfig {
  promptInjection?: boolean
  piiDetection?: boolean
  maxTokensPerRequest?: number
  blockedPatterns?: RegExp[]
  onBlocked?: (ctx: ArmorContext, reason: string) => void
}
FieldTypeRequiredDescription
promptInjectionbooleanNoEnable detection of common prompt injection patterns.
piiDetectionbooleanNoEnable detection of PII (email, phone, SSN, credit card).
maxTokensPerRequestnumberNoMaximum total tokens allowed per request.
blockedPatternsRegExp[]NoCustom regex patterns that block matching request content.
onBlocked(ctx: ArmorContext, reason: string) => voidNoCallback fired when a request is blocked by a safety check.

LoggingConfig

Configuration for logging and observability.

ts
interface LoggingConfig {
  enabled: boolean
  include: Array<'model' | 'tokens' | 'cost' | 'latency' | 'userId' | 'cached' | 'fallback'>
  onRequest?: (log: ArmorLog) => void | Promise<void>
  maxEntries?: number
}
FieldTypeRequiredDescription
enabledbooleanYesEnable or disable logging.
includeArrayYesFields to include in filtered log output. id and timestamp are always included.
onRequest(log: ArmorLog) => void | Promise<void>NoAsync callback fired after each request is logged. Use for external analytics.
maxEntriesnumberNoMaximum log entries to keep in memory. Default: 10000. Oldest entries are removed when exceeded.

ArmorContext

Context object passed to rate limit checks, budget checks, and callbacks. Represents the identity and metadata of the current request.

ts
interface ArmorContext {
  userId?: string
  ip?: string
  apiKey?: string
  headers?: Record<string, string>
  model?: string
  [key: string]: unknown
}
FieldTypeDescription
userIdstring?User identifier. Used for per-user rate limits and per-user budgets.
ipstring?Client IP address. Used for IP-based rate limiting.
apiKeystring?API key. Used for per-key rate limiting.
headersRecord<string, string>?HTTP headers from the request.
modelstring?Model name (set by some integrations).
[key: string]unknownExtensible -- add any custom properties for use in keyResolver or callbacks.

ArmorRequest

Represents an AI API request for caching and safety checks.

ts
interface ArmorRequest {
  model: string
  messages: unknown[]
  temperature?: number
  tools?: unknown[]
}
FieldTypeRequiredDescription
modelstringYesModel name (after alias resolution).
messagesunknown[]YesArray of chat messages.
temperaturenumberNoSampling temperature.
toolsunknown[]NoTool/function definitions.

ArmorLog

Structured log entry for each AI request.

ts
interface ArmorLog {
  id: string
  timestamp: number
  model: string
  provider: string
  inputTokens: number
  outputTokens: number
  cost: number
  latency: number
  cached: boolean
  fallback: boolean
  userId?: string
  blocked?: string
  rateLimited: boolean
}
FieldTypeDescription
idstringUnique request identifier (UUID).
timestampnumberUnix timestamp in milliseconds.
modelstringModel used for this request.
providerstringProvider name (e.g., 'openai', 'anthropic', 'google').
inputTokensnumberNumber of input/prompt tokens.
outputTokensnumberNumber of output/completion tokens.
costnumberCalculated cost in USD.
latencynumberRequest duration in milliseconds.
cachedbooleantrue if this was served from cache.
fallbackbooleantrue if a fallback model was used.
userIdstring?User ID if provided in context.
blockedstring?Reason the request was blocked (error message or safety reason).
rateLimitedbooleantrue if this request was rate limited.

ArmorInstance

The object returned by createArmor(). Contains all configured protections and methods.

ts
interface ArmorInstance {
  config: ArmorConfig
  checkRateLimit: (ctx: ArmorContext) => Promise<RateLimitResult>
  peekRateLimit: (ctx: ArmorContext) => Promise<{ remaining: number, resetAt: number }>
  trackCost: (model: string, inputTokens: number, outputTokens: number, userId?: string) => Promise<void>
  checkBudget: (model: string, ctx: ArmorContext) => Promise<{ allowed: boolean, action: string, suggestedModel?: string }>
  getDailyCost: (userId?: string) => Promise<number>
  getMonthlyCost: (userId?: string) => Promise<number>
  resolveModel: (model: string) => string
  getCachedResponse: (request: ArmorRequest) => Promise<unknown | undefined>
  setCachedResponse: (request: ArmorRequest, response: unknown) => Promise<void>
  log: (entry: ArmorLog) => Promise<void>
  getLogs: () => ArmorLog[]
  estimateCost: (model: string, inputTokens: number, outputTokens: number) => number
  getProvider: (model: string) => string
  checkSafety: (request: ArmorRequest, ctx: ArmorContext) => SafetyCheckResult
  executeFallback: <T>(request: ArmorRequest, handler: (model: string) => Promise<T>) => Promise<FallbackResult<T>>
}

See createArmor API Reference for detailed method documentation.


SafetyCheckResult

Result from armor.checkSafety().

ts
interface SafetyCheckResult {
  allowed: boolean
  blocked: boolean
  reason: string | null
  details: string[]
}
FieldTypeDescription
allowedbooleantrue if the request passed all safety checks.
blockedbooleantrue if the request was blocked.
reasonstring | nullPrimary reason for blocking, or null if allowed.
detailsstring[]Array of all triggered safety check details.

FallbackResult

Result from armor.executeFallback().

ts
interface FallbackResult<T = unknown> {
  result: T
  model: string
  attempts: number
  fallbackUsed: boolean
}
FieldTypeDescription
resultTThe response from the successful model call.
modelstringThe model that ultimately succeeded.
attemptsnumberTotal number of attempts made.
fallbackUsedbooleantrue if a fallback model was used instead of the primary.

StorageAdapter

Interface for custom storage backends (e.g., Redis, database). Used by rate limiting and budget tracking for shared state across multiple server instances.

ts
interface StorageAdapter {
  getItem: (key: string) => Promise<unknown>
  setItem: (key: string, value: unknown) => Promise<void>
  removeItem: (key: string) => Promise<void>
}
MethodDescription
getItem(key)Retrieve a value by key. Return null or undefined if not found.
setItem(key, value)Store a value. The value is always JSON-serializable.
removeItem(key)Delete a value by key.

Example implementation (Redis):

ts
import { createArmor, createRedisAdapter } from 'ai-armor'
import Redis from 'ioredis'

const redis = new Redis()

const armor = createArmor({
  rateLimit: {
    strategy: 'sliding-window',
    rules: [{ key: 'user', limit: 100, window: '1m' }],
    store: createRedisAdapter(redis, { prefix: 'armor:', ttl: 86400 }),
  },
})

ModelPricing

Pricing information for a single model. Exported from ai-armor.

ts
interface ModelPricing {
  model: string // Model identifier
  provider: string // Provider name
  input: number // USD per 1M input tokens
  output: number // USD per 1M output tokens
}
ts
import type { ModelPricing } from 'ai-armor'
import { getModelPricing } from 'ai-armor'

const pricing: ModelPricing | undefined = getModelPricing('gpt-4o')
// { model: 'gpt-4o', provider: 'openai', input: 2.50, output: 10.00 }

Released under the MIT License.