@opentiny/tiny-robot-kit 0.4.0-alpha.1 → 0.4.0-alpha.11

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/index.d.mts CHANGED
@@ -1,27 +1,57 @@
1
1
  import { Ref, ComputedRef } from 'vue';
2
2
 
3
- type MaybePromise<T> = T | Promise<T>;
4
-
5
3
  /**
6
- * 工具函数模块
7
- * 提供一些实用的辅助函数
4
+ * 模型Provider基类
8
5
  */
6
+ declare abstract class BaseModelProvider {
7
+ protected config: AIModelConfig;
8
+ /**
9
+ * @param config AI模型配置
10
+ */
11
+ constructor(config: AIModelConfig);
12
+ /**
13
+ * 发送聊天请求并获取响应
14
+ * @param request 聊天请求参数
15
+ * @returns 聊天响应
16
+ */
17
+ abstract chat(request: ChatCompletionRequest): Promise<ChatCompletionResponse>;
18
+ /**
19
+ * 发送流式聊天请求并通过处理器处理响应
20
+ * @param request 聊天请求参数
21
+ * @param handler 流式响应处理器
22
+ */
23
+ abstract chatStream(request: ChatCompletionRequest, handler: StreamHandler): Promise<void>;
24
+ /**
25
+ * 更新配置
26
+ * @param config 新的AI模型配置
27
+ */
28
+ updateConfig(config: AIModelConfig): void;
29
+ /**
30
+ * 获取当前配置
31
+ * @returns AI模型配置
32
+ */
33
+ getConfig(): AIModelConfig;
34
+ /**
35
+ * 验证请求参数
36
+ * @param request 聊天请求参数
37
+ */
38
+ protected validateRequest(request: ChatCompletionRequest): void;
39
+ }
9
40
 
10
- declare function createSSEStreamGenerator<T = any>(response: Response, options?: {
11
- signal?: AbortSignal;
12
- }): AsyncGenerator<T, void, unknown>;
13
-
14
- interface Tool {
41
+ type MaybePromise<T> = T | Promise<T>;
42
+ /**
43
+ * 消息角色类型
44
+ */
45
+ type MessageRole = 'system' | 'user' | 'assistant';
46
+ interface ToolCall {
47
+ index: number;
48
+ id: string;
15
49
  type: 'function';
16
50
  function: {
17
51
  name: string;
18
- description: string;
19
- /**
20
- * function 的输入参数,以 JSON Schema 对象描述
21
- */
22
- parameters: any;
52
+ arguments: string;
53
+ result?: string;
23
54
  };
24
- [key: string]: any;
25
55
  }
26
56
  interface MessageMetadata {
27
57
  createdAt?: number;
@@ -30,31 +60,254 @@ interface MessageMetadata {
30
60
  model?: string;
31
61
  [key: string]: any;
32
62
  }
63
+ /**
64
+ * 聊天消息接口
65
+ */
33
66
  interface ChatMessage {
34
67
  role: string;
35
68
  content: string;
69
+ reasoning_content?: string;
36
70
  metadata?: MessageMetadata;
37
71
  tool_calls?: ToolCall[];
38
72
  tool_call_id?: string;
39
73
  [key: string]: any;
40
74
  [key: symbol]: any;
41
75
  }
42
- interface MessageRequestBody {
43
- messages: Partial<ChatMessage>[];
44
- [key: string]: any;
76
+ /**
77
+ * 聊天历史记录
78
+ */
79
+ type ChatHistory = ChatMessage[];
80
+ /**
81
+ * 聊天完成请求选项
82
+ */
83
+ interface ChatCompletionOptions {
84
+ model?: string;
85
+ temperature?: number;
86
+ top_p?: number;
87
+ n?: number;
88
+ stream?: boolean;
89
+ max_tokens?: number;
90
+ signal?: AbortSignal;
45
91
  }
46
- type RequestState = 'idle' | 'processing' | 'completed' | 'aborted' | 'error';
47
- type RequestProcessingState = 'requesting' | 'completing' | string;
48
- interface ToolCall {
92
+ /**
93
+ * 聊天完成请求参数
94
+ */
95
+ interface ChatCompletionRequest {
96
+ messages: ChatMessage[];
97
+ options?: ChatCompletionOptions;
98
+ }
99
+ /**
100
+ * 聊天完成响应消息
101
+ */
102
+ interface ChatCompletionResponseMessage {
103
+ role: MessageRole;
104
+ content: string;
105
+ [x: string]: unknown;
106
+ }
107
+ /**
108
+ * 聊天完成响应选择
109
+ */
110
+ interface ChatCompletionResponseChoice {
111
+ index: number;
112
+ message: ChatCompletionResponseMessage;
113
+ finish_reason: string;
114
+ }
115
+ /**
116
+ * 聊天完成响应使用情况
117
+ */
118
+ interface ChatCompletionResponseUsage {
119
+ prompt_tokens: number;
120
+ completion_tokens: number;
121
+ total_tokens: number;
122
+ }
123
+ /**
124
+ * 聊天完成响应
125
+ */
126
+ interface ChatCompletionResponse {
127
+ id: string;
128
+ object: string;
129
+ created: number;
130
+ model: string;
131
+ choices: ChatCompletionResponseChoice[];
132
+ usage: ChatCompletionResponseUsage;
133
+ }
134
+ /**
135
+ * 流式聊天完成响应增量
136
+ */
137
+ interface ChatCompletionStreamResponseDelta {
138
+ content?: string;
139
+ role?: MessageRole;
140
+ [x: string]: unknown;
141
+ }
142
+ /**
143
+ * 流式聊天完成响应选择
144
+ */
145
+ interface ChatCompletionStreamResponseChoice {
49
146
  index: number;
147
+ delta: ChatCompletionStreamResponseDelta;
148
+ finish_reason: string | null;
149
+ }
150
+ /**
151
+ * 流式聊天完成响应
152
+ */
153
+ interface ChatCompletionStreamResponse {
50
154
  id: string;
155
+ object: string;
156
+ created: number;
157
+ model: string;
158
+ choices: ChatCompletionStreamResponseChoice[];
159
+ }
160
+ /**
161
+ * AI模型提供商类型
162
+ */
163
+ type AIProvider = 'openai' | 'deepseek' | 'custom';
164
+ /**
165
+ * AI模型配置接口
166
+ */
167
+ interface AIModelConfig {
168
+ provider: AIProvider;
169
+ providerImplementation?: BaseModelProvider;
170
+ apiKey?: string;
171
+ apiUrl?: string;
172
+ apiVersion?: string;
173
+ defaultModel?: string;
174
+ defaultOptions?: ChatCompletionOptions;
175
+ }
176
+ /**
177
+ * 错误类型
178
+ */
179
+ declare enum ErrorType {
180
+ NETWORK_ERROR = "network_error",
181
+ AUTHENTICATION_ERROR = "authentication_error",
182
+ RATE_LIMIT_ERROR = "rate_limit_error",
183
+ SERVER_ERROR = "server_error",
184
+ MODEL_ERROR = "model_error",
185
+ TIMEOUT_ERROR = "timeout_error",
186
+ UNKNOWN_ERROR = "unknown_error"
187
+ }
188
+ /**
189
+ * AI适配器错误
190
+ */
191
+ interface AIAdapterError {
192
+ type: ErrorType;
193
+ message: string;
194
+ statusCode?: number;
195
+ originalError?: object;
196
+ }
197
+ /**
198
+ * 流式响应事件类型
199
+ */
200
+ declare enum StreamEventType {
201
+ DATA = "data",
202
+ ERROR = "error",
203
+ DONE = "done"
204
+ }
205
+ /**
206
+ * 流式响应处理器
207
+ */
208
+ interface StreamHandler {
209
+ onData: (data: ChatCompletionStreamResponse) => void;
210
+ onError: (error: AIAdapterError) => void;
211
+ onDone: (finishReason?: string) => void;
212
+ }
213
+
214
+ /**
215
+ * AI客户端类
216
+ * 负责根据配置选择合适的提供商并处理请求
217
+ */
218
+
219
+ /**
220
+ * @deprecated
221
+ * AI客户端类
222
+ */
223
+ declare class AIClient {
224
+ private provider;
225
+ private config;
226
+ /**
227
+ * 构造函数
228
+ * @param config AI模型配置
229
+ */
230
+ constructor(config: AIModelConfig);
231
+ /**
232
+ * 创建提供商实例
233
+ * @param config AI模型配置
234
+ * @returns 提供商实例
235
+ */
236
+ private createProvider;
237
+ /**
238
+ * 发送聊天请求并获取响应
239
+ * @param request 聊天请求参数
240
+ * @returns 聊天响应
241
+ */
242
+ chat(request: ChatCompletionRequest): Promise<ChatCompletionResponse>;
243
+ /**
244
+ * 发送流式聊天请求并通过处理器处理响应
245
+ * @param request 聊天请求参数
246
+ * @param handler 流式响应处理器
247
+ */
248
+ chatStream(request: ChatCompletionRequest, handler: StreamHandler): Promise<void>;
249
+ /**
250
+ * 获取当前配置
251
+ * @returns AI模型配置
252
+ */
253
+ getConfig(): AIModelConfig;
254
+ /**
255
+ * 更新配置
256
+ * @param config 新的AI模型配置
257
+ */
258
+ updateConfig(config: Partial<AIModelConfig>): void;
259
+ }
260
+
261
+ /**
262
+ * OpenAI提供商
263
+ * 用于与OpenAI API进行交互
264
+ */
265
+
266
+ declare class OpenAIProvider extends BaseModelProvider {
267
+ private baseURL;
268
+ private apiKey;
269
+ private defaultModel;
270
+ /**
271
+ * @param config AI模型配置
272
+ */
273
+ constructor(config: AIModelConfig);
274
+ /**
275
+ * 发送聊天请求并获取响应
276
+ * @param request 聊天请求参数
277
+ * @returns 聊天响应
278
+ */
279
+ chat(request: ChatCompletionRequest): Promise<ChatCompletionResponse>;
280
+ /**
281
+ * 发送流式聊天请求并通过处理器处理响应
282
+ * @param request 聊天请求参数
283
+ * @param handler 流式响应处理器
284
+ */
285
+ chatStream(request: ChatCompletionRequest, handler: StreamHandler): Promise<void>;
286
+ /**
287
+ * 更新配置
288
+ * @param config 新的AI模型配置
289
+ */
290
+ updateConfig(config: AIModelConfig): void;
291
+ }
292
+
293
+ interface Tool {
51
294
  type: 'function';
52
295
  function: {
53
296
  name: string;
54
- arguments: string;
55
- result?: string;
297
+ description: string;
298
+ /**
299
+ * function 的输入参数,以 JSON Schema 对象描述
300
+ */
301
+ parameters: any;
56
302
  };
303
+ [key: string]: any;
304
+ }
305
+ interface MessageRequestBody {
306
+ messages: Partial<ChatMessage>[];
307
+ [key: string]: any;
57
308
  }
309
+ type RequestState = 'idle' | 'processing' | 'completed' | 'aborted' | 'error';
310
+ type RequestProcessingState = 'requesting' | 'completing' | string;
58
311
  interface Usage {
59
312
  prompt_tokens: number;
60
313
  completion_tokens: number;
@@ -101,7 +354,16 @@ interface ChatCompletion {
101
354
  }
102
355
  interface UseMessageOptions {
103
356
  initialMessages?: ChatMessage[];
104
- requestMessageFields?: (keyof ChatMessage)[];
357
+ /**
358
+ * 请求消息时,要包含的字段(白名单)。默认包含所有字段。
359
+ * 如果 `requestMessageFieldsExclude` 存在,会先取 `requestMessageFields` 中的字段,再排除 `requestMessageFieldsExclude` 中的字段
360
+ */
361
+ requestMessageFields?: string[];
362
+ /**
363
+ * 请求消息时,要排除的字段(黑名单)。默认会排除 `state`、`metadata`、`loading` 字段(这几个字段是给UI展示用的)。
364
+ * 如果 `requestMessageFields` 存在,会先取 `requestMessageFields` 中的字段,再排除 `requestMessageFieldsExclude` 中的字段
365
+ */
366
+ requestMessageFieldsExclude?: string[];
105
367
  plugins?: UseMessagePlugin[];
106
368
  responseProvider: <T = ChatCompletion>(requestBody: MessageRequestBody, abortSignal: AbortSignal) => Promise<T> | AsyncGenerator<T> | Promise<AsyncGenerator<T>>;
107
369
  /**
@@ -111,6 +373,7 @@ interface UseMessageOptions {
111
373
  */
112
374
  onCompletionChunk?: (context: BasePluginContext & {
113
375
  currentMessage: ChatMessage;
376
+ choice: CompletionChoice;
114
377
  chunk: ChatCompletion;
115
378
  }, runDefault: () => void) => void;
116
379
  }
@@ -129,7 +392,6 @@ interface BasePluginContext {
129
392
  currentTurn: ChatMessage[];
130
393
  requestState: RequestState;
131
394
  processingState?: RequestProcessingState;
132
- requestMessageFields: (keyof ChatMessage)[];
133
395
  plugins: UseMessagePlugin[];
134
396
  setRequestState: (state: RequestState, processingState?: RequestProcessingState) => void;
135
397
  abortSignal: AbortSignal;
@@ -150,7 +412,7 @@ interface UseMessagePlugin {
150
412
  /**
151
413
  * 是否禁用插件。useMessage 可能会内置一些默认插件,如果需要禁用,可以设置为 true。
152
414
  */
153
- disabled?: boolean;
415
+ disabled?: boolean | ((context: BasePluginContext) => boolean);
154
416
  /**
155
417
  * 一次对话回合(turn)开始钩子:用户消息入队后、正式发起请求之前触发。
156
418
  * 按插件注册顺序串行执行,便于做有序初始化/校验;出错则中断流程。
@@ -195,6 +457,7 @@ interface UseMessagePlugin {
195
457
  onError?: (context: BasePluginContext & {
196
458
  error: unknown;
197
459
  }) => void;
460
+ onFinally?: (context: BasePluginContext) => void;
198
461
  }
199
462
 
200
463
  interface ConversationInfo {
@@ -215,28 +478,6 @@ interface Conversation extends ConversationInfo {
215
478
  */
216
479
  engine: UseMessageReturn;
217
480
  }
218
- interface ConversationStorageStrategy {
219
- /**
220
- * Load all conversations (id and title only).
221
- */
222
- loadConversations?: () => MaybePromise<ConversationInfo[]>;
223
- /**
224
- * Load all messages for a given conversation.
225
- */
226
- loadMessages?: (conversationId: string) => MaybePromise<ChatMessage[]>;
227
- /**
228
- * Persist conversation metadata (create or update).
229
- */
230
- saveConversation?: (conversation: ConversationInfo) => MaybePromise<void>;
231
- /**
232
- * Persist messages for a given conversation.
233
- */
234
- saveMessages?: (conversationId: string, messages: ChatMessage[]) => MaybePromise<void>;
235
- /**
236
- * Optional method to delete a conversation and its messages.
237
- */
238
- deleteConversation?: (conversationId: string) => MaybePromise<void>;
239
- }
240
481
  interface UseConversationOptions {
241
482
  /**
242
483
  * Base useMessage options for all conversations.
@@ -260,6 +501,11 @@ interface UseConversationOptions {
260
501
  * When provided, conversation list and messages can be loaded and persisted.
261
502
  */
262
503
  storage?: ConversationStorageStrategy;
504
+ /**
505
+ * Called when the initial conversation list has been loaded from storage.
506
+ * Only fired when storage.loadConversations is available and has completed.
507
+ */
508
+ onLoad?: (conversations: ConversationInfo[]) => void;
263
509
  }
264
510
  interface UseConversationReturn {
265
511
  conversations: Ref<ConversationInfo[]>;
@@ -277,12 +523,144 @@ interface UseConversationReturn {
277
523
  }) => Conversation;
278
524
  switchConversation: (id: string) => Promise<Conversation | null>;
279
525
  deleteConversation: (id: string) => Promise<void>;
526
+ clear: () => void;
280
527
  updateConversationTitle: (id: string, title?: string) => void;
281
528
  saveMessages: (id?: string) => void;
282
529
  sendMessage: (content: string) => void;
283
530
  abortActiveRequest: () => Promise<void>;
284
531
  }
285
532
 
533
+ /**
534
+ * 存储策略接口
535
+ */
536
+ interface ConversationStorageStrategy {
537
+ /**
538
+ * Load all conversations (id and title only).
539
+ */
540
+ loadConversations: () => MaybePromise<ConversationInfo[]>;
541
+ /**
542
+ * Load all messages for a given conversation.
543
+ */
544
+ loadMessages: (conversationId: string) => MaybePromise<ChatMessage[]>;
545
+ /**
546
+ * Persist conversation metadata (create or update).
547
+ */
548
+ saveConversation: (conversation: ConversationInfo) => MaybePromise<void>;
549
+ /**
550
+ * Persist messages for a given conversation.
551
+ */
552
+ saveMessages: (conversationId: string, messages: ChatMessage[]) => MaybePromise<void>;
553
+ /**
554
+ * Optional method to delete a conversation and its messages.
555
+ */
556
+ deleteConversation?: (conversationId: string) => MaybePromise<void>;
557
+ }
558
+
559
+ /**
560
+ * 本地存储策略
561
+ */
562
+ declare class LocalStorageStrategy implements ConversationStorageStrategy {
563
+ private storageKey;
564
+ constructor(storageKey?: string);
565
+ saveConversation(conversation: ConversationInfo): void;
566
+ loadConversations(): ConversationInfo[];
567
+ saveMessages(conversationId: string, messages: ChatMessage[]): void;
568
+ loadMessages(conversationId: string): ChatMessage[];
569
+ deleteConversation(conversationId: string): void;
570
+ }
571
+
572
+ /**
573
+ * IndexedDB 存储策略
574
+ */
575
+ declare class IndexedDBStrategy implements ConversationStorageStrategy {
576
+ private dbName;
577
+ private dbVersion;
578
+ private db;
579
+ constructor(dbName?: string, dbVersion?: number);
580
+ /**
581
+ * 获取或初始化数据库连接
582
+ */
583
+ private getDB;
584
+ /**
585
+ * 加载所有会话(只包含元数据)
586
+ */
587
+ loadConversations(): Promise<ConversationInfo[]>;
588
+ /**
589
+ * 加载指定会话的所有消息
590
+ */
591
+ loadMessages(conversationId: string): Promise<ChatMessage[]>;
592
+ /**
593
+ * 保存或更新会话元数据
594
+ */
595
+ saveConversation(conversation: ConversationInfo): Promise<void>;
596
+ /**
597
+ * 保存指定会话的消息
598
+ */
599
+ saveMessages(conversationId: string, messages: ChatMessage[]): Promise<void>;
600
+ /**
601
+ * 删除会话及其所有消息
602
+ */
603
+ deleteConversation(conversationId: string): Promise<void>;
604
+ }
605
+
606
+ interface LocalStorageConfig {
607
+ /** 存储键名 (default: 'tiny-robot-ai-conversations') */
608
+ key?: string;
609
+ }
610
+ interface IndexedDBConfig {
611
+ /** 数据库名称 (default: 'tiny-robot-ai-db') */
612
+ dbName?: string;
613
+ /** 数据库版本 (default: 1) */
614
+ dbVersion?: number;
615
+ }
616
+ /**
617
+ * LocalStorage 策略工厂函数
618
+ */
619
+ declare function localStorageStrategyFactory(config?: LocalStorageConfig): ConversationStorageStrategy;
620
+ /**
621
+ * IndexedDB 策略工厂函数
622
+ */
623
+ declare function indexedDBStorageStrategyFactory(config?: IndexedDBConfig): ConversationStorageStrategy;
624
+
625
+ /**
626
+ * 工具函数模块
627
+ * 提供一些实用的辅助函数
628
+ */
629
+
630
+ /**
631
+ * 处理SSE流式响应
632
+ * @param response fetch响应对象
633
+ * @param handler 流处理器
634
+ */
635
+ declare function handleSSEStream(response: Response, handler: StreamHandler, signal?: AbortSignal): Promise<void>;
636
+ /**
637
+ * 格式化消息
638
+ * 将各种格式的消息转换为标准的ChatMessage格式
639
+ * @param messages 消息数组
640
+ * @returns 标准格式的消息数组
641
+ */
642
+ declare function formatMessages(messages: Array<ChatMessage | string>): ChatMessage[];
643
+ /**
644
+ * 从响应中提取文本内容
645
+ * @param response 聊天完成响应
646
+ * @returns 文本内容
647
+ */
648
+ declare function extractTextFromResponse(response: ChatCompletionResponse): string;
649
+ /**
650
+ * 将 SSE 流转换为异步生成器。
651
+ * 将服务器发送事件(SSE)流式响应转换为异步生成器,逐个产出解析后的数据
652
+ *
653
+ * 当取消信号被触发时,会抛出 name 为 'AbortError' 的错误
654
+ * @param response fetch 响应对象
655
+ * @param options 配置选项
656
+ * @param options.signal 可选的取消信号,用于中断流处理
657
+ * @returns 异步生成器,产出类型为 T 的数据
658
+ * @template T 生成器产出的数据类型,默认为 any
659
+ */
660
+ declare function sseStreamToGenerator<T = any>(response: Response, options?: {
661
+ signal?: AbortSignal;
662
+ }): AsyncGenerator<T, void, unknown>;
663
+
286
664
  declare const useConversation: (options: UseConversationOptions) => UseConversationReturn;
287
665
 
288
666
  declare const fallbackRolePlugin: (options?: UseMessagePlugin & {
@@ -366,4 +744,4 @@ declare const toolPlugin: (options: UseMessagePlugin & {
366
744
 
367
745
  declare const useMessage: (options: UseMessageOptions) => UseMessageReturn;
368
746
 
369
- export { type BasePluginContext, type ChatCompletion, type ChatMessage, type Choice, type CompletionChoice, type Conversation, type ConversationInfo, type ConversationStorageStrategy, type DeltaChoice, EXCLUDE_MODE_REMOVE, type MessageMetadata, type MessageRequestBody, type RequestProcessingState, type RequestState, type Tool, type ToolCall, type Usage, type UseConversationOptions, type UseConversationReturn, type UseMessageOptions, type UseMessagePlugin, type UseMessageReturn, createSSEStreamGenerator, fallbackRolePlugin, lengthPlugin, thinkingPlugin, toolPlugin, useConversation, useMessage };
747
+ export { type AIAdapterError, AIClient, type AIModelConfig, type AIProvider, BaseModelProvider, type BasePluginContext, type ChatCompletion, type ChatCompletionOptions, type ChatCompletionRequest, type ChatCompletionResponse, type ChatCompletionResponseChoice, type ChatCompletionResponseMessage, type ChatCompletionResponseUsage, type ChatCompletionStreamResponse, type ChatCompletionStreamResponseChoice, type ChatCompletionStreamResponseDelta, type ChatHistory, type ChatMessage, type Choice, type CompletionChoice, type Conversation, type ConversationInfo, type ConversationStorageStrategy, type DeltaChoice, EXCLUDE_MODE_REMOVE, ErrorType, type IndexedDBConfig, IndexedDBStrategy, type LocalStorageConfig, LocalStorageStrategy, type MaybePromise, type MessageMetadata, type MessageRequestBody, type MessageRole, OpenAIProvider, type RequestProcessingState, type RequestState, StreamEventType, type StreamHandler, type Tool, type ToolCall, type Usage, type UseConversationOptions, type UseConversationReturn, type UseMessageOptions, type UseMessagePlugin, type UseMessageReturn, extractTextFromResponse, fallbackRolePlugin, formatMessages, handleSSEStream, indexedDBStorageStrategyFactory, lengthPlugin, localStorageStrategyFactory, sseStreamToGenerator, thinkingPlugin, toolPlugin, useConversation, useMessage };