ai-patterns
Version:
Production-ready TypeScript patterns to build solid and robust AI applications. Retry logic, circuit breakers, rate limiting, human-in-the-loop escalation, prompt versioning, response validation, context window management, and more—all with complete type
110 lines • 3.24 kB
TypeScript
/**
* Circuit Breaker Pattern - Protect against failing external services
*/
import { AsyncFunction, Logger } from "../types/common";
import { CircuitState, CircuitBreakerOptions, CircuitBreakerStats } from "../types/circuit-breaker";
/**
* Internal options (without execute field)
*/
interface CircuitBreakerInternalOptions {
failureThreshold?: number;
openDuration?: number;
halfOpenMaxAttempts?: number;
timeout?: number;
shouldCountFailure?: (error: Error) => boolean;
logger?: Logger;
onStateChange?: (oldState: CircuitState, newState: CircuitState) => void;
onOpen?: () => void;
onClose?: () => void;
onHalfOpen?: () => void;
}
/**
* Circuit Breaker - Protects application from failing services
*/
export declare class CircuitBreaker<TResult = any, TArgs extends any[] = any[]> {
private readonly fn;
private state;
private consecutiveFailures;
private totalFailures;
private totalSuccesses;
private totalCalls;
private lastFailureTime;
private lastSuccessTime;
private halfOpenAttempts;
private nextAttemptTime;
private readonly failureThreshold;
private readonly openDuration;
private readonly halfOpenMaxAttempts;
private readonly timeout;
private readonly shouldCountFailure;
private readonly logger;
private readonly onStateChange?;
private readonly onOpen?;
private readonly onClose?;
private readonly onHalfOpen?;
constructor(fn: AsyncFunction<TResult, TArgs>, options?: CircuitBreakerInternalOptions);
/**
* Execute function with circuit breaker protection
*/
execute(...args: TArgs): Promise<TResult>;
/**
* Execute function with timeout
*/
private executeWithTimeout;
/**
* Handle successful execution
*/
private onSuccess;
/**
* Handle failed execution
*/
private onFailure;
/**
* Change circuit state
*/
private changeState;
/**
* Get circuit statistics
*/
getStats(): CircuitBreakerStats;
/**
* Reset circuit to closed state
*/
reset(): void;
/**
* Get current state
*/
getState(): CircuitState;
}
/**
* Callable circuit breaker type (Vercel-style)
*/
export interface CallableCircuitBreaker<TResult = any, TArgs extends any[] = any[]> {
(...args: TArgs): Promise<TResult>;
getState(): CircuitState;
getStats(): CircuitBreakerStats;
reset(): void;
}
/**
* Define a circuit breaker with Vercel-style callable API
*
* @example
* ```typescript
* const breaker = defineCircuitBreaker({
* execute: async () => callAPI(),
* failureThreshold: 5,
* openDuration: 60000
* });
*
* const result = await breaker(); // Direct call
* console.log(breaker.getState()); // Check state
* ```
*/
export declare function defineCircuitBreaker<TResult = any, TArgs extends any[] = any[]>(options: CircuitBreakerOptions<TResult>): CallableCircuitBreaker<TResult, TArgs>;
/**
* @deprecated Use `defineCircuitBreaker` instead for better alignment with Vercel AI SDK patterns
* @see defineCircuitBreaker
*/
export declare const circuitBreaker: typeof defineCircuitBreaker;
export {};
//# sourceMappingURL=circuit-breaker.d.ts.map