Skip to content

Commit 82aae14

Browse files
committed
Rewrite README with MSW comparison, real E2E examples, and Responses API docs
Move MSW comparison above the fold so readers immediately understand when to use this vs MSW. Add E2E test patterns section with real-world examples from the CopilotKit Dojo test suite: global setup/teardown, JSON fixture files, fixture load ordering, predicate-based routing for supervisor agents, tool result catch-all, and universal fallback. Document /v1/responses endpoint.
1 parent ec10916 commit 82aae14

1 file changed

Lines changed: 243 additions & 42 deletions

File tree

‎README.md‎

Lines changed: 243 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,65 @@
11
# @copilotkit/mock-openai
22

3-
Deterministic mock OpenAI server for testing. Streams SSE responses in real OpenAI chat completion format, driven entirely by fixtures. Zero runtime dependencies — built on Node.js builtins only.
3+
Deterministic mock OpenAI server for testing. Streams SSE responses in real OpenAI Chat Completions and Responses API format, driven entirely by fixtures. Zero runtime dependencies — built on Node.js builtins only.
4+
5+
Supports both streaming (SSE) and non-streaming JSON responses, text completions, tool calls, and error injection. Point any process at it via `OPENAI_BASE_URL` and get reproducible, instant responses.
46

57
## Install
68

79
```bash
810
npm install @copilotkit/mock-openai
911
```
1012

13+
## When to Use This vs MSW
14+
15+
[MSW (Mock Service Worker)](https://mswjs.io/) is a popular API mocking library, but it solves a different problem.
16+
17+
**The key difference is architecture.** mock-openai runs a real HTTP server on a port. MSW patches `http`/`https`/`fetch` modules inside a single Node.js process. MSW can only intercept requests from the process that calls `server.listen()` — child processes, separate services, and workers are unaffected.
18+
19+
This matters for E2E tests where multiple processes make OpenAI calls:
20+
21+
```
22+
Playwright test runner (Node)
23+
└─ controls browser → Next.js app (separate process)
24+
└─ OPENAI_BASE_URL → mock-openai :5555
25+
├─ Mastra agent workers
26+
├─ LangGraph workers
27+
└─ CopilotKit runtime
28+
```
29+
30+
MSW can't intercept any of those calls. mock-openai can — it's a real server on a real port.
31+
32+
**Use mock-openai when:**
33+
34+
- Multiple processes need to hit the same mock (E2E tests, agent frameworks, microservices)
35+
- You want OpenAI-specific SSE format out of the box (Chat Completions + Responses API)
36+
- You prefer defining fixtures as JSON files rather than code
37+
- You need a standalone CLI server
38+
39+
**Use MSW when:**
40+
41+
- All API calls originate from a single Node.js process (unit tests, SDK client tests)
42+
- You're mocking many different APIs, not just OpenAI
43+
- You want in-process interception without running a server
44+
45+
| Capability | mock-openai | MSW |
46+
| ---------------------------- | --------------------- | ------------------------------------------------------------------------- |
47+
| Cross-process interception | **Yes** (real server) | **No** (in-process only) |
48+
| OpenAI Chat Completions SSE | **Built-in** | Manual — build `data: {json}\n\n` + `[DONE]` yourself |
49+
| OpenAI Responses API SSE | **Built-in** | Manual — MSW's `sse()` sends `data:` events, not OpenAI's `event:` format |
50+
| Fixture file loading (JSON) | **Yes** | **No** — handlers are code-only |
51+
| Request journal / inspection | **Yes** | **No** — track requests manually |
52+
| Non-streaming responses | **Yes** | **Yes** |
53+
| Error injection (one-shot) | **Yes** | **Yes** (via `server.use()`) |
54+
| CLI for standalone use | **Yes** | **No** |
55+
| Zero dependencies | **Yes** | **No** (~300KB) |
56+
1157
## Quick Start
1258

1359
```typescript
1460
import { MockOpenAI } from "@copilotkit/mock-openai";
1561

16-
const mock = new MockOpenAI();
62+
const mock = new MockOpenAI({ port: 5555 });
1763

1864
mock.onMessage("hello", { content: "Hi there!" });
1965

@@ -25,6 +71,193 @@ const url = await mock.start();
2571
await mock.stop();
2672
```
2773

74+
## E2E Test Patterns
75+
76+
Real-world patterns from using mock-openai in Playwright E2E tests with CopilotKit, Mastra, LangGraph, and Agno agent frameworks.
77+
78+
### Global Setup/Teardown
79+
80+
Start the mock server once for the entire test suite. All child processes (Next.js, agent workers) inherit the URL via environment variable.
81+
82+
```typescript
83+
// e2e/mock-openai-setup.ts
84+
import { MockOpenAI } from "@copilotkit/mock-openai";
85+
import * as path from "node:path";
86+
87+
let mockServer: MockOpenAI | null = null;
88+
89+
export async function setupMockOpenAI(): Promise<void> {
90+
mockServer = new MockOpenAI({ port: 5555 });
91+
92+
// Load JSON fixtures from a directory
93+
mockServer.loadFixtureDir(path.join(__dirname, "fixtures", "openai"));
94+
95+
const url = await mockServer.start();
96+
97+
// Child processes use this to find the mock
98+
process.env.MOCK_OPENAI_URL = `${url}/v1`;
99+
}
100+
101+
export async function teardownMockOpenAI(): Promise<void> {
102+
if (mockServer) {
103+
await mockServer.stop();
104+
mockServer = null;
105+
}
106+
}
107+
```
108+
109+
The Next.js app (or any other service) just needs:
110+
111+
```env
112+
OPENAI_BASE_URL=http://localhost:5555/v1
113+
OPENAI_API_KEY=mock-key
114+
```
115+
116+
### JSON Fixture Files
117+
118+
Define fixtures as JSON — one file per feature, loaded with `loadFixtureFile` or `loadFixtureDir`.
119+
120+
**Text responses** — match on a substring of the last user message:
121+
122+
```json
123+
{
124+
"fixtures": [
125+
{
126+
"match": { "userMessage": "stock price of AAPL" },
127+
"response": { "content": "The current stock price of Apple Inc. (AAPL) is $150.25." }
128+
},
129+
{
130+
"match": { "userMessage": "capital of France" },
131+
"response": { "content": "The capital of France is Paris." }
132+
}
133+
]
134+
}
135+
```
136+
137+
**Tool call responses** — the agent framework receives these as tool calls and executes them:
138+
139+
```json
140+
{
141+
"fixtures": [
142+
{
143+
"match": { "userMessage": "one step with eggs" },
144+
"response": {
145+
"toolCalls": [
146+
{
147+
"name": "generate_task_steps",
148+
"arguments": "{\"steps\":[{\"description\":\"Crack eggs into bowl\",\"status\":\"enabled\"},{\"description\":\"Preheat oven to 350F\",\"status\":\"enabled\"}]}"
149+
}
150+
]
151+
}
152+
},
153+
{
154+
"match": { "userMessage": "background color to blue" },
155+
"response": {
156+
"toolCalls": [
157+
{
158+
"name": "change_background",
159+
"arguments": "{\"background\":\"blue\"}"
160+
}
161+
]
162+
}
163+
}
164+
]
165+
}
166+
```
167+
168+
### Fixture Load Order Matters
169+
170+
Fixtures are evaluated first-match-wins. When two fixtures could match the same message, load the more specific one first:
171+
172+
```typescript
173+
// Load HITL fixtures first — "one step with eggs" is more specific than
174+
// "plan to make brownies" which also appears in the HITL user message
175+
mockServer.loadFixtureFile(path.join(FIXTURES_DIR, "human-in-the-loop.json"));
176+
177+
// Then load everything else — earlier matches take priority
178+
mockServer.loadFixtureDir(FIXTURES_DIR);
179+
```
180+
181+
### Predicate-Based Routing
182+
183+
When substring matching isn't enough — for example, when the last user message is the same across multiple requests but the system prompt differs — use predicates:
184+
185+
```typescript
186+
// Supervisor agent: same user message every time, but system prompt
187+
// contains state flags like "Flights found: false"
188+
mockServer.addFixture({
189+
match: {
190+
predicate: (req) => {
191+
const sysMsg = req.messages.find((m) => m.role === "system");
192+
return sysMsg?.content?.includes("Flights found: false") ?? false;
193+
},
194+
},
195+
response: {
196+
toolCalls: [
197+
{
198+
name: "supervisor_response",
199+
arguments: '{"answer":"Let me find flights for you!","next_agent":"flights_agent"}',
200+
},
201+
],
202+
},
203+
});
204+
205+
mockServer.addFixture({
206+
match: {
207+
predicate: (req) => {
208+
const sys = req.messages.find((m) => m.role === "system")?.content ?? "";
209+
return sys.includes("Flights found: true") && sys.includes("Hotels found: false");
210+
},
211+
},
212+
response: {
213+
toolCalls: [
214+
{
215+
name: "supervisor_response",
216+
arguments: '{"answer":"Now let me find hotels.","next_agent":"hotels_agent"}',
217+
},
218+
],
219+
},
220+
});
221+
```
222+
223+
### Tool Result Catch-All
224+
225+
After a tool executes, the next request contains a `role: "tool"` message with the result. Add a catch-all for these so the conversation can continue:
226+
227+
```typescript
228+
const toolResultFixture = {
229+
match: {
230+
predicate: (req) => {
231+
const last = req.messages[req.messages.length - 1];
232+
return last?.role === "tool";
233+
},
234+
},
235+
response: { content: "Done! I've completed that for you." },
236+
};
237+
mockServer.addFixture(toolResultFixture);
238+
239+
// Move it to the front so it matches before substring-based fixtures
240+
// (the last user message hasn't changed, so substring fixtures would
241+
// match the same fixture again otherwise)
242+
const fixtures = (mockServer as any).fixtures;
243+
const idx = fixtures.indexOf(toolResultFixture);
244+
if (idx > 0) {
245+
fixtures.splice(idx, 1);
246+
fixtures.unshift(toolResultFixture);
247+
}
248+
```
249+
250+
### Universal Catch-All
251+
252+
Append a catch-all last to handle any request that doesn't match a specific fixture, preventing 404s from crashing the test:
253+
254+
```typescript
255+
mockServer.addFixture({
256+
match: { predicate: () => true },
257+
response: { content: "I understand. How can I help you with that?" },
258+
});
259+
```
260+
28261
## Programmatic API
29262

30263
### `new MockOpenAI(options?)`
@@ -75,7 +308,7 @@ mock.onMessage(/greet/i, { content: "Hey there!" });
75308

76309
#### `onToolCall(name, response, opts?)`
77310

78-
Shorthand — matches when the request contains a tool call with the given name.
311+
Shorthand — matches when the request contains a tool with the given name.
79312

80313
```typescript
81314
mock.onToolCall("get_weather", {
@@ -97,7 +330,7 @@ Add raw `Fixture` objects directly.
97330

98331
#### `loadFixtureFile(path)` / `loadFixtureDir(path)`
99332

100-
Load fixtures from JSON files on disk. See [Fixture Files](#fixture-files) below.
333+
Load fixtures from JSON files on disk. See [Fixture Files](#json-fixture-files) above.
101334

102335
#### `clearFixtures()`
103336

@@ -121,7 +354,7 @@ mock.nextRequestError(429, {
121354

122355
### Request Journal
123356

124-
Every request to `/v1/chat/completions` is recorded in a journal.
357+
Every request to `/v1/chat/completions` and `/v1/responses` is recorded in a journal.
125358

126359
#### Programmatic Access
127360

@@ -183,7 +416,7 @@ Fixtures are evaluated in registration order (first match wins). A fixture match
183416
}
184417
```
185418

186-
Streams as SSE chunks, splitting `content` by `chunkSize`.
419+
Streams as SSE chunks, splitting `content` by `chunkSize`. With `stream: false`, returns a standard `chat.completion` JSON object.
187420

188421
### Tool Calls
189422

@@ -202,33 +435,12 @@ Streams as SSE chunks, splitting `content` by `chunkSize`.
202435
}
203436
```
204437

205-
## Fixture Files
438+
## API Endpoints
206439

207-
Fixtures can be defined in JSON files for use with the CLI or `loadFixtureFile`/`loadFixtureDir`.
440+
The server handles:
208441

209-
```json
210-
{
211-
"fixtures": [
212-
{
213-
"match": { "userMessage": "hello" },
214-
"response": { "content": "Hello! How can I help you today?" }
215-
},
216-
{
217-
"match": { "toolName": "get_weather" },
218-
"response": {
219-
"toolCalls": [
220-
{
221-
"name": "get_weather",
222-
"arguments": "{\"location\":\"San Francisco\"}"
223-
}
224-
]
225-
}
226-
}
227-
]
228-
}
229-
```
230-
231-
Each entry can also include `latency` and `chunkSize` overrides.
442+
- **POST `/v1/chat/completions`** — OpenAI Chat Completions API (streaming and non-streaming)
443+
- **POST `/v1/responses`** — OpenAI Responses API (streaming and non-streaming). Requests are translated to the Chat Completions fixture format internally, so the same fixtures work for both endpoints.
232444

233445
## CLI
234446

@@ -274,17 +486,6 @@ const { server, journal, url } = await createServer(fixtures, { port: 0 });
274486
server.close();
275487
```
276488

277-
### Custom Matching with Predicates
278-
279-
```typescript
280-
mock.on(
281-
{
282-
predicate: (req) => req.messages.length > 5 && req.model.startsWith("gpt-4"),
283-
},
284-
{ content: "You've been chatting a while!" },
285-
);
286-
```
287-
288489
### Per-Fixture Timing
289490

290491
```typescript

0 commit comments

Comments
 (0)