wavespeed 0.0.15 → 0.2.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 WaveSpeedAI
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,6 +1,22 @@
1
- # WaveSpeed JavaScript/TypeScript Client
1
+ <div align="center">
2
+ <a href="https://wavespeed.ai" target="_blank" rel="noopener noreferrer">
3
+ <img src="https://raw.githubusercontent.com/WaveSpeedAI/waverless/main/docs/images/wavespeed-dark-logo.png" alt="WaveSpeedAI logo" width="200"/>
4
+ </a>
2
5
 
3
- A JavaScript/TypeScript client for the WaveSpeed AI image generation API. This client is compatible with both JavaScript and TypeScript projects.
6
+ <h1>WaveSpeedAI JavaScript SDK</h1>
7
+
8
+ <p>
9
+ <strong>Official JavaScript/TypeScript SDK for the WaveSpeedAI inference platform</strong>
10
+ </p>
11
+
12
+ <p>
13
+ <a href="https://wavespeed.ai" target="_blank" rel="noopener noreferrer">🌐 Visit wavespeed.ai</a> •
14
+ <a href="https://wavespeed.ai/docs">📖 Documentation</a> •
15
+ <a href="https://github.com/WaveSpeedAI/wavespeed-javascript/issues">💬 Issues</a>
16
+ </p>
17
+ </div>
18
+
19
+ ---
4
20
 
5
21
  ## Installation
6
22
 
@@ -8,185 +24,111 @@ A JavaScript/TypeScript client for the WaveSpeed AI image generation API. This c
8
24
  npm install wavespeed
9
25
  ```
10
26
 
11
- ## Usage
27
+ ## API Client
12
28
 
13
- ### JavaScript
29
+ Run WaveSpeed AI models with a simple API:
14
30
 
15
31
  ```javascript
16
- const { WaveSpeed } = require('wavespeed');
17
-
18
- // Initialize the client with your API key
19
- const client = new WaveSpeed('YOUR_API_KEY');
20
-
21
- // Generate an image and wait for the result
22
- async function generateImage() {
23
- const prediction = await client.run(
24
- 'wavespeed-ai/flux-dev',
25
- {
26
- prompt: 'A futuristic cityscape with flying cars and neon lights',
27
- size: '1024*1024',
28
- num_inference_steps: 28,
29
- guidance_scale: 5.0,
30
- num_images: 1,
31
- seed: -1,
32
- enable_safety_checker: true
33
- }
34
- );
35
-
36
- // Print the generated image URLs
37
- prediction.outputs.forEach((imgUrl, i) => {
38
- console.log(`Image ${i+1}: ${imgUrl}`);
39
- });
40
- }
41
-
42
- generateImage().catch(console.error);
43
- ```
44
-
45
- ### TypeScript
46
-
47
- ```typescript
48
- import WaveSpeed from 'wavespeed';
32
+ import wavespeed from 'wavespeed';
49
33
 
50
- // Initialize the client with your API key
51
- const client = new WaveSpeed('YOUR_API_KEY');
34
+ const output = await wavespeed.run(
35
+ "wavespeed-ai/z-image/turbo",
36
+ { prompt: "Cat" }
37
+ );
52
38
 
53
- // Generate an image and wait for the result
54
- async function generateImage(): Promise<void> {
55
- const input: Record<string, any> = {
56
- prompt: 'A futuristic cityscape with flying cars and neon lights',
57
- size: '1024*1024',
58
- num_inference_steps: 28,
59
- guidance_scale: 5.0,
60
- num_images: 1,
61
- seed: -1,
62
- enable_safety_checker: true
63
- };
39
+ console.log(output["outputs"][0]); // Output URL
40
+ ```
64
41
 
65
- const prediction = await client.run('wavespeed-ai/flux-dev', input);
42
+ ### Authentication
66
43
 
67
- // Print the generated image URLs
68
- prediction.outputs.forEach((imgUrl, i) => {
69
- console.log(`Image ${i+1}: ${imgUrl}`);
70
- });
71
- }
44
+ Set your API key via environment variable (You can get your API key from [https://wavespeed.ai/accesskey](https://wavespeed.ai/accesskey)):
72
45
 
73
- generateImage().catch(console.error);
46
+ ```bash
47
+ export WAVESPEED_API_KEY="your-api-key"
74
48
  ```
75
49
 
76
- ### Manual Status Polling Example
77
-
78
- If you need more control over the polling process, you can use the `create` method and manually poll for status updates:
79
-
80
- ```typescript
81
- import WaveSpeed from 'wavespeed';
82
-
83
- // Initialize the client with your API key
84
- const client = new WaveSpeed('YOUR_API_KEY');
85
-
86
- async function generateWithManualPolling(): Promise<void> {
87
- // Create a prediction without waiting
88
- const prediction = await client.create('wavespeed-ai/flux-dev', {
89
- prompt: 'A beautiful mountain landscape at sunset',
90
- size: '1024*1024',
91
- num_inference_steps: 28,
92
- guidance_scale: 5.0,
93
- num_images: 1
94
- });
95
-
96
- console.log(`Prediction created with ID: ${prediction.id}`);
97
- console.log(`Initial status: ${prediction.status}`);
98
-
99
- // Manually poll for status updates
100
- let currentPrediction = prediction;
101
-
102
- while (currentPrediction.status !== 'completed' && currentPrediction.status !== 'failed') {
103
- console.log('Prediction still processing, checking again in 2 seconds...');
104
- await new Promise(resolve => setTimeout(resolve, 2000));
105
-
106
- // Reload the prediction to get the latest status
107
- currentPrediction = await currentPrediction.reload();
108
- console.log(`Updated status: ${currentPrediction.status}`);
109
- }
110
-
111
- if (currentPrediction.status === 'completed') {
112
- console.log('Prediction completed successfully!');
113
- currentPrediction.outputs.forEach((imgUrl, i) => {
114
- console.log(`Image ${i+1}: ${imgUrl}`);
115
- });
116
- } else {
117
- console.error(`Prediction failed: ${currentPrediction.error}`);
118
- }
119
- }
50
+ Or pass it directly:
120
51
 
121
- generateWithManualPolling().catch(console.error);
122
- ```
52
+ ```javascript
53
+ import { Client } from 'wavespeed';
123
54
 
124
- ## API Reference
55
+ const client = new Client("your-api-key");
56
+ const output = await client.run("wavespeed-ai/z-image/turbo", { prompt: "Cat" });
57
+ ```
125
58
 
126
- ### WaveSpeed Client
59
+ ### Options
127
60
 
128
- ```typescript
129
- new WaveSpeed(apiKey?: string, options?: {
130
- baseUrl?: string,
131
- pollInterval?: number,
132
- timeout?: number
133
- })
61
+ ```javascript
62
+ const output = await wavespeed.run(
63
+ "wavespeed-ai/z-image/turbo",
64
+ { prompt: "Cat" },
65
+ {
66
+ timeout: 36000.0, // Max wait time in seconds (default: 36000.0)
67
+ pollInterval: 1.0, // Status check interval (default: 1.0)
68
+ enableSyncMode: false, // Single request mode, no polling (default: false)
69
+ }
70
+ );
134
71
  ```
135
72
 
136
- #### Parameters:
137
- - `apiKey` (string): Your WaveSpeed API key
138
- - `options` (object, optional):
139
- - `baseUrl` (string): API base URL (default: 'https://api.wavespeed.ai/api/v2/')
140
- - `pollInterval` (number): Interval in seconds for polling prediction status (default: 1)
141
- - `timeout` (number): Timeout in seconds for API requests (default: 60)
73
+ ### Sync Mode
142
74
 
143
- ### Methods
75
+ Use `enableSyncMode: true` for a single request that waits for the result (no polling).
144
76
 
145
- #### run
77
+ > **Note:** Not all models support sync mode. Check the model documentation for availability.
146
78
 
147
- ```typescript
148
- run(modelId: string, input: Record<string, any>, options?: RequestOptions): Promise<Prediction>
79
+ ```javascript
80
+ const output = await wavespeed.run(
81
+ "wavespeed-ai/z-image/turbo",
82
+ { prompt: "Cat" },
83
+ { enableSyncMode: true }
84
+ );
149
85
  ```
150
86
 
151
- Generate an image and wait for the result.
87
+ ### Retry Configuration
88
+
89
+ Configure retries at the client level:
152
90
 
153
- #### create
91
+ ```javascript
92
+ import { Client } from 'wavespeed';
154
93
 
155
- ```typescript
156
- create(modelId: string, input: Record<string, any>, options?: RequestOptions): Promise<Prediction>
94
+ const client = new Client("your-api-key", {
95
+ maxRetries: 0, // Task-level retries (default: 0)
96
+ maxConnectionRetries: 5, // HTTP connection retries (default: 5)
97
+ retryInterval: 1.0, // Base delay between retries in seconds (default: 1.0)
98
+ });
157
99
  ```
158
100
 
159
- Create a prediction without waiting for it to complete.
101
+ ### Upload Files
160
102
 
161
- ### Prediction Model
103
+ Upload images, videos, or audio files:
162
104
 
163
- The Prediction object contains information about an image generation job:
105
+ ```javascript
106
+ import wavespeed from 'wavespeed';
164
107
 
165
- ```typescript
166
- prediction.id // Unique ID of the prediction
167
- prediction.model // Model ID used for the prediction
168
- prediction.status // Status of the prediction (processing, completed, failed)
169
- prediction.input // Input parameters used for the prediction
170
- prediction.outputs // List of output image URLs
171
- prediction.urls.get // URL to get the prediction status
172
- prediction.has_nsfw_contents // List of booleans indicating if each image has NSFW content
173
- prediction.created_at // Creation timestamp
174
- prediction.error // Error message (if any)
175
- prediction.executionTime // Time taken to execute the prediction in milliseconds
108
+ const url = await wavespeed.upload("/path/to/image.png");
109
+ console.log(url);
176
110
  ```
177
111
 
178
- #### Methods
112
+ ## Running Tests
113
+
114
+ ```bash
115
+ # Run all tests
116
+ npm test
179
117
 
180
- ```typescript
181
- prediction.wait(): Promise<Prediction> // Wait for the prediction to complete
182
- prediction.reload(): Promise<Prediction> // Reload the prediction status
118
+ # Run a single test file
119
+ npm test -- tests/test_api.ts
120
+
121
+ # Run a specific test
122
+ npm test -- tests/test_api.ts -t "run success"
183
123
  ```
184
124
 
185
125
  ## Environment Variables
186
126
 
187
- - `WAVESPEED_API_KEY`: Your WaveSpeed API key
188
- - `WAVESPEED_POLL_INTERVAL`: Interval in seconds for polling prediction status (default: 1)
189
- - `WAVESPEED_TIMEOUT`: Timeout in seconds for API requests (default: 60)
127
+ ### API Client
128
+
129
+ | Variable | Description |
130
+ |----------|-------------|
131
+ | `WAVESPEED_API_KEY` | WaveSpeed API key |
190
132
 
191
133
  ## License
192
134
 
@@ -0,0 +1,157 @@
1
+ /**
2
+ * WaveSpeed API client implementation.
3
+ */
4
+ /**
5
+ * Run options interface.
6
+ */
7
+ export interface RunOptions {
8
+ timeout?: number;
9
+ pollInterval?: number;
10
+ enableSyncMode?: boolean;
11
+ maxRetries?: number;
12
+ }
13
+ /**
14
+ * WaveSpeed API client.
15
+ *
16
+ * Example:
17
+ * const client = new Client("your-api-key");
18
+ * const output = await client.run("wavespeed-ai/z-image/turbo", { prompt: "Cat" });
19
+ *
20
+ * // With sync mode (single request, waits for result)
21
+ * const output2 = await client.run("wavespeed-ai/z-image/turbo", { prompt: "Cat" }, { enableSyncMode: true });
22
+ *
23
+ * // With retry
24
+ * const output3 = await client.run("wavespeed-ai/z-image/turbo", { prompt: "Cat" }, { maxRetries: 3 });
25
+ */
26
+ export declare class Client {
27
+ private apiKey;
28
+ private baseUrl;
29
+ readonly connectionTimeout: number;
30
+ readonly timeout: number;
31
+ readonly maxRetries: number;
32
+ readonly maxConnectionRetries: number;
33
+ readonly retryInterval: number;
34
+ /**
35
+ * Initialize the client.
36
+ *
37
+ * Args:
38
+ * apiKey: WaveSpeed API key. If not provided, uses wavespeed.config.api.apiKey.
39
+ * options.baseUrl: Base URL for the API. If not provided, uses wavespeed.config.api.baseUrl.
40
+ * options.connectionTimeout: Timeout for HTTP requests in seconds.
41
+ * options.timeout: Total API call timeout in seconds.
42
+ * options.maxRetries: Maximum number of retries for the entire operation.
43
+ * options.maxConnectionRetries: Maximum retries for individual HTTP requests.
44
+ * options.retryInterval: Base interval between retries in seconds.
45
+ */
46
+ constructor(apiKey?: string, options?: {
47
+ baseUrl?: string;
48
+ connectionTimeout?: number;
49
+ timeout?: number;
50
+ maxRetries?: number;
51
+ maxConnectionRetries?: number;
52
+ retryInterval?: number;
53
+ });
54
+ /**
55
+ * Get request headers with authentication.
56
+ */
57
+ private _getHeaders;
58
+ /**
59
+ * Submit a prediction request.
60
+ *
61
+ * Args:
62
+ * model: Model identifier.
63
+ * input: Input parameters.
64
+ * enableSyncMode: If true, wait for result in single request.
65
+ * timeout: Request timeout in seconds.
66
+ *
67
+ * Returns:
68
+ * Tuple of [requestId, result]. In async mode, result is null.
69
+ * In sync mode, requestId is null and result contains the response.
70
+ *
71
+ * Throws:
72
+ * Error: If submission fails after retries.
73
+ */
74
+ private _submit;
75
+ /**
76
+ * Get prediction result.
77
+ *
78
+ * Args:
79
+ * requestId: The prediction request ID.
80
+ * timeout: Request timeout in seconds.
81
+ *
82
+ * Returns:
83
+ * Full API response.
84
+ *
85
+ * Throws:
86
+ * Error: If fetching result fails after retries.
87
+ */
88
+ private _getResult;
89
+ /**
90
+ * Wait for prediction to complete.
91
+ *
92
+ * Args:
93
+ * requestId: The prediction request ID.
94
+ * timeout: Maximum wait time in seconds (undefined = no timeout).
95
+ * pollInterval: Time between polls in seconds.
96
+ *
97
+ * Returns:
98
+ * Dict with "outputs" array.
99
+ *
100
+ * Throws:
101
+ * Error: If prediction fails.
102
+ * Error: If prediction times out.
103
+ */
104
+ private _wait;
105
+ /**
106
+ * Determine if an error is worth retrying at the task level.
107
+ *
108
+ * Args:
109
+ * error: The exception to check.
110
+ *
111
+ * Returns:
112
+ * True if the error is retryable.
113
+ */
114
+ private _isRetryableError;
115
+ /**
116
+ * Run a model and wait for the output.
117
+ *
118
+ * Args:
119
+ * model: Model identifier (e.g., "wavespeed-ai/flux-dev").
120
+ * input: Input parameters for the model.
121
+ * options.timeout: Maximum time to wait for completion (undefined = no timeout).
122
+ * options.pollInterval: Interval between status checks in seconds.
123
+ * options.enableSyncMode: If true, use synchronous mode (single request).
124
+ * options.maxRetries: Maximum task-level retries (overrides client setting).
125
+ *
126
+ * Returns:
127
+ * Dict containing "outputs" array with model outputs.
128
+ *
129
+ * Throws:
130
+ * Error: If API key is not configured.
131
+ * Error: If the prediction fails.
132
+ * Error: If the prediction times out.
133
+ */
134
+ run(model: string, input?: Record<string, any>, options?: RunOptions): Promise<Record<string, any>>;
135
+ /**
136
+ * Upload a file to WaveSpeed.
137
+ *
138
+ * Args:
139
+ * file: File path string to upload.
140
+ * options.timeout: Total API call timeout in seconds.
141
+ *
142
+ * Returns:
143
+ * URL of the uploaded file.
144
+ *
145
+ * Throws:
146
+ * Error: If API key is not configured.
147
+ * Error: If file path does not exist.
148
+ * Error: If upload fails.
149
+ *
150
+ * Example:
151
+ * const url = await client.upload("/path/to/image.png");
152
+ * console.log(url);
153
+ */
154
+ upload(file: string, options?: {
155
+ timeout?: number;
156
+ }): Promise<string>;
157
+ }