ai-sdk-guardrails
Version:
Input and output guardrails middleware for Vercel AI SDK.
235 lines (223 loc) • 9.38 kB
TypeScript
import { q as GuardrailContext, C as CheckFn, G as GuardrailResult, P as PipelineConfig, r as GuardrailBundle, s as GuardrailBundleResult, I as InputGuardrail, O as OutputGuardrail } from '../types-C7t6e3EI.js';
export { t as GuardrailConfig } from '../types-C7t6e3EI.js';
import { z } from 'zod';
import 'ai';
import '@ai-sdk/provider';
/**
* Guardrail specification and instantiation helpers aligned with the
* OpenAI Guardrails configuration/runtime model.
*
* Guardrails are registered via GuardrailSpec objects that describe the
* guardrail's name, description, media type, configuration schema, and
* check implementation. Configured guardrails are produced by binding a
* specification to a validated configuration object.
*/
/**
* Structured metadata describing how a guardrail behaves.
*
* We retain the richer metadata surface we historically exposed while
* remaining compatible with the OpenAI registry model.
*/
interface GuardrailSpecMetadata {
engine?: string;
version?: string;
category?: 'security' | 'quality' | 'compliance' | 'performance' | 'content';
requiresExternalApi?: boolean;
estimatedLatencyMs?: number;
tags?: string[];
usesConversationHistory?: boolean;
[key: string]: unknown;
}
/**
* Immutable descriptor for a registered guardrail.
*
* The constructor arguments match the OpenAI implementation so configs
* generated by https://guardrails.openai.com can be consumed directly.
*/
declare class GuardrailSpec<TContext extends GuardrailContext = GuardrailContext, TInput = unknown, TConfig = Record<string, unknown>> {
readonly name: string;
readonly description: string;
readonly mediaType: string;
readonly configSchema: z.ZodType<TConfig>;
readonly checkFn: CheckFn<TContext, TInput, TConfig>;
readonly ctxRequirements?: z.ZodType<TContext> | undefined;
readonly metadata?: GuardrailSpecMetadata | undefined;
constructor(name: string, description: string, mediaType: string, configSchema: z.ZodType<TConfig>, checkFn: CheckFn<TContext, TInput, TConfig>, ctxRequirements?: z.ZodType<TContext> | undefined, metadata?: GuardrailSpecMetadata | undefined);
/**
* Return a JSON schema-like representation for tooling/SDKs.
*/
schema(): Record<string, unknown>;
/**
* Instantiate the guardrail with validated configuration.
*/
instantiate(config: TConfig): ConfiguredGuardrail<TContext, TInput, TConfig>;
}
/**
* An executable guardrail bound to configuration.
*
* Mirrors the OpenAI implementation but keeps our richer result context.
*/
declare class ConfiguredGuardrail<TContext extends GuardrailContext = GuardrailContext, TInput = unknown, TConfig = Record<string, unknown>> {
readonly spec: GuardrailSpec<TContext, TInput, TConfig>;
readonly config: TConfig;
constructor(spec: GuardrailSpec<TContext, TInput, TConfig>, config: TConfig);
private ensureAsync;
run(context: TContext, input: TInput): Promise<GuardrailResult>;
}
/**
* Runtime execution module for guardrails with parallel processing support.
*
* This module provides the runtime infrastructure for executing guardrails,
* including parallel execution, timeout handling, and configuration loading.
*/
/**
* Options for running guardrails
*/
interface RunGuardrailsOptions {
/** Whether to throw on guardrail execution errors */
raiseGuardrailErrors?: boolean;
/** Whether to run guardrails in parallel */
parallelExecution?: boolean;
/** Timeout for individual guardrails */
timeoutMs?: number;
/** Global timeout for all guardrails */
globalTimeoutMs?: number;
/** Abort signal for cancellation */
signal?: AbortSignal;
}
/**
* Run multiple guardrails and return aggregated results
*/
declare function runGuardrails(input: unknown, bundle: GuardrailBundle, context?: GuardrailContext, options?: RunGuardrailsOptions): Promise<GuardrailBundleResult>;
/**
* Instantiate guardrails from a bundle configuration
*/
declare function instantiateGuardrails(bundle: GuardrailBundle): Promise<ConfiguredGuardrail[]>;
/**
* Load pipeline configuration from various sources
*/
declare function loadPipelineConfig(config: string | PipelineConfig): Promise<PipelineConfig>;
/**
* Load a guardrail bundle from configuration
*/
declare function loadGuardrailBundle(config: unknown): GuardrailBundle;
/**
* Check plain text with a guardrail bundle
*/
declare function checkPlainText(text: string, bundle: GuardrailBundle, context?: GuardrailContext, options?: RunGuardrailsOptions): Promise<void>;
/**
* Run guardrails for a specific stage in the pipeline
*/
declare function runStageGuardrails(input: unknown, pipeline: PipelineConfig, stage: 'pre_flight' | 'input' | 'output', context?: GuardrailContext, options?: RunGuardrailsOptions): Promise<GuardrailBundleResult | null>;
/**
* Validate a pipeline configuration
*/
declare function validatePipelineConfig(config: PipelineConfig): string[];
/**
* Export configuration utilities
*/
declare const configUtils: {
loadPipelineConfig: typeof loadPipelineConfig;
loadGuardrailBundle: typeof loadGuardrailBundle;
validatePipelineConfig: typeof validatePipelineConfig;
};
/**
* Export runtime utilities
*/
declare const runtimeUtils: {
runGuardrails: typeof runGuardrails;
runStageGuardrails: typeof runStageGuardrails;
checkPlainText: typeof checkPlainText;
instantiateGuardrails: typeof instantiateGuardrails;
};
/**
* Guardrail specification registry compatible with OpenAI's config/runtime.
*
* This closely mirrors the implementation from openai-guardrails-js so
* guardrail names and metadata align with configs authored in the wizard.
*/
interface RegistryMetadataSnapshot {
name: string;
description: string;
mediaType: string;
hasConfig: boolean;
hasContext: boolean;
metadata?: GuardrailSpecMetadata;
}
declare class GuardrailRegistry {
private specs;
registerSpec(spec: GuardrailSpec<GuardrailContext, unknown, Record<string, unknown>>): void;
register<TContext extends GuardrailContext = GuardrailContext, TInput = unknown, TConfig = Record<string, unknown>>(name: string, checkFn: CheckFn<TContext, TInput, TConfig>, description: string, mediaType?: string, configSchema?: z.ZodType<TConfig>, ctxRequirements?: z.ZodType<TContext>, metadata?: GuardrailSpecMetadata): void;
get(name: string): GuardrailSpec | undefined;
has(name: string): boolean;
remove(name: string): boolean;
size(): number;
all(): GuardrailSpec[];
list(): GuardrailSpec[];
metadata(): RegistryMetadataSnapshot[];
}
declare const defaultRegistry: GuardrailRegistry;
declare function createRegistry(): GuardrailRegistry;
/**
* Configuration mapper for converting between OpenAI config format and our internal convention
*
* This module provides utilities to map from OpenAI's guardrails config format
* (used at https://guardrails.openai.com) to our internal `withGuardrails` API format.
* This enables public-facing APIs to accept OpenAI configs while using our internal conventions.
*/
/**
* Converts OpenAI PipelineConfig format to our internal `withGuardrails` config format
*
* This function maps from OpenAI's config structure (with pre_flight, input, output stages)
* to our internal format that can be used with `withGuardrails()`.
*
* @param openAIConfig - OpenAI guardrails config format
* @returns Config object compatible with `withGuardrails()` API
*
* @example
* ```typescript
* import { openai } from '@ai-sdk/openai';
* import { withGuardrails, mapOpenAIConfigToGuardrails } from 'ai-sdk-guardrails';
*
* const openAIConfig = {
* version: 1,
* input: {
* version: 1,
* guardrails: [
* { name: 'Contains PII', config: { entities: ['EMAIL_ADDRESS'] } }
* ]
* }
* };
*
* const guardrailsConfig = mapOpenAIConfigToGuardrails(openAIConfig);
* const model = withGuardrails(openai('gpt-4o'), guardrailsConfig);
* ```
*/
declare function mapOpenAIConfigToGuardrails(openAIConfig: PipelineConfig): {
inputGuardrails?: InputGuardrail<Record<string, unknown>>[];
outputGuardrails?: OutputGuardrail<Record<string, unknown>>[];
};
/**
* Type helper for the result of mapOpenAIConfigToGuardrails
*/
type GuardrailsConfigFromOpenAI = ReturnType<typeof mapOpenAIConfigToGuardrails>;
/**
* Adapters for converting between guardrails and spec patterns
*
* This module enables:
* - Guardrails to work with evaluation framework
* - Enhanced specs to export as standard guardrails
* - Parallel execution for guardrails
* - Configuration support for guardrails
*/
/**
* Register guardrails in the enhanced registry
* This enables:
* - Discovery through registry
* - Evaluation support
* - Configuration management
*/
declare function registerGuardrails(guardrails: Array<InputGuardrail | OutputGuardrail>, options?: {
prefix?: string;
}): void;
export { ConfiguredGuardrail, GuardrailBundle, GuardrailBundleResult, GuardrailContext, GuardrailRegistry, GuardrailResult, GuardrailSpec, type GuardrailsConfigFromOpenAI, PipelineConfig, checkPlainText, configUtils, createRegistry, defaultRegistry, instantiateGuardrails, loadGuardrailBundle, loadPipelineConfig, mapOpenAIConfigToGuardrails, registerGuardrails, runGuardrails, runStageGuardrails, runtimeUtils, validatePipelineConfig };