ai-sdk-guardrails
Version:
Input and output guardrails middleware for Vercel AI SDK.
156 lines (153 loc) • 6.34 kB
TypeScript
import { I as InputGuardrail, a as InputGuardrailContext } from '../types-C7t6e3EI.js';
import { D as DetectNormalizationOptions } from '../normalization-D6TVuWIv.js';
import 'ai';
import '@ai-sdk/provider';
declare const SEVERITY_LEVELS: {
readonly LOW: "low";
readonly MEDIUM: "medium";
readonly HIGH: "high";
readonly CRITICAL: "critical";
};
type SeverityLevel = (typeof SEVERITY_LEVELS)[keyof typeof SEVERITY_LEVELS];
declare function extractTextContent(context: InputGuardrailContext): {
prompt: string;
messages: Array<{
content?: unknown;
}>;
system: string;
allText: string;
allTextLower: string;
totalBytes: number;
totalWords: number;
};
declare function extractMetadata(context: InputGuardrailContext): {
model?: unknown;
temperature?: number;
maxOutputTokens?: number;
};
interface LengthLimitOptions {
maxLength: number;
countMethod?: 'characters' | 'bytes' | 'words';
severity?: SeverityLevel;
}
declare const inputLengthLimit: (options: LengthLimitOptions | number) => InputGuardrail;
declare const lengthLimit: (maxLength: number) => InputGuardrail;
interface BlockedWordsOptions {
words: string[];
allowlist?: string[];
useWordBoundaries?: boolean;
severity?: SeverityLevel;
}
declare const blockedWords: (options: BlockedWordsOptions | string[]) => InputGuardrail;
declare const contentLengthLimit: (maxLength: number) => InputGuardrail;
declare const blockedKeywords: (keywords: string[]) => InputGuardrail;
interface RateLimitingOptions {
maxRequestsPerMinute: number;
windowMs?: number;
privacyMode?: boolean;
includeServerHints?: boolean;
}
declare const rateLimiting: (options: RateLimitingOptions | number) => InputGuardrail;
interface ProfanityCategory {
words: string[];
severity: SeverityLevel;
category: string;
}
interface ProfanityFilterOptions {
categories?: ProfanityCategory[];
customWords?: string[];
locale?: string;
useWordBoundaries?: boolean;
}
declare const profanityFilter: (options?: ProfanityFilterOptions | string[]) => InputGuardrail;
interface CustomValidationInput {
prompt: string;
messages: Array<{
content?: unknown;
}>;
system: string;
model?: string;
temperature?: number;
maxOutputTokens?: number;
allText: string;
allTextLower: string;
totalBytes: number;
totalWords: number;
}
interface CustomValidationResult {
isValid: boolean;
reasonCode?: string;
details?: Record<string, unknown>;
}
type CustomValidationFn = (payload: CustomValidationInput) => CustomValidationResult | boolean;
interface CustomValidationOptions {
name: string;
description: string;
validator: CustomValidationFn;
message?: string;
severity?: SeverityLevel;
reasonCode?: string;
}
declare const customValidation: (options: CustomValidationOptions | [string, string, CustomValidationFn, string]) => InputGuardrail;
interface PromptInjectionOptions {
threshold?: number;
includeExamples?: boolean;
/**
* Normalize input before matching to defeat obfuscation (homoglyphs,
* zero-width characters, leetspeak, spaced letters, typos). Enabled by
* default. Pass `false` to match raw text, or an object to tune stages.
*/
normalize?: boolean | DetectNormalizationOptions;
}
declare const promptInjectionDetector: (options?: PromptInjectionOptions) => InputGuardrail;
interface HighEntropyOptions {
/** Bits/char at or above which input is flagged. Default 4.5. */
threshold?: number;
/** Skip strings shorter than this (entropy is noisy on short text). Default 40. */
minLength?: number;
severity?: SeverityLevel;
}
/**
* Flags input whose Shannon entropy is abnormally high — a signal of encoded or
* obfuscated payloads (base64 blobs, ciphertext, packed data) smuggled into a
* prompt. Natural language sits well below the default threshold.
*
* @example
* withGuardrails({ model, inputGuardrails: [highEntropyDetector()] });
*/
declare const highEntropyDetector: (options?: HighEntropyOptions) => InputGuardrail;
declare const piiDetector: () => InputGuardrail;
declare const toxicityDetector: (threshold?: number) => InputGuardrail;
interface MathHomeworkOptions {
enabled?: boolean;
strictMode?: boolean;
allowedContexts?: string[];
severity?: SeverityLevel;
}
declare const mathHomeworkDetector: (options?: MathHomeworkOptions) => InputGuardrail;
type CodeGenerationMode = 'deny' | 'allow-only';
interface CodeGenerationOptions {
allowedLanguages?: string[];
deniedLanguages?: string[];
mode?: CodeGenerationMode;
severity?: SeverityLevel;
}
declare const codeGenerationLimiter: (options?: CodeGenerationOptions | string[]) => InputGuardrail;
/**
* Allowed tools guardrail that validates tool calls against allowed/denied lists
* This guardrail works with the AI SDK's tool system to prevent unauthorized tool usage
*/
interface AllowedToolsOptions {
/** List of explicitly allowed tool names - REQUIRED for security */
allowedTools: string[];
/** List of explicitly denied tool names (takes precedence over allowed) */
deniedTools?: string[];
/** Custom tool validation function */
customValidator?: (toolName: string, context: InputGuardrailContext) => boolean;
/** Whether to detect tool calls in natural language requests */
detectNaturalLanguageTools?: boolean;
/** Custom tool name patterns to detect in natural language */
toolPatterns?: RegExp[];
}
declare const allowedToolsGuardrail: (options: AllowedToolsOptions) => InputGuardrail;
export { type AllowedToolsOptions, type BlockedWordsOptions, type CodeGenerationMode, type CodeGenerationOptions, type CustomValidationInput, type CustomValidationOptions, type CustomValidationResult, type HighEntropyOptions, type LengthLimitOptions, type MathHomeworkOptions, type ProfanityCategory, type ProfanityFilterOptions, type PromptInjectionOptions, type RateLimitingOptions, allowedToolsGuardrail, blockedKeywords, blockedWords, codeGenerationLimiter, contentLengthLimit, customValidation, extractMetadata, extractTextContent, highEntropyDetector, inputLengthLimit, lengthLimit, mathHomeworkDetector, piiDetector, profanityFilter, promptInjectionDetector, rateLimiting, toxicityDetector };