ai-mock-provider 0.0.0-stage → 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 +433 -2
- package/dist/index.cjs +1119 -0
- package/dist/index.mjs +1076 -0
- package/dist/types/index.d.ts +11 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/lorem.d.ts +20 -0
- package/dist/types/lorem.d.ts.map +1 -0
- package/dist/types/model.d.ts +29 -0
- package/dist/types/model.d.ts.map +1 -0
- package/dist/types/provider.d.ts +3 -0
- package/dist/types/provider.d.ts.map +1 -0
- package/dist/types/random.d.ts +3 -0
- package/dist/types/random.d.ts.map +1 -0
- package/dist/types/scenarios.d.ts +6 -0
- package/dist/types/scenarios.d.ts.map +1 -0
- package/dist/types/speed.d.ts +10 -0
- package/dist/types/speed.d.ts.map +1 -0
- package/dist/types/tool-input.d.ts +4 -0
- package/dist/types/tool-input.d.ts.map +1 -0
- package/dist/types/types.d.ts +94 -0
- package/dist/types/types.d.ts.map +1 -0
- package/package.json +79 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Magiksoft s.r.o.
|
|
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
CHANGED
|
@@ -1,3 +1,434 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ai-mock-provider
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A **mock provider for the [Vercel AI SDK](https://ai-sdk.dev)** — a fake LLM for testing streaming, tool calling and agents. No API keys, no network, no GPU.
|
|
4
|
+
|
|
5
|
+
Implements the [Vercel AI SDK](https://ai-sdk.dev) `LanguageModelV4` provider specification, so it drops straight into `generateText`, `streamText`, `generateObject`, `embed` and multi-step agents. It answers with **canned, scenario-based responses** (markdown headings, tables, LaTeX math, code blocks, JSON, images, files, tool calls, reasoning…), streams them at a **configurable tokens-per-second rate** — controllable straight from the user message — and supports sequential multi-call scripts, error simulation and abort handling.
|
|
6
|
+
|
|
7
|
+
## Why
|
|
8
|
+
|
|
9
|
+
Testing UIs and agents that consume LLM streams needs a model that behaves like a real one:
|
|
10
|
+
|
|
11
|
+
- streams token by token, at a realistic (and controllable) speed
|
|
12
|
+
- responds differently depending on what the user asks for
|
|
13
|
+
- can produce reasoning tokens, tool calls, files, structured output
|
|
14
|
+
- can fail mid-stream, get truncated, or be aborted
|
|
15
|
+
|
|
16
|
+
`ai-mock-provider` does all of this deterministically. Related tools: the built-in `MockLanguageModelV4` from `ai/test` gives you raw stream parts but no scenarios or speed control; [`@copilotkit/aimock`](https://github.com/CopilotKit/aimock) mocks providers over HTTP instead of in-process; [`llmao`](https://github.com/icernigoj/llmao) scripts responses but has no scenario library and no prompt-driven speed control.
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npm install ai-mock-provider
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Peer dependency: `@ai-sdk/provider` v4 (already available if you use AI SDK v7 or any v4 provider).
|
|
25
|
+
|
|
26
|
+
## Quick start
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { createMockProvider } from 'ai-mock-provider';
|
|
30
|
+
import { streamText } from 'ai';
|
|
31
|
+
|
|
32
|
+
const provider = createMockProvider();
|
|
33
|
+
|
|
34
|
+
const result = streamText({
|
|
35
|
+
model: provider.languageModel('tables'),
|
|
36
|
+
prompt: 'compare cloud providers',
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
for await (const delta of result.textStream) {
|
|
40
|
+
process.stdout.write(delta);
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
You can select a scenario two ways:
|
|
45
|
+
|
|
46
|
+
1. **Model id** — `provider.languageModel('math')` forces the `math` scenario for every call.
|
|
47
|
+
2. **Keywords in the user message** — with any model id, the last user message is matched against scenario keywords: *"please respond with tables"* selects the `tables` scenario.
|
|
48
|
+
|
|
49
|
+
If nothing matches, the `default` scenario answers with an overview of everything the provider can do.
|
|
50
|
+
|
|
51
|
+
## Controlling streaming speed from the user message
|
|
52
|
+
|
|
53
|
+
Include a speed directive anywhere in the prompt. The directive is parsed, applied to the current call, and stripped from the text before scenario matching.
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
at 30 t/s
|
|
57
|
+
at 20 tokens per second
|
|
58
|
+
at 45 tps
|
|
59
|
+
at 12 tok/s
|
|
60
|
+
instantly
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
const result = streamText({
|
|
65
|
+
model: provider.languageModel('long-text'),
|
|
66
|
+
prompt: 'write a long story at 20 tokens per second',
|
|
67
|
+
});
|
|
68
|
+
// streams for ~length/4/20 seconds
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Precedence: **prompt directive > scenario/response override > provider default**.
|
|
72
|
+
|
|
73
|
+
## Built-in scenarios
|
|
74
|
+
|
|
75
|
+
| Scenario id | Triggered by keywords | Produces |
|
|
76
|
+
|---|---|---|
|
|
77
|
+
| `headings` | heading, headings, title, section | Markdown headings H1–H6, bold/italic/inline code |
|
|
78
|
+
| `tables` | table, tables, tabular, comparison, columns | Two markdown tables (default + aligned) |
|
|
79
|
+
| `code` | code, snippet, function, typescript, javascript, python… | Fenced code blocks in TypeScript and Python |
|
|
80
|
+
| `math` | math, formula, equations, latex, katex, integral | Inline `$…$` and display `$$…$$` LaTeX |
|
|
81
|
+
| `lists` | list, bullet, steps, checklist | Ordered, unordered and nested lists |
|
|
82
|
+
| `links` | link, hyperlink, citation, url | Markdown links and bare URLs |
|
|
83
|
+
| `blockquotes` | quote, blockquote, quotation | Simple and nested blockquotes |
|
|
84
|
+
| `long-text` | long, essay, article, detailed, story | Multi-paragraph prose |
|
|
85
|
+
| `reasoning` | think, reasoning, reason, why, step by step | Reasoning deltas followed by the answer |
|
|
86
|
+
| `tool-calls` | tool, weather, lookup | A `get_weather` tool call (input generated from your declared tools) |
|
|
87
|
+
| `provider-tools` | web search, provider tool, provider-executed, built-in tool | Tool call + provider-executed tool-result in one response |
|
|
88
|
+
| `json` | json, structured, schema | Pretty-printed JSON (also used for `responseFormat: json`) |
|
|
89
|
+
| `image-part` | image, picture, photo, png | A 1×1 PNG file part surrounded by text |
|
|
90
|
+
| `file-part` | file, attachment, document, pdf | A `text/plain` file part surrounded by text |
|
|
91
|
+
| `lorem` | lorem, filler, dummy text, placeholder text, random text | Random lorem-ipsum filler text (see below) |
|
|
92
|
+
| `error` | error, fail, crash, explode | Text, then a mid-stream error |
|
|
93
|
+
| `max-tokens` | max tokens, token limit, truncate, cut off | Truncated text with `length` finish reason |
|
|
94
|
+
| `default` | (fallback) | Overview of all scenarios |
|
|
95
|
+
|
|
96
|
+
### Random text (lorem ipsum)
|
|
97
|
+
|
|
98
|
+
The `lorem` scenario streams freshly generated lorem-ipsum filler (powered by the zero-dependency [`lorem-ipsum`](https://www.npmjs.com/package/lorem-ipsum) package) — ideal for testing long-stream rendering, truncation and performance without canned content.
|
|
99
|
+
|
|
100
|
+
The amount is controllable **from the user message**:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
await generateText({ model: provider.languageModel('lorem'), prompt: 'write 30 words of lorem ipsum' });
|
|
104
|
+
await generateText({ model: provider.languageModel('lorem'), prompt: 'give me 4 sentences of filler' });
|
|
105
|
+
await generateText({ model: provider.languageModel('lorem'), prompt: 'generate 3 paragraphs of lorem' });
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Randomness is reproducible: pass a `seed` and every provider instance generates the identical sequence of texts — perfect for snapshot tests. Without a seed, each instance is different.
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const deterministic = createMockProvider({ seed: 42 });
|
|
112
|
+
const chaotic = createMockProvider();
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Configuration
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
const provider = createMockProvider({
|
|
119
|
+
// Streaming speed fallback (tokens/second). 0 = instant (default).
|
|
120
|
+
tokensPerSecond: 100,
|
|
121
|
+
|
|
122
|
+
// Delay before the first streamed content part, in ms (default 0).
|
|
123
|
+
firstTokenDelayMs: 250,
|
|
124
|
+
|
|
125
|
+
// Characters per simulated token (default 4).
|
|
126
|
+
chunkSize: 4,
|
|
127
|
+
|
|
128
|
+
// Scenario used when neither the model id nor keywords match.
|
|
129
|
+
defaultScenario: 'default',
|
|
130
|
+
|
|
131
|
+
// Add or override scenarios (see below).
|
|
132
|
+
scenarios: { /* ... */ },
|
|
133
|
+
|
|
134
|
+
// Sequential per-call scripts (see "Multi-call responses").
|
|
135
|
+
responses: ['headings', 'tables'],
|
|
136
|
+
|
|
137
|
+
// Seed for the internal PRNG: identical seeds produce identical
|
|
138
|
+
// random text sequences (deterministic tests). Omit for true randomness.
|
|
139
|
+
seed: 42,
|
|
140
|
+
|
|
141
|
+
// Defaults for lorem parts (see "Random text" above).
|
|
142
|
+
lorem: {
|
|
143
|
+
unit: 'paragraphs', // 'words' | 'sentences' | 'paragraphs'
|
|
144
|
+
count: 3,
|
|
145
|
+
sentencesPerParagraph: { min: 3, max: 7 },
|
|
146
|
+
wordsPerSentence: { min: 6, max: 14 },
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
// Preset tool inputs by name (see "Tool calls" below) — beat schema generation.
|
|
150
|
+
toolInputs: { get_weather: { city: 'Oslo', unit: 'celsius', days: 3 } },
|
|
151
|
+
});
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
## Configuration
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
const provider = createMockProvider({
|
|
158
|
+
// Streaming speed fallback (tokens/second). 0 = instant (default).
|
|
159
|
+
tokensPerSecond: 100,
|
|
160
|
+
|
|
161
|
+
// Delay before the first streamed content part, in ms (default 0).
|
|
162
|
+
firstTokenDelayMs: 250,
|
|
163
|
+
|
|
164
|
+
// Characters per simulated token (default 4).
|
|
165
|
+
chunkSize: 4,
|
|
166
|
+
|
|
167
|
+
// Scenario used when neither the model id nor keywords match.
|
|
168
|
+
defaultScenario: 'default',
|
|
169
|
+
|
|
170
|
+
// Add or override scenarios (see below).
|
|
171
|
+
scenarios: { /* ... */ },
|
|
172
|
+
|
|
173
|
+
// Sequential per-call scripts (see "Multi-call responses").
|
|
174
|
+
responses: ['headings', 'tables'],
|
|
175
|
+
});
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Models are created like with any other provider:
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
provider(modelId);
|
|
182
|
+
provider.languageModel(modelId);
|
|
183
|
+
provider.chat(modelId);
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Each model instance records its calls for assertions:
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
model.calls;
|
|
190
|
+
// [{ modelId, scenarioId, prompt, tokensPerSecond, firstTokenDelayMs, timestamp }]
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
## Multi-call responses
|
|
194
|
+
|
|
195
|
+
Script different responses per call — useful for multi-step agents ("call 1 plans, call 2 answers"). Queue items are consumed in order; after exhaustion, normal scenario resolution resumes.
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
const provider = createMockProvider({
|
|
199
|
+
responses: [
|
|
200
|
+
'headings', // a scenario id
|
|
201
|
+
{ text: 'Second scripted answer.' }, // inline text shorthand
|
|
202
|
+
{ parts: [{ type: 'tool-call', toolName: 'get_weather', input: { city: 'Oslo' } }] },
|
|
203
|
+
{ text: 'Now it is 12°C.', tokensPerSecond: 50 },
|
|
204
|
+
],
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
const model = provider.languageModel('agent-model');
|
|
208
|
+
await generateText({ model, prompt: 'step 1' }); // headings
|
|
209
|
+
await generateText({ model, prompt: 'step 2' }); // 'Second scripted answer.'
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
A queue item may set `tokensPerSecond` / `firstTokenDelayMs` for that call (a prompt directive still wins).
|
|
213
|
+
|
|
214
|
+
## Tool calls
|
|
215
|
+
|
|
216
|
+
The provider emits provider-spec tool call stream parts, so real tool execution works:
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
import { generateText, tool, stepCountIs, jsonSchema } from 'ai';
|
|
220
|
+
|
|
221
|
+
const provider = createMockProvider({
|
|
222
|
+
responses: [
|
|
223
|
+
{ parts: [{ type: 'tool-call', toolName: 'get_weather', input: { city: 'San Francisco' } }] },
|
|
224
|
+
{ text: 'It is 18°C and foggy.' },
|
|
225
|
+
],
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
const result = await generateText({
|
|
229
|
+
model: provider.languageModel('weather-model'),
|
|
230
|
+
prompt: 'what is the weather in San Francisco?',
|
|
231
|
+
tools: {
|
|
232
|
+
get_weather: tool({
|
|
233
|
+
description: 'Get the weather for a city',
|
|
234
|
+
inputSchema: jsonSchema({ type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }),
|
|
235
|
+
execute: async (input) => ({ temperature: 18, condition: 'foggy' }),
|
|
236
|
+
}),
|
|
237
|
+
},
|
|
238
|
+
stopWhen: stepCountIs(5),
|
|
239
|
+
});
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### Inputs from your declared tools
|
|
243
|
+
|
|
244
|
+
You don't have to script inputs. When the client passes `tools`, the provider generates schema-plausible inputs for the tool it calls — respecting `enum`, `minimum`/`maximum`, `minLength`/`maxLength`, formats (`email`, `uri`, `date-time`, `uuid`…), `default`/`examples`/`const`, and common property-name hints (`city` → `"San Francisco"`, `name` → `"Ada Lovelace"`…). If a canned scenario names a tool that isn't declared, it is remapped to your first declared tool and its input is generated from your schema.
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
const provider = createMockProvider(); // 'tool-calls' scenario matches "what is the weather?"
|
|
248
|
+
const result = await generateText({
|
|
249
|
+
model: provider.languageModel('agent'),
|
|
250
|
+
prompt: 'what is the weather? use the tool',
|
|
251
|
+
tools: {
|
|
252
|
+
get_weather: tool({
|
|
253
|
+
inputSchema: jsonSchema({
|
|
254
|
+
type: 'object',
|
|
255
|
+
properties: {
|
|
256
|
+
city: { type: 'string', minLength: 3 },
|
|
257
|
+
unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
|
|
258
|
+
days: { type: 'integer', minimum: 1, maximum: 7 },
|
|
259
|
+
},
|
|
260
|
+
required: ['city', 'unit', 'days'],
|
|
261
|
+
}),
|
|
262
|
+
execute: async (input) => {
|
|
263
|
+
// input is schema-valid: { city: 'San Francisco', unit: 'fahrenheit', days: 4 } (seeded → reproducible)
|
|
264
|
+
return { temperature: 21 };
|
|
265
|
+
},
|
|
266
|
+
}),
|
|
267
|
+
},
|
|
268
|
+
});
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
Prefer fixed inputs? Preset them per tool — presets win over generation:
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
const provider = createMockProvider({ toolInputs: { get_weather: { city: 'Oslo', unit: 'celsius', days: 3 } } });
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
Or author explicit inputs on the tool-call part (kept verbatim when the tool is declared).
|
|
278
|
+
|
|
279
|
+
### toolChoice support
|
|
280
|
+
|
|
281
|
+
| `toolChoice` | Behavior |
|
|
282
|
+
|---|---|
|
|
283
|
+
| `auto` / omitted | Scenario decides (the `tool-calls` scenario calls tools) |
|
|
284
|
+
| `none` | Tool-call parts are stripped — text only |
|
|
285
|
+
| `required` | Guarantees a tool call (first declared tool, generated input) |
|
|
286
|
+
| `{ type: 'tool', toolName }` | Forces a call to that exact tool on every step |
|
|
287
|
+
|
|
288
|
+
After a tool result is sent back (natural `auto` flow), the provider answers with text instead of calling the tool again — so agent loops terminate cleanly.
|
|
289
|
+
|
|
290
|
+
### Provider-executed tool results
|
|
291
|
+
|
|
292
|
+
The v4 spec supports tools executed by the provider itself (like real web search or code interpreter). Author a `tool-result` part after a tool-call part and the provider emits a provider-spec `tool-result` stream part — AI SDK surfaces it in `fullStream` with `providerExecuted: true`:
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
const provider = createMockProvider({
|
|
296
|
+
scenarios: {
|
|
297
|
+
research: {
|
|
298
|
+
parts: [
|
|
299
|
+
{ type: 'tool-call', toolName: 'web_search', input: { query: 'latest AI SDK release' } },
|
|
300
|
+
{ type: 'tool-result', toolName: 'web_search', result: { sources: ['https://ai-sdk.dev'], summary: 'A new release shipped.' } },
|
|
301
|
+
{ type: 'text', text: 'Here is what I found.' },
|
|
302
|
+
],
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
});
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
The built-in `provider-tools` scenario (keywords: *web search*, *provider tool*, *provider-executed*, *built-in tool*) demos this flow.
|
|
309
|
+
|
|
310
|
+
## Custom scenarios
|
|
311
|
+
|
|
312
|
+
Override built-ins or register new ones. Scenarios are selected by exact model id or by keyword match against the last user message.
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
const provider = createMockProvider({
|
|
316
|
+
scenarios: {
|
|
317
|
+
// Override the built-in 'error' scenario
|
|
318
|
+
error: { parts: [{ type: 'text', text: 'friendly failure' }], finishReason: 'stop' },
|
|
319
|
+
|
|
320
|
+
// New scenario: matched by id 'haiku' or by the keywords
|
|
321
|
+
haiku: {
|
|
322
|
+
keywords: ['haiku', 'poem'],
|
|
323
|
+
parts: [
|
|
324
|
+
{ type: 'text', text: 'An old silent pond\nA frog jumps into water\nSplash! Silence again.' },
|
|
325
|
+
],
|
|
326
|
+
},
|
|
327
|
+
},
|
|
328
|
+
});
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
A scenario is a `MockScenarioContent`:
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
type MockScenarioContent = {
|
|
335
|
+
text?: string; // shorthand for a single text part
|
|
336
|
+
parts?: MockPart[]; // ordered content parts
|
|
337
|
+
finishReason?: 'stop' | 'length' | 'tool-calls' | 'error' | ...;
|
|
338
|
+
keywords?: string[]; // word-boundary matched against the last user message
|
|
339
|
+
tokensPerSecond?: number; // speed override for this scenario
|
|
340
|
+
firstTokenDelayMs?: number; // latency override for this scenario
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
type MockPart =
|
|
344
|
+
| { type: 'text'; text: string }
|
|
345
|
+
| { type: 'reasoning'; text: string }
|
|
346
|
+
| { type: 'tool-call'; toolName: string; input?: Record<string, unknown> } // input generated from declared tools when omitted
|
|
347
|
+
| { type: 'tool-result'; toolName: string; result?: Record<string, unknown>; isError?: boolean } // provider-executed tool result
|
|
348
|
+
| { type: 'file'; mediaType: string; data: string } // base64
|
|
349
|
+
| { type: 'lorem'; unit: 'words' | 'sentences' | 'paragraphs'; count: number } // generated at call time
|
|
350
|
+
| { type: 'error'; message: string };
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
The `lorem` part generates random filler at call time using the provider's PRNG (seeded or not), so custom scenarios can mix canned and random content:
|
|
354
|
+
|
|
355
|
+
```ts
|
|
356
|
+
const provider = createMockProvider({
|
|
357
|
+
seed: 123, // reproducible filler
|
|
358
|
+
scenarios: {
|
|
359
|
+
story: {
|
|
360
|
+
parts: [{ type: 'text', text: 'Once upon a time:' }, { type: 'lorem', unit: 'sentences', count: 3 }],
|
|
361
|
+
},
|
|
362
|
+
},
|
|
363
|
+
});
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
## Error simulation
|
|
367
|
+
|
|
368
|
+
The `error` scenario streams a few text chunks, then emits an error part and stops — no finish part is produced at the model level.
|
|
369
|
+
|
|
370
|
+
- With `streamText`, the AI SDK surfaces the error as an `error` part in `fullStream` and via the `onError` callback (AI SDK v7 semantics: stream errors are delivered in-stream).
|
|
371
|
+
- With `generateText`, `doGenerate` throws a retryable-shaped `APICallError` (status 500).
|
|
372
|
+
|
|
373
|
+
## Structured output
|
|
374
|
+
|
|
375
|
+
`generateObject` against the `json` scenario (or any scenario producing JSON text):
|
|
376
|
+
|
|
377
|
+
```ts
|
|
378
|
+
const { object } = await generateObject({
|
|
379
|
+
model: provider.languageModel('json'),
|
|
380
|
+
schema: jsonSchema({ type: 'object', properties: { name: { type: 'string' }, email: { type: 'string' } }, required: ['name', 'email'] }),
|
|
381
|
+
prompt: 'give me a structured object',
|
|
382
|
+
});
|
|
383
|
+
// { name: 'Ada Lovelace', email: 'ada@example.com', ... }
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
When `responseFormat` is `json` and no scenario matches, the `json` scenario is used automatically.
|
|
387
|
+
|
|
388
|
+
## Aborting
|
|
389
|
+
|
|
390
|
+
The stream honors the `abortSignal` passed by the AI SDK: emission stops at the next chunk boundary, so cancellation is immediate even at low tokens-per-second.
|
|
391
|
+
|
|
392
|
+
## Usage reporting
|
|
393
|
+
|
|
394
|
+
Every call reports usage derived from the simulated tokenization: `usage.inputTokens` estimates prompt tokens, `usage.outputTokens` counts emitted text/reasoning chunks.
|
|
395
|
+
|
|
396
|
+
## E2E harness
|
|
397
|
+
|
|
398
|
+
The package ships with an end-to-end harness that exercises the provider through the real AI SDK (`generateText`, `streamText`, `generateObject`, tools, aborts) across 31 checks — scenario content, speed timing, parsing of all directive notations, tool execution with schema-generated inputs and `toolChoice` modes, provider-executed tool results, reasoning order, file parts, errors, multi-call queues, custom scenarios, seeded and unseeded lorem generation, usage and abort.
|
|
399
|
+
|
|
400
|
+
```sh
|
|
401
|
+
npm run harness # runs the harness and prints a PASS/FAIL table
|
|
402
|
+
npm test # same checks as a vitest suite, plus unit tests
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
## API summary
|
|
406
|
+
|
|
407
|
+
| Export | Description |
|
|
408
|
+
|---|---|
|
|
409
|
+
| `createMockProvider(options?)` | Creates the provider (`provider(modelId)`, `.languageModel`, `.chat`) |
|
|
410
|
+
| `MockLanguageModelV4` | The model class implementing the v4 spec |
|
|
411
|
+
| `DEFAULT_SCENARIOS` | The built-in scenario list |
|
|
412
|
+
| `parseSpeedDirective(text)` | Parses speed directives → `{ tokensPerSecond, cleanedText }` |
|
|
413
|
+
| `parseLoremDirective(text)` | Parses lorem amount directives → `{ unit?, count? }` |
|
|
414
|
+
| `generateLoremText(part, rng, config?)` | Generates lorem text for a `lorem` part |
|
|
415
|
+
| `generateToolInput(schema, rng)` | Generates a schema-plausible tool input from a JSON Schema |
|
|
416
|
+
| `createRng(seed?)` | Seeded PRNG factory (mulberry32) |
|
|
417
|
+
| `tokenize(text, chunkSize)` / `estimateTokenCount(text, chunkSize)` | Token chunking helpers |
|
|
418
|
+
| `scenarioFromSpecifier(id, specifier)` | Normalizes a scenario specifier |
|
|
419
|
+
| `matchScenarioByKeywords(text, scenarios)` | Keyword-based scenario resolution |
|
|
420
|
+
|
|
421
|
+
Types: `MockProvider`, `MockProviderOptions`, `MockScenario`, `MockScenarioContent`, `MockPart`, `MockLoremPart`, `MockLoremOptions`, `MockResponseSpecifier`, `MockFinishReason`, `MockCallInfo`, `MockLanguageModel`, `Prng`.
|
|
422
|
+
|
|
423
|
+
## Development
|
|
424
|
+
|
|
425
|
+
```sh
|
|
426
|
+
npm run typecheck # tsc --noEmit
|
|
427
|
+
npm run build # dual ESM + CJS bundle + type declarations into dist/
|
|
428
|
+
npm test # unit + e2e tests
|
|
429
|
+
npm run harness # standalone e2e harness
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
## License
|
|
433
|
+
|
|
434
|
+
MIT
|