Battle-tested TypeScript patterns for building rock-solid AI applications.
We provide developers with battle-tested tools for resilient AI workflows: retry logic, circuit breakers, rate limiting, human-in-the-loop escalation, and more — all with complete type safety and composability. Inspired by Vercel AI SDK's developer experience.
✨ 20 Battle-Tested Patterns - Retry, Circuit Breaker, Timeout, Rate Limiter, Fallback, Cache, Debounce, Throttle, Bulkhead, A/B Testing, Cost Tracking, Prompt Versioning, Response Validation, Context Window Management, and more 🎨 Elegant Composition - Compose patterns together for complex workflows 🔒 Type-Safe - Full TypeScript support with generics and strict mode 🧩 Composable - Patterns work together seamlessly for robust workflows 📊 Observable - Built-in lifecycle callbacks for monitoring and debugging 🪶 Lightweight - Zero dependencies, minimal overhead ⚡ Production-Ready - Build solid AI applications with confidence 🎯 Developer-Friendly - Inspired by Vercel AI SDK's excellent DX 💰 Cost Control - Track and control AI spending in real-time 🧪 Experimentation - A/B test prompts and models to optimize performance
💡 Note: While Vercel AI SDK has built-in retry (maxRetries: 2), ai-patterns gives you more flexibility:
- 🎛️ Custom backoff strategies (exponential, linear, fixed)
- 📊 Detailed observability (attempts, delays, errors)
- 🔄 Cross-provider fallback (OpenAI → Claude → Gemini)
- 🎯 Advanced retry logic (conditional, circuit breakers)
Building AI applications? You're probably facing these challenges:
❌ Copy-pasting retry logic across every API call ❌ No circuit breakers — one API failure brings down your entire app ❌ Constantly hitting rate limits with no systematic handling ❌ No human oversight for edge cases that need review
With ai-patterns:
✅ Battle-tested patterns ready to use out of the box ✅ Compose like Lego blocks — combine patterns seamlessly ✅ Full type safety — catch errors at compile time ✅ Zero dependencies — lightweight and production-ready
Before ai-patterns:
After ai-patterns:
That's it. Simple, reliable, production-ready.
Use defineCircuitBreaker and defineRateLimiter for patterns that maintain state:
Compose patterns together for robust workflows using the compose() function:
Tip: You can also nest patterns directly if you prefer explicit control flow.
For advanced composition strategies:
| compose | Functional pattern composition | Complex AI pipelines | 📖 |
| retry | Automatic retry with exponential backoff | Unstable APIs, network issues | 📖 |
| timeout | Time limits with AbortSignal support | Long-running operations | 📖 |
| fallback | Execute alternatives on failure | Multi-provider failover | 📖 |
| defineCircuitBreaker | Protect against failing services | External API calls | 📖 |
| defineRateLimiter | Control request throughput | API rate limiting | 📖 |
| memoize | Cache function results with TTL | Response caching | 📖 |
| defineDebounce | Delay execution until silence period | User input handling | 📖 |
| defineThrottle | Limit execution frequency | API call throttling | 📖 |
| defineBulkhead | Isolate resources with concurrency limits | Resource isolation | 📖 |
| deadLetterQueue | Handle failed operations | Error recovery | 📖 |
| fanOut | Parallel processing with concurrency control | Batch operations | 📖 |
| saga | Distributed transactions with compensation | Multi-step workflows | 📖 |
| conditionalBranch | Route based on conditions | Dynamic workflow routing | 📖 |
| humanInTheLoop | AI → Human escalation | Content moderation | 📖 |
| smartContextWindow | Manage context token limits automatically | Long conversations, chat apps | 📖 |
| idempotency | Prevent duplicate operations | Payment processing | 📖 |
| abTest | Test multiple variants simultaneously | Prompt optimization, model selection | 📖 |
| costTracking | Monitor and control AI spending | Budget management, cost optimization | 📖 |
| versionedPrompt | Manage prompt versions with rollback | Prompt experimentation, gradual rollout | 📖 |
| validateResponse | Validate AI responses with auto-retry | Quality assurance, business rules | 📖 |
For detailed pattern documentation:
- Compose Pattern →
- Retry Pattern →
- Timeout Pattern →
- Circuit Breaker →
- Rate Limiter →
- Fan-Out →
- Saga →
- Human-in-the-Loop →
- Smart Context Window →
- Idempotency →
- A/B Testing →
- Cost Tracking →
- Prompt Versioning →
- Response Validation →
Runnable examples:
Each pattern has a simple runnable example:
- retry-simple.ts
- timeout-simple.ts
- circuit-breaker-simple.ts
- rate-limiter-simple.ts
- fan-out-simple.ts
- saga-simple.ts
- human-in-loop-simple.ts
- idempotency-simple.ts
- ab-test-simple.ts
- cost-tracking-simple.ts
- prompt-versioning-simple.ts
- response-validation-simple.ts
- context-window-simple.ts
- ab-test-with-cost-tracking.ts - Combine A/B testing with cost tracking for ROI optimization
- prompt-versioning-with-monitoring.ts - Prompt versioning with retry logic and analytics
- response-validation-with-retry.ts - Response validation with timeout, retry, and moderation
- context-window-with-summarization.ts - Context window management with AI summarization
Coming soon:
- E-commerce - Order processing with saga, retry, and idempotency
- AI Agent - Chatbot with human escalation and circuit breakers
- Microservices - API gateway with rate limiting and retries
- Retry Pattern
- Timeout Pattern
- Circuit Breaker Pattern
- Rate Limiter Pattern
- Fan-Out Pattern
- Saga Pattern
- Human-in-the-Loop Pattern
- Smart Context Window Pattern
- Idempotency Pattern
- A/B Testing Pattern
- Cost Tracking Pattern
- Prompt Versioning Pattern
- Response Validation Pattern
All patterns follow a consistent API design:
See the API Reference for complete details.
Built with TypeScript strict mode for maximum type safety:
Contributions are welcome! Please read our Contributing Guide.
MIT © Serge KOKOUA
Inspired by:
- Vercel AI SDK - Developer experience
- Polly - Resilience patterns
- ts-retry - TypeScript patterns
Built with ❤️ by Serge KOKOUA
Empowering developers to build solid and robust AI applications.
.png)

