File size: 13,906 Bytes
f871fed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
373
374
375
376
'use client'

import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { useAsk } from '@/lib/hooks/use-ask'
import { useModels } from '@/lib/hooks/use-models'
import { LoadingSpinner } from '@/components/common/LoadingSpinner'
import { 
  Sparkles, 
  Brain,
  Lightbulb,
  Network
} from 'lucide-react'
import ReactMarkdown from 'react-markdown'

interface KnowledgeGraphInsightsPanelProps {
  notebookId: string
  graphStats: {
    nodeCount: number
    edgeCount: number
    topConcepts?: Array<{ 
      label: string
      mentions: number
      type?: string
      importance?: number
    }>
    nodeTypes?: Record<string, number>
    relationshipTypes?: Record<string, number>
    allNodes?: Array<{
      label: string
      type: string
      mentions: number
    }>
  }
}

export function KnowledgeGraphInsightsPanel({ 
  notebookId, 
  graphStats 
}: KnowledgeGraphInsightsPanelProps) {
  const [question, setQuestion] = useState('')
  const [selectedStrategyModel, setSelectedStrategyModel] = useState<string>('')
  const [selectedAnswerModel, setSelectedAnswerModel] = useState<string>('')
  const [selectedFinalModel, setSelectedFinalModel] = useState<string>('')

  const askHook = useAsk()
  const askState = {
    isStreaming: askHook.isStreaming,
    strategy: askHook.strategy,
    answers: askHook.answers,
    finalAnswer: askHook.finalAnswer,
    error: askHook.error
  }
  const { sendAsk, sendDirectAsk } = askHook
  const { data: models, isLoading: modelsLoading } = useModels()

  const handleAsk = async () => {
    if (!question.trim()) return

    // Build context from knowledge graph
    const graphContext = buildGraphContext()
    const contextualQuestion = `${graphContext}\n\nQuestion: ${question}`

    if (!selectedStrategyModel || !selectedAnswerModel || !selectedFinalModel) {
      // Use first available model as default
      const defaultModel = models?.[0]?.id
      await sendAsk(contextualQuestion, {
        strategy: selectedStrategyModel || defaultModel || 'gpt-4o',
        answer: selectedAnswerModel || defaultModel || 'gpt-4o',
        finalAnswer: selectedFinalModel || defaultModel || 'gpt-4o',
      })
    } else {
      await sendAsk(contextualQuestion, {
        strategy: selectedStrategyModel,
        answer: selectedAnswerModel,
        finalAnswer: selectedFinalModel,
      })
    }
  }

  const handleDirectAsk = async () => {
    if (!question.trim()) return
    
    // Build context from knowledge graph
    const graphContext = buildGraphContext()
    const contextualQuestion = `${graphContext}\n\nQuestion: ${question}`
    
    await sendDirectAsk(contextualQuestion, selectedAnswerModel)
  }

  // Build context string from graph statistics
  const buildGraphContext = () => {
    const { nodeCount, edgeCount, topConcepts, nodeTypes, relationshipTypes, allNodes } = graphStats
    
    let context = `You are analyzing a Knowledge Graph with the following structure:\n\n`
    context += `## Graph Statistics:\n`
    context += `- Total Nodes: ${nodeCount}\n`
    context += `- Total Connections: ${edgeCount}\n\n`
    
    // Node types breakdown
    if (nodeTypes && Object.keys(nodeTypes).length > 0) {
      context += `## Node Types Distribution:\n`
      Object.entries(nodeTypes).forEach(([type, count]) => {
        context += `- ${type}: ${count} nodes\n`
      })
      context += `\n`
    }
    
    // Top concepts with details
    if (topConcepts && topConcepts.length > 0) {
      context += `## Top ${Math.min(10, topConcepts.length)} Most Important Concepts:\n`
      topConcepts.forEach((concept, index) => {
        context += `${index + 1}. **${concept.label}**`
        if (concept.type) context += ` [${concept.type}]`
        context += ` - ${concept.mentions} mentions`
        if (concept.importance) context += ` (importance: ${Math.round(concept.importance * 100)}%)`
        context += `\n`
      })
      context += `\n`
    }
    
    // Relationship types
    if (relationshipTypes && Object.keys(relationshipTypes).length > 0) {
      context += `## Relationship Types:\n`
      Object.entries(relationshipTypes)
        .sort(([, a], [, b]) => b - a)
        .slice(0, 10)
        .forEach(([type, count]) => {
          context += `- ${type}: ${count} connections\n`
        })
      context += `\n`
    }
    
    // All concepts (for comprehensive understanding)
    if (allNodes && allNodes.length > 0 && allNodes.length <= 50) {
      context += `## All Concepts in Graph:\n`
      allNodes.forEach(node => {
        context += `- ${node.label} [${node.type}]\n`
      })
      context += `\n`
    }
    
    context += `Please answer the following question based on this knowledge graph structure and content.\n`
    
    return context
  }

  const suggestedQuestions = [
    "What are the main concepts in this knowledge graph?",
    "How are the key ideas connected?",
    "Summarize the relationships between the top concepts",
    "What patterns can you identify in the graph?",
    "Explain the most important nodes and their connections"
  ]

  return (
    <Card className="h-full">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg flex items-center gap-2">
            <Brain className="h-5 w-5 text-purple-500" />
            Knowledge Graph Insights
          </CardTitle>
          <Badge variant="secondary" className="gap-1">
            <Network className="h-3 w-3" />
            {graphStats.nodeCount} nodes
          </Badge>
        </div>
        <p className="text-sm text-muted-foreground">
          Ask AI questions about your knowledge graph
        </p>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Quick Stats */}
        <div className="grid grid-cols-3 gap-3 p-3 bg-muted/30 rounded-lg">
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-500">{graphStats.nodeCount}</div>
            <div className="text-xs text-muted-foreground">Nodes</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-green-500">{graphStats.edgeCount}</div>
            <div className="text-xs text-muted-foreground">Connections</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-purple-500">
              {graphStats.topConcepts?.length || 0}
            </div>
            <div className="text-xs text-muted-foreground">Top Concepts</div>
          </div>
        </div>

        <Separator />

        {/* Ask AI Section */}
        <div className="space-y-4">
          {/* Model Selection */}
          <div className="space-y-2">
            <label className="text-sm font-medium">AI Model</label>
            <Select
              value={selectedAnswerModel}
              onValueChange={setSelectedAnswerModel}
              disabled={modelsLoading}
            >
              <SelectTrigger>
                <SelectValue placeholder="Select model for answers" />
              </SelectTrigger>
              <SelectContent>
                {models?.map((model) => (
                  <SelectItem key={model.id} value={model.id}>
                    {model.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

            {/* Question Input */}
            <div className="space-y-2">
              <label className="text-sm font-medium">Your Question</label>
              <Textarea
                placeholder="Ask a question about your knowledge graph..."
                value={question}
                onChange={(e) => setQuestion(e.target.value)}
                className="min-h-[100px] resize-none"
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
                    handleDirectAsk()
                  }
                }}
              />
            </div>

            {/* Suggested Questions */}
            <div className="space-y-2">
              <label className="text-sm font-medium flex items-center gap-2">
                <Lightbulb className="h-4 w-4 text-yellow-500" />
                Suggested Questions
              </label>
              <ScrollArea className="h-[120px]">
                <div className="space-y-2">
                  {suggestedQuestions.map((q, i) => (
                    <Button
                      key={i}
                      variant="ghost"
                      size="sm"
                      className="w-full justify-start text-left h-auto py-2 px-3"
                      onClick={() => setQuestion(q)}
                    >
                      <span className="text-xs line-clamp-2">{q}</span>
                    </Button>
                  ))}
                </div>
              </ScrollArea>
            </div>

            {/* Ask Buttons */}
            <div className="flex gap-2">
              <Button
                onClick={handleDirectAsk}
                disabled={!question.trim() || askState.isStreaming}
                className="flex-1 gap-2"
              >
                {askState.isStreaming ? (
                  <>
                    <LoadingSpinner className="h-4 w-4" />
                    Thinking...
                  </>
                ) : (
                  <>
                    <Sparkles className="h-4 w-4" />
                    Quick Ask
                  </>
                )}
              </Button>
              <Button
                onClick={handleAsk}
                disabled={!question.trim() || askState.isStreaming}
                variant="secondary"
                className="flex-1 gap-2"
              >
                <Brain className="h-4 w-4" />
                Deep Analysis
              </Button>
            </div>

            {/* Answer Display */}
            {(askState.finalAnswer || askState.answers.length > 0 || askState.strategy) && (
              <Card className="border-purple-500/20">
                <CardHeader className="pb-3">
                  <CardTitle className="text-sm flex items-center gap-2">
                    <Sparkles className="h-4 w-4 text-purple-500" />
                    AI Response
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <ScrollArea className="h-[300px]">
                    {/* Strategy */}
                    {askState.strategy && (
                      <div className="mb-4 p-3 bg-muted/50 rounded-lg">
                        <h4 className="text-xs font-semibold mb-2 flex items-center gap-1">
                          <Brain className="h-3 w-3" />
                          Analysis Strategy
                        </h4>
                        <p className="text-xs text-muted-foreground">
                          {askState.strategy.reasoning}
                        </p>
                        {askState.strategy.searches.length > 0 && (
                          <div className="mt-2 flex flex-wrap gap-1">
                            {askState.strategy.searches.map((s: { term: string; instructions: string }, i: number) => (
                              <Badge key={i} variant="outline" className="text-xs">
                                {s.term}
                              </Badge>
                            ))}
                          </div>
                        )}
                      </div>
                    )}

                    {/* Partial Answers */}
                    {askState.answers.map((answer: string, i: number) => (
                      <div key={i} className="mb-3 p-3 bg-muted/30 rounded-lg">
                        <h4 className="text-xs font-semibold mb-2">Answer {i + 1}</h4>
                        <div className="prose prose-sm dark:prose-invert max-w-none">
                          <ReactMarkdown>{answer}</ReactMarkdown>
                        </div>
                      </div>
                    ))}

                    {/* Final Answer */}
                    {askState.finalAnswer && (
                      <div className="p-4 bg-gradient-to-br from-purple-500/10 to-blue-500/10 rounded-lg border border-purple-500/20">
                        <h4 className="text-sm font-semibold mb-3 flex items-center gap-2">
                          <Sparkles className="h-4 w-4 text-purple-500" />
                          Final Answer
                        </h4>
                        <div className="prose prose-sm dark:prose-invert max-w-none">
                          <ReactMarkdown>{askState.finalAnswer}</ReactMarkdown>
                        </div>
                      </div>
                    )}

                    {askState.isStreaming && !askState.finalAnswer && (
                      <div className="flex items-center justify-center py-8">
                        <LoadingSpinner className="h-6 w-6" />
                      </div>
                    )}
                  </ScrollArea>
                </CardContent>
              </Card>
            )}

            {askState.error && (
              <Card className="border-destructive">
                <CardContent className="pt-4">
                  <p className="text-sm text-destructive">{askState.error}</p>
                </CardContent>
              </Card>
            )}
          </div>
      </CardContent>
    </Card>
  )
}