@snap-agent/core 0.1.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.
@@ -0,0 +1,472 @@
1
+ import { P as ProviderConfig, a as ProviderType, A as AgentData, S as StorageAdapter, b as AgentConfig, c as AgentFile, d as Plugin, R as RAGDocument, I as IngestOptions, e as IngestResult, B as BulkOperation, f as BulkResult, U as URLSource, g as URLIngestResult, T as ThreadData, h as ThreadConfig, M as MessageRole, i as MessageAttachment, j as MessageData, C as ClientConfig, k as ChatRequest, l as ChatResponse, m as StreamCallbacks, n as RAGPlugin, o as ToolPlugin, p as MiddlewarePlugin, q as AnalyticsPlugin, r as RAGContext } from './index-CDsqnM8L.js';
2
+ export { F as AgentNotFoundError, D as AgentSDKError, t as BasePlugin, E as ErrorTrackingData, J as InvalidConfigError, L as MemoryStorage, K as MongoDBStorage, O as MongoDBStorageConfig, v as PerformanceTimings, H as ProviderNotFoundError, s as RAGConfig, w as RAGMetrics, y as RequestTrackingData, z as ResponseTrackingData, G as ThreadNotFoundError, x as TokenMetrics, u as Tool, N as UpstashStorage, Q as UpstashStorageConfig } from './index-CDsqnM8L.js';
3
+ import { LanguageModel, UserModelMessage, AssistantModelMessage } from 'ai';
4
+
5
+ /**
6
+ * Provider factory for creating language model instances
7
+ * Supports OpenAI, Anthropic, and Google providers via Vercel AI SDK
8
+ */
9
+ declare class ProviderFactory {
10
+ private config;
11
+ private modelCache;
12
+ constructor(config: ProviderConfig);
13
+ /**
14
+ * Get a language model for the specified provider and model
15
+ * Uses dynamic imports for edge runtime compatibility
16
+ */
17
+ getModel(provider: ProviderType, modelName: string): Promise<LanguageModel>;
18
+ /**
19
+ * Check if a provider is configured
20
+ */
21
+ isProviderConfigured(provider: ProviderType): boolean;
22
+ /**
23
+ * Get list of configured providers
24
+ */
25
+ getConfiguredProviders(): ProviderType[];
26
+ /**
27
+ * Clear the model cache
28
+ */
29
+ clearCache(): void;
30
+ }
31
+ /**
32
+ * Common model names for quick reference
33
+ */
34
+ declare const Models: {
35
+ readonly OpenAI: {
36
+ readonly GPT4O: "gpt-4o";
37
+ readonly GPT4O_MINI: "gpt-4o-mini";
38
+ readonly GPT4_TURBO: "gpt-4-turbo";
39
+ readonly GPT35_TURBO: "gpt-3.5-turbo";
40
+ };
41
+ readonly Anthropic: {
42
+ readonly CLAUDE_35_SONNET: "claude-3-5-sonnet-20241022";
43
+ readonly CLAUDE_35_HAIKU: "claude-3-5-haiku-20241022";
44
+ readonly CLAUDE_3_OPUS: "claude-3-opus-20240229";
45
+ };
46
+ readonly Google: {
47
+ readonly GEMINI_2_FLASH: "gemini-2.0-flash-exp";
48
+ readonly GEMINI_15_PRO: "gemini-1.5-pro";
49
+ readonly GEMINI_15_FLASH: "gemini-1.5-flash";
50
+ };
51
+ };
52
+
53
+ type AIMessage$1 = UserModelMessage | AssistantModelMessage;
54
+ /**
55
+ * Agent class representing an AI agent with persistent state
56
+ */
57
+ declare class Agent {
58
+ private data;
59
+ private storage;
60
+ private providerFactory;
61
+ private pluginManager;
62
+ constructor(data: AgentData, storage: StorageAdapter, providerFactory: ProviderFactory);
63
+ /**
64
+ * Create a new agent
65
+ */
66
+ static create(config: AgentConfig, storage: StorageAdapter, providerFactory: ProviderFactory): Promise<Agent>;
67
+ /**
68
+ * Load an existing agent by ID
69
+ */
70
+ static load(agentId: string, storage: StorageAdapter, providerFactory: ProviderFactory): Promise<Agent | null>;
71
+ /**
72
+ * Update agent properties
73
+ */
74
+ update(updates: Partial<AgentConfig>): Promise<void>;
75
+ /**
76
+ * Delete this agent
77
+ */
78
+ delete(): Promise<void>;
79
+ /**
80
+ * Add files to the agent
81
+ */
82
+ addFiles(files: AgentFile[]): Promise<void>;
83
+ /**
84
+ * Generate a text response with optional plugin support
85
+ */
86
+ generateResponse(messages: AIMessage$1[], options?: {
87
+ useRAG?: boolean;
88
+ ragFilters?: Record<string, any>;
89
+ threadId?: string;
90
+ }): Promise<{
91
+ text: string;
92
+ metadata?: Record<string, any>;
93
+ }>;
94
+ /**
95
+ * Stream a text response with optional plugin support
96
+ */
97
+ streamResponse(messages: AIMessage$1[], onChunk: (chunk: string) => void, onComplete?: (fullText: string, metadata?: Record<string, any>) => void, onError?: (error: Error) => void, options?: {
98
+ useRAG?: boolean;
99
+ ragFilters?: Record<string, any>;
100
+ threadId?: string;
101
+ }): Promise<void>;
102
+ /**
103
+ * Get agent ID
104
+ */
105
+ get id(): string;
106
+ /**
107
+ * Get agent name
108
+ */
109
+ get name(): string;
110
+ /**
111
+ * Get agent instructions
112
+ */
113
+ get instructions(): string;
114
+ /**
115
+ * Get agent provider
116
+ */
117
+ get provider(): string;
118
+ /**
119
+ * Get agent model
120
+ */
121
+ get model(): string;
122
+ /**
123
+ * Get all plugins attached to this agent
124
+ */
125
+ get plugins(): Plugin[];
126
+ /**
127
+ * Add a plugin to this agent
128
+ */
129
+ addPlugin(plugin: Plugin): void;
130
+ /**
131
+ * Remove a plugin by name
132
+ */
133
+ removePlugin(pluginName: string): void;
134
+ /**
135
+ * Get all agent data
136
+ */
137
+ toJSON(): AgentData;
138
+ /**
139
+ * Ingest documents into RAG plugins
140
+ * Documents will be ingested into all RAG plugins that support ingestion
141
+ */
142
+ ingestDocuments(documents: RAGDocument[], options?: IngestOptions): Promise<IngestResult[]>;
143
+ /**
144
+ * Update a document in RAG plugins
145
+ */
146
+ updateDocument(id: string, document: Partial<RAGDocument>, options?: IngestOptions): Promise<void>;
147
+ /**
148
+ * Delete documents from RAG plugins
149
+ */
150
+ deleteDocuments(ids: string | string[], options?: IngestOptions): Promise<number>;
151
+ /**
152
+ * Perform bulk operations on RAG plugins
153
+ */
154
+ bulkDocumentOperations(operations: BulkOperation[], options?: IngestOptions): Promise<BulkResult[]>;
155
+ /**
156
+ * Ingest documents from a URL source (CSV, JSON, XML, API)
157
+ * Supports authentication, scheduling, and data transformation
158
+ */
159
+ ingestFromUrl(source: URLSource, options?: IngestOptions): Promise<URLIngestResult[]>;
160
+ /**
161
+ * Handle webhook payload for real-time document updates
162
+ * Useful for product inventory updates, price changes, etc.
163
+ */
164
+ handleWebhook(payload: any, source: string, options?: IngestOptions): Promise<IngestResult[]>;
165
+ }
166
+
167
+ type AIMessage = UserModelMessage | AssistantModelMessage;
168
+ /**
169
+ * Thread class representing a conversation thread
170
+ */
171
+ declare class Thread {
172
+ private data;
173
+ private storage;
174
+ constructor(data: ThreadData, storage: StorageAdapter);
175
+ /**
176
+ * Create a new thread
177
+ */
178
+ static create(config: ThreadConfig, storage: StorageAdapter): Promise<Thread>;
179
+ /**
180
+ * Load an existing thread by ID
181
+ */
182
+ static load(threadId: string, storage: StorageAdapter): Promise<Thread | null>;
183
+ /**
184
+ * Update thread properties
185
+ */
186
+ update(updates: Partial<ThreadConfig>): Promise<void>;
187
+ /**
188
+ * Delete this thread
189
+ */
190
+ delete(): Promise<void>;
191
+ /**
192
+ * Add a message to the thread
193
+ */
194
+ addMessage(role: MessageRole, content: string, attachments?: MessageAttachment[]): Promise<string>;
195
+ /**
196
+ * Get messages from this thread
197
+ */
198
+ getMessages(limit?: number): Promise<MessageData[]>;
199
+ /**
200
+ * Get conversation context for AI (formatted for Vercel AI SDK)
201
+ */
202
+ getConversationContext(maxMessages?: number): Promise<AIMessage[]>;
203
+ /**
204
+ * Update thread name
205
+ */
206
+ updateName(name: string): Promise<void>;
207
+ /**
208
+ * Update pending status
209
+ */
210
+ updatePendingStatus(isPending: boolean): Promise<void>;
211
+ /**
212
+ * Get thread ID
213
+ */
214
+ get id(): string;
215
+ /**
216
+ * Get thread name
217
+ */
218
+ get name(): string | undefined;
219
+ /**
220
+ * Get agent ID
221
+ */
222
+ get agentId(): string;
223
+ /**
224
+ * Get messages (cached from last load)
225
+ */
226
+ get messages(): MessageData[];
227
+ /**
228
+ * Check if thread is pending
229
+ */
230
+ get isPending(): boolean;
231
+ /**
232
+ * Get all thread data
233
+ */
234
+ toJSON(): ThreadData;
235
+ }
236
+
237
+ /**
238
+ * Main SDK Client for managing AI agents and conversations
239
+ */
240
+ declare class AgentClient {
241
+ private storage;
242
+ private providerFactory;
243
+ private providers;
244
+ constructor(config: ClientConfig);
245
+ private validateConfig;
246
+ /**
247
+ * Create a new agent
248
+ */
249
+ createAgent(config: Omit<AgentConfig, 'provider'> & {
250
+ provider?: AgentConfig['provider'];
251
+ }): Promise<Agent>;
252
+ /**
253
+ * Get an agent by ID
254
+ */
255
+ getAgent(agentId: string): Promise<Agent>;
256
+ /**
257
+ * List agents for a user
258
+ */
259
+ listAgents(userId: string, organizationId?: string): Promise<AgentData[]>;
260
+ /**
261
+ * Delete an agent
262
+ */
263
+ deleteAgent(agentId: string): Promise<void>;
264
+ /**
265
+ * Create a new thread
266
+ */
267
+ createThread(config: ThreadConfig): Promise<Thread>;
268
+ /**
269
+ * Get a thread by ID
270
+ */
271
+ getThread(threadId: string | undefined): Promise<Thread>;
272
+ /**
273
+ * List threads by user or agent
274
+ */
275
+ listThreads(filters: {
276
+ userId?: string;
277
+ agentId?: string;
278
+ organizationId?: string;
279
+ }): Promise<ThreadData[]>;
280
+ /**
281
+ * Delete a thread
282
+ */
283
+ deleteThread(threadId: string): Promise<void>;
284
+ /**
285
+ * Send a message and get a response (non-streaming)
286
+ */
287
+ chat(request: ChatRequest): Promise<ChatResponse>;
288
+ /**
289
+ * Send a message and stream the response
290
+ */
291
+ chatStream(request: ChatRequest, callbacks: StreamCallbacks): Promise<void>;
292
+ /**
293
+ * Generate a name for a thread based on its first message
294
+ */
295
+ generateThreadName(firstMessage: string): Promise<string>;
296
+ /**
297
+ * Get list of configured providers
298
+ */
299
+ getConfiguredProviders(): ProviderType[];
300
+ /**
301
+ * Check if a provider is configured
302
+ */
303
+ isProviderConfigured(provider: string): boolean;
304
+ }
305
+
306
+ /**
307
+ * Plugin Manager
308
+ * Manages and orchestrates plugin execution for agents
309
+ */
310
+ declare class PluginManager {
311
+ private plugins;
312
+ constructor(plugins?: Plugin[]);
313
+ getRAGPlugins(): RAGPlugin[];
314
+ getToolPlugins(): ToolPlugin[];
315
+ getMiddlewarePlugins(): MiddlewarePlugin[];
316
+ getAnalyticsPlugins(): AnalyticsPlugin[];
317
+ getAllPlugins(): Plugin[];
318
+ /**
319
+ * Execute all RAG plugins and merge their contexts
320
+ * Returns an array of context strings, one per plugin
321
+ */
322
+ executeRAG(message: string, options: {
323
+ agentId: string;
324
+ threadId?: string;
325
+ filters?: Record<string, any>;
326
+ metadata?: Record<string, any>;
327
+ }): Promise<{
328
+ contexts: string[];
329
+ allMetadata: Record<string, any>[];
330
+ }>;
331
+ /**
332
+ * Execute all middleware plugins before request
333
+ */
334
+ executeBeforeRequest(messages: any[], context: {
335
+ agentId: string;
336
+ threadId?: string;
337
+ }): Promise<{
338
+ messages: any[];
339
+ metadata?: any;
340
+ }>;
341
+ /**
342
+ * Execute all middleware plugins after response
343
+ */
344
+ executeAfterResponse(response: string, context: {
345
+ agentId: string;
346
+ threadId?: string;
347
+ metadata?: any;
348
+ }): Promise<{
349
+ response: string;
350
+ metadata?: any;
351
+ }>;
352
+ /**
353
+ * Track request in all analytics plugins
354
+ */
355
+ trackRequest(data: {
356
+ agentId: string;
357
+ threadId?: string;
358
+ message: string;
359
+ timestamp: Date;
360
+ }): Promise<void>;
361
+ /**
362
+ * Track response in all analytics plugins
363
+ */
364
+ trackResponse(data: {
365
+ agentId: string;
366
+ threadId?: string;
367
+ response: string;
368
+ latency: number;
369
+ tokensUsed?: number;
370
+ timestamp: Date;
371
+ }): Promise<void>;
372
+ /**
373
+ * Check if any plugins of a specific type exist
374
+ */
375
+ hasPluginsOfType(type: Plugin['type']): boolean;
376
+ /**
377
+ * Get plugin by name
378
+ */
379
+ getPluginByName(name: string): Plugin | undefined;
380
+ }
381
+
382
+ /**
383
+ * Configuration for the default RAG plugin
384
+ */
385
+ interface DefaultRAGConfig {
386
+ /**
387
+ * API key for the embedding provider
388
+ */
389
+ embeddingProviderApiKey: string;
390
+ /**
391
+ * Embedding provider to use
392
+ * @default 'openai'
393
+ */
394
+ embeddingProvider?: 'openai';
395
+ /**
396
+ * OpenAI embedding model
397
+ * @default 'text-embedding-3-small'
398
+ */
399
+ embeddingModel?: string;
400
+ /**
401
+ * Number of results to return from search
402
+ * @default 5
403
+ */
404
+ limit?: number;
405
+ }
406
+ /**
407
+ * Default RAG Plugin
408
+ *
409
+ * A minimal, zero-config RAG plugin that provides basic document storage,
410
+ * embedding generation, and semantic search capabilities.
411
+ *
412
+ * Features:
413
+ * - In-memory vector storage (for simplicity)
414
+ * - OpenAI embeddings
415
+ * - Cosine similarity search
416
+ * - Simple ingestion and retrieval
417
+ *
418
+ * For production use cases with advanced features (attribute extraction,
419
+ * rescoring, reranking, etc.), use specialized plugins like @snap-agent/rag-ecommerce
420
+ */
421
+ declare class DefaultRAGPlugin implements RAGPlugin {
422
+ name: string;
423
+ type: "rag";
424
+ private config;
425
+ private documents;
426
+ constructor(config: DefaultRAGConfig);
427
+ /**
428
+ * Retrieve context for a message using semantic search
429
+ */
430
+ retrieveContext(message: string, options: {
431
+ agentId: string;
432
+ threadId?: string;
433
+ filters?: Record<string, any>;
434
+ metadata?: Record<string, any>;
435
+ }): Promise<RAGContext>;
436
+ /**
437
+ * Ingest documents into the RAG system
438
+ */
439
+ ingest(documents: RAGDocument[], options?: IngestOptions): Promise<IngestResult>;
440
+ /**
441
+ * Update a single document
442
+ */
443
+ update(id: string, document: Partial<RAGDocument>, options?: IngestOptions): Promise<void>;
444
+ /**
445
+ * Delete document(s) by ID
446
+ */
447
+ delete(ids: string | string[], options?: IngestOptions): Promise<number>;
448
+ /**
449
+ * Generate embedding using OpenAI
450
+ */
451
+ private generateEmbedding;
452
+ /**
453
+ * Calculate cosine similarity between two vectors
454
+ */
455
+ private cosineSimilarity;
456
+ /**
457
+ * Get statistics about stored documents
458
+ */
459
+ getStats(): Record<string, any>;
460
+ /**
461
+ * Clear all documents for an agent
462
+ */
463
+ clearAgent(agentId: string): void;
464
+ /**
465
+ * Clear all documents
466
+ */
467
+ clearAll(): void;
468
+ }
469
+
470
+ declare function createClient(config: ClientConfig): AgentClient;
471
+
472
+ export { Agent, AgentClient, AgentConfig, AgentData, AgentFile, AnalyticsPlugin, BulkOperation, BulkResult, ChatRequest, ChatResponse, ClientConfig, type DefaultRAGConfig, DefaultRAGPlugin, IngestOptions, IngestResult, MessageAttachment, MessageData, MessageRole, MiddlewarePlugin, Models, Plugin, PluginManager, ProviderConfig, ProviderFactory, ProviderType, RAGContext, RAGDocument, RAGPlugin, StorageAdapter, StreamCallbacks, Thread, ThreadConfig, ThreadData, ToolPlugin, createClient };