openai-api-mock 0.1.32 → 0.1.34

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.md CHANGED
@@ -1,21 +1,21 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2024 Nabil Chiheb
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.
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Nabil Chiheb
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,147 +1,275 @@
1
- # OpenAI API Mock
2
-
3
- This is a Node.js module for mocking OpenAI API responses in a development environment.
4
-
5
- [![Tests](https://github.com/chihebnabil/openai-api-mock/actions/workflows/test.yml/badge.svg)](https://github.com/chihebnabil/openai-api-mock/actions/workflows/test.yml)
6
-
7
- It's useful for testing and development purposes when you don't want to make actual API calls.
8
-
9
- The module supports the following OpenAI API endpoints:
10
- - chat completions
11
- - chat completions with streaming
12
- - chat completions with functions
13
- - image generations
14
-
15
- > This module is powering the sandbox mode for [Aipify](https://aipify.co).
16
-
17
- ## Installation
18
-
19
- You can install this module using npm as a dev dependency :
20
-
21
- ```sh
22
- npm install -D openai-api-mock
23
- ```
24
-
25
- ## Usage
26
-
27
- The module supports both ESM and CommonJS imports:
28
-
29
- ```js
30
- // ESM
31
- import { mockOpenAIResponse } from 'openai-api-mock';
32
-
33
- // CommonJS
34
- const { mockOpenAIResponse } = require('openai-api-mock');
35
- ```
36
-
37
- Then, call the mockOpenAIResponse function to set up the mock response:
38
-
39
- ```js
40
- // Basic usage
41
- mockOpenAIResponse();
42
-
43
- // Force mocking regardless of environment
44
- mockOpenAIResponse(true);
45
-
46
- // With configuration options
47
- mockOpenAIResponse(false, {
48
- includeErrors: true, // Simulate random API errors
49
- latency: 1000, // Add 1 second delay to responses
50
- logRequests: true // Log incoming requests to console
51
- });
52
- ```
53
-
54
- The function accepts two parameters:
55
- - `force` (boolean): Determines whether the mock response should be used regardless of the environment. If false or not provided, mocking only occurs in development environment.
56
- - `options` (object): Additional configuration options
57
- - `includeErrors` (boolean): When true, randomly simulates API errors
58
- - `latency` (number): Adds artificial delay to responses in milliseconds
59
- - `logRequests` (boolean): Logs incoming requests to console for debugging
60
-
61
- The function returns an object with control methods:
62
- ```js
63
- const mock = mockOpenAIResponse();
64
-
65
- // Check if mocking is active
66
- console.log(mock.isActive);
67
-
68
- // Stop all mocks
69
- mock.stopMocking();
70
-
71
- // Add custom endpoint mock (uses api.openai.com as base url)
72
- mock.addCustomEndpoint('POST', '/v1/custom', (uri, body) => {
73
- return [200, { custom: 'response' }];
74
- });
75
- ```
76
-
77
- ### Example responses
78
-
79
- ```js
80
- // Call the mockOpenAIResponse function once to set up the mock
81
- mockOpenAIResponse()
82
-
83
- // Now, when you call the OpenAI API, it will return a mock response
84
- const response = await openai.chat.completions.create({
85
- model: "gpt-3.5",
86
- messages: [
87
- { role: 'system', content: "You're an expert chef" },
88
- { role: 'user', content: "Suggest at least 5 recipes" },
89
- ]
90
- });
91
- ```
92
- In this example, the `response` constant will contain mock data, simulating a response from the OpenAI API:
93
-
94
- ```javascript
95
- {
96
- choices: [
97
- {
98
- finish_reason: 'stop',
99
- index: 0,
100
- message: [Object],
101
- logprobs: null
102
- }
103
- ],
104
- created: 1707040459,
105
- id: 'chatcmpl-tggOnwW8Lp2XiwQ8dmHHAcNYJ8CfzR',
106
- model: 'gpt-3.5-mock',
107
- object: 'chat.completion',
108
- usage: { completion_tokens: 17, prompt_tokens: 57, total_tokens: 74 }
109
- }
110
- ```
111
- The library also supports mocking `stream` responses
112
-
113
- ```js
114
- // Call the mockOpenAIResponse function once to set up the mock
115
- mockOpenAIResponse()
116
- // Now, when you call the OpenAI API, it will return a mock response
117
- const response = await openai.chat.completions.create({
118
- model: "gpt-3.5",
119
- stream : true,
120
- messages: [
121
- { role: 'system', content: "You're an expert chef" },
122
- { role: 'user', content: "Suggest at least 5 recipes" },
123
- ]
124
- });
125
-
126
- // then read it
127
- for await (const part of response) {
128
- console.log(part.choices[0]?.delta?.content || '')
129
- }
130
- ```
131
-
132
- ## Intercepted URLs
133
-
134
- This module uses the `nock` library to intercept HTTP calls to the following OpenAI API endpoints:
135
-
136
- - `https://api.openai.com/v1/chat/completions`: This endpoint is used for generating chat completions.
137
- - `https://api.openai.com/v1/images/generations`: This endpoint is used for generating images.
138
-
139
-
140
- ## Dependencies
141
- This module depends on the following npm packages:
142
-
143
- - nock : For intercepting HTTP calls.
144
- - @faker-js/faker : For generating fake data.
145
-
146
- ## License
147
- This project is licensed under the MIT License.
1
+ # OpenAI API Mock
2
+
3
+ This is a Node.js module for mocking OpenAI API responses in a development environment .
4
+
5
+ [![Tests](https://github.com/chihebnabil/openai-api-mock/actions/workflows/test.yml/badge.svg)](https://github.com/chihebnabil/openai-api-mock/actions/workflows/test.yml)
6
+
7
+ It's useful for testing and development purposes when you don't want to make actual API calls.
8
+
9
+ The module supports the following OpenAI API endpoints:
10
+ - chat completions
11
+ - chat completions with streaming
12
+ - chat completions with functions
13
+ - image generations
14
+
15
+ > This module is powering the sandbox mode for [Aipify](https://aipify.co).
16
+
17
+ ## Table of Contents
18
+
19
+ - [Installation](#installation)
20
+ - [Usage](#usage)
21
+ - [Consistent Outputs for Testing](#consistent-outputs-for-testing)
22
+ - [Intercepted URLs](#intercepted-urls)
23
+ - [TypeScript Support](#typescript-support)
24
+ - [Dependencies](#dependencies)
25
+ - [License](#license)
26
+
27
+ ## Installation
28
+
29
+ You can install this module using npm as a dev dependency :
30
+
31
+ ```sh
32
+ npm install -D openai-api-mock
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ The module supports both ESM and CommonJS imports:
38
+
39
+ ```js
40
+ // ESM
41
+ import { mockOpenAIResponse } from 'openai-api-mock';
42
+
43
+ // CommonJS
44
+ const { mockOpenAIResponse } = require('openai-api-mock');
45
+ ```
46
+
47
+ Then, call the mockOpenAIResponse function to set up the mock response:
48
+
49
+ ```js
50
+ // Basic usage
51
+ mockOpenAIResponse();
52
+
53
+ // Force mocking regardless of environment
54
+ mockOpenAIResponse(true);
55
+
56
+ // With configuration options
57
+ mockOpenAIResponse(false, {
58
+ includeErrors: true, // Simulate random API errors
59
+ latency: 1000, // Add 1 second delay to responses
60
+ logRequests: true, // Log incoming requests to console
61
+ seed: 12345, // Seed for consistent/deterministic responses
62
+ useFixedResponses: true // Use predefined fixed response templates
63
+ });
64
+ ```
65
+
66
+ The function accepts two parameters:
67
+ - `force` (boolean): Determines whether the mock response should be used regardless of the environment. If false or not provided, mocking only occurs in development environment.
68
+ - `options` (object): Additional configuration options
69
+ - `includeErrors` (boolean): When true, randomly simulates API errors
70
+ - `latency` (number): Adds artificial delay to responses in milliseconds
71
+ - `logRequests` (boolean): Logs incoming requests to console for debugging
72
+ - `seed` (number|string): Seed value for consistent/deterministic responses using faker.js
73
+ - `useFixedResponses` (boolean): Use predefined fixed response templates for completely consistent responses
74
+
75
+ The function returns an object with control methods:
76
+ ```js
77
+ const mock = mockOpenAIResponse();
78
+
79
+ // Check if mocking is active
80
+ console.log(mock.isActive);
81
+
82
+ // Stop all mocks
83
+ mock.stopMocking();
84
+
85
+ // Seed management for consistent outputs
86
+ mock.setSeed(12345); // Set a new seed for deterministic responses
87
+ mock.resetSeed(); // Reset to random responses
88
+
89
+ // Template management
90
+ const templates = mock.getResponseTemplates(); // Get available templates
91
+ const customTemplate = mock.createResponseTemplate('SIMPLE_CHAT', {
92
+ choices: [{ message: { content: 'Custom response' } }]
93
+ });
94
+
95
+ // Add custom endpoint mock (uses api.openai.com as base url)
96
+ mock.addCustomEndpoint('POST', '/v1/custom', (uri, body) => {
97
+ return [200, { custom: 'response' }];
98
+ });
99
+ ```
100
+
101
+ ### Example responses
102
+
103
+ ```js
104
+ // Call the mockOpenAIResponse function once to set up the mock
105
+ mockOpenAIResponse()
106
+
107
+ // Now, when you call the OpenAI API, it will return a mock response
108
+ const response = await openai.chat.completions.create({
109
+ model: "gpt-3.5",
110
+ messages: [
111
+ { role: 'system', content: "You're an expert chef" },
112
+ { role: 'user', content: "Suggest at least 5 recipes" },
113
+ ]
114
+ });
115
+ ```
116
+ In this example, the `response` constant will contain mock data, simulating a response from the OpenAI API:
117
+
118
+ ```javascript
119
+ {
120
+ choices: [
121
+ {
122
+ finish_reason: 'stop',
123
+ index: 0,
124
+ message: [Object],
125
+ logprobs: null
126
+ }
127
+ ],
128
+ created: 1707040459,
129
+ id: 'chatcmpl-tggOnwW8Lp2XiwQ8dmHHAcNYJ8CfzR',
130
+ model: 'gpt-3.5-mock',
131
+ object: 'chat.completion',
132
+ usage: { completion_tokens: 17, prompt_tokens: 57, total_tokens: 74 }
133
+ }
134
+ ```
135
+ The library also supports mocking `stream` responses
136
+
137
+ ```js
138
+ // Call the mockOpenAIResponse function once to set up the mock
139
+ mockOpenAIResponse()
140
+ // Now, when you call the OpenAI API, it will return a mock response
141
+ const response = await openai.chat.completions.create({
142
+ model: "gpt-3.5",
143
+ stream : true,
144
+ messages: [
145
+ { role: 'system', content: "You're an expert chef" },
146
+ { role: 'user', content: "Suggest at least 5 recipes" },
147
+ ]
148
+ });
149
+
150
+ // then read it
151
+ for await (const part of response) {
152
+ console.log(part.choices[0]?.delta?.content || '')
153
+ }
154
+ ```
155
+
156
+ ## Consistent Outputs for Testing
157
+
158
+ The library provides several mechanisms to achieve consistent, deterministic outputs for reliable testing:
159
+
160
+ ### Seed-based Consistency
161
+
162
+ Use seeds to ensure reproducible responses across test runs:
163
+
164
+ ```js
165
+ // Set up mock with a fixed seed
166
+ const mock = mockOpenAIResponse(true, { seed: 12345 });
167
+
168
+ // Multiple calls will return identical responses
169
+ const response1 = await openai.chat.completions.create({
170
+ model: 'gpt-3.5-turbo',
171
+ messages: [{ role: 'user', content: 'Hello' }]
172
+ });
173
+
174
+ const response2 = await openai.chat.completions.create({
175
+ model: 'gpt-3.5-turbo',
176
+ messages: [{ role: 'user', content: 'Hello' }]
177
+ });
178
+
179
+ // response1 and response2 will be identical
180
+ console.log(JSON.stringify(response1) === JSON.stringify(response2)); // true
181
+ ```
182
+
183
+ ### Fixed Response Templates
184
+
185
+ For maximum consistency, use predefined response templates:
186
+
187
+ ```js
188
+ // Enable fixed responses
189
+ const mock = mockOpenAIResponse(true, { useFixedResponses: true });
190
+
191
+ const response = await openai.chat.completions.create({
192
+ model: 'gpt-3.5-turbo',
193
+ messages: [{ role: 'user', content: 'Any message' }]
194
+ });
195
+
196
+ // Will always return the same fixed response
197
+ console.log(response.choices[0].message.content);
198
+ // "This is a consistent test response."
199
+ ```
200
+
201
+ ### Runtime Seed Management
202
+
203
+ Change seeds during runtime for different test scenarios:
204
+
205
+ ```js
206
+ const mock = mockOpenAIResponse(true);
207
+
208
+ // Test scenario A
209
+ mock.setSeed(12345);
210
+ const responseA = await openai.chat.completions.create({...});
211
+
212
+ // Test scenario B
213
+ mock.setSeed(54321);
214
+ const responseB = await openai.chat.completions.create({...});
215
+
216
+ // Reset to random behavior
217
+ mock.resetSeed();
218
+ const responseRandom = await openai.chat.completions.create({...});
219
+ ```
220
+
221
+ For comprehensive examples and best practices, see [CONSISTENCY_EXAMPLES.md](./CONSISTENCY_EXAMPLES.md).
222
+ ```
223
+
224
+ ## Intercepted URLs
225
+
226
+ This module uses the `nock` library to intercept HTTP calls to the following OpenAI API endpoints:
227
+
228
+ - `https://api.openai.com/v1/chat/completions`: This endpoint is used for generating chat completions.
229
+ - `https://api.openai.com/v1/images/generations`: This endpoint is used for generating images.
230
+
231
+
232
+ ## TypeScript Support
233
+
234
+ This package includes TypeScript definitions out of the box. After installing the package, you can use it with full type support:
235
+
236
+ ```typescript
237
+ import { mockOpenAIResponse, MockOptions } from 'openai-api-mock';
238
+
239
+ // Configure with TypeScript types
240
+ const options: MockOptions = {
241
+ includeErrors: true, // Optional: simulate random API errors
242
+ latency: 1000, // Optional: add 1 second delay
243
+ logRequests: true, // Optional: log requests to console
244
+ seed: 12345, // Optional: seed for consistent responses
245
+ useFixedResponses: true // Optional: use fixed response templates
246
+ };
247
+
248
+ const mock = mockOpenAIResponse(true, options);
249
+
250
+ // TypeScript provides full type checking and autocompletion
251
+ console.log(mock.isActive); // boolean
252
+ mock.stopMocking(); // function
253
+ mock.setSeed(54321); // function with type checking
254
+ mock.resetSeed(); // function
255
+
256
+ // Template methods with type safety
257
+ const templates = mock.getResponseTemplates(); // Record<string, any>
258
+ const customTemplate = mock.createResponseTemplate('SIMPLE_CHAT', {
259
+ choices: [{ message: { content: 'Custom content' } }]
260
+ });
261
+
262
+ // Custom endpoints with type safety
263
+ mock.addCustomEndpoint('POST', '/v1/custom', (uri, body) => {
264
+ return [200, { custom: 'response' }];
265
+ });
266
+ ```
267
+
268
+ ## Dependencies
269
+ This module depends on the following npm packages:
270
+
271
+ - nock : For intercepting HTTP calls.
272
+ - @faker-js/faker : For generating fake data.
273
+
274
+ ## License
275
+ This project is licensed under the MIT License.