File size: 11,215 Bytes
7c012de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e9dcae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c012de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/**
 * Smart Document Ingestion Service
 * Combines Modal's serverless compute with Nebius AI analysis
 */

import { modalClient, type DocumentProcessingTask } from './modal-client';
import { nebiusClient } from './nebius-client';
import { storage } from './storage';
import type { InsertDocument } from '@shared/schema';

interface DocumentUpload {
  file: Buffer | string;
  filename: string;
  contentType: string;
  metadata?: Record<string, any>;
}

interface IngestionResult {
  documentId: number;
  processingTaskId: string;
  analysis: {
    category: string;
    summary: string;
    keyPoints: string[];
    qualityScore: number;
  };
  embeddings: number[];
  status: 'processing' | 'completed' | 'failed';
}

class SmartIngestionService {
  /**
   * Process uploaded document with full AI pipeline
   */
  async ingestDocument(upload: DocumentUpload): Promise<IngestionResult> {
    try {
      // Step 1: Extract text content using Modal OCR if needed
      let textContent: string;
      
      if (upload.contentType.includes('pdf') || upload.contentType.includes('image')) {
        const ocrTask = await modalClient.extractTextFromDocuments([
          this.uploadToTempStorage(upload)
        ]);
        
        // Wait for OCR completion (simplified for demo)
        textContent = await this.waitForTaskCompletion(ocrTask.taskId);
      } else {
        textContent = upload.file.toString();
      }

      // Step 2: Analyze document using Nebius AI
      const [
        categoryAnalysis,
        summaryAnalysis,
        keyPointsAnalysis,
        qualityAnalysis
      ] = await Promise.all([
        nebiusClient.analyzeDocument({
          content: textContent,
          analysisType: 'classification'
        }),
        nebiusClient.analyzeDocument({
          content: textContent,
          analysisType: 'summary'
        }),
        nebiusClient.analyzeDocument({
          content: textContent,
          analysisType: 'key_points'
        }),
        nebiusClient.analyzeDocument({
          content: textContent,
          analysisType: 'quality_score'
        })
      ]);

      // Step 3: Generate embeddings using Nebius
      const embeddingResponse = await nebiusClient.createEmbeddings({
        input: textContent.substring(0, 8000), // Limit for token constraints
        model: 'text-embedding-3-large'
      });

      // Step 4: Create document in storage
      const documentData: InsertDocument = {
        title: upload.filename,
        content: textContent,
        sourceType: this.extractSourceType(categoryAnalysis.analysis),
        source: upload.filename,
        url: upload.metadata?.url,
        metadata: {
          ...upload.metadata,
          analysis: {
            category: categoryAnalysis.analysis,
            summary: summaryAnalysis.analysis,
            keyPoints: keyPointsAnalysis.analysis,
            qualityScore: this.extractQualityScore(qualityAnalysis.analysis)
          },
          contentType: upload.contentType,
          fileSize: Buffer.isBuffer(upload.file) ? upload.file.length : upload.file.length,
          processingTimestamp: new Date().toISOString()
        }
      };

      const document = await storage.createDocument(documentData);

      // Step 5: Queue vector indexing with Modal
      const indexTask = await modalClient.buildVectorIndex([{
        id: document.id.toString(),
        content: textContent,
        embeddings: embeddingResponse.data[0].embedding,
        metadata: document.metadata
      }]);

      return {
        documentId: document.id,
        processingTaskId: indexTask.taskId,
        analysis: {
          category: this.extractCategory(categoryAnalysis.analysis),
          summary: summaryAnalysis.analysis,
          keyPoints: this.parseKeyPoints(keyPointsAnalysis.analysis),
          qualityScore: this.extractQualityScore(qualityAnalysis.analysis)
        },
        embeddings: embeddingResponse.data[0].embedding,
        status: 'completed'
      };

    } catch (error) {
      console.error('Document ingestion failed:', error);
      throw new Error(`Ingestion failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * Batch process multiple documents using Modal's distributed compute
   */
  async batchIngestDocuments(uploads: DocumentUpload[]): Promise<{
    taskId: string;
    estimatedCompletion: Date;
    documentsQueued: number;
  }> {
    // Prepare documents for batch processing
    const documents = uploads.map((upload, index) => ({
      id: `batch_${Date.now()}_${index}`,
      content: upload.file.toString(),
      metadata: {
        filename: upload.filename,
        contentType: upload.contentType,
        ...upload.metadata
      }
    }));

    // Submit to Modal for distributed processing
    const task = await modalClient.batchProcessDocuments({
      documents,
      modelName: 'text-embedding-3-large',
      batchSize: 20
    });

    return {
      taskId: task.taskId,
      estimatedCompletion: new Date(Date.now() + uploads.length * 2000), // 2s per doc estimate
      documentsQueued: uploads.length
    };
  }

  /**
   * Enhanced search using both Modal vector search and Nebius query understanding
   */
  async enhancedSearch(query: string, options: {
    maxResults?: number;
    searchType?: 'semantic' | 'hybrid';
    useQueryEnhancement?: boolean;
  } = {}): Promise<{
    results: any[];
    enhancedQuery?: any;
    searchInsights?: any;
  }> {
    const { maxResults = 10, searchType = 'semantic', useQueryEnhancement = true } = options;

    // Step 1: Enhance query using Nebius AI
    let enhancedQueryData;
    let searchQuery = query;
    
    if (useQueryEnhancement) {
      enhancedQueryData = await nebiusClient.enhanceQuery(query);
      searchQuery = enhancedQueryData.enhancedQuery;
    }

    // Step 2: Perform vector search using Modal's high-performance endpoint
    let modalResults = [];
    
    // Skip Modal if not configured properly
    if (process.env.MODAL_TOKEN_ID && process.env.MODAL_TOKEN_SECRET) {
      try {
        console.log('πŸ”„ Attempting Modal vector search...');
        const modalResponse = await modalClient.vectorSearch(
          searchQuery,
          'main_index', // Assuming we have a main index
          maxResults
        );
        modalResults = modalResponse.results || [];
        console.log(`βœ… Modal search returned ${modalResults.length} results`);
      } catch (error) {
        console.log('❌ Modal search failed:', error instanceof Error ? error.message : String(error));
        console.log('πŸ”„ Falling back to local search');
      }
    } else {
      console.log('⚠️ Modal not configured, using local search only');
    }

    // Step 3: Get local results as backup/supplement
    const localResults = await storage.searchDocuments({
      query: searchQuery,
      searchType: searchType as "semantic" | "keyword" | "hybrid",
      limit: maxResults,
      offset: 0
    });

    // Step 4: Combine and rank results using Nebius AI
    const combinedResults = [...modalResults, ...localResults.results]
      .slice(0, maxResults * 2); // Get more for re-ranking

    // Step 5: Score relevance using Nebius AI
    const scoredResults = await Promise.all(
      combinedResults.map(async (result) => {
        try {
          const relevanceData = await nebiusClient.scoreCitationRelevance(query, {
            title: result.title,
            content: result.content,
            snippet: result.snippet || result.content.substring(0, 200)
          });
          
          return {
            ...result,
            relevanceScore: relevanceData.relevanceScore,
            aiExplanation: relevanceData.explanation,
            keyReasons: relevanceData.keyReasons
          };
        } catch (error) {
          return { ...result, relevanceScore: result.relevanceScore || 0.5 };
        }
      })
    );

    // Step 6: Sort by AI-enhanced relevance scores
    const finalResults = scoredResults
      .sort((a, b) => (b.relevanceScore || 0) - (a.relevanceScore || 0))
      .slice(0, maxResults);

    return {
      results: finalResults,
      enhancedQuery: enhancedQueryData,
      searchInsights: {
        totalResults: finalResults.length,
        avgRelevanceScore: finalResults.reduce((acc, r) => acc + (r.relevanceScore || 0), 0) / finalResults.length,
        modalResultsCount: modalResults.length,
        localResultsCount: localResults.results.length
      }
    };
  }

  /**
   * Generate research synthesis using Nebius AI
   */
  async generateResearchSynthesis(query: string, documents: any[]): Promise<any> {
    if (documents.length === 0) {
      return {
        synthesis: 'No documents available for synthesis',
        keyFindings: [],
        gaps: ['Insufficient source material'],
        recommendations: ['Search for more relevant documents']
      };
    }

    return nebiusClient.generateResearchInsights(
      documents.map(doc => ({
        title: doc.title,
        content: doc.content,
        metadata: doc.metadata
      })),
      query
    );
  }

  // Helper methods
  private uploadToTempStorage(upload: DocumentUpload): string {
    // In production, upload to cloud storage and return URL
    return `temp://documents/${upload.filename}`;
  }

  private async waitForTaskCompletion(taskId: string): Promise<string> {
    // Simplified polling for demo - in production use webhooks
    const maxAttempts = 30;
    let attempts = 0;
    
    while (attempts < maxAttempts) {
      const status = await modalClient.getTaskStatus(taskId);
      if (status.status === 'completed') {
        return status.result?.extractedText || 'Text extraction completed';
      } else if (status.status === 'failed') {
        throw new Error(`Task failed: ${status.error}`);
      }
      
      await new Promise(resolve => setTimeout(resolve, 2000));
      attempts++;
    }
    
    throw new Error('Task timed out');
  }

  private extractSourceType(analysis: string): string {
    const types: Record<string, string> = {
      'academic_paper': 'academic',
      'technical_documentation': 'technical',
      'research_report': 'research',
      'code_repository': 'code',
      'blog_post': 'web',
      'news_article': 'news'
    };
    
    for (const [key, value] of Object.entries(types)) {
      if (analysis.toLowerCase().includes(key)) {
        return value;
      }
    }
    
    return 'general';
  }

  private extractCategory(analysis: string): string {
    return analysis.split('\n')[0] || 'Unknown';
  }

  private parseKeyPoints(analysis: string): string[] {
    return analysis.split('\n')
      .filter(line => line.trim().startsWith('-') || line.trim().startsWith('β€’') || line.match(/^\d+\./))
      .map(line => line.replace(/^[-β€’\d.]\s*/, '').trim())
      .slice(0, 5);
  }

  private extractQualityScore(analysis: string): number {
    const scoreMatch = analysis.match(/(\d+(?:\.\d+)?)\s*\/?\s*10/);
    if (scoreMatch) {
      return parseFloat(scoreMatch[1]);
    }
    return 7.0; // Default score
  }
}

export const smartIngestionService = new SmartIngestionService();
export type { DocumentUpload, IngestionResult };