Skip to content

Commit d8c96c6

Browse files
committed
Initial commit: WaveSpeed JavaScript/TypeScript SDK - Official JS/TS SDK for WaveSpeedAI inference platform, supporting AI model inference with async/await and polling, file upload with progress handling, complete TypeScript types and error handling, Jest test suite with 90%+ coverage, and ESM/CommonJS support.
0 parents  commit d8c96c6

11 files changed

Lines changed: 6828 additions & 0 deletions

File tree

.gitignore

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Dependencies
2+
node_modules/
3+
npm-debug.log*
4+
yarn-debug.log*
5+
yarn-error.log*
6+
7+
# Build outputs
8+
dist/
9+
coverage/
10+
*.tsbuildinfo
11+
12+
# IDE
13+
.vscode/
14+
.idea/
15+
*.swp
16+
*.swo
17+
18+
# OS
19+
.DS_Store
20+
Thumbs.db
21+
22+
# Logs
23+
logs/
24+
*.log
25+
26+
# Runtime data
27+
pids/
28+
*.pid
29+
*.seed
30+
*.pid.lock
31+
32+
# Coverage directory used by tools like istanbul
33+
lib-cov/
34+
35+
# nyc test coverage
36+
.nyc_output/
37+
38+
# Dependency directories
39+
jspm_packages/
40+
41+
# Optional npm cache directory
42+
.npm
43+
44+
# Optional REPL history
45+
.node_repl_history
46+
47+
# Output of 'npm pack'
48+
*.tgz
49+
50+
# Yarn Integrity file
51+
.yarn-integrity
52+
53+
# ESLint cache
54+
.eslintcache
55+
56+
# Optional REPL history
57+
.node_repl_history
58+
59+
# Output of 'npm pack'
60+
*.tgz
61+
62+
# Yarn Integrity file
63+
.yarn-integrity
64+
65+
# dotenv environment variables file
66+
.env
67+
68+
# macOS
69+
.DS_Store
70+
71+
# Windows
72+
Thumbs.db
73+
ehthumbs.db
74+
Desktop.ini
75+
76+
# JetBrains IDEs
77+
.idea/
78+
79+
# VS Code
80+
.vscode/
81+
82+
# Temporary files
83+
*.tmp
84+
*.temp

README.md

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
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>
5+
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/client-javascript/issues">💬 Issues</a>
16+
</p>
17+
</div>
18+
19+
---
20+
21+
## Installation
22+
23+
```bash
24+
npm install wavespeed
25+
```
26+
27+
## API Client
28+
29+
Run WaveSpeed AI models with a simple API:
30+
31+
```javascript
32+
const WaveSpeed = require('wavespeed');
33+
34+
const client = new WaveSpeed('your-api-key');
35+
36+
client.run('wavespeed-ai/z-image/turbo', { prompt: 'Cat' })
37+
.then(prediction => {
38+
console.log(prediction.outputs[0]); // Output URL
39+
})
40+
.catch(console.error);
41+
```
42+
43+
Or with TypeScript:
44+
45+
```typescript
46+
import WaveSpeed from 'wavespeed';
47+
48+
const client = new WaveSpeed('your-api-key');
49+
50+
const prediction = await client.run('wavespeed-ai/z-image/turbo', {
51+
prompt: 'Cat'
52+
});
53+
54+
console.log(prediction.outputs[0]); // Output URL
55+
```
56+
57+
### Authentication
58+
59+
Set your API key via environment variable (You can get your API key from [https://wavespeed.ai/accesskey](https://wavespeed.ai/accesskey)):
60+
61+
```bash
62+
export WAVESPEED_API_KEY="your-api-key"
63+
```
64+
65+
Or pass it directly:
66+
67+
```javascript
68+
const client = new WaveSpeed('your-api-key');
69+
```
70+
71+
### Options
72+
73+
```javascript
74+
const client = new WaveSpeed('your-api-key', {
75+
timeout: 36000, // Max wait time in seconds (default: 36000)
76+
pollInterval: 1, // Status check interval (default: 1)
77+
});
78+
```
79+
80+
### Upload Files
81+
82+
Upload images, videos, or audio files:
83+
84+
```javascript
85+
client.upload('/path/to/image.png')
86+
.then(url => console.log(url))
87+
.catch(console.error);
88+
```
89+
90+
## API Reference
91+
92+
### WaveSpeed Client
93+
94+
```typescript
95+
new WaveSpeed(apiKey?: string, options?: {
96+
baseUrl?: string,
97+
pollInterval?: number,
98+
timeout?: number
99+
})
100+
```
101+
102+
#### Parameters:
103+
- `apiKey` (string): Your WaveSpeed API key
104+
- `options` (object, optional):
105+
- `baseUrl` (string): API base URL without path (default: `https://api.wavespeed.ai`)
106+
- `pollInterval` (number): Poll interval in seconds (default: 1)
107+
- `timeout` (number): Overall wait timeout in seconds (default: 36000)
108+
109+
### Methods
110+
111+
#### run
112+
113+
```typescript
114+
run(modelId: string, input: Record<string, any>, options?: { pollInterval?: number; timeout?: number }): Promise<Prediction>
115+
```
116+
117+
Run a model and wait for completion.
118+
119+
#### create
120+
121+
```typescript
122+
create(modelId: string, input: Record<string, any>): Promise<Prediction>
123+
```
124+
125+
Create a prediction without waiting for completion.
126+
127+
#### upload
128+
129+
```typescript
130+
upload(filePath: string): Promise<string>
131+
```
132+
133+
Upload a file and get a download URL.
134+
135+
### Prediction
136+
137+
```typescript
138+
prediction.id // Unique prediction ID
139+
prediction.status // Status: processing, completed, failed
140+
prediction.outputs // Array of output URLs
141+
prediction.error // Error message if failed
142+
```
143+
144+
## Environment Variables
145+
146+
### API Client
147+
148+
| Variable | Description |
149+
|----------|-------------|
150+
| `WAVESPEED_API_KEY` | WaveSpeed API key |
151+
| `WAVESPEED_BASE_URL` | API base URL without path (default: `https://api.wavespeed.ai`) |
152+
| `WAVESPEED_POLL_INTERVAL` | Poll interval seconds for `run` (default: `1`) |
153+
| `WAVESPEED_TIMEOUT` | Overall wait timeout seconds for `run` (default: `36000`)
154+
155+
## License
156+
157+
MIT

examples/basic-usage.js

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
// Example of using the WaveSpeed client in JavaScript
2+
3+
const { WaveSpeed } = require('wavespeed');
4+
5+
// Initialize the client with your API key (or set WAVESPEED_API_KEY environment variable)
6+
const client = new WaveSpeed();
7+
8+
// Example 1: Synchronous Image Generation (wait for result)
9+
async function generateImageSync() {
10+
try {
11+
// Generate an image and wait for the result
12+
const prediction = await client.run(
13+
'wavespeed-ai/flux-dev',
14+
{
15+
prompt: 'A futuristic cityscape with flying cars and neon lights',
16+
size: '1024*1024',
17+
num_inference_steps: 28,
18+
guidance_scale: 5.0,
19+
num_images: 1,
20+
seed: -1,
21+
enable_safety_checker: true
22+
}
23+
);
24+
25+
// Print the generated image URLs
26+
console.log(JSON.stringify(prediction, null, 2));
27+
prediction.outputs.forEach((imgUrl, i) => {
28+
console.log(`Image ${i+1}: ${imgUrl}`);
29+
});
30+
} catch (error) {
31+
console.error('Error generating image:', error);
32+
}
33+
}
34+
35+
// Example 2: Non-blocking Image Generation with manual status checking
36+
async function generateImageAsync() {
37+
try {
38+
// Create a prediction without waiting
39+
const prediction = await client.create(
40+
'wavespeed-ai/flux-dev',
41+
{
42+
prompt: 'A beautiful mountain landscape at sunset',
43+
size: '1024*1024',
44+
num_inference_steps: 28,
45+
guidance_scale: 5.0,
46+
num_images: 1,
47+
seed: -1,
48+
enable_safety_checker: true
49+
}
50+
);
51+
52+
console.log(`Prediction created with ID: ${prediction.id}`);
53+
console.log(`Initial status: ${prediction.status}`);
54+
55+
// Manually check status by reloading the prediction
56+
let currentPrediction = prediction;
57+
58+
// Poll until the prediction is complete
59+
while (currentPrediction.status !== 'completed' && currentPrediction.status !== 'failed') {
60+
console.log('Prediction still processing, checking again in 2 seconds...');
61+
await new Promise(resolve => setTimeout(resolve, 2000));
62+
63+
// Reload the prediction to get the latest status
64+
currentPrediction = await currentPrediction.reload();
65+
console.log(`Updated status: ${currentPrediction.status}`);
66+
}
67+
68+
// Check the final status
69+
if (currentPrediction.status === 'completed') {
70+
console.log('Prediction completed successfully!');
71+
72+
// Print the generated image URLs
73+
currentPrediction.outputs.forEach((imgUrl, i) => {
74+
console.log(`Image ${i+1}: ${imgUrl}`);
75+
});
76+
} else {
77+
console.error(`Prediction failed with status: ${currentPrediction.status}`);
78+
if (currentPrediction.error) {
79+
console.error(`Error: ${currentPrediction.error}`);
80+
}
81+
}
82+
} catch (error) {
83+
console.error('Error generating image:', error);
84+
}
85+
}
86+
87+
// Example 3: Custom fetch options
88+
async function generateImageWithOptions() {
89+
try {
90+
// Generate an image with custom fetch options
91+
const prediction = await client.run(
92+
'wavespeed-ai/flux-dev',
93+
{
94+
prompt: 'A serene beach at dawn',
95+
size: '1024*1024',
96+
num_inference_steps: 28,
97+
guidance_scale: 5.0,
98+
num_images: 1,
99+
seed: -1,
100+
enable_safety_checker: true
101+
},
102+
{
103+
timeout: 120000, // 2 minutes timeout
104+
headers: {
105+
'X-Custom-Header': 'custom-value'
106+
}
107+
}
108+
);
109+
110+
console.log(`Generated image: ${prediction.outputs[0]}`);
111+
} catch (error) {
112+
console.error('Error generating image:', error);
113+
}
114+
}
115+
116+
// Run the examples
117+
if (require.main === module) {
118+
// Uncomment one of these to run the example
119+
// generateImageSync();
120+
// generateImageAsync();
121+
// generateImageWithOptions();
122+
console.log('Uncomment one of the example functions to run it');
123+
}

0 commit comments

Comments
 (0)