ai-world-sdk 1.0.0

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/README.md ADDED
@@ -0,0 +1,1006 @@
1
+ # ai-world-sdk
2
+
3
+ TypeScript SDK for AI World Platform - 一个功能完整的 AI 应用开发 SDK
4
+
5
+ [![npm version](https://img.shields.io/npm/v/ai-world-sdk)](https://www.npmjs.com/package/ai-world-sdk)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ## 简介
9
+
10
+ `ai-world-sdk` 是一个功能完整的 TypeScript SDK,用于与 AI World 平台交互。它提供了:
11
+
12
+ - **聊天模型**: 兼容 LangChain.js 接口的聊天模型(OpenAI、Google Gemini、Anthropic Claude、Doubao)
13
+ - **图像生成**: 支持豆包 Seedream 模型的图像生成 API
14
+ - **视频生成**: 支持豆包 Seedance 模型的视频生成 API
15
+ - **全局配置**: 支持全局 baseUrl 和 token 配置,简化客户端初始化
16
+
17
+ 设计灵感来自 [LangChain.js](https://github.com/langchain-ai/langchainjs) 的接口风格。
18
+
19
+ ## 安装
20
+
21
+ ```bash
22
+ npm install ai-world-sdk
23
+ # 或
24
+ yarn add ai-world-sdk
25
+ # 或
26
+ pnpm add ai-world-sdk
27
+ ```
28
+
29
+ ## 快速开始
30
+
31
+ ### 1. 全局配置(推荐)
32
+
33
+ ```typescript
34
+ import { sdkConfig, ChatGoogleGenerativeAI, ImageGenerationClient, VideoGenerationClient } from 'ai-world-sdk';
35
+
36
+ // 设置全局配置(只需设置一次)
37
+ sdkConfig.setBaseUrl('http://localhost:8000');
38
+ sdkConfig.setToken('your-jwt-token');
39
+
40
+ // 现在可以创建客户端而不需要提供 baseUrl 和 token
41
+ const chatModel = new ChatGoogleGenerativeAI({
42
+ modelName: 'gemini-2.0-flash-exp-image-generation',
43
+ temperature: 0.7,
44
+ });
45
+
46
+ const imageClient = new ImageGenerationClient({});
47
+ const videoClient = new VideoGenerationClient({});
48
+ ```
49
+
50
+ ### 2. 基础聊天模型使用
51
+
52
+ ```typescript
53
+ import {
54
+ ChatGoogleGenerativeAI,
55
+ HumanMessage,
56
+ SystemMessage,
57
+ AIMessageChunk,
58
+ } from 'ai-world-sdk';
59
+
60
+ // 初始化聊天模型
61
+ const model = new ChatGoogleGenerativeAI({
62
+ baseUrl: 'http://localhost:8000',
63
+ token: 'your-jwt-token',
64
+ modelName: 'gemini-2.0-flash-exp-image-generation',
65
+ temperature: 0.7,
66
+ });
67
+
68
+ // 非流式调用
69
+ const response = await model.invoke([
70
+ new SystemMessage('You are a helpful assistant.'),
71
+ new HumanMessage('Hello! What is AI?'),
72
+ ]);
73
+
74
+ console.log(response.content); // 输出: AI 是...
75
+
76
+ // 流式调用
77
+ for await (const chunk of model.stream([
78
+ new HumanMessage('Tell me a story about AI'),
79
+ ])) {
80
+ // chunk 是 AIMessageChunk 对象
81
+ if (typeof chunk.content === 'string') {
82
+ process.stdout.write(chunk.content);
83
+ }
84
+ }
85
+ ```
86
+
87
+ ## 完整 API 文档
88
+
89
+ ### 全局配置 API
90
+
91
+ #### `sdkConfig.setBaseUrl(baseUrl: string): void`
92
+
93
+ 设置全局 baseUrl。所有客户端实例如果没有提供 baseUrl,将使用此全局值。
94
+
95
+ ```typescript
96
+ import { sdkConfig } from 'ai-world-sdk';
97
+
98
+ sdkConfig.setBaseUrl('http://localhost:8000');
99
+ ```
100
+
101
+ #### `sdkConfig.setToken(token: string): void`
102
+
103
+ 设置全局 token。所有客户端实例如果没有提供 token,将使用此全局值。
104
+
105
+ ```typescript
106
+ sdkConfig.setToken('your-jwt-token');
107
+ ```
108
+
109
+ #### `sdkConfig.setHeaders(headers: Record<string, string>): void`
110
+
111
+ 设置全局 headers。这些 headers 会与每个客户端实例的 headers 合并。
112
+
113
+ ```typescript
114
+ sdkConfig.setHeaders({
115
+ 'X-Custom-Header': 'value',
116
+ });
117
+ ```
118
+
119
+ #### `sdkConfig.getBaseUrl(): string | null`
120
+
121
+ 获取全局 baseUrl。
122
+
123
+ #### `sdkConfig.getToken(): string | null`
124
+
125
+ 获取全局 token。
126
+
127
+ #### `sdkConfig.getHeaders(): Record<string, string>`
128
+
129
+ 获取全局 headers。
130
+
131
+ #### `sdkConfig.reset(): void`
132
+
133
+ 重置所有全局配置。
134
+
135
+ ### 聊天模型 API
136
+
137
+ #### 支持的模型类
138
+
139
+ - `ChatOpenAI` - OpenAI 兼容模型(GPT、O1、Doubao)
140
+ - `ChatGoogleGenerativeAI` - Google Gemini 模型
141
+ - `ChatAnthropic` - Anthropic Claude 模型
142
+
143
+ #### `BaseChatModel` 接口
144
+
145
+ 所有聊天模型都继承自 `BaseChatModel`,提供以下方法:
146
+
147
+ ##### `invoke(messages: BaseMessage[]): Promise<AIMessage>`
148
+
149
+ 发送非流式请求。
150
+
151
+ **参数:**
152
+ - `messages`: 消息数组,可以是 `HumanMessage`、`SystemMessage`、`AIMessage`
153
+
154
+ **返回:** `AIMessage` 对象,包含 `content` 字段
155
+
156
+ **示例:**
157
+ ```typescript
158
+ const response = await model.invoke([
159
+ new HumanMessage('What is the capital of France?'),
160
+ ]);
161
+ console.log(response.content); // "The capital of France is Paris."
162
+ ```
163
+
164
+ ##### `stream(messages: BaseMessage[]): AsyncGenerator<AIMessageChunk, void, unknown>`
165
+
166
+ 发送流式请求。
167
+
168
+ **参数:**
169
+ - `messages`: 消息数组
170
+
171
+ **返回:** 异步生成器,每次 yield 一个 `AIMessageChunk` 对象
172
+
173
+ **示例:**
174
+ ```typescript
175
+ for await (const chunk of model.stream([
176
+ new HumanMessage('Tell me a story'),
177
+ ])) {
178
+ if (typeof chunk.content === 'string') {
179
+ process.stdout.write(chunk.content);
180
+ }
181
+ }
182
+ ```
183
+
184
+ ##### `batch(messagesList: BaseMessage[][]): Promise<AIMessage[]>`
185
+
186
+ 批量处理多个消息集。
187
+
188
+ **参数:**
189
+ - `messagesList`: 消息数组的数组
190
+
191
+ **返回:** `AIMessage` 数组
192
+
193
+ **示例:**
194
+ ```typescript
195
+ const responses = await model.batch([
196
+ [new HumanMessage('What is AI?')],
197
+ [new HumanMessage('What is ML?')],
198
+ [new HumanMessage('What is DL?')],
199
+ ]);
200
+
201
+ responses.forEach((response, index) => {
202
+ console.log(`Response ${index + 1}:`, response.content);
203
+ });
204
+ ```
205
+
206
+ ##### `bind(options: BindOptions): BaseChatModel`
207
+
208
+ 绑定参数到模型实例,返回新的模型实例。
209
+
210
+ **参数:**
211
+ - `options.temperature`: 温度参数
212
+ - `options.maxTokens`: 最大 token 数
213
+ - `options.topP`: Top-p 采样参数
214
+ - `options.tools`: 工具定义数组
215
+ - `options.toolChoice`: 工具选择策略
216
+
217
+ **示例:**
218
+ ```typescript
219
+ const boundModel = model.bind({
220
+ temperature: 0.9,
221
+ maxTokens: 1000,
222
+ });
223
+
224
+ const response = await boundModel.invoke([
225
+ new HumanMessage('Hello!'),
226
+ ]);
227
+ ```
228
+
229
+ ##### `bindTools(tools: ToolDefinition[]): BaseChatModel`
230
+
231
+ 绑定工具到模型实例。
232
+
233
+ **参数:**
234
+ - `tools`: 工具定义数组
235
+
236
+ **示例:**
237
+ ```typescript
238
+ import { ToolDefinition } from 'ai-world-sdk';
239
+
240
+ const tools: ToolDefinition[] = [
241
+ {
242
+ type: 'function',
243
+ function: {
244
+ name: 'get_weather',
245
+ description: 'Get the current weather in a location',
246
+ parameters: {
247
+ type: 'object',
248
+ properties: {
249
+ location: { type: 'string' },
250
+ },
251
+ required: ['location'],
252
+ },
253
+ },
254
+ },
255
+ ];
256
+
257
+ const modelWithTools = model.bindTools(tools);
258
+ const response = await modelWithTools.invoke([
259
+ new HumanMessage('What is the weather in Paris?'),
260
+ ]);
261
+ ```
262
+
263
+ ##### `getModelName(): string`
264
+
265
+ 获取当前模型名称。
266
+
267
+ #### 消息类型
268
+
269
+ ##### `HumanMessage`
270
+
271
+ 用户消息。
272
+
273
+ ```typescript
274
+ import { HumanMessage } from 'ai-world-sdk';
275
+
276
+ const message = new HumanMessage('Hello!');
277
+ ```
278
+
279
+ ##### `SystemMessage`
280
+
281
+ 系统消息,用于设置助手的行为。
282
+
283
+ ```typescript
284
+ import { SystemMessage } from 'ai-world-sdk';
285
+
286
+ const message = new SystemMessage('You are a helpful assistant.');
287
+ ```
288
+
289
+ ##### `AIMessage`
290
+
291
+ 助手消息。
292
+
293
+ ```typescript
294
+ import { AIMessage } from 'ai-world-sdk';
295
+
296
+ const message = new AIMessage('Hello! How can I help you?');
297
+ ```
298
+
299
+ ##### `AIMessageChunk`
300
+
301
+ 流式响应中的消息块。
302
+
303
+ ```typescript
304
+ import { AIMessageChunk } from 'ai-world-sdk';
305
+
306
+ // 在流式调用中使用
307
+ for await (const chunk of model.stream([...])) {
308
+ // chunk 是 AIMessageChunk 实例
309
+ console.log(chunk.content);
310
+ console.log(chunk.id);
311
+ console.log(chunk.response_metadata);
312
+ }
313
+ ```
314
+
315
+ #### 多模态输入
316
+
317
+ 支持文本和图像混合输入:
318
+
319
+ ```typescript
320
+ const response = await model.invoke([
321
+ {
322
+ role: 'user',
323
+ content: [
324
+ { type: 'text', text: 'Describe this image' },
325
+ {
326
+ type: 'image_url',
327
+ image_url: 'data:image/jpeg;base64,/9j/4AAQSkZJRg...',
328
+ },
329
+ ],
330
+ },
331
+ ]);
332
+ ```
333
+
334
+ #### 工厂函数
335
+
336
+ 使用 `createChatModel` 根据模型名称自动选择正确的模型类:
337
+
338
+ ```typescript
339
+ import { createChatModel } from 'ai-world-sdk';
340
+
341
+ // 自动选择 ChatGoogleGenerativeAI
342
+ const gemini = createChatModel('gemini-1.5-pro', {
343
+ baseUrl: 'http://localhost:8000',
344
+ token: 'your-token',
345
+ temperature: 0.7,
346
+ });
347
+
348
+ // 自动选择 ChatOpenAI
349
+ const gpt = createChatModel('gpt-4', {
350
+ baseUrl: 'http://localhost:8000',
351
+ token: 'your-token',
352
+ });
353
+
354
+ // 自动选择 ChatAnthropic
355
+ const claude = createChatModel('claude-3-sonnet-20240229', {
356
+ baseUrl: 'http://localhost:8000',
357
+ token: 'your-token',
358
+ });
359
+ ```
360
+
361
+ **支持的模型前缀:**
362
+ - `gpt-*`, `o1-*` → `ChatOpenAI`
363
+ - `doubao-*` → `ChatOpenAI` (Doubao 与 OpenAI 兼容)
364
+ - `gemini-*` → `ChatGoogleGenerativeAI`
365
+ - `claude-*` → `ChatAnthropic`
366
+
367
+ ### 图像生成 API
368
+
369
+ #### `ImageGenerationClient`
370
+
371
+ 图像生成客户端,支持 OpenAI 标准格式的图像生成。
372
+
373
+ ##### 初始化
374
+
375
+ ```typescript
376
+ import { ImageGenerationClient } from 'ai-world-sdk';
377
+
378
+ const imageClient = new ImageGenerationClient({
379
+ baseUrl: 'http://localhost:8000', // 可选,如果设置了全局配置
380
+ token: 'your-jwt-token', // 可选,如果设置了全局配置
381
+ headers: { // 可选
382
+ 'X-Custom-Header': 'value',
383
+ },
384
+ });
385
+ ```
386
+
387
+ ##### `generate(request: ImageGenerationRequest): Promise<ImageGenerationResponse>`
388
+
389
+ 生成图像(同步)。
390
+
391
+ **请求参数 (`ImageGenerationRequest`):**
392
+ - `prompt` (必需): 图像生成提示词
393
+ - `model` (可选): 模型名称,默认: `doubao-seedream-4-5-251128`
394
+ - `n` (可选): 生成图像数量,1-10,默认: 1
395
+ - `size` (可选): 图像尺寸,支持: `256x256`, `512x512`, `1024x1024`, `1792x1024`, `1024x1792`, `1K`, `2K`, `4K`,默认: `1024x1024`
396
+ - `quality` (可选): 图像质量,`standard` 或 `hd`,默认: `standard`
397
+ - `response_format` (可选): 响应格式,`url` 或 `b64_json`,默认: `url`
398
+ - `style` (可选): 图像风格,`vivid` 或 `natural`(仅部分模型支持)
399
+ - `user` (可选): 用户标识(用于追踪和审计)
400
+
401
+ **返回 (`ImageGenerationResponse`):**
402
+ - `created`: 创建时间戳(Unix 时间戳)
403
+ - `data`: 图像数据数组,每个元素包含:
404
+ - `url`: 图像 URL(如果 `response_format` 为 `url`)
405
+ - `b64_json`: Base64 编码的图像数据(如果 `response_format` 为 `b64_json`)
406
+
407
+ **示例:**
408
+ ```typescript
409
+ const result = await imageClient.generate({
410
+ prompt: '充满活力的特写编辑肖像,模特眼神犀利,头戴雕塑感帽子',
411
+ model: 'doubao-seedream-4-5-251128',
412
+ size: '2K',
413
+ n: 1,
414
+ quality: 'hd',
415
+ response_format: 'url',
416
+ });
417
+
418
+ console.log('生成的图像:', result.data);
419
+ console.log('第一张图像 URL:', result.data[0]?.url);
420
+ ```
421
+
422
+ ### 视频生成 API
423
+
424
+ #### `VideoGenerationClient`
425
+
426
+ 视频生成客户端,支持豆包 Seedance 模型的视频生成。
427
+
428
+ ##### 初始化
429
+
430
+ ```typescript
431
+ import { VideoGenerationClient } from 'ai-world-sdk';
432
+
433
+ const videoClient = new VideoGenerationClient({
434
+ baseUrl: 'http://localhost:8000', // 可选,如果设置了全局配置
435
+ token: 'your-jwt-token', // 可选,如果设置了全局配置
436
+ headers: { // 可选
437
+ 'X-Custom-Header': 'value',
438
+ },
439
+ });
440
+ ```
441
+
442
+ ##### `create(request: VideoGenerationRequest): Promise<ContentGenerationTaskID>`
443
+
444
+ 创建视频生成任务。
445
+
446
+ **请求参数 (`VideoGenerationRequest`):**
447
+ - `prompt` (可选): 文本提示词(文本生成视频)
448
+ - `image_url` (可选): 图像 URL(图像生成视频)
449
+ - `model` (可选): 模型名称,默认: `doubao-seedance-1-0-pro-fast-251015`
450
+ - `content` (可选): 内容列表(如果提供,将直接使用,忽略 prompt 和 image_url)
451
+ - `callback_url` (可选): 回调 URL(任务完成时通知)
452
+ - `return_last_frame` (可选): 是否返回最后一帧图像
453
+ - `service_tier` (可选): 服务层级
454
+ - `execution_expires_after` (可选): 执行过期时间(秒)
455
+ - `duration` (可选): 视频时长(秒),1-10,默认: 5(将添加到 prompt)
456
+ - `aspect_ratio` (可选): 视频宽高比,`16:9`, `9:16`, `1:1`,默认: `16:9`(将添加到 prompt)
457
+ - `resolution` (可选): 视频分辨率,例如: `720p`, `1080p`(将添加到 prompt)
458
+ - `user` (可选): 用户标识(用于追踪和审计)
459
+
460
+ **注意:** `prompt` 和 `image_url` 必须提供其中之一,或者直接提供 `content`。
461
+
462
+ **返回 (`ContentGenerationTaskID`):**
463
+ - `id`: 任务 ID
464
+
465
+ **示例(文本生成视频):**
466
+ ```typescript
467
+ const task = await videoClient.create({
468
+ prompt: 'A beautiful sunset over the ocean with waves crashing on the shore',
469
+ model: 'doubao-seedance-1-0-pro-fast-251015',
470
+ duration: 5,
471
+ aspect_ratio: '16:9',
472
+ resolution: '720p',
473
+ });
474
+
475
+ console.log('任务 ID:', task.id);
476
+ ```
477
+
478
+ **示例(图像生成视频):**
479
+ ```typescript
480
+ const task = await videoClient.create({
481
+ image_url: 'https://example.com/image.jpg',
482
+ model: 'doubao-seedance-1-0-pro-fast-251015',
483
+ duration: 5,
484
+ });
485
+
486
+ console.log('任务 ID:', task.id);
487
+ ```
488
+
489
+ **示例(直接提供 content):**
490
+ ```typescript
491
+ const task = await videoClient.create({
492
+ model: 'doubao-seedance-1-0-pro-fast-251015',
493
+ content: [
494
+ {
495
+ type: 'text',
496
+ text: 'A beautiful sunset --ratio 16:9 --duration 5',
497
+ },
498
+ ],
499
+ return_last_frame: true,
500
+ callback_url: 'https://example.com/callback',
501
+ });
502
+ ```
503
+
504
+ ##### `get(taskId: string): Promise<ContentGenerationTask>`
505
+
506
+ 查询视频生成任务状态。
507
+
508
+ **参数:**
509
+ - `taskId`: 任务 ID
510
+
511
+ **返回 (`ContentGenerationTask`):**
512
+ - `id`: 任务 ID
513
+ - `model`: 使用的模型
514
+ - `status`: 任务状态,`queued` | `running` | `succeeded` | `failed` | `cancelled`
515
+ - `error`: 错误信息(如果失败),包含 `message` 和 `code`
516
+ - `content`: 生成的内容,包含:
517
+ - `video_url`: 视频 URL(任务完成时)
518
+ - `last_frame_url`: 最后一帧图像 URL(如果 `return_last_frame` 为 true)
519
+ - `file_url`: 文件 URL
520
+ - `usage`: 使用情况,包含 `completion_tokens`
521
+ - `created_at`: 创建时间戳(Unix 时间戳)
522
+ - `updated_at`: 更新时间戳
523
+ - 其他字段: `subdivisionlevel`, `fileformat`, `frames`, `framespersecond`, `seed`, `revised_prompt`, `service_tier`, `execution_expires_after`
524
+
525
+ **示例:**
526
+ ```typescript
527
+ const task = await videoClient.get(taskId);
528
+
529
+ console.log('任务状态:', task.status);
530
+ console.log('使用的模型:', task.model);
531
+
532
+ if (task.status === 'succeeded' && task.content?.video_url) {
533
+ console.log('视频 URL:', task.content.video_url);
534
+ } else if (task.error) {
535
+ console.error('错误:', task.error.message);
536
+ }
537
+ ```
538
+
539
+ ##### `poll(taskId: string, options?: PollOptions): Promise<ContentGenerationTask>`
540
+
541
+ 轮询视频生成任务直到完成。
542
+
543
+ **参数:**
544
+ - `taskId`: 任务 ID
545
+ - `options.interval` (可选): 轮询间隔(毫秒),默认: 5000
546
+ - `options.timeout` (可选): 超时时间(毫秒),默认: 300000 (5分钟)
547
+
548
+ **返回:** 完成后的 `ContentGenerationTask`
549
+
550
+ **示例:**
551
+ ```typescript
552
+ // 创建任务
553
+ const createTask = await videoClient.create({
554
+ prompt: 'A short video of a cat playing',
555
+ model: 'doubao-seedance-1-0-pro-fast-251015',
556
+ duration: 3,
557
+ });
558
+
559
+ // 轮询直到完成
560
+ const result = await videoClient.poll(createTask.id, {
561
+ interval: 2000, // 每 2 秒轮询一次
562
+ timeout: 60000, // 60 秒超时
563
+ });
564
+
565
+ if (result.status === 'succeeded' && result.content?.video_url) {
566
+ console.log('视频生成成功:', result.content.video_url);
567
+ } else if (result.error) {
568
+ console.error('生成失败:', result.error.message);
569
+ }
570
+ ```
571
+
572
+ ## 支持的模型
573
+
574
+ ### 聊天模型
575
+
576
+ #### OpenAI 兼容模型
577
+ - `gpt-3.5-turbo`
578
+ - `gpt-4`
579
+ - `gpt-4-turbo`
580
+ - `o1-preview`
581
+ - `o1-mini`
582
+ - `doubao-*` (豆包模型,与 OpenAI 兼容)
583
+
584
+ #### Google Gemini
585
+ - `gemini-pro`
586
+ - `gemini-1.5-pro`
587
+ - `gemini-1.5-flash`
588
+ - `gemini-2.0-flash-exp-image-generation`
589
+
590
+ #### Anthropic Claude
591
+ - `claude-3-opus-20240229`
592
+ - `claude-3-sonnet-20240229`
593
+ - `claude-3-haiku-20240307`
594
+
595
+ ### 图像生成模型
596
+
597
+ - `doubao-seedream-4-5-251128` (默认)
598
+ - 其他 Seedream 模型版本
599
+
600
+ ### 视频生成模型
601
+
602
+ - `doubao-seedance-1-0-pro-fast-251015` (默认,推荐)
603
+ - `doubao-seedance-1-0-pro-250528`
604
+ - `doubao-seedance-1-0-lite-t2v-250428` (文本生成视频)
605
+ - `doubao-seedance-1-0-lite-i2v-250428` (图像生成视频)
606
+
607
+ ## 完整示例
608
+
609
+ ### 示例 1: 使用全局配置
610
+
611
+ ```typescript
612
+ import {
613
+ sdkConfig,
614
+ ChatGoogleGenerativeAI,
615
+ ImageGenerationClient,
616
+ VideoGenerationClient,
617
+ HumanMessage,
618
+ } from 'ai-world-sdk';
619
+
620
+ // 设置全局配置
621
+ sdkConfig.setBaseUrl('http://localhost:8000');
622
+ sdkConfig.setToken('your-jwt-token');
623
+
624
+ // 创建客户端(不需要提供 baseUrl 和 token)
625
+ const chatModel = new ChatGoogleGenerativeAI({
626
+ modelName: 'gemini-2.0-flash-exp-image-generation',
627
+ temperature: 0.7,
628
+ });
629
+
630
+ const imageClient = new ImageGenerationClient({});
631
+ const videoClient = new VideoGenerationClient({});
632
+
633
+ // 使用
634
+ const response = await chatModel.invoke([
635
+ new HumanMessage('Hello!'),
636
+ ]);
637
+
638
+ const imageResult = await imageClient.generate({
639
+ prompt: 'A beautiful sunset',
640
+ });
641
+ ```
642
+
643
+ ### 示例 2: 流式聊天
644
+
645
+ ```typescript
646
+ import { ChatGoogleGenerativeAI, HumanMessage, AIMessageChunk } from 'ai-world-sdk';
647
+
648
+ const model = new ChatGoogleGenerativeAI({
649
+ baseUrl: 'http://localhost:8000',
650
+ token: 'your-token',
651
+ modelName: 'gemini-2.0-flash-exp-image-generation',
652
+ });
653
+
654
+ let fullText = '';
655
+ for await (const chunk of model.stream([
656
+ new HumanMessage('Tell me a story about AI'),
657
+ ])) {
658
+ // chunk 是 AIMessageChunk 对象
659
+ if (typeof chunk.content === 'string') {
660
+ fullText += chunk.content;
661
+ process.stdout.write(chunk.content);
662
+ }
663
+ }
664
+
665
+ console.log('\n完整回复:', fullText);
666
+ ```
667
+
668
+ ### 示例 3: 图像生成工作流
669
+
670
+ ```typescript
671
+ import { ImageGenerationClient } from 'ai-world-sdk';
672
+
673
+ const imageClient = new ImageGenerationClient({
674
+ baseUrl: 'http://localhost:8000',
675
+ token: 'your-token',
676
+ });
677
+
678
+ // 生成单张图像
679
+ const result = await imageClient.generate({
680
+ prompt: 'A futuristic city skyline at sunset',
681
+ model: 'doubao-seedream-4-5-251128',
682
+ size: '2K',
683
+ quality: 'hd',
684
+ n: 1,
685
+ });
686
+
687
+ console.log('图像 URL:', result.data[0]?.url);
688
+
689
+ // 生成多张图像
690
+ const multiResult = await imageClient.generate({
691
+ prompt: 'A beautiful landscape',
692
+ n: 3,
693
+ size: '2K',
694
+ });
695
+
696
+ multiResult.data.forEach((image, index) => {
697
+ console.log(`图像 ${index + 1}:`, image.url);
698
+ });
699
+ ```
700
+
701
+ ### 示例 4: 视频生成工作流
702
+
703
+ ```typescript
704
+ import { VideoGenerationClient } from 'ai-world-sdk';
705
+
706
+ const videoClient = new VideoGenerationClient({
707
+ baseUrl: 'http://localhost:8000',
708
+ token: 'your-token',
709
+ });
710
+
711
+ // 1. 创建视频生成任务
712
+ const createTask = await videoClient.create({
713
+ prompt: 'A beautiful sunset over the ocean with waves',
714
+ model: 'doubao-seedance-1-0-pro-fast-251015',
715
+ duration: 5,
716
+ aspect_ratio: '16:9',
717
+ resolution: '720p',
718
+ });
719
+
720
+ console.log('任务已创建,ID:', createTask.id);
721
+
722
+ // 2. 查询任务状态
723
+ const task = await videoClient.get(createTask.id);
724
+ console.log('当前状态:', task.status);
725
+
726
+ // 3. 轮询直到完成
727
+ const result = await videoClient.poll(createTask.id, {
728
+ interval: 3000, // 每 3 秒查询一次
729
+ timeout: 300000, // 5 分钟超时
730
+ });
731
+
732
+ if (result.status === 'succeeded') {
733
+ console.log('视频生成成功!');
734
+ console.log('视频 URL:', result.content?.video_url);
735
+ if (result.content?.last_frame_url) {
736
+ console.log('最后一帧:', result.content.last_frame_url);
737
+ }
738
+ } else {
739
+ console.error('生成失败:', result.error?.message);
740
+ }
741
+ ```
742
+
743
+ ### 示例 5: 批量处理
744
+
745
+ ```typescript
746
+ import { ChatGoogleGenerativeAI, HumanMessage } from 'ai-world-sdk';
747
+
748
+ const model = new ChatGoogleGenerativeAI({
749
+ baseUrl: 'http://localhost:8000',
750
+ token: 'your-token',
751
+ modelName: 'gemini-2.0-flash-exp-image-generation',
752
+ });
753
+
754
+ // 批量处理多个问题
755
+ const questions = [
756
+ 'What is artificial intelligence?',
757
+ 'What is machine learning?',
758
+ 'What is deep learning?',
759
+ ];
760
+
761
+ const responses = await model.batch(
762
+ questions.map(q => [new HumanMessage(q)])
763
+ );
764
+
765
+ responses.forEach((response, index) => {
766
+ console.log(`问题 ${index + 1}:`, questions[index]);
767
+ console.log(`回答:`, response.content);
768
+ console.log('---');
769
+ });
770
+ ```
771
+
772
+ ### 示例 6: 工具调用
773
+
774
+ ```typescript
775
+ import {
776
+ ChatGoogleGenerativeAI,
777
+ HumanMessage,
778
+ ToolDefinition,
779
+ } from 'ai-world-sdk';
780
+
781
+ const model = new ChatGoogleGenerativeAI({
782
+ baseUrl: 'http://localhost:8000',
783
+ token: 'your-token',
784
+ modelName: 'gemini-2.0-flash-exp-image-generation',
785
+ });
786
+
787
+ const tools: ToolDefinition[] = [
788
+ {
789
+ type: 'function',
790
+ function: {
791
+ name: 'get_weather',
792
+ description: 'Get the current weather in a location',
793
+ parameters: {
794
+ type: 'object',
795
+ properties: {
796
+ location: {
797
+ type: 'string',
798
+ description: 'The city and state, e.g. San Francisco, CA',
799
+ },
800
+ unit: {
801
+ type: 'string',
802
+ enum: ['celsius', 'fahrenheit'],
803
+ description: 'The unit of temperature',
804
+ },
805
+ },
806
+ required: ['location'],
807
+ },
808
+ },
809
+ },
810
+ ];
811
+
812
+ const modelWithTools = model.bindTools(tools);
813
+
814
+ const response = await modelWithTools.invoke([
815
+ new HumanMessage('What is the weather in Paris?'),
816
+ ]);
817
+
818
+ console.log('响应:', response.content);
819
+ // 检查是否有工具调用
820
+ if (response.tool_calls && response.tool_calls.length > 0) {
821
+ console.log('工具调用:', response.tool_calls);
822
+ }
823
+ ```
824
+
825
+ ## 类型定义
826
+
827
+ ### 核心类型
828
+
829
+ ```typescript
830
+ // 消息类型
831
+ export class HumanMessage extends BaseMessage { ... }
832
+ export class SystemMessage extends BaseMessage { ... }
833
+ export class AIMessage extends BaseMessage { ... }
834
+ export class AIMessageChunk extends BaseMessage { ... }
835
+
836
+ // 配置类型
837
+ export interface BaseChatModelParams {
838
+ temperature?: number;
839
+ maxTokens?: number;
840
+ topP?: number;
841
+ modelName?: string;
842
+ provider?: string;
843
+ apiKey?: string;
844
+ }
845
+
846
+ export interface LangchainClientConfig {
847
+ baseUrl?: string;
848
+ token?: string;
849
+ headers?: Record<string, string>;
850
+ }
851
+
852
+ // 工具类型
853
+ export interface ToolDefinition {
854
+ type: 'function';
855
+ function: {
856
+ name: string;
857
+ description: string;
858
+ parameters?: Record<string, any>;
859
+ };
860
+ }
861
+
862
+ export interface BindOptions {
863
+ temperature?: number;
864
+ maxTokens?: number;
865
+ topP?: number;
866
+ tools?: ToolDefinition[];
867
+ toolChoice?: 'auto' | 'none' | 'required' | { type: 'function'; function: { name: string } };
868
+ }
869
+ ```
870
+
871
+ ## 错误处理
872
+
873
+ 所有 API 调用都可能抛出错误。建议使用 try-catch 进行错误处理:
874
+
875
+ ```typescript
876
+ import { ChatGoogleGenerativeAI, HumanMessage } from 'ai-world-sdk';
877
+
878
+ const model = new ChatGoogleGenerativeAI({
879
+ baseUrl: 'http://localhost:8000',
880
+ token: 'your-token',
881
+ modelName: 'gemini-2.0-flash-exp-image-generation',
882
+ });
883
+
884
+ try {
885
+ const response = await model.invoke([
886
+ new HumanMessage('Hello!'),
887
+ ]);
888
+ console.log(response.content);
889
+ } catch (error) {
890
+ console.error('API 调用失败:', error);
891
+ if (error instanceof Error) {
892
+ console.error('错误消息:', error.message);
893
+ }
894
+ }
895
+ ```
896
+
897
+ ## 参考地址
898
+
899
+ ### 官方文档
900
+
901
+ - **AI World 平台**: [项目仓库](https://github.com/your-org/ai-world)
902
+ - **LangChain.js**: [https://github.com/langchain-ai/langchainjs](https://github.com/langchain-ai/langchainjs)
903
+ - **火山引擎方舟平台**: [https://www.volcengine.com/docs/82379](https://www.volcengine.com/docs/82379)
904
+
905
+ ### API 文档
906
+
907
+ - **图像生成 API**: [https://www.volcengine.com/docs/82379/1824121](https://www.volcengine.com/docs/82379/1824121)
908
+ - **视频生成 API**: [https://www.volcengine.com/docs/82379/1366799](https://www.volcengine.com/docs/82379/1366799)
909
+ - **对话 API**: [https://www.volcengine.com/docs/82379/1541595](https://www.volcengine.com/docs/82379/1541595)
910
+
911
+ ### 模型文档
912
+
913
+ - **Seedream 4.0-4.5 教程**: [https://www.volcengine.com/docs/82379/1824121?lang=zh](https://www.volcengine.com/docs/82379/1824121?lang=zh)
914
+ - **Seedance 提示词指南**: [https://www.volcengine.com/docs/82379/1901652](https://www.volcengine.com/docs/82379/1901652)
915
+
916
+ ## 开发
917
+
918
+ ### 构建
919
+
920
+ ```bash
921
+ npm run build
922
+ ```
923
+
924
+ ### 测试
925
+
926
+ ```bash
927
+ # 运行所有测试
928
+ npm test
929
+
930
+ # 运行特定测试
931
+ npm run test:stream
932
+ npm run test:image-generation
933
+ npm run test:video-generation
934
+ ```
935
+
936
+ ### 项目结构
937
+
938
+ ```
939
+ ai-world-sdk/
940
+ ├── src/
941
+ │ ├── base.ts # 基础聊天模型类
942
+ │ ├── config.ts # 全局配置管理
943
+ │ ├── messages.ts # 消息类型定义
944
+ │ ├── image_generation.ts # 图像生成客户端
945
+ │ ├── video_generation.ts # 视频生成客户端
946
+ │ ├── chat_models/ # 具体模型实现
947
+ │ │ ├── openai.ts
948
+ │ │ ├── google.ts
949
+ │ │ └── anthropic.ts
950
+ │ └── index.ts # 主入口文件
951
+ ├── __tests__/ # 测试文件
952
+ ├── package.json
953
+ ├── tsconfig.json
954
+ └── README.md
955
+ ```
956
+
957
+ ## 发布
958
+
959
+ ### 安装
960
+
961
+ ```bash
962
+ npm install ai-world-sdk
963
+ ```
964
+
965
+ ### 发布到 npm
966
+
967
+ 详细的发布指南请参考 [PUBLISH.md](./PUBLISH.md)。
968
+
969
+ **快速发布步骤:**
970
+
971
+ ```bash
972
+ # 1. 构建项目
973
+ npm run build
974
+
975
+ # 2. 运行测试
976
+ npm test
977
+
978
+ # 3. 更新版本号(如果需要)
979
+ npm version patch # 或 minor, major
980
+
981
+ # 4. 登录 npm
982
+ npm login
983
+
984
+ # 5. 发布(scope 包需要 --access public)
985
+ npm publish --access public
986
+ ```
987
+
988
+ ## 许可证
989
+
990
+ MIT
991
+
992
+ ## 贡献
993
+
994
+ 欢迎提交 Issue 和 Pull Request!
995
+
996
+ ## 更新日志
997
+
998
+ ### 1.0.0
999
+
1000
+ - ✨ 初始版本发布
1001
+ - ✨ 支持聊天模型(OpenAI、Gemini、Claude、Doubao)
1002
+ - ✨ 支持图像生成(Seedream)
1003
+ - ✨ 支持视频生成(Seedance)
1004
+ - ✨ 支持全局配置(baseUrl、token)
1005
+ - ✨ 兼容 LangChain.js 接口风格
1006
+ - ✨ 完整的 TypeScript 类型定义