wavespeed 0.0.15 → 0.2.2

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,26 @@
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
+ ---
20
+
21
+ ## Introduction
22
+
23
+ **WaveSpeedAI** JavaScript/TypeScript SDK — Official JS/TS SDK for **WaveSpeedAI** inference platform. This library offers a clean, unified, and high-performance API for your applications.
4
24
 
5
25
  ## Installation
6
26
 
@@ -8,185 +28,111 @@ A JavaScript/TypeScript client for the WaveSpeed AI image generation API. This c
8
28
  npm install wavespeed
9
29
  ```
10
30
 
11
- ## Usage
31
+ ## API Client
12
32
 
13
- ### JavaScript
33
+ Run WaveSpeed AI models with a simple API:
14
34
 
15
35
  ```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
36
+ import wavespeed from 'wavespeed';
46
37
 
47
- ```typescript
48
- import WaveSpeed from 'wavespeed';
38
+ const output = await wavespeed.run(
39
+ "wavespeed-ai/z-image/turbo",
40
+ { prompt: "Cat" }
41
+ );
49
42
 
50
- // Initialize the client with your API key
51
- const client = new WaveSpeed('YOUR_API_KEY');
52
-
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
- };
43
+ console.log(output["outputs"][0]); // Output URL
44
+ ```
64
45
 
65
- const prediction = await client.run('wavespeed-ai/flux-dev', input);
46
+ ### Authentication
66
47
 
67
- // Print the generated image URLs
68
- prediction.outputs.forEach((imgUrl, i) => {
69
- console.log(`Image ${i+1}: ${imgUrl}`);
70
- });
71
- }
48
+ Set your API key via environment variable (You can get your API key from [https://wavespeed.ai/accesskey](https://wavespeed.ai/accesskey)):
72
49
 
73
- generateImage().catch(console.error);
50
+ ```bash
51
+ export WAVESPEED_API_KEY="your-api-key"
74
52
  ```
75
53
 
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
- }
54
+ Or pass it directly:
120
55
 
121
- generateWithManualPolling().catch(console.error);
122
- ```
56
+ ```javascript
57
+ import { Client } from 'wavespeed';
123
58
 
124
- ## API Reference
59
+ const client = new Client("your-api-key");
60
+ const output = await client.run("wavespeed-ai/z-image/turbo", { prompt: "Cat" });
61
+ ```
125
62
 
126
- ### WaveSpeed Client
63
+ ### Options
127
64
 
128
- ```typescript
129
- new WaveSpeed(apiKey?: string, options?: {
130
- baseUrl?: string,
131
- pollInterval?: number,
132
- timeout?: number
133
- })
65
+ ```javascript
66
+ const output = await wavespeed.run(
67
+ "wavespeed-ai/z-image/turbo",
68
+ { prompt: "Cat" },
69
+ {
70
+ timeout: 36000.0, // Max wait time in seconds (default: 36000.0)
71
+ pollInterval: 1.0, // Status check interval (default: 1.0)
72
+ enableSyncMode: false, // Single request mode, no polling (default: false)
73
+ }
74
+ );
134
75
  ```
135
76
 
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)
77
+ ### Sync Mode
142
78
 
143
- ### Methods
79
+ Use `enableSyncMode: true` for a single request that waits for the result (no polling).
144
80
 
145
- #### run
81
+ > **Note:** Not all models support sync mode. Check the model documentation for availability.
146
82
 
147
- ```typescript
148
- run(modelId: string, input: Record<string, any>, options?: RequestOptions): Promise<Prediction>
83
+ ```javascript
84
+ const output = await wavespeed.run(
85
+ "wavespeed-ai/z-image/turbo",
86
+ { prompt: "Cat" },
87
+ { enableSyncMode: true }
88
+ );
149
89
  ```
150
90
 
151
- Generate an image and wait for the result.
91
+ ### Retry Configuration
92
+
93
+ Configure retries at the client level:
152
94
 
153
- #### create
95
+ ```javascript
96
+ import { Client } from 'wavespeed';
154
97
 
155
- ```typescript
156
- create(modelId: string, input: Record<string, any>, options?: RequestOptions): Promise<Prediction>
98
+ const client = new Client("your-api-key", {
99
+ maxRetries: 0, // Task-level retries (default: 0)
100
+ maxConnectionRetries: 5, // HTTP connection retries (default: 5)
101
+ retryInterval: 1.0, // Base delay between retries in seconds (default: 1.0)
102
+ });
157
103
  ```
158
104
 
159
- Create a prediction without waiting for it to complete.
105
+ ### Upload Files
160
106
 
161
- ### Prediction Model
107
+ Upload images, videos, or audio files:
162
108
 
163
- The Prediction object contains information about an image generation job:
109
+ ```javascript
110
+ import wavespeed from 'wavespeed';
164
111
 
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
112
+ const url = await wavespeed.upload("/path/to/image.png");
113
+ console.log(url);
176
114
  ```
177
115
 
178
- #### Methods
116
+ ## Running Tests
117
+
118
+ ```bash
119
+ # Run all tests
120
+ npm test
121
+
122
+ # Run a single test file
123
+ npm test -- tests/test_api.ts
179
124
 
180
- ```typescript
181
- prediction.wait(): Promise<Prediction> // Wait for the prediction to complete
182
- prediction.reload(): Promise<Prediction> // Reload the prediction status
125
+ # Run a specific test
126
+ npm test -- tests/test_api.ts -t "run success"
183
127
  ```
184
128
 
185
129
  ## Environment Variables
186
130
 
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)
131
+ ### API Client
132
+
133
+ | Variable | Description |
134
+ |----------|-------------|
135
+ | `WAVESPEED_API_KEY` | WaveSpeed API key |
190
136
 
191
137
  ## License
192
138
 
@@ -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
+ }