@allanfsouza/aether-sdk 2.4.10 → 2.5.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/src/ai.ts ADDED
@@ -0,0 +1,580 @@
1
+ // src/ai.ts
2
+ // [NOVO] Módulo de IA do Aether SDK
3
+ // Permite que clientes adicionem IA aos seus apps com poucas linhas de código
4
+ // Data: Dezembro 2025
5
+
6
+ import type { AxiosInstance } from "axios";
7
+ import type { PlataformaClient } from "./index.js";
8
+
9
+ // =============================================================================
10
+ // TIPOS
11
+ // =============================================================================
12
+
13
+ /**
14
+ * Opções para o método chat()
15
+ */
16
+ export interface ChatOptions {
17
+ /** ID da conversa para manter contexto entre mensagens */
18
+ conversationId?: string;
19
+
20
+ /** Contexto adicional (ex: "vendas", "suporte", "produtos") */
21
+ context?: string;
22
+
23
+ /** Callback chamado a cada chunk de texto recebido (streaming) */
24
+ onChunk?: (chunk: string) => void;
25
+
26
+ /** Callback chamado quando a resposta completa é recebida */
27
+ onComplete?: (fullResponse: string, metadata: ChatMetadata) => void;
28
+
29
+ /** Callback chamado em caso de erro */
30
+ onError?: (error: Error) => void;
31
+
32
+ /** Timeout em ms (padrão: 30000) */
33
+ timeout?: number;
34
+ }
35
+
36
+ /**
37
+ * Metadados retornados após uma resposta completa
38
+ */
39
+ export interface ChatMetadata {
40
+ conversationId: string;
41
+ messageId?: string;
42
+ tokensUsed?: number;
43
+ sources?: RetrievedSource[];
44
+ }
45
+
46
+ /**
47
+ * Fonte de dados usada pelo RAG
48
+ */
49
+ export interface RetrievedSource {
50
+ type: string;
51
+ content: string;
52
+ similarity: number;
53
+ }
54
+
55
+ /**
56
+ * Resposta do método ask()
57
+ */
58
+ export interface AskResponse {
59
+ text: string;
60
+ conversationId: string;
61
+ sources?: RetrievedSource[];
62
+ }
63
+
64
+ /**
65
+ * Conversa persistida
66
+ */
67
+ export interface Conversation {
68
+ id: string;
69
+ title: string;
70
+ context: string;
71
+ createdAt: string;
72
+ updatedAt: string;
73
+ messageCount?: number;
74
+ }
75
+
76
+ /**
77
+ * Mensagem de uma conversa
78
+ */
79
+ export interface Message {
80
+ id: string;
81
+ conversationId: string;
82
+ role: 'user' | 'assistant';
83
+ content: string;
84
+ metadata?: Record<string, any>;
85
+ createdAt: string;
86
+ }
87
+
88
+ /**
89
+ * Tipo de feedback
90
+ */
91
+ export type FeedbackType = 'thumbs_up' | 'thumbs_down';
92
+
93
+ /**
94
+ * Opções para busca semântica
95
+ */
96
+ export interface SemanticSearchOptions {
97
+ /** Número máximo de resultados (padrão: 10) */
98
+ limit?: number;
99
+
100
+ /** Score mínimo de similaridade 0-1 (padrão: 0.5) */
101
+ minScore?: number;
102
+
103
+ /** Filtrar por collection específica */
104
+ collection?: string;
105
+ }
106
+
107
+ /**
108
+ * Resultado de busca semântica
109
+ */
110
+ export interface SemanticSearchResult {
111
+ id: string;
112
+ content: string;
113
+ collection: string;
114
+ similarity: number;
115
+ metadata?: Record<string, any>;
116
+ }
117
+
118
+ /**
119
+ * Opções para geração de conteúdo
120
+ */
121
+ export interface GenerateOptions {
122
+ /** Tom do texto (formal, casual, técnico, etc) */
123
+ tone?: 'formal' | 'casual' | 'technical' | 'friendly';
124
+
125
+ /** Tamanho aproximado (short, medium, long) */
126
+ length?: 'short' | 'medium' | 'long';
127
+
128
+ /** Idioma (padrão: pt-BR) */
129
+ language?: string;
130
+
131
+ /** Contexto adicional para a geração */
132
+ context?: string;
133
+ }
134
+
135
+ // =============================================================================
136
+ // MÓDULO PRINCIPAL
137
+ // =============================================================================
138
+
139
+ export class AIModule {
140
+ private client: PlataformaClient;
141
+ private http: AxiosInstance;
142
+
143
+ /** Sub-módulo para gerenciar conversas */
144
+ public conversations: ConversationsAPI;
145
+
146
+ /** Sub-módulo para funções administrativas */
147
+ public admin: AIAdminAPI;
148
+
149
+ constructor(client: PlataformaClient, http: AxiosInstance) {
150
+ this.client = client;
151
+ this.http = http;
152
+ this.conversations = new ConversationsAPI(client, http);
153
+ this.admin = new AIAdminAPI(client, http);
154
+ }
155
+
156
+ // ===========================================================================
157
+ // MÉTODOS PRINCIPAIS
158
+ // ===========================================================================
159
+
160
+ /**
161
+ * Faz uma pergunta simples e aguarda a resposta completa.
162
+ * Ideal para quando não precisa de streaming.
163
+ *
164
+ * @example
165
+ * const { text } = await aether.ai.ask("Quais produtos estão em promoção?");
166
+ * console.log(text);
167
+ */
168
+ async ask(message: string, conversationId?: string): Promise<AskResponse> {
169
+ return new Promise((resolve, reject) => {
170
+ let fullText = '';
171
+ let metadata: ChatMetadata = { conversationId: conversationId || '' };
172
+
173
+ this.chat(message, {
174
+ conversationId,
175
+ onChunk: (chunk) => {
176
+ fullText += chunk;
177
+ },
178
+ onComplete: (response, meta) => {
179
+ metadata = meta;
180
+ resolve({
181
+ text: fullText,
182
+ conversationId: meta.conversationId,
183
+ sources: meta.sources
184
+ });
185
+ },
186
+ onError: reject
187
+ }).catch(reject);
188
+ });
189
+ }
190
+
191
+ /**
192
+ * Inicia um chat com streaming de resposta.
193
+ * A resposta chega em chunks conforme a IA gera.
194
+ *
195
+ * @example
196
+ * await aether.ai.chat("Explique como funciona o sistema de pagamentos", {
197
+ * onChunk: (chunk) => {
198
+ * // Atualiza UI em tempo real
199
+ * setResponse(prev => prev + chunk);
200
+ * },
201
+ * onComplete: (full, meta) => {
202
+ * console.log("Conversa ID:", meta.conversationId);
203
+ * }
204
+ * });
205
+ */
206
+ async chat(message: string, options: ChatOptions = {}): Promise<void> {
207
+ const projectId = this.client.projectId;
208
+ const token = this.client.getToken();
209
+
210
+ if (!token) {
211
+ const error = new Error('Usuário não autenticado. Faça login primeiro.');
212
+ if (options.onError) {
213
+ options.onError(error);
214
+ return;
215
+ }
216
+ throw error;
217
+ }
218
+
219
+ const timeout = options.timeout || 30000;
220
+ const controller = new AbortController();
221
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
222
+
223
+ try {
224
+ const response = await fetch(`${this.client.apiUrl}/v1/ai/chat`, {
225
+ method: 'POST',
226
+ headers: {
227
+ 'Content-Type': 'application/json',
228
+ 'Authorization': `Bearer ${token}`,
229
+ 'X-Project-ID': projectId
230
+ },
231
+ body: JSON.stringify({
232
+ message,
233
+ projectId,
234
+ conversationId: options.conversationId,
235
+ context: options.context || 'general'
236
+ }),
237
+ signal: controller.signal
238
+ });
239
+
240
+ clearTimeout(timeoutId);
241
+
242
+ if (!response.ok) {
243
+ const errorText = await response.text();
244
+ throw new Error(`Erro na API: ${response.status} - ${errorText}`);
245
+ }
246
+
247
+ // Captura conversation ID do header (se disponível)
248
+ const convIdFromHeader = response.headers.get('X-Conversation-ID');
249
+
250
+ // Processa o stream
251
+ const reader = response.body?.getReader();
252
+ const decoder = new TextDecoder();
253
+ let fullResponse = '';
254
+
255
+ if (!reader) {
256
+ throw new Error('Stream não disponível');
257
+ }
258
+
259
+ while (true) {
260
+ const { done, value } = await reader.read();
261
+
262
+ if (done) break;
263
+
264
+ const chunk = decoder.decode(value, { stream: true });
265
+ fullResponse += chunk;
266
+
267
+ if (options.onChunk) {
268
+ options.onChunk(chunk);
269
+ }
270
+ }
271
+
272
+ // Callback de conclusão
273
+ if (options.onComplete) {
274
+ options.onComplete(fullResponse, {
275
+ conversationId: convIdFromHeader || options.conversationId || '',
276
+ });
277
+ }
278
+
279
+ } catch (error: any) {
280
+ clearTimeout(timeoutId);
281
+
282
+ if (error.name === 'AbortError') {
283
+ error = new Error(`Timeout: A requisição excedeu ${timeout}ms`);
284
+ }
285
+
286
+ if (options.onError) {
287
+ options.onError(error);
288
+ } else {
289
+ throw error;
290
+ }
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Envia feedback sobre uma resposta da IA.
296
+ * Ajuda a melhorar as respostas futuras.
297
+ *
298
+ * @example
299
+ * await aether.ai.feedback(messageId, 'thumbs_up');
300
+ * await aether.ai.feedback(messageId, 'thumbs_down', 'Resposta incorreta');
301
+ */
302
+ async feedback(
303
+ messageId: string,
304
+ type: FeedbackType,
305
+ comment?: string
306
+ ): Promise<{ success: boolean }> {
307
+ const { data } = await this.http.post('/ai/feedback', {
308
+ messageId,
309
+ feedbackType: type,
310
+ comment
311
+ });
312
+ return data;
313
+ }
314
+
315
+ // ===========================================================================
316
+ // BUSCA SEMÂNTICA
317
+ // ===========================================================================
318
+
319
+ /**
320
+ * Busca semântica nos dados do projeto.
321
+ * Encontra documentos similares usando embeddings.
322
+ *
323
+ * @example
324
+ * // Busca produtos similares a uma descrição
325
+ * const results = await aether.ai.search("tênis confortável para corrida");
326
+ *
327
+ * // Com filtros
328
+ * const results = await aether.ai.search("problema no login", {
329
+ * collection: "support_tickets",
330
+ * limit: 5,
331
+ * minScore: 0.7
332
+ * });
333
+ */
334
+ async search(
335
+ query: string,
336
+ options: SemanticSearchOptions = {}
337
+ ): Promise<SemanticSearchResult[]> {
338
+ const { data } = await this.http.post('/ai/search', {
339
+ query,
340
+ projectId: this.client.projectId,
341
+ limit: options.limit || 10,
342
+ minScore: options.minScore || 0.5,
343
+ collection: options.collection
344
+ });
345
+ return data.results;
346
+ }
347
+
348
+ // ===========================================================================
349
+ // GERAÇÃO DE CONTEÚDO
350
+ // ===========================================================================
351
+
352
+ /**
353
+ * Gera texto baseado em um prompt e contexto.
354
+ * Útil para descrições de produtos, resumos, etc.
355
+ *
356
+ * @example
357
+ * // Gerar descrição de produto
358
+ * const descricao = await aether.ai.generate(
359
+ * "Escreva uma descrição para o produto",
360
+ * { productName: "iPhone 15", price: 5999, features: ["5G", "48MP"] },
361
+ * { tone: 'friendly', length: 'medium' }
362
+ * );
363
+ */
364
+ async generate(
365
+ prompt: string,
366
+ data: Record<string, any>,
367
+ options: GenerateOptions = {}
368
+ ): Promise<string> {
369
+ const { data: response } = await this.http.post('/ai/generate', {
370
+ prompt,
371
+ data,
372
+ projectId: this.client.projectId,
373
+ tone: options.tone || 'friendly',
374
+ length: options.length || 'medium',
375
+ language: options.language || 'pt-BR',
376
+ context: options.context
377
+ });
378
+ return response.text;
379
+ }
380
+
381
+ // ===========================================================================
382
+ // ANÁLISE DE DADOS
383
+ // ===========================================================================
384
+
385
+ /**
386
+ * Analisa dados e retorna insights em linguagem natural.
387
+ *
388
+ * @example
389
+ * const insights = await aether.ai.analyze("orders", {
390
+ * question: "Como foram as vendas essa semana?",
391
+ * period: "7d"
392
+ * });
393
+ */
394
+ async analyze(
395
+ collection: string,
396
+ options: { question: string; period?: string }
397
+ ): Promise<{ insights: string; data?: any }> {
398
+ const { data } = await this.http.post('/ai/analyze', {
399
+ collection,
400
+ projectId: this.client.projectId,
401
+ question: options.question,
402
+ period: options.period || '7d'
403
+ });
404
+ return data;
405
+ }
406
+
407
+ /**
408
+ * Processa linguagem natural e converte em query estruturada.
409
+ * Útil para criar filtros de busca baseados em texto do usuário.
410
+ *
411
+ * @example
412
+ * const query = await aether.ai.parseQuery(
413
+ * "produtos vermelhos acima de 100 reais ordenados por preço"
414
+ * );
415
+ * // Retorna: { filter: { color: 'vermelho', price: { $gt: 100 } }, sort: { price: 'ASC' } }
416
+ */
417
+ async parseQuery(
418
+ naturalLanguage: string,
419
+ collection?: string
420
+ ): Promise<{ filter?: Record<string, any>; sort?: Record<string, any> }> {
421
+ const { data } = await this.http.post('/ai/parse-query', {
422
+ query: naturalLanguage,
423
+ collection,
424
+ projectId: this.client.projectId
425
+ });
426
+ return data;
427
+ }
428
+ }
429
+
430
+ // =============================================================================
431
+ // SUB-MÓDULO: CONVERSAS
432
+ // =============================================================================
433
+
434
+ class ConversationsAPI {
435
+ private client: PlataformaClient;
436
+ private http: AxiosInstance;
437
+
438
+ constructor(client: PlataformaClient, http: AxiosInstance) {
439
+ this.client = client;
440
+ this.http = http;
441
+ }
442
+
443
+ /**
444
+ * Lista todas as conversas do usuário no projeto.
445
+ *
446
+ * @example
447
+ * const conversas = await aether.ai.conversations.list();
448
+ */
449
+ async list(): Promise<Conversation[]> {
450
+ const { data } = await this.http.get('/ai/conversations', {
451
+ params: { projectId: this.client.projectId }
452
+ });
453
+ return data;
454
+ }
455
+
456
+ /**
457
+ * Busca o histórico de mensagens de uma conversa.
458
+ *
459
+ * @example
460
+ * const mensagens = await aether.ai.conversations.getMessages(conversationId);
461
+ */
462
+ async getMessages(conversationId: string): Promise<Message[]> {
463
+ const { data } = await this.http.get(`/ai/messages/${conversationId}`);
464
+ return data;
465
+ }
466
+
467
+ /**
468
+ * Deleta uma conversa e todo seu histórico.
469
+ *
470
+ * @example
471
+ * await aether.ai.conversations.delete(conversationId);
472
+ */
473
+ async delete(conversationId: string): Promise<{ success: boolean }> {
474
+ const { data } = await this.http.delete(`/ai/conversations/${conversationId}`);
475
+ return data;
476
+ }
477
+
478
+ /**
479
+ * Renomeia uma conversa.
480
+ *
481
+ * @example
482
+ * await aether.ai.conversations.rename(conversationId, "Suporte Técnico");
483
+ */
484
+ async rename(conversationId: string, title: string): Promise<Conversation> {
485
+ const { data } = await this.http.patch(`/ai/conversations/${conversationId}`, {
486
+ title
487
+ });
488
+ return data;
489
+ }
490
+ }
491
+
492
+ // =============================================================================
493
+ // SUB-MÓDULO: ADMIN
494
+ // =============================================================================
495
+
496
+ class AIAdminAPI {
497
+ private client: PlataformaClient;
498
+ private http: AxiosInstance;
499
+
500
+ constructor(client: PlataformaClient, http: AxiosInstance) {
501
+ this.client = client;
502
+ this.http = http;
503
+ }
504
+
505
+ /**
506
+ * Reindexa todos os dados do projeto para RAG.
507
+ * Use após adicionar/modificar grandes volumes de dados.
508
+ * Executa em background.
509
+ *
510
+ * @example
511
+ * await aether.ai.admin.reindex();
512
+ */
513
+ async reindex(): Promise<{ message: string }> {
514
+ const { data } = await this.http.post('/ai/reindex', {
515
+ projectId: this.client.projectId
516
+ });
517
+ return data;
518
+ }
519
+
520
+ /**
521
+ * Limpa todos os embeddings do projeto.
522
+ * CUIDADO: A IA "esquece" todo o contexto aprendido.
523
+ *
524
+ * @example
525
+ * const { deletedCount } = await aether.ai.admin.clear();
526
+ */
527
+ async clear(): Promise<{ deletedCount: number }> {
528
+ const { data } = await this.http.post('/ai/clear', {
529
+ projectId: this.client.projectId
530
+ });
531
+ return data;
532
+ }
533
+
534
+ /**
535
+ * Retorna estatísticas de uso da IA.
536
+ *
537
+ * @example
538
+ * const stats = await aether.ai.admin.stats();
539
+ * console.log(stats.totalConversations, stats.totalMessages);
540
+ */
541
+ async stats(): Promise<{
542
+ totalConversations: number;
543
+ totalMessages: number;
544
+ totalEmbeddings: number;
545
+ storageUsedMB: number;
546
+ }> {
547
+ const { data } = await this.http.get('/ai/stats', {
548
+ params: { projectId: this.client.projectId }
549
+ });
550
+ return data;
551
+ }
552
+
553
+ /**
554
+ * Configura quais collections são indexadas automaticamente.
555
+ *
556
+ * @example
557
+ * await aether.ai.admin.setIndexedCollections(['products', 'articles', 'faq']);
558
+ */
559
+ async setIndexedCollections(collections: string[]): Promise<{ success: boolean }> {
560
+ const { data } = await this.http.post('/ai/config/collections', {
561
+ projectId: this.client.projectId,
562
+ collections
563
+ });
564
+ return data;
565
+ }
566
+
567
+ /**
568
+ * Busca configurações atuais de IA do projeto.
569
+ */
570
+ async getConfig(): Promise<{
571
+ indexedCollections: string[];
572
+ autoIndex: boolean;
573
+ embeddingModel: string;
574
+ }> {
575
+ const { data } = await this.http.get('/ai/config', {
576
+ params: { projectId: this.client.projectId }
577
+ });
578
+ return data;
579
+ }
580
+ }
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ import { StorageModule } from "./storage.js";
7
7
  import { FunctionsModule } from "./functions.js";
8
8
  import { PushModule } from "./push.js";
9
9
  import { TenantAuthModule, TenantUser, TenantLoginResponse, TenantRegisterCredentials, TenantLoginCredentials } from "./tenant-auth.js";
10
+ import { AIModule } from "./ai.js";
10
11
 
11
12
  // =============================================================================
12
13
  // CONSTANTES DE STORAGE
@@ -59,6 +60,7 @@ export class PlataformaClient {
59
60
  public functions: FunctionsModule;
60
61
  public push: PushModule;
61
62
  public tenantAuth: TenantAuthModule;
63
+ public ai: AIModule;
62
64
 
63
65
  // Alias para 'db' que o showcase tenta usar como 'database'
64
66
  public database: DatabaseModule;
@@ -101,6 +103,7 @@ export class PlataformaClient {
101
103
  this.functions = new FunctionsModule(this, this.http);
102
104
  this.push = new PushModule(this, this.http);
103
105
  this.tenantAuth = new TenantAuthModule(this, this.http);
106
+ this.ai = new AIModule(this, this.http);
104
107
 
105
108
  // Cria o alias que o Showcase App espera
106
109
  this.database = this.db;
@@ -258,4 +261,16 @@ export type {
258
261
  TenantLoginResponse,
259
262
  TenantRegisterCredentials,
260
263
  TenantLoginCredentials,
261
- } from "./tenant-auth.js";
264
+ } from "./tenant-auth.js";
265
+ export type {
266
+ ChatOptions,
267
+ ChatMetadata,
268
+ AskResponse,
269
+ Conversation,
270
+ Message,
271
+ FeedbackType,
272
+ SemanticSearchOptions,
273
+ SemanticSearchResult,
274
+ GenerateOptions,
275
+ RetrievedSource,
276
+ } from "./ai.js";