@qelos/sdk 3.11.3 → 3.11.4

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/src/ai.ts CHANGED
@@ -1,103 +1,113 @@
1
1
  import { QelosSDKOptions } from './types';
2
2
  import BaseSDK from './base-sdk';
3
-
4
- export interface IMessage {
5
- role: string;
6
- content: string;
7
- timestamp?: Date | string;
8
- tool_calls?: any[];
9
- name?: string;
10
- tool_call_id?: string;
11
- function_call?: any;
12
- message_id?: string;
13
- }
14
-
15
- export interface IMessageSummary {
16
- fromIndex: number;
17
- toIndex: number;
18
- summary: string;
19
- }
20
-
21
- export interface IThread {
22
- _id?: string;
23
- integration: string;
24
- title?: string;
25
- messages: IMessage[];
26
- messageSummaries: IMessageSummary[];
27
- created?: Date;
28
- updated?: Date;
29
- user?: string;
30
- workspace?: string;
31
- }
32
-
33
- export interface IChatCompletionOptions {
34
- messages: IMessage[];
35
- model?: string;
36
- temperature?: number;
37
- top_p?: number;
38
- frequency_penalty?: number;
39
- presence_penalty?: number;
40
- stop?: string | string[];
41
- max_tokens?: number;
42
- response_format?: any;
43
- context?: Record<string, any>;
44
- stream?: boolean;
45
- }
46
-
47
- export interface ISSEStreamProcessor extends AsyncIterable<any> {
48
- processManually(onData: (data: any) => void | boolean): Promise<void>;
49
- }
50
-
51
- export interface IChatCompletionResponse {
52
- id: string;
53
- object: string;
54
- created: number;
55
- model: string;
56
- choices: Array<{
57
- index: number;
58
- message: IMessage;
59
- finish_reason: string;
60
- }>;
61
- usage?: {
62
- prompt_tokens: number;
63
- completion_tokens: number;
64
- total_tokens: number;
65
- };
66
- }
67
-
68
- export interface ICreateThreadRequest {
69
- integration: string;
70
- title?: string;
71
- }
72
-
3
+ import ThreadsSDK from './ai/threads';
4
+ import ChatSDK from './ai/chat';
5
+ import RAGSDK from './ai/rag';
6
+ import {
7
+ IMessage,
8
+ IMessageSummary,
9
+ IThread,
10
+ IChatCompletionOptions,
11
+ ISSEStreamProcessor,
12
+ IChatCompletionResponse,
13
+ ICreateThreadRequest,
14
+ ICreateVectorStorageRequest,
15
+ IUploadContentRequest,
16
+ IClearStorageRequest,
17
+ IVectorStore
18
+ } from './ai/types';
19
+
20
+ // Re-export types for backward compatibility
21
+ export {
22
+ IMessage,
23
+ IMessageSummary,
24
+ IThread,
25
+ IChatCompletionOptions,
26
+ ISSEStreamProcessor,
27
+ IChatCompletionResponse,
28
+ ICreateThreadRequest,
29
+ ICreateVectorStorageRequest,
30
+ IUploadContentRequest,
31
+ IClearStorageRequest,
32
+ IVectorStore
33
+ };
34
+
35
+ /**
36
+ * Qelos AI SDK - Main SDK class with three sub-SDKs
37
+ *
38
+ * This class provides access to AI functionality through three sub-SDKs:
39
+ * - `threads`: Thread CRUD operations for managing conversation threads
40
+ * - `chat`: Chat completion operations (streaming and non-streaming)
41
+ * - `rag`: Vector storage management for Retrieval-Augmented Generation
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * const sdk = new QelosSDK({
46
+ * appUrl: 'https://your-qelos-instance.com',
47
+ * fetch: globalThis.fetch,
48
+ * accessToken: 'your-token'
49
+ * });
50
+ *
51
+ * // Create a thread
52
+ * const thread = await sdk.ai.threads.create({ integration: 'id' });
53
+ *
54
+ * // Stream chat
55
+ * const stream = await sdk.ai.chat.stream('id', { messages: [...] });
56
+ * for await (const chunk of sdk.ai.chat.parseSSEStream(stream)) {
57
+ * console.log(chunk);
58
+ * }
59
+ *
60
+ * // Upload RAG content
61
+ * await sdk.ai.rag.uploadContent('sourceId', { content: '...' });
62
+ * ```
63
+ */
64
+ // Main AI SDK with sub-SDKs
73
65
  export default class QlAI extends BaseSDK {
74
- private relativePath = '/api/ai';
66
+ /**
67
+ * Threads sub-SDK for managing conversation threads
68
+ */
69
+ public threads: ThreadsSDK;
70
+
71
+ /**
72
+ * Chat sub-SDK for chat completion operations
73
+ */
74
+ public chat: ChatSDK;
75
+
76
+ /**
77
+ * RAG sub-SDK for vector storage management
78
+ */
79
+ public rag: RAGSDK;
80
+
81
+ /**
82
+ * Initialize the AI SDK with sub-SDKs
83
+ *
84
+ * @param options - SDK configuration options
85
+ */
75
86
  constructor(options: QelosSDKOptions) {
76
87
  super(options);
88
+ this.threads = new ThreadsSDK(options);
89
+ this.chat = new ChatSDK(options);
90
+ this.rag = new RAGSDK(options);
77
91
  }
78
92
 
79
- // Thread CRUD Operations
80
-
93
+ // Legacy methods for backward compatibility
94
+
81
95
  /**
82
- * Create a new thread
96
+ * @deprecated Use sdk.threads.create() instead
83
97
  */
84
98
  createThread(data: ICreateThreadRequest): Promise<IThread> {
85
- return this.callJsonApi<IThread>(this.relativePath + '/threads', {
86
- method: 'POST',
87
- headers: { 'content-type': 'application/json' },
88
- body: JSON.stringify(data)
89
- });
99
+ return this.threads.create(data);
90
100
  }
91
101
 
92
102
  /**
93
- * Get a specific thread by ID
103
+ * @deprecated Use sdk.threads.getOne() instead
94
104
  */
95
105
  getThread(threadId: string): Promise<IThread> {
96
- return this.callJsonApi<IThread>(`${this.relativePath}/threads/${threadId}${this.getQueryParams({})}`);
106
+ return this.threads.getOne(threadId);
97
107
  }
98
108
 
99
109
  /**
100
- * List threads with optional filters
110
+ * @deprecated Use sdk.threads.list() instead
101
111
  */
102
112
  listThreads(options?: {
103
113
  integration?: string;
@@ -108,188 +118,62 @@ export default class QlAI extends BaseSDK {
108
118
  workspace?: string;
109
119
  [key: string]: string | number;
110
120
  }): Promise<IThread[]> {
111
- const queryParams = this.getQueryParams(options);
112
- return this.callJsonApi<IThread[]>(
113
- `${this.relativePath}/threads${queryParams}`
114
- );
121
+ return this.threads.list(options);
115
122
  }
116
123
 
117
124
  /**
118
- * Delete a thread
125
+ * @deprecated Use sdk.threads.delete() instead
119
126
  */
120
127
  deleteThread(threadId: string): Promise<{ success: boolean }> {
121
- return this.callJsonApi<{ success: boolean }>(`${this.relativePath}/threads/${threadId}${this.getQueryParams({})}`, {
122
- method: 'DELETE'
123
- });
128
+ return this.threads.delete(threadId);
124
129
  }
125
130
 
126
- // Chat Completion Operations
127
-
128
131
  /**
129
- * Create a chat completion without a thread
132
+ * @deprecated Use sdk.chat.chat() instead
130
133
  */
131
- chat(
134
+ chatCompletion(
132
135
  integrationId: string,
133
136
  options: IChatCompletionOptions
134
137
  ): Promise<IChatCompletionResponse> {
135
- return this.callJsonApi<IChatCompletionResponse>(`${this.relativePath}/${integrationId}/chat-completion${this.getQueryParams({})}`, {
136
- method: 'POST',
137
- headers: { 'content-type': 'application/json' },
138
- body: JSON.stringify(options)
139
- });
138
+ return this.chat.chat(integrationId, options);
140
139
  }
141
140
 
142
141
  /**
143
- * Create a chat completion with a thread
142
+ * @deprecated Use sdk.chat.chatInThread() instead
144
143
  */
145
- chatInThread(
144
+ chatCompletionInThread(
146
145
  integrationId: string,
147
146
  threadId: string,
148
147
  options: IChatCompletionOptions
149
148
  ): Promise<IChatCompletionResponse> {
150
- return this.callJsonApi<IChatCompletionResponse>(
151
- `${this.relativePath}/${integrationId}/chat-completion/${threadId}${this.getQueryParams({})}`,
152
- {
153
- method: 'POST',
154
- headers: { 'content-type': 'application/json' },
155
- body: JSON.stringify(options)
156
- }
157
- );
149
+ return this.chat.chatInThread(integrationId, threadId, options);
158
150
  }
159
151
 
160
152
  /**
161
- * Create a streaming chat completion without a thread
162
- * Returns a ReadableStream for Server-Sent Events
153
+ * @deprecated Use sdk.chat.stream() instead
163
154
  */
164
155
  async streamChat(
165
156
  integrationId: string,
166
157
  options: IChatCompletionOptions
167
158
  ): Promise<ReadableStream<Uint8Array>> {
168
- const response = await this.callApi(`${this.relativePath}/${integrationId}/chat-completion${this.getQueryParams({ stream: true })}`, {
169
- method: 'POST',
170
- headers: {
171
- 'content-type': 'application/json',
172
- 'accept': 'text/event-stream'
173
- },
174
- body: JSON.stringify({ ...options, stream: true })
175
- });
176
-
177
- if (!response.ok) {
178
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
179
- }
180
-
181
- return response.body!;
159
+ return this.chat.stream(integrationId, options);
182
160
  }
183
161
 
184
162
  /**
185
- * Create a streaming chat completion with a thread
186
- * Returns a ReadableStream for Server-Sent Events
163
+ * @deprecated Use sdk.chat.streamInThread() instead
187
164
  */
188
165
  async streamChatInThread(
189
166
  integrationId: string,
190
167
  threadId: string,
191
168
  options: IChatCompletionOptions
192
169
  ): Promise<ReadableStream<Uint8Array>> {
193
- const response = await this.callApi(
194
- `${this.relativePath}/${integrationId}/chat-completion/${threadId}${this.getQueryParams({ stream: true })}`,
195
- {
196
- method: 'POST',
197
- headers: {
198
- 'content-type': 'application/json',
199
- 'accept': 'text/event-stream'
200
- },
201
- body: JSON.stringify({ ...options, stream: true })
202
- }
203
- );
204
-
205
- if (!response.ok) {
206
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
207
- }
208
-
209
- return response.body!;
170
+ return this.chat.streamInThread(integrationId, threadId, options);
210
171
  }
211
172
 
212
173
  /**
213
- * Helper method to parse Server-Sent Events stream
174
+ * @deprecated Use sdk.chat.parseSSEStream() instead
214
175
  */
215
176
  parseSSEStream(stream: ReadableStream<Uint8Array>): ISSEStreamProcessor {
216
- const processStream = async (onData: (data: any) => void | boolean): Promise<void> => {
217
- const reader = stream.getReader();
218
- const decoder = new TextDecoder();
219
- let buffer = "";
220
-
221
- try {
222
- while (true) {
223
- const { done, value } = await reader.read();
224
- if (done) break;
225
-
226
- buffer += decoder.decode(value, { stream: true });
227
- let lines = buffer.split(/\r?\n/);
228
- buffer = lines.pop() || ""; // Keep incomplete line
229
-
230
- for (const line of lines) {
231
- if (line.startsWith('data: ')) {
232
- const data = line.slice(6);
233
- if (data === '[DONE]') return;
234
-
235
- try {
236
- const parsed = JSON.parse(data);
237
- const shouldContinue = onData(parsed);
238
- if (shouldContinue === false) {
239
- return;
240
- }
241
- } catch (e) {
242
- // Skip invalid JSON
243
- }
244
- }
245
- }
246
- }
247
- } finally {
248
- reader.releaseLock();
249
- }
250
- };
251
-
252
- const processor = {
253
- async *[Symbol.asyncIterator]() {
254
- const reader = stream.getReader();
255
- const decoder = new TextDecoder();
256
- let buffer = "";
257
-
258
- try {
259
- while (true) {
260
- const { done, value } = await reader.read();
261
- if (done) {
262
- break;
263
- }
264
-
265
- buffer += decoder.decode(value, { stream: true });
266
- let lines = buffer.split(/\r?\n/);
267
- buffer = lines.pop() || ""; // Keep incomplete line
268
-
269
- for (const line of lines) {
270
- if (line.startsWith('data: ')) {
271
- const data = line.slice(6);
272
- if (data === '[DONE]') {
273
- return;
274
- }
275
-
276
- try {
277
- const parsed = JSON.parse(data);
278
- yield parsed;
279
- } catch (e) {
280
- //
281
- }
282
- }
283
- }
284
- }
285
- } finally {
286
- reader.releaseLock();
287
- }
288
- },
289
-
290
- processManually: processStream
291
- };
292
-
293
- return processor as ISSEStreamProcessor;
177
+ return this.chat.parseSSEStream(stream);
294
178
  }
295
179
  }