@allanfsouza/aether-sdk 2.4.9 → 2.4.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/ai.d.ts +300 -0
- package/dist/ai.js +370 -0
- package/dist/database.js +16 -6
- package/dist/http-client.js +5 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.js +2 -0
- package/package.json +1 -1
- package/src/ai.ts +580 -0
- package/src/database.ts +21 -7
- package/src/http-client.ts +6 -1
- package/src/index.ts +8 -0
package/dist/database.js
CHANGED
|
@@ -199,7 +199,6 @@ export class CollectionReference {
|
|
|
199
199
|
console.warn("[SDK] Realtime falhou: Token ou ProjectId ausentes.");
|
|
200
200
|
return () => { };
|
|
201
201
|
}
|
|
202
|
-
// URL correta de subscribe
|
|
203
202
|
const url = `${this.wsUrl}/v1/db/subscribe/${this.collectionName}?token=${token}&projectId=${projectId}`;
|
|
204
203
|
let ws = null;
|
|
205
204
|
try {
|
|
@@ -207,7 +206,7 @@ export class CollectionReference {
|
|
|
207
206
|
if (!ws)
|
|
208
207
|
return () => { };
|
|
209
208
|
ws.onopen = () => {
|
|
210
|
-
|
|
209
|
+
console.log(`[SDK] Realtime conectado: ${this.collectionName}`);
|
|
211
210
|
};
|
|
212
211
|
ws.onmessage = (event) => {
|
|
213
212
|
try {
|
|
@@ -215,16 +214,27 @@ export class CollectionReference {
|
|
|
215
214
|
if (raw === "pong")
|
|
216
215
|
return;
|
|
217
216
|
const payload = JSON.parse(raw);
|
|
218
|
-
|
|
217
|
+
console.log(`[SDK] Evento recebido:`, payload.action, payload.data?.id);
|
|
218
|
+
// [FIX] Mapeia 'insert' do Postgres para 'create' do SDK
|
|
219
|
+
let action = payload.action;
|
|
220
|
+
if (payload.action === 'insert') {
|
|
221
|
+
action = 'create';
|
|
222
|
+
}
|
|
223
|
+
callback(action, payload.data);
|
|
219
224
|
}
|
|
220
225
|
catch (e) {
|
|
221
|
-
|
|
226
|
+
console.error('[SDK] Erro ao parsear evento:', e);
|
|
222
227
|
}
|
|
223
228
|
};
|
|
229
|
+
ws.onerror = (err) => {
|
|
230
|
+
console.error('[SDK] WebSocket erro:', err);
|
|
231
|
+
};
|
|
232
|
+
ws.onclose = () => {
|
|
233
|
+
console.log(`[SDK] Realtime desconectado: ${this.collectionName}`);
|
|
234
|
+
};
|
|
224
235
|
// Heartbeat
|
|
225
236
|
const pingInterval = setInterval(() => {
|
|
226
|
-
|
|
227
|
-
if (ws && ws.readyState === 1) { // 1 = OPEN
|
|
237
|
+
if (ws && ws.readyState === 1) {
|
|
228
238
|
ws.send("ping");
|
|
229
239
|
}
|
|
230
240
|
}, 30000);
|
package/dist/http-client.js
CHANGED
|
@@ -115,7 +115,7 @@ export function createHttpClient(client, retryConfig = {}) {
|
|
|
115
115
|
});
|
|
116
116
|
// ===========================================================================
|
|
117
117
|
// INTERCEPTOR DE REQUEST
|
|
118
|
-
// Injeta token e
|
|
118
|
+
// Injeta token, projectId e API Key em todas as requisições
|
|
119
119
|
// ===========================================================================
|
|
120
120
|
http.interceptors.request.use((reqConfig) => {
|
|
121
121
|
const token = client.getToken();
|
|
@@ -125,6 +125,10 @@ export function createHttpClient(client, retryConfig = {}) {
|
|
|
125
125
|
if (client.projectId) {
|
|
126
126
|
reqConfig.headers["X-Project-ID"] = client.projectId;
|
|
127
127
|
}
|
|
128
|
+
// [NOVO] Envia API Key para autenticação de operações de banco de dados
|
|
129
|
+
if (client.serviceApiKey) {
|
|
130
|
+
reqConfig.headers["X-API-Key"] = client.serviceApiKey;
|
|
131
|
+
}
|
|
128
132
|
// Inicializa contador de retry
|
|
129
133
|
if (reqConfig._retryCount === undefined) {
|
|
130
134
|
reqConfig._retryCount = 0;
|
package/dist/index.d.ts
CHANGED
|
@@ -13,6 +13,11 @@ export type ClientConfig = {
|
|
|
13
13
|
baseUrl?: string;
|
|
14
14
|
projectId?: string;
|
|
15
15
|
apiKey?: string;
|
|
16
|
+
/**
|
|
17
|
+
* [NOVO] API Key de serviço para autenticação em operações de banco de dados.
|
|
18
|
+
* Necessário para apps client-side que usam tenant auth.
|
|
19
|
+
*/
|
|
20
|
+
serviceApiKey?: string;
|
|
16
21
|
/**
|
|
17
22
|
* Habilita persistência automática de sessão no localStorage.
|
|
18
23
|
* Padrão: true em browsers, false em Node.js/SSR.
|
|
@@ -29,6 +34,7 @@ export declare class PlataformaClient {
|
|
|
29
34
|
database: DatabaseModule;
|
|
30
35
|
apiUrl: string;
|
|
31
36
|
projectId: string;
|
|
37
|
+
serviceApiKey: string | null;
|
|
32
38
|
http: AxiosInstance;
|
|
33
39
|
private _token;
|
|
34
40
|
private _persistSession;
|
package/dist/index.js
CHANGED
|
@@ -24,6 +24,7 @@ function isBrowser() {
|
|
|
24
24
|
}
|
|
25
25
|
export class PlataformaClient {
|
|
26
26
|
constructor(config) {
|
|
27
|
+
this.serviceApiKey = null;
|
|
27
28
|
this._token = null;
|
|
28
29
|
// Resolve URL (prioridade para baseUrl se existir, senão apiUrl)
|
|
29
30
|
const url = config.baseUrl || config.apiUrl;
|
|
@@ -33,6 +34,7 @@ export class PlataformaClient {
|
|
|
33
34
|
}
|
|
34
35
|
this.apiUrl = url.replace(/\/+$/, "");
|
|
35
36
|
this.projectId = project;
|
|
37
|
+
this.serviceApiKey = config.serviceApiKey || null;
|
|
36
38
|
// Persistência habilitada por padrão apenas em browsers
|
|
37
39
|
this._persistSession = config.persistSession ?? isBrowser();
|
|
38
40
|
// Restaura sessão salva ANTES de criar o httpClient
|
package/package.json
CHANGED
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
|
+
}
|