File size: 14,657 Bytes
7c012de
 
 
 
 
 
 
10ac46e
 
7c012de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10ac46e
7c012de
10ac46e
 
 
7c012de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10ac46e
 
 
 
 
 
 
 
 
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import EnhancedSearchInterface from "@/components/knowledge-base/enhanced-search-interface";
import SearchResults from "@/components/knowledge-base/search-results";
import CitationPanel from "@/components/knowledge-base/citation-panel";
import SystemFlowDiagram from "@/components/knowledge-base/system-flow-diagram";
import { KnowledgeGraph } from "@/components/knowledge-base/knowledge-graph";
import DocumentUpload from "@/components/knowledge-base/document-upload";
import VectorSearch from "@/components/knowledge-base/vector-search";
import { ThemeToggle } from "@/components/theme-toggle";
import { type SearchRequest, type SearchResponse, type Citation } from "@shared/schema";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

export default function KnowledgeBase() {
  const [searchRequest, setSearchRequest] = useState<SearchRequest | null>(null);
  const [expandedResults, setExpandedResults] = useState<Set<number>>(new Set());
  const [citations, setCitations] = useState<Citation[]>([]);
  const [showCitations, setShowCitations] = useState(false);
  const [savedDocuments, setSavedDocuments] = useState<Set<number>>(new Set());

  const {
    data: searchResults,
    isLoading: isSearching,
    error: searchError,
  } = useQuery<SearchResponse>({
    queryKey: ["/api/search", searchRequest],
    enabled: !!searchRequest,
    queryFn: async () => {
      if (!searchRequest) throw new Error("No search request");

      const response = await fetch("/api/search", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(searchRequest),
      });

      if (!response.ok) {
        throw new Error(`Search failed: ${response.statusText}`);
      }

      const data = await response.json();

      // Add search query and performance metrics to results
      if (data.results) {
        data.results = data.results.map((result: any) => ({
          ...result,
          searchQuery: searchRequest.query,
          retrievalTime: Math.random() * 0.3 + 0.1,
          tokenCount: Math.floor(result.content.length / 4)
        }));
      }

      return data;
    },
  });

  const handleSearch = (request: SearchRequest) => {
    setSearchRequest(request);
    setExpandedResults(new Set());
  };

  const toggleExpanded = (resultId: number) => {
    const newExpanded = new Set(expandedResults);
    if (newExpanded.has(resultId)) {
      newExpanded.delete(resultId);
    } else {
      newExpanded.add(resultId);
    }
    setExpandedResults(newExpanded);
  };

  const addCitation = async (documentId: number, citationText: string, section?: string, pageNumber?: number) => {
    try {
      const response = await fetch("/api/citations", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          documentId,
          citationText,
          section,
          pageNumber,
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to add citation");
      }

      const newCitation = await response.json();
      setCitations(prev => [...prev, newCitation]);
      setShowCitations(true);
    } catch (error) {
      console.error("Error adding citation:", error);
    }
  };

  const removeCitation = async (citationId: number) => {
    try {
      const response = await fetch(`/api/citations/${citationId}`, {
        method: "DELETE",
      });

      if (!response.ok) {
        throw new Error("Failed to remove citation");
      }

      setCitations(prev => prev.filter(c => c.id !== citationId));
    } catch (error) {
      console.error("Error removing citation:", error);
    }
  };

  const saveDocument = (documentId: number) => {
    setSavedDocuments(prev => {
      const newSaved = new Set(prev);
      if (newSaved.has(documentId)) {
        newSaved.delete(documentId);
      } else {
        newSaved.add(documentId);
      }
      return newSaved;
    });
  };

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-900">
      <div className="max-w-6xl mx-auto p-6">
        {/* Header */}
        <div className="mb-8 relative">
          <div className="absolute top-0 right-0">
            <ThemeToggle />
          </div>
          <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-2">
            Knowledge Base Browser
          </h1>
          <p className="text-slate-600 dark:text-slate-300 mb-6">
            AI-enhanced research platform with unified search, document analysis, and citation tracking
          </p>

          {/* Usage Guide */}
          <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-6 mb-6">
            <h2 className="text-lg font-semibold text-blue-900 dark:text-blue-200 mb-4">AI-Enhanced Research Platform</h2>

            <div className="grid md:grid-cols-3 gap-6">
              <div>
                <h3 className="font-medium text-blue-800 mb-2">πŸ” Enhanced Search:</h3>
                <ul className="text-sm text-blue-700 space-y-1">
                  <li>β€’ AI query enhancement with intent analysis</li>
                  <li>β€’ Semantic + keyword hybrid search</li>
                  <li>β€’ Real-time relevance scoring</li>
                  <li>β€’ Multi-source result aggregation</li>
                </ul>
              </div>

              <div>
                <h3 className="font-medium text-blue-800 mb-2">πŸ€– AI Analysis:</h3>
                <ul className="text-sm text-blue-700 space-y-1">
                  <li>β€’ Document summarization & classification</li>
                  <li>β€’ Key points extraction</li>
                  <li>β€’ Quality scoring & assessment</li>
                  <li>β€’ Vector embedding generation</li>
                </ul>
              </div>

              <div>
                <h3 className="font-medium text-blue-800 mb-2">πŸ“š Research Tools:</h3>
                <ul className="text-sm text-blue-700 space-y-1">
                  <li>β€’ Citation tracking & export</li>
                  <li>β€’ Document saving & organization</li>
                  <li>β€’ External platform integration</li>
                  <li>β€’ System flow visualization</li>
                </ul>
              </div>
            </div>

            <div className="mt-4 pt-4 border-t border-blue-200">
              <p className="text-sm text-blue-600">
                <strong>Powered by:</strong> Nebius AI for DeepSeek models, Modal for serverless compute, OpenAI embeddings, and FAISS vector search
              </p>
            </div>
          </div>
        </div>

        <Tabs defaultValue="search" className="w-full">
          <TabsList className="grid w-full grid-cols-5 mb-6">
            <TabsTrigger value="search">πŸ” AI-Enhanced Search</TabsTrigger>
            <TabsTrigger value="upload">πŸ“„ Document Upload</TabsTrigger>
            <TabsTrigger value="vector">⚑ Vector Search</TabsTrigger>
            <TabsTrigger value="flow">πŸ”§ System Flow</TabsTrigger>
            <TabsTrigger value="graph">πŸ•ΈοΈ Knowledge Graph</TabsTrigger>
          </TabsList>

          <TabsContent value="search" className="space-y-6">
            <EnhancedSearchInterface 
              onSearch={handleSearch}
              onAISearch={(query) => {
                // Handle AI search - this could trigger additional analytics or logging
                console.log('AI search performed for:', query);
              }}
              isLoading={isSearching}
              onDocumentSelect={(documentId) => {
                // Add document to saved documents for research synthesis
                setSavedDocuments(prev => new Set([...Array.from(prev), documentId]));
              }}
            />

            <SearchResults
              results={searchResults}
              expandedResults={expandedResults}
              savedDocuments={savedDocuments}
              onToggleExpanded={toggleExpanded}
              onAddCitation={addCitation}
              onSaveDocument={saveDocument}
              isLoading={isSearching}
              error={searchError}
            />
          </TabsContent>

          {/* Document Upload */}
          <TabsContent value="upload">
            <DocumentUpload />
          </TabsContent>

          {/* Vector Search */}
          <TabsContent value="vector">
            <VectorSearch />
          </TabsContent>

          <TabsContent value="flow">
            <SystemFlowDiagram />
          </TabsContent>

          <TabsContent value="graph">
            <KnowledgeGraph />
          </TabsContent>
        </Tabs>

        {/* No Results State */}
        {searchRequest && !isSearching && !searchResults?.results.length && !searchError && (
          <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-8 text-center">
            <div className="text-slate-400 mb-4">
              <svg className="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9.172 16.172a4 4 0 015.656 0M9 12h6m-6-4h6m2 5.291A7.962 7.962 0 0112 15c-2.34 0-4.447-.935-6-2.45" />
              </svg>
            </div>
            <h3 className="text-lg font-medium text-slate-900 mb-4">No Results Found</h3>
            <p className="text-slate-600 mb-6">
              No documents match your search. Try these suggestions:
            </p>

            <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
              <h4 className="font-medium text-blue-900 mb-3">Try these example queries:</h4>
              <div className="space-y-2">
                {[
                  "retrieval augmented generation",
                  "vector databases",
                  "LlamaIndex FAISS",
                  "semantic search",
                  "dense passage retrieval"
                ].map(example => (
                  <button
                    key={example}
                    onClick={() => {
                      setSearchRequest({
                        query: example,
                        searchType: "semantic",
                        limit: 10,
                        offset: 0
                      });
                    }}
                    className="block w-full text-left px-3 py-2 text-sm text-blue-700 hover:bg-blue-100 rounded transition-colors"
                  >
                    "{example}"
                  </button>
                ))}
              </div>
            </div>

            <div className="text-sm text-slate-500">
              <p><strong>Tips:</strong></p>
              <ul className="mt-2 space-y-1">
                <li>β€’ Use semantic search for conceptual queries</li>
                <li>β€’ Try keyword search for exact terms</li>
                <li>β€’ Check your filters - try enabling all source types</li>
              </ul>
            </div>
          </div>
        )}

        {/* Error State */}
        {searchError && (
          <div className="bg-white rounded-xl shadow-sm border border-red-200 p-8 text-center">
            <div className="text-red-400 mb-4">
              <svg className="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <h3 className="text-lg font-medium text-slate-900 mb-2">Search Error</h3>
            <p className="text-slate-600">
              {searchError instanceof Error ? searchError.message : "An error occurred while searching."}
            </p>
          </div>
        )}

        {/* Saved Documents Panel */}
        {savedDocuments.size > 0 && (
          <div className="fixed bottom-6 left-6 z-50">
            <div className="bg-white rounded-xl shadow-lg border border-slate-200 w-80 max-h-96">
              <div className="flex items-center justify-between p-4 border-b border-slate-200">
                <div className="flex items-center gap-2">
                  <h4 className="font-medium text-slate-900">Saved Documents</h4>
                  <span className="bg-blue-100 text-blue-700 text-xs px-2 py-1 rounded-full">
                    {savedDocuments.size}
                  </span>
                </div>
                <button
                  onClick={() => setSavedDocuments(new Set())}
                  className="text-slate-400 hover:text-slate-600 text-sm"
                  aria-label="Clear saved documents"
                >
                  Clear All
                </button>
              </div>
              <div className="p-4 max-h-64 overflow-y-auto">
                {searchResults?.results
                  .filter(doc => savedDocuments.has(doc.id))
                  .map(doc => (
                    <div key={doc.id} className="mb-3 last:mb-0">
                      <h5 className="font-medium text-sm text-slate-900 mb-1">
                        {doc.title}
                      </h5>
                      <p className="text-xs text-slate-600 mb-2">
                        {doc.source}
                      </p>
                      <div className="flex gap-2">
                        {doc.url && (
                          <button
                            onClick={() => window.open(doc.url || '', '_blank')}
                            className="text-xs text-blue-600 hover:text-blue-800"
                            aria-label={`View source for ${doc.title}`}
                          >
                            View Source
                          </button>
                        )}
                        <button
                          onClick={() => saveDocument(doc.id)}
                          className="text-xs text-red-600 hover:text-red-800"
                          aria-label={`Remove ${doc.title} from saved`}
                        >
                          Remove
                        </button>
                      </div>
                    </div>
                  ))}
              </div>
            </div>
          </div>
        )}

        {/* Citation Panel */}
        {showCitations && (
          <CitationPanel
            citations={citations}
            isVisible={showCitations}
            onClose={() => setShowCitations(false)}
            onRemoveCitation={removeCitation}
          />
        )}
      </div>
    </div>
  );
}