ai-world-sdk 1.1.1 → 1.1.3

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/dist/log.js CHANGED
@@ -27,7 +27,7 @@ function logRequest(method, url, headers, body) {
27
27
  debugLog("📤 HTTP Request");
28
28
  debugLog(" Method:", method);
29
29
  debugLog(" URL:", url);
30
- debugLog(" Headers:", { ...headers, Authorization: headers?.Authorization ? "Bearer ***" : undefined });
30
+ debugLog(" Headers:", { ...headers, Authorization: headers?.Authorization });
31
31
  if (body) {
32
32
  try {
33
33
  const bodyStr = typeof body === "string" ? body : JSON.stringify(body, null, 2);
@@ -0,0 +1,188 @@
1
+ /**
2
+ * OpenAI Video Generation Client
3
+ * OpenAI 视频生成客户端
4
+ */
5
+ export interface OpenAIVideoGenerationConfig {
6
+ baseUrl?: string;
7
+ token?: string;
8
+ headers?: Record<string, string>;
9
+ }
10
+ export interface OpenAIVideoGenerationRequest {
11
+ prompt: string;
12
+ model?: string;
13
+ provider?: "aihubmix" | "shubiaobiao" | "api2img";
14
+ seconds?: "4" | "8" | "12";
15
+ size?: "720x1280" | "1280x720" | "1024x1792" | "1792x1024";
16
+ input_reference?: string;
17
+ }
18
+ export interface OpenAIVideoTaskResponse {
19
+ id: string;
20
+ object?: string;
21
+ status: "queued" | "in_progress" | "completed" | "failed";
22
+ created_at: number;
23
+ model?: string;
24
+ prompt?: string;
25
+ seconds?: "4" | "8" | "12";
26
+ size?: string;
27
+ url?: string;
28
+ error?: Record<string, any>;
29
+ }
30
+ /**
31
+ * OpenAI Video Generation Client
32
+ * OpenAI 视频生成客户端
33
+ *
34
+ * 使用示例:
35
+ * ```typescript
36
+ * import { OpenAIVideoGenerationClient } from 'ai-world-sdk';
37
+ *
38
+ * const client = new OpenAIVideoGenerationClient({
39
+ * baseUrl: 'http://localhost:8000',
40
+ * token: 'your-auth-token'
41
+ * });
42
+ *
43
+ * // 生成视频
44
+ * const task = await client.generate({
45
+ * prompt: 'A beautiful sunset over the ocean',
46
+ * model: 'sora-2',
47
+ * provider: 'aihubmix',
48
+ * seconds: '4',
49
+ * size: '1280x720'
50
+ * });
51
+ *
52
+ * console.log('Task ID:', task.id);
53
+ *
54
+ * // 查询任务状态
55
+ * const status = await client.getTask(task.id);
56
+ * console.log('Status:', status.status);
57
+ * if (status.video_url) {
58
+ * console.log('Video URL:', status.video_url);
59
+ * }
60
+ * ```
61
+ */
62
+ export declare class OpenAIVideoGenerationClient {
63
+ private headers;
64
+ constructor(config?: OpenAIVideoGenerationConfig);
65
+ /**
66
+ * 生成视频
67
+ * Generate video
68
+ *
69
+ * @param request - 视频生成请求参数
70
+ * @returns 任务响应,包含任务 ID
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * // 文本生成视频
75
+ * const task = await client.generate({
76
+ * prompt: 'A beautiful sunset over the ocean with waves crashing on the shore',
77
+ * model: 'sora-2',
78
+ * provider: 'aihubmix',
79
+ * seconds: '4',
80
+ * size: '1280x720'
81
+ * });
82
+ *
83
+ * // 图像生成视频(使用 base64)
84
+ * const taskWithImage = await client.generate({
85
+ * prompt: 'Animate this image with gentle waves',
86
+ * input_reference: 'data:image/png;base64,iVBORw0KGgo...',
87
+ * model: 'sora-2',
88
+ * seconds: '4'
89
+ * });
90
+ * console.log('Task ID:', task.id);
91
+ * ```
92
+ */
93
+ generate(request: OpenAIVideoGenerationRequest): Promise<OpenAIVideoTaskResponse>;
94
+ /**
95
+ * 查询视频任务状态
96
+ * Get video task status
97
+ *
98
+ * @param taskId - 任务 ID
99
+ * @returns 任务状态信息
100
+ *
101
+ * @example
102
+ * ```typescript
103
+ * const status = await client.getTask('vid_abc123');
104
+ * console.log('Status:', status.status);
105
+ * if (status.status === 'completed' && status.url) {
106
+ * console.log('Video URL:', status.url);
107
+ * }
108
+ * ```
109
+ */
110
+ getTask(taskId: string, provider: "aihubmix" | "shubiaobiao" | "api2img"): Promise<OpenAIVideoTaskResponse>;
111
+ /**
112
+ * 轮询等待任务完成
113
+ * Poll and wait for task completion
114
+ *
115
+ * @param taskId - 任务 ID
116
+ * @param options - 轮询选项
117
+ * @returns 完成的任务信息
118
+ *
119
+ * @example
120
+ * ```typescript
121
+ * const result = await client.waitForCompletion('vid_abc123', {
122
+ * maxAttempts: 60,
123
+ * interval: 5000
124
+ * });
125
+ * console.log('Video URL:', result.url);
126
+ * ```
127
+ */
128
+ waitForCompletion(taskId: string, provider?: "aihubmix" | "shubiaobiao" | "api2img", options?: {
129
+ maxAttempts?: number;
130
+ interval?: number;
131
+ onProgress?: (status: OpenAIVideoTaskResponse) => void;
132
+ }): Promise<OpenAIVideoTaskResponse>;
133
+ /**
134
+ * 生成视频并等待完成
135
+ * Generate video and wait for completion
136
+ *
137
+ * @param request - 视频生成请求参数
138
+ * @param options - 轮询选项
139
+ * @returns 完成的任务信息,包含视频 URL
140
+ *
141
+ * @example
142
+ * ```typescript
143
+ * const result = await client.generateAndWait({
144
+ * prompt: 'A beautiful sunset',
145
+ * model: 'sora-2',
146
+ * provider: 'aihubmix',
147
+ * seconds: '4'
148
+ * }, {
149
+ * onProgress: (status) => {
150
+ * console.log('Status:', status.status);
151
+ * }
152
+ * });
153
+ * console.log('Video URL:', result.video_url);
154
+ * ```
155
+ */
156
+ generateAndWait(request: OpenAIVideoGenerationRequest, options?: {
157
+ maxAttempts?: number;
158
+ interval?: number;
159
+ onProgress?: (status: OpenAIVideoTaskResponse) => void;
160
+ }): Promise<OpenAIVideoTaskResponse>;
161
+ /**
162
+ * 下载视频文件
163
+ * Download video file
164
+ *
165
+ * @param taskId - 视频任务 ID
166
+ * @param provider - 提供商类型 (aihubmix, api2img)
167
+ * @param variant - 下载类型 (video, thumbnail),默认: video
168
+ * @returns Blob 对象(可用于下载或显示)
169
+ *
170
+ * @example
171
+ * ```typescript
172
+ * // 下载视频
173
+ * const videoBlob = await client.downloadVideo('vid_abc123', 'aihubmix', 'video');
174
+ *
175
+ * // 在浏览器中创建下载链接
176
+ * const url = URL.createObjectURL(videoBlob);
177
+ * const a = document.createElement('a');
178
+ * a.href = url;
179
+ * a.download = 'video.mp4';
180
+ * a.click();
181
+ * URL.revokeObjectURL(url);
182
+ *
183
+ * // 或下载缩略图
184
+ * const thumbnail = await client.downloadVideo('vid_abc123', 'aihubmix', 'thumbnail');
185
+ * ```
186
+ */
187
+ downloadVideo(taskId: string, provider?: "aihubmix" | "shubiaobiao" | "api2img", variant?: "video" | "thumbnail"): Promise<Blob>;
188
+ }
@@ -0,0 +1,287 @@
1
+ "use strict";
2
+ /**
3
+ * OpenAI Video Generation Client
4
+ * OpenAI 视频生成客户端
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.OpenAIVideoGenerationClient = void 0;
8
+ const config_1 = require("./config");
9
+ const log_1 = require("./log");
10
+ /**
11
+ * OpenAI Video Generation Client
12
+ * OpenAI 视频生成客户端
13
+ *
14
+ * 使用示例:
15
+ * ```typescript
16
+ * import { OpenAIVideoGenerationClient } from 'ai-world-sdk';
17
+ *
18
+ * const client = new OpenAIVideoGenerationClient({
19
+ * baseUrl: 'http://localhost:8000',
20
+ * token: 'your-auth-token'
21
+ * });
22
+ *
23
+ * // 生成视频
24
+ * const task = await client.generate({
25
+ * prompt: 'A beautiful sunset over the ocean',
26
+ * model: 'sora-2',
27
+ * provider: 'aihubmix',
28
+ * seconds: '4',
29
+ * size: '1280x720'
30
+ * });
31
+ *
32
+ * console.log('Task ID:', task.id);
33
+ *
34
+ * // 查询任务状态
35
+ * const status = await client.getTask(task.id);
36
+ * console.log('Status:', status.status);
37
+ * if (status.video_url) {
38
+ * console.log('Video URL:', status.video_url);
39
+ * }
40
+ * ```
41
+ */
42
+ class OpenAIVideoGenerationClient {
43
+ constructor(config = {}) {
44
+ const globalHeaders = config_1.sdkConfig.getHeaders();
45
+ this.headers = {
46
+ "Content-Type": "application/json",
47
+ "Authorization": `Bearer ${config_1.sdkConfig.getToken()}`,
48
+ "X-Base-Url": config?.baseUrl || "",
49
+ ...globalHeaders,
50
+ ...config?.headers,
51
+ };
52
+ }
53
+ /**
54
+ * 生成视频
55
+ * Generate video
56
+ *
57
+ * @param request - 视频生成请求参数
58
+ * @returns 任务响应,包含任务 ID
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * // 文本生成视频
63
+ * const task = await client.generate({
64
+ * prompt: 'A beautiful sunset over the ocean with waves crashing on the shore',
65
+ * model: 'sora-2',
66
+ * provider: 'aihubmix',
67
+ * seconds: '4',
68
+ * size: '1280x720'
69
+ * });
70
+ *
71
+ * // 图像生成视频(使用 base64)
72
+ * const taskWithImage = await client.generate({
73
+ * prompt: 'Animate this image with gentle waves',
74
+ * input_reference: 'data:image/png;base64,iVBORw0KGgo...',
75
+ * model: 'sora-2',
76
+ * seconds: '4'
77
+ * });
78
+ * console.log('Task ID:', task.id);
79
+ * ```
80
+ */
81
+ async generate(request) {
82
+ const url = `${config_1.sdkConfig.getServerUrl()}/api/openai-video-proxy/generate`;
83
+ // 记录请求日志
84
+ (0, log_1.logRequest)("POST", url, this.headers, request);
85
+ try {
86
+ const response = await fetch(url, {
87
+ method: "POST",
88
+ headers: this.headers,
89
+ body: JSON.stringify(request),
90
+ });
91
+ // 记录响应日志
92
+ (0, log_1.logResponse)(response.status, response.statusText, response.headers, response.body);
93
+ if (!response.ok) {
94
+ const errorData = await response.json().catch(() => ({
95
+ detail: response.statusText,
96
+ }));
97
+ // 检查版本兼容性错误
98
+ if (response.status === 400 &&
99
+ errorData.detail?.includes("version")) {
100
+ throw new config_1.VersionCompatibilityError(errorData.detail);
101
+ }
102
+ throw new Error(errorData.detail || `HTTP error! status: ${response.status}`);
103
+ }
104
+ const data = await response.json();
105
+ return data;
106
+ }
107
+ catch (error) {
108
+ if (error instanceof config_1.VersionCompatibilityError) {
109
+ throw error;
110
+ }
111
+ throw new Error(`OpenAI 视频生成失败: ${error instanceof Error ? error.message : String(error)}`);
112
+ }
113
+ }
114
+ /**
115
+ * 查询视频任务状态
116
+ * Get video task status
117
+ *
118
+ * @param taskId - 任务 ID
119
+ * @returns 任务状态信息
120
+ *
121
+ * @example
122
+ * ```typescript
123
+ * const status = await client.getTask('vid_abc123');
124
+ * console.log('Status:', status.status);
125
+ * if (status.status === 'completed' && status.url) {
126
+ * console.log('Video URL:', status.url);
127
+ * }
128
+ * ```
129
+ */
130
+ async getTask(taskId, provider) {
131
+ const url = `${config_1.sdkConfig.getServerUrl()}/api/openai-video-proxy/${taskId}?provider=${provider}`;
132
+ // 记录请求日志
133
+ (0, log_1.logRequest)("GET", url, this.headers, {});
134
+ try {
135
+ const response = await fetch(url, {
136
+ method: "GET",
137
+ headers: this.headers,
138
+ });
139
+ // 记录响应日志
140
+ (0, log_1.logResponse)(response.status, response.statusText, response.headers, response.body);
141
+ if (!response.ok) {
142
+ const errorData = await response.json().catch(() => ({
143
+ detail: response.statusText,
144
+ }));
145
+ // 检查版本兼容性错误
146
+ if (response.status === 400 &&
147
+ errorData.detail?.includes("version")) {
148
+ throw new config_1.VersionCompatibilityError(errorData.detail);
149
+ }
150
+ throw new Error(errorData.detail || `HTTP error! status: ${response.status}`);
151
+ }
152
+ const data = await response.json();
153
+ return data;
154
+ }
155
+ catch (error) {
156
+ if (error instanceof config_1.VersionCompatibilityError) {
157
+ throw error;
158
+ }
159
+ throw new Error(`查询任务失败: ${error instanceof Error ? error.message : String(error)}`);
160
+ }
161
+ }
162
+ /**
163
+ * 轮询等待任务完成
164
+ * Poll and wait for task completion
165
+ *
166
+ * @param taskId - 任务 ID
167
+ * @param options - 轮询选项
168
+ * @returns 完成的任务信息
169
+ *
170
+ * @example
171
+ * ```typescript
172
+ * const result = await client.waitForCompletion('vid_abc123', {
173
+ * maxAttempts: 60,
174
+ * interval: 5000
175
+ * });
176
+ * console.log('Video URL:', result.url);
177
+ * ```
178
+ */
179
+ async waitForCompletion(taskId, provider = "aihubmix", options = {}) {
180
+ const { maxAttempts = 60, interval = 5000, onProgress } = options;
181
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
182
+ const task = await this.getTask(taskId, provider || "aihubmix");
183
+ if (onProgress) {
184
+ onProgress(task);
185
+ }
186
+ if (task.status === "completed") {
187
+ return task;
188
+ }
189
+ if (task.status === "failed") {
190
+ throw new Error(`任务失败: ${task.error || "未知错误"}`);
191
+ }
192
+ // 等待指定时间后继续轮询
193
+ await new Promise((resolve) => setTimeout(resolve, interval));
194
+ }
195
+ throw new Error(`任务超时: 已轮询 ${maxAttempts} 次,任务仍未完成`);
196
+ }
197
+ /**
198
+ * 生成视频并等待完成
199
+ * Generate video and wait for completion
200
+ *
201
+ * @param request - 视频生成请求参数
202
+ * @param options - 轮询选项
203
+ * @returns 完成的任务信息,包含视频 URL
204
+ *
205
+ * @example
206
+ * ```typescript
207
+ * const result = await client.generateAndWait({
208
+ * prompt: 'A beautiful sunset',
209
+ * model: 'sora-2',
210
+ * provider: 'aihubmix',
211
+ * seconds: '4'
212
+ * }, {
213
+ * onProgress: (status) => {
214
+ * console.log('Status:', status.status);
215
+ * }
216
+ * });
217
+ * console.log('Video URL:', result.video_url);
218
+ * ```
219
+ */
220
+ async generateAndWait(request, options) {
221
+ const task = await this.generate(request);
222
+ return this.waitForCompletion(task.id, request.provider || "aihubmix", options);
223
+ }
224
+ /**
225
+ * 下载视频文件
226
+ * Download video file
227
+ *
228
+ * @param taskId - 视频任务 ID
229
+ * @param provider - 提供商类型 (aihubmix, api2img)
230
+ * @param variant - 下载类型 (video, thumbnail),默认: video
231
+ * @returns Blob 对象(可用于下载或显示)
232
+ *
233
+ * @example
234
+ * ```typescript
235
+ * // 下载视频
236
+ * const videoBlob = await client.downloadVideo('vid_abc123', 'aihubmix', 'video');
237
+ *
238
+ * // 在浏览器中创建下载链接
239
+ * const url = URL.createObjectURL(videoBlob);
240
+ * const a = document.createElement('a');
241
+ * a.href = url;
242
+ * a.download = 'video.mp4';
243
+ * a.click();
244
+ * URL.revokeObjectURL(url);
245
+ *
246
+ * // 或下载缩略图
247
+ * const thumbnail = await client.downloadVideo('vid_abc123', 'aihubmix', 'thumbnail');
248
+ * ```
249
+ */
250
+ async downloadVideo(taskId, provider = "aihubmix", variant = "video") {
251
+ const url = `${config_1.sdkConfig.getServerUrl()}/api/openai-video-proxy/${taskId}/download?provider=${provider}&variant=${variant}`;
252
+ // 记录请求日志
253
+ (0, log_1.logRequest)("GET", url, this.headers, { taskId, provider, variant });
254
+ try {
255
+ const response = await fetch(url, {
256
+ method: "GET",
257
+ headers: this.headers,
258
+ });
259
+ if (!response.ok) {
260
+ const errorData = await response.json().catch(() => null);
261
+ // 记录错误响应日志
262
+ (0, log_1.logResponse)(response.status, response.statusText, response.headers, errorData);
263
+ // 检查版本兼容性错误
264
+ if (response.status === 400 &&
265
+ errorData?.detail?.includes("version")) {
266
+ throw new config_1.VersionCompatibilityError(errorData.detail);
267
+ }
268
+ throw new Error(errorData?.detail || `HTTP error! status: ${response.status}`);
269
+ }
270
+ // 流式下载视频(浏览器会自动处理流式传输)
271
+ const blob = await response.blob();
272
+ // 记录成功日志
273
+ (0, log_1.logResponse)(response.status, response.statusText, response.headers, {
274
+ blobSize: blob.size,
275
+ blobType: blob.type,
276
+ });
277
+ return blob;
278
+ }
279
+ catch (error) {
280
+ if (error instanceof config_1.VersionCompatibilityError) {
281
+ throw error;
282
+ }
283
+ throw new Error(`下载视频失败: ${error instanceof Error ? error.message : String(error)}`);
284
+ }
285
+ }
286
+ }
287
+ exports.OpenAIVideoGenerationClient = OpenAIVideoGenerationClient;
@@ -0,0 +1,8 @@
1
+ export type AIModelProvider = "aihubmix" | "api2img" | "doubao" | "gemini" | "shubiaobiao";
2
+ export type ProviderModelType = "openai" | "gemini";
3
+ export interface ProviderConfig {
4
+ provider: AIModelProvider;
5
+ modelType: ProviderModelType;
6
+ }
7
+ export declare const PROVIDER_CONFIGS: Record<AIModelProvider, ProviderConfig>;
8
+ export declare function getProviderConfig(provider: AIModelProvider): ProviderConfig;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PROVIDER_CONFIGS = void 0;
4
+ exports.getProviderConfig = getProviderConfig;
5
+ exports.PROVIDER_CONFIGS = {
6
+ aihubmix: { provider: "aihubmix", modelType: "openai" },
7
+ shubiaobiao: { provider: "shubiaobiao", modelType: "openai" },
8
+ api2img: { provider: "api2img", modelType: "openai" },
9
+ doubao: { provider: "doubao", modelType: "openai" },
10
+ gemini: { provider: "gemini", modelType: "gemini" },
11
+ };
12
+ function getProviderConfig(provider) {
13
+ return exports.PROVIDER_CONFIGS[provider];
14
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-world-sdk",
3
- "version": "1.1.1",
3
+ "version": "1.1.3",
4
4
  "description": "TypeScript SDK for AI World Platform - Chat Models, Image Generation, and Video Generation",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",