Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,17 @@ const output = await wavespeed.run(
{
timeout: 36000.0, // Max wait time in seconds (default: 36000.0)
pollInterval: 1.0, // Status check interval (default: 1.0)
enableSyncMode: false, // Single request mode, no polling (default: false)
enableSyncMode: false, // Best-effort sync result attempt (default: false)
}
);
```

### Sync Mode

Use `enableSyncMode: true` for a single request that waits for the result (no polling).
Use `enableSyncMode: true` to ask the API to wait for the result in the initial
request. If the server-side sync wait times out, the SDK raises
`WavespeedSyncTimeoutException` with the task ID/result URL; the task continues
processing and can be queried later.

> **Note:** Not all models support sync mode. Check the model documentation for availability.

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "wavespeed",
"version": "0.2.3",
"version": "0.2.4",
"description": "WaveSpeed Client SDK for Wavespeed API",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
96 changes: 80 additions & 16 deletions src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { api as apiConfig } from '../config';
export interface RunOptions {
timeout?: number; // Maximum time to wait for completion
pollInterval?: number; // Interval between status checks in seconds
enableSyncMode?: boolean; // If true, use synchronous mode (single request)
enableSyncMode?: boolean; // If true, attempt synchronous mode in one request
maxRetries?: number; // Maximum task-level retries (overrides client setting)
}

Expand Down Expand Up @@ -38,6 +38,24 @@ export class WavespeedTimeoutException extends WavespeedException {
}
}

/**
* Sync-mode wait timed out, but the task is still processing asynchronously
*/
export class WavespeedSyncTimeoutException extends WavespeedException {
constructor(
taskId: string,
model: string,
errorMessage: string,
public readonly resultUrl?: string
) {
const suffix = resultUrl && !errorMessage.includes(resultUrl)
? ` Query the result later at: ${resultUrl}`
: '';
super(`Sync mode timed out (task_id: ${taskId}): ${errorMessage}${suffix}`, taskId, model);
this.name = 'WavespeedSyncTimeoutException';
}
}

/**
* Connection exception
*/
Expand Down Expand Up @@ -73,10 +91,11 @@ export class WavespeedUnknownException extends WavespeedException {
*/
export interface RunDetail {
taskId: string; // Task ID for tracking and debugging
status: 'completed' | 'failed'; // Task status
status: 'completed' | 'failed' | 'processing'; // Task status
model: string; // Model identifier
error?: WavespeedException; // Exception instance if failed
createdAt?: string; // Task creation timestamp
resultUrl?: string; // URL for querying the task result later
}

/**
Expand Down Expand Up @@ -108,7 +127,7 @@ interface UploadFileResp {
* const client = new Client("your-api-key");
* const output = await client.run("wavespeed-ai/z-image/turbo", { prompt: "Cat" });
*
* // With sync mode (single request, waits for result)
* // With sync mode (best-effort single request, waits for result)
* const output2 = await client.run("wavespeed-ai/z-image/turbo", { prompt: "Cat" }, { enableSyncMode: true });
*
* // With retry
Expand Down Expand Up @@ -413,6 +432,9 @@ export class Client {

// Always retry timeout and connection errors
const errorStr = error.toString().toLowerCase();
if (errorStr.includes('sync mode timed out')) {
return false;
}
if (errorStr.includes('timeout') || errorStr.includes('connection')) {
return true;
}
Expand All @@ -425,6 +447,35 @@ export class Client {
return false;
}

private _resultUrlFromData(data: Record<string, any>): string | undefined {
const urls = data.urls;
return urls && typeof urls === 'object' && typeof urls.get === 'string'
? urls.get
: undefined;
}

private _isSyncTimeoutData(data: Record<string, any>): boolean {
const error = data.error || '';
return data.code === 5004 ||
(data.status === 'processing' && typeof error === 'string' && error.includes('Sync mode timed out'));
Comment on lines +459 to +460

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require processing status for sync timeout classification

For a sync-mode response such as { status: 'failed', code: 5004 }, this classifies WaveSpeed's generic timeout error code as a still-running sync timeout before checking the task status. That makes run() throw a non-retryable WavespeedSyncTimeoutException and makes runNoThrow() report detail.status === 'processing' even though the task is terminally failed; require status === 'processing' or the sync-timeout message when treating 5004 as queryable.

Useful? React with 👍 / 👎.

}

private _syncModeError(data: Record<string, any>, model: string): Error {
const error = data.error || 'Unknown error';
const taskId = data.id || 'unknown';

if (this._isSyncTimeoutData(data)) {
return new WavespeedSyncTimeoutException(
taskId,
model,
error,
this._resultUrlFromData(data)
);
}

return new Error(`Prediction failed (task_id: ${taskId}): ${error}`);
}

/**
* Run a model and wait for the output.
*
Expand All @@ -433,7 +484,7 @@ export class Client {
* input: Input parameters for the model.
* options.timeout: Maximum time to wait for completion (undefined = no timeout).
* options.pollInterval: Interval between status checks in seconds.
* options.enableSyncMode: If true, use synchronous mode (single request).
* options.enableSyncMode: If true, use synchronous mode (best-effort single request).
* options.maxRetries: Maximum task-level retries (overrides client setting).
*
* Returns:
Expand Down Expand Up @@ -469,9 +520,7 @@ export class Client {
const data = syncResult?.data || {};
const status = data.status;
if (status !== 'completed') {
const error = data.error || 'Unknown error';
const requestId = data.id || 'unknown';
throw new Error(`Prediction failed (task_id: ${requestId}): ${error}`);
throw this._syncModeError(data, model);
}
return { outputs: data.outputs || [] };
}
Expand Down Expand Up @@ -516,7 +565,7 @@ export class Client {
* input: Input parameters for the model.
* options.timeout: Maximum time to wait for completion (undefined = no timeout).
* options.pollInterval: Interval between status checks in seconds.
* options.enableSyncMode: If true, use synchronous mode (single request).
* options.enableSyncMode: If true, use synchronous mode (best-effort single request).
* options.maxRetries: Maximum task-level retries (overrides client setting).
*
* Returns:
Expand Down Expand Up @@ -562,14 +611,19 @@ export class Client {

if (status !== 'completed') {
const errorMsg = data.error || 'Unknown error';
const resultUrl = this._resultUrlFromData(data);
const isSyncTimeout = this._isSyncTimeoutData(data);
return {
outputs: null,
detail: {
taskId,
status: 'failed',
status: isSyncTimeout ? 'processing' : 'failed',
model,
error: new WavespeedPredictionException(taskId, model, errorMsg),
createdAt: data.created_at
error: isSyncTimeout
? new WavespeedSyncTimeoutException(taskId, model, errorMsg, resultUrl)
: new WavespeedPredictionException(taskId, model, errorMsg),
createdAt: data.created_at,
resultUrl
}
};
}
Expand Down Expand Up @@ -614,19 +668,28 @@ export class Client {
// If not retryable or last attempt, return error result
if (!isRetryable || attempt >= taskRetries) {
// Try to extract taskId from error message
const taskIdMatch = error.message?.match(/task_id: ([a-f0-9-]+)/);
const taskIdMatch = error.message?.match(/task_id:\s*([^)]+)/);
const taskId = taskIdMatch ? taskIdMatch[1] : 'unknown';
const resultUrlMatch = error.message?.match(/Query the result later at:\s*(\S+)/);
const resultUrl = resultUrlMatch ? resultUrlMatch[1] : undefined;

// Determine exception type based on error
let exception: WavespeedException;
const errorStr = error.toString().toLowerCase();

if (errorStr.includes('timeout') || errorStr.includes('timed out')) {
if (errorStr.includes('sync mode timed out')) {
exception = new WavespeedSyncTimeoutException(
taskId,
model,
error.message?.replace(/Sync mode timed out \(task_id: [^)]+\):\s*/, '') || String(error),
resultUrl
);
} else if (errorStr.includes('timeout') || errorStr.includes('timed out')) {
exception = new WavespeedTimeoutException(taskId, model, timeout || 0);
} else if (errorStr.includes('connection') || errorStr.includes('fetch') || error.name === 'AbortError' || error.name === 'TypeError') {
exception = new WavespeedConnectionException(taskId, model, error.message || String(error));
} else if (errorStr.includes('prediction failed')) {
const errorMsg = error.message?.replace(/Prediction failed \(task_id: [a-f0-9-]+\): /, '') || 'Unknown error';
const errorMsg = error.message?.replace(/Prediction failed \(task_id: [^)]+\): /, '') || 'Unknown error';
exception = new WavespeedPredictionException(taskId, model, errorMsg);
} else {
exception = new WavespeedUnknownException(taskId, model, error);
Expand All @@ -636,9 +699,10 @@ export class Client {
outputs: null,
detail: {
taskId,
status: 'failed',
status: errorStr.includes('sync mode timed out') ? 'processing' : 'failed',
model,
error: exception
error: exception,
resultUrl
}
};
}
Expand Down
4 changes: 3 additions & 1 deletion src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import type { RunOptions, RunDetail, RunNoThrowResult } from './client';
import {
WavespeedException,
WavespeedTimeoutException,
WavespeedSyncTimeoutException,
WavespeedConnectionException,
WavespeedPredictionException,
WavespeedUnknownException
Expand All @@ -33,6 +34,7 @@ export type { RunOptions, RunDetail, RunNoThrowResult };
export {
WavespeedException,
WavespeedTimeoutException,
WavespeedSyncTimeoutException,
WavespeedConnectionException,
WavespeedPredictionException,
WavespeedUnknownException
Expand All @@ -59,7 +61,7 @@ function _getDefaultClient(): Client {
* input: Input parameters for the model.
* options.timeout: Maximum time to wait for completion (undefined = no timeout).
* options.pollInterval: Interval between status checks in seconds.
* options.enableSyncMode: If true, use synchronous mode (single request).
* options.enableSyncMode: If true, use synchronous mode (best-effort single request).
* options.maxRetries: Maximum retries for this request (overrides default setting).
*
* Returns:
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import type { RunOptions, RunDetail, RunNoThrowResult } from './api/client';
import {
WavespeedException,
WavespeedTimeoutException,
WavespeedSyncTimeoutException,
WavespeedConnectionException,
WavespeedPredictionException,
WavespeedUnknownException
Expand All @@ -36,6 +37,7 @@ export type { RunOptions, RunDetail, RunNoThrowResult };
export {
WavespeedException,
WavespeedTimeoutException,
WavespeedSyncTimeoutException,
WavespeedConnectionException,
WavespeedPredictionException,
WavespeedUnknownException
Expand Down
64 changes: 63 additions & 1 deletion tests/test_api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*/

import * as wavespeed from '../src/index';
import { Client } from '../src/api/client';
import { Client, WavespeedSyncTimeoutException } from '../src/api/client';
import { api as apiConfig } from '../src/config';

// Mock fetch globally
Expand Down Expand Up @@ -224,6 +224,68 @@ describe('Client', () => {
).rejects.toThrow('Prediction failed (task_id: req-456): Model error');
});

test('run sync mode timeout raises queryable error', async () => {
const resultUrl = 'https://api.wavespeed.ai/api/v3/predictions/req-timeout/result';
const mockResponse = {
ok: true,
status: 200,
json: async () => ({
data: {
id: 'req-timeout',
status: 'processing',
code: 5004,
error: 'Sync mode timed out after 90 seconds. The prediction is still processing asynchronously.',
urls: { get: resultUrl }
}
}),
};

(global.fetch as jest.Mock).mockResolvedValue(mockResponse);

const client = new Client('test-key');

await expect(
client.run('wavespeed-ai/z-image/turbo', { prompt: 'test' }, { enableSyncMode: true, maxRetries: 1 })
).rejects.toThrow(WavespeedSyncTimeoutException);
await expect(
client.run('wavespeed-ai/z-image/turbo', { prompt: 'test' }, { enableSyncMode: true })
).rejects.toThrow(resultUrl);
expect(global.fetch).toHaveBeenCalledTimes(2);
});

test('runNoThrow sync mode timeout returns processing detail', async () => {
const resultUrl = 'https://api.wavespeed.ai/api/v3/predictions/req-timeout/result';
const mockResponse = {
ok: true,
status: 200,
json: async () => ({
data: {
id: 'req-timeout',
status: 'processing',
code: 5004,
error: 'Sync mode timed out after 90 seconds. The prediction is still processing asynchronously.',
urls: { get: resultUrl }
}
}),
};

(global.fetch as jest.Mock).mockResolvedValue(mockResponse);

const client = new Client('test-key');
const result = await client.runNoThrow(
'wavespeed-ai/z-image/turbo',
{ prompt: 'test' },
{ enableSyncMode: true }
);

expect(result.outputs).toBeNull();
expect(result.detail.status).toBe('processing');
expect(result.detail.taskId).toBe('req-timeout');
expect(result.detail.resultUrl).toBe(resultUrl);
expect(result.detail.error).toBeInstanceOf(WavespeedSyncTimeoutException);
expect(global.fetch).toHaveBeenCalledTimes(1);
});

test('_submit no request id', async () => {
const mockResponse = {
ok: true,
Expand Down
Loading