Skip to content

API Reference

Public exports from the shieldkit npm package (src/index.ts).

Functions

shield(model, config?)

Wraps a LanguageModelV3 with the full middleware chain.

ParameterTypeDescription
modelLanguageModelBase model from any AI SDK provider
configShieldConfig?Optional shield configuration

Returns: LanguageModel — use with generateText, streamText, etc.

See: Architecture overview · Verification matrix


shieldGenerateText(params)

Like generateText, with extra retry handling when NoObjectGeneratedError is thrown.

ParameterTypeDescription
paramsGenerateTextParamsStandard AI SDK params
params.modelLanguageModelShield-wrapped model
params.configShieldConfig?Repair config override
params.outputSchemaz.ZodType?Schema for validation/repair
params.maxRepairAttemptsnumber?Override maxAttempts

Returns: Promise<GenerateTextResult>

Throws: ShieldRepairError when retries are exhausted

See: Structured output


shieldStreamText(params)

Like streamText, merging outputSchema into providerOptions.aiShield.

ParameterTypeDescription
paramsStreamTextParamsStandard AI SDK params
params.modelLanguageModelShield-wrapped model
params.outputSchemaz.ZodType?Schema for repair middleware

Returns: StreamTextResult

Note: No dedicated test coverage — see verification matrix.


guardTools(tools, options?)

Wraps tool execute functions with invocation policies.

ParameterTypeDescription
toolsRecord<string, Tool>AI SDK tool definitions
optionsToolGuardOptions?Allow/deny, limits, approval

Returns: Same tool record shape with wrapped execute functions.

See: Tool guards


resolveConfig(config?)

Resolves ShieldConfig to a fully merged ResolvedShieldConfig without wrapping a model.

See: Configuration


Session helpers

FunctionDescription
createShieldContext(sessionId?)Initialize or reset session state (default ID: "default")
getOrCreateSession(sessionId?)Get existing session or create new
resetSession(sessionId)Delete session from store
createRequestContext(options)Build per-request context from ShieldProviderOptions
sessionStoreIn-memory Map<string, SessionState> (advanced use)

See: Cost tracking


Error classes

All extend AISDKError from @ai-sdk/provider.

ShieldBlockedError

Guard blocked the request (input or output).

PropertyTypeDescription
guardstringGuard name (injection, pii, keywords)
summarystringHuman-readable reason

ShieldBudgetError

Session cost budget exceeded.

PropertyTypeDescription
sessionIdstringSession key
totalCostUsdnumberCurrent or projected total
maxCostUsdnumberConfigured limit

ShieldRepairError

Structured output repair exhausted all attempts.

PropertyTypeDescription
partialTextstringLast model output
attemptsnumberTotal attempts made
lastErrorstringFinal validation error
usageobject?Merged token usage

ShieldToolError

Tool policy violation.

PropertyTypeDescription
toolNamestringBlocked tool
reasonstringPolicy reason

Types

ShieldConfig

Top-level configuration passed to shield().

ts
interface ShieldConfig {
  mode?: ShieldMode;
  guardrails?: GuardrailsConfig;
  cost?: CostConfig;
  audit?: AuditConfig;
}

ShieldMode

'balanced' | 'strict' | 'cheap' | 'local' | 'custom'

GuardAction

'block' | 'redact' | 'warn'

GuardrailsConfig

ts
interface GuardrailsConfig {
  input?: {
    injection?: InjectionGuardConfig;
    pii?: PiiGuardConfig;
    keywords?: KeywordsGuardConfig;
  };
  output?: {
    repair?: RepairConfig;
    pii?: PiiGuardConfig;
    keywords?: KeywordsGuardConfig;
  };
}

RepairConfig

ts
interface RepairConfig {
  enabled?: boolean;
  maxAttempts?: number;
  includePartialInRetry?: boolean; // default: true
}

CostConfig

ts
interface CostConfig {
  maxCostPerSession?: number;
  trackOnly?: boolean;
  warnAtPercent?: number;
  pricing?: Record<string, ModelPricing>;
  defaultPricing?: ModelPricing;
}

AuditConfig

ts
interface AuditConfig {
  enabled?: boolean;
  logLevel?: 'basic' | 'detailed';
  sink?: (log: AuditLog) => void | Promise<void>;
  console?: boolean;
}

ShieldProviderOptions

Per-request options via providerOptions.aiShield:

ts
interface ShieldProviderOptions {
  sessionId?: string;
  userId?: string;
  requestId?: string;
  approved?: boolean;
  metadata?: Record<string, unknown>;
  outputSchema?: z.ZodType;
}

SessionState

ts
interface SessionState {
  sessionId: string;
  totalCostUsd: number;
  totalInputTokens: number;
  totalOutputTokens: number;
  requestCount: number;
  budgetExceeded: boolean;
}

AuditLog

ts
interface AuditLog {
  type: AuditEventType;
  timestamp: string;
  sessionId?: string;
  userId?: string;
  requestId?: string;
  modelId?: string;
  details?: Record<string, unknown>;
}

AuditEventType

'request.start' | 'request.complete' | 'request.blocked' | 'guard.triggered' | 'repair.attempt' | 'repair.success' | 'repair.failed' | 'cost.recorded' | 'budget.exceeded' | 'budget.warn' | 'tool.executed' | 'tool.blocked'

ToolGuardOptions

ts
interface ToolGuardOptions {
  allow?: string[];
  deny?: string[];
  maxCallsPerRequest?: number;
  requireApproval?: boolean;
  requestId?: string;
  sessionId?: string;
  userId?: string;
  onBlocked?: (toolName: string, reason: string) => void;
  auditSink?: (log: AuditLog) => void | Promise<void>;
}

Other exported types

| Type | Description | | ---------------------- | ------------------------------------------ | ----------- | | ResolvedShieldConfig | Fully merged config from resolveConfig() | | RequestContext | Internal per-request state | | GuardResult | Result from a guard function | | ModelPricing | { inputPer1M?, outputPer1M? } | | LanguageModel | Alias for LanguageModelV3 | | ShieldRuntime | Shared middleware runtime (advanced) | | AuditLogLevel | 'basic' | 'detailed' |

Feature cross-reference

SymbolFeature doc
Input guardsinput-guardrails.md
Output guardsoutput-guardrails.md
Repairstructured-output.md
Costcost-tracking.md
Auditaudit-logging.md
Toolstool-guards.md