ai-resilient 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +139 -0
- package/dist/index.cjs +645 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +187 -0
- package/dist/index.d.ts +187 -0
- package/dist/index.js +612 -0
- package/dist/index.js.map +1 -0
- package/package.json +66 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Usman Gurowa
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# ai-resilient
|
|
2
|
+
|
|
3
|
+
Smart model fallback for the [Vercel AI SDK](https://ai-sdk.dev) (v5).
|
|
4
|
+
|
|
5
|
+
`ai-resilient` wraps a chain of language models in a single `LanguageModelV2` that:
|
|
6
|
+
|
|
7
|
+
- **Reactively falls back** to the next model on rate-limit (429/quota) and transient (5xx/network) errors — but _not_ on fatal errors (400/401/403), which throw immediately.
|
|
8
|
+
- **Proactively switches** away from models that are near a known rate limit, using provider rate-limit response headers (OpenAI, Anthropic, Groq, Google, Mistral) and/or self-counted usage against limits you declare.
|
|
9
|
+
|
|
10
|
+
Works transparently with `generateText`, `streamText`, `generateObject`, and `streamObject`, using your own API keys — no gateway required.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm install ai-resilient ai
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`ai` (v5) and `@ai-sdk/provider` are peer dependencies (`@ai-sdk/provider` ships with `ai`, so most package managers install it automatically). `ai-resilient` has zero runtime dependencies.
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import { generateText } from 'ai';
|
|
24
|
+
import { createResilient } from 'ai-resilient';
|
|
25
|
+
import { groq } from '@ai-sdk/groq';
|
|
26
|
+
import { google } from '@ai-sdk/google';
|
|
27
|
+
|
|
28
|
+
const model = createResilient({
|
|
29
|
+
models: [
|
|
30
|
+
{
|
|
31
|
+
model: groq('llama-3.3-70b-versatile'),
|
|
32
|
+
limits: { requestsPerMinute: 30 },
|
|
33
|
+
},
|
|
34
|
+
{ model: google('gemini-2.0-flash') },
|
|
35
|
+
],
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const { text } = await generateText({ model, prompt: 'Hello!' });
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Models are tried in the order you configure them. The first model is the primary; the rest are fallbacks.
|
|
42
|
+
|
|
43
|
+
## Options
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
createResilient({
|
|
47
|
+
models, // required: [{ model, limits? }, ...]
|
|
48
|
+
store: memoryStore(), // default; pluggable (Redis/KV)
|
|
49
|
+
threshold: 0.1, // skip a model when <10% of a known limit remains
|
|
50
|
+
cooldown: 60_000, // ms to bench a model after a rate-limit error
|
|
51
|
+
onFallback: (info) => {}, // { from, to, reason: 'rate-limit' | 'transient' | 'proactive' }
|
|
52
|
+
onError: (error, modelId) => {},
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Per-model `limits` (`requestsPerMinute`, `requestsPerDay`, `tokensPerMinute`) enable self-counted sliding-window tracking for providers that expose no rate-limit headers.
|
|
57
|
+
|
|
58
|
+
## Behavior
|
|
59
|
+
|
|
60
|
+
| Situation | Behavior |
|
|
61
|
+
| --------------------------------------- | --------------------------------------------------- |
|
|
62
|
+
| 429 / quota exceeded | Bench model (`retry-after` or `cooldown`), try next |
|
|
63
|
+
| 5xx / overloaded / network error | Try next model (no bench) |
|
|
64
|
+
| 400 / 401 / 403 | Throw immediately |
|
|
65
|
+
| Stream error before first content chunk | Fall back, fresh stream on next model |
|
|
66
|
+
| Stream error after first content chunk | Propagate to caller |
|
|
67
|
+
| All models fail | `AllModelsExhaustedError` with per-model attempts |
|
|
68
|
+
| All models near a limit | Try all in order anyway |
|
|
69
|
+
| Store unavailable | Assume available, skip recording |
|
|
70
|
+
|
|
71
|
+
### Error handling
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { AllModelsExhaustedError } from 'ai-resilient';
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
await generateText({ model, prompt: '...' });
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (AllModelsExhaustedError.isInstance(error)) {
|
|
80
|
+
for (const { modelId, classification, error: cause } of error.attempts) {
|
|
81
|
+
console.error(`${modelId} failed (${classification})`, cause);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Custom stores
|
|
88
|
+
|
|
89
|
+
The default `memoryStore()` keeps state in-process, which suits long-running servers. For serverless deployments, plug in any store implementing:
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
interface Store {
|
|
93
|
+
get(key: string): Promise<string | null>;
|
|
94
|
+
set(key: string, value: string, ttlMs?: number): Promise<void>;
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Example Redis adapter (using `ioredis`):
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import Redis from 'ioredis';
|
|
102
|
+
import type { Store } from 'ai-resilient';
|
|
103
|
+
|
|
104
|
+
function redisStore(redis: Redis): Store {
|
|
105
|
+
return {
|
|
106
|
+
async get(key) {
|
|
107
|
+
return redis.get(key);
|
|
108
|
+
},
|
|
109
|
+
async set(key, value, ttlMs) {
|
|
110
|
+
if (ttlMs !== undefined) await redis.set(key, value, 'PX', ttlMs);
|
|
111
|
+
else await redis.set(key, value);
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Store failures never break your calls: if the store throws, models are assumed available and recording is skipped.
|
|
118
|
+
|
|
119
|
+
## API
|
|
120
|
+
|
|
121
|
+
Beyond `createResilient`, these building blocks are exported:
|
|
122
|
+
|
|
123
|
+
| Export | Kind | Purpose |
|
|
124
|
+
| ------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
125
|
+
| `memoryStore()` | function | Default in-process `Store` with TTL eviction. |
|
|
126
|
+
| `AllModelsExhaustedError` | class | Thrown when every model fails; has `attempts: ModelAttempt[]` and static `isInstance(error)`. |
|
|
127
|
+
| `classifyError(error)` | function | Classify any error as `'rate-limit' \| 'transient' \| 'fatal'` — the same logic the fallback loop uses. |
|
|
128
|
+
| `getRetryAfterMs(error)` | function | Parse a `retry-after` header (delta-seconds or HTTP-date) from an error's `responseHeaders` into milliseconds. |
|
|
129
|
+
| `parseRateLimitHeaders(provider, headers)` | function | Parse provider rate-limit headers (OpenAI, Anthropic, Groq, Google, Mistral, IETF draft) into a normalized `ParsedRateLimit`. |
|
|
130
|
+
| `LimitTracker` | class | The tracker behind proactive switching: bench state, header snapshots, sliding-window counters. Useful for custom orchestration on top of the same `Store`. |
|
|
131
|
+
| `Store`, `Limits`, `ModelConfig`, `ResilientOptions`, `FallbackInfo`, `FallbackReason`, `ErrorClassification`, `ModelAttempt`, `ParsedRateLimit` | types | Public types for the options and callbacks above. |
|
|
132
|
+
|
|
133
|
+
## Scope (v1)
|
|
134
|
+
|
|
135
|
+
Language models only. Not included: embeddings/image/speech models, mid-stream fallback (restarting after tokens were emitted), multi-key rotation, cost/latency-based routing.
|
|
136
|
+
|
|
137
|
+
## License
|
|
138
|
+
|
|
139
|
+
MIT
|