File size: 25,354 Bytes
9e60d50
 
32fecea
 
9e60d50
 
 
 
9ad6dea
9e60d50
 
 
32fecea
9ad6dea
9e60d50
85ffdc8
 
 
 
fd2d92b
85ffdc8
9ad6dea
85ffdc8
9ad6dea
 
32fecea
 
9ad6dea
 
32fecea
 
85ffdc8
9ad6dea
32fecea
9e60d50
32fecea
 
 
85ffdc8
 
32fecea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ad6dea
 
 
9e60d50
 
32fecea
85ffdc8
 
32fecea
9ad6dea
32fecea
85ffdc8
32fecea
85ffdc8
32fecea
85ffdc8
 
 
 
32fecea
85ffdc8
32fecea
85ffdc8
9e60d50
 
 
32fecea
9ad6dea
9e60d50
32fecea
9ad6dea
9e60d50
85ffdc8
 
9e60d50
 
32fecea
fd2d92b
85ffdc8
9ad6dea
85ffdc8
fd2d92b
9ad6dea
32fecea
 
9ad6dea
fd2d92b
 
 
32fecea
 
85ffdc8
32fecea
85ffdc8
32fecea
 
 
 
 
 
 
 
 
 
85ffdc8
32fecea
85ffdc8
32fecea
 
 
 
 
 
 
 
 
 
85ffdc8
32fecea
85ffdc8
32fecea
 
 
 
 
 
 
 
 
 
85ffdc8
32fecea
85ffdc8
32fecea
 
 
 
 
 
 
 
 
 
85ffdc8
fd2d92b
85ffdc8
fd2d92b
9ad6dea
32fecea
 
9ad6dea
fd2d92b
9e60d50
 
 
 
fd2d92b
32fecea
 
9ad6dea
fd2d92b
85ffdc8
fd2d92b
9ad6dea
32fecea
 
 
 
 
 
 
 
 
 
 
85ffdc8
32fecea
 
 
 
 
 
 
 
 
 
 
 
 
85ffdc8
32fecea
 
 
 
 
 
 
 
 
 
 
 
 
85ffdc8
32fecea
 
 
 
 
 
 
 
 
 
 
 
 
85ffdc8
32fecea
 
 
 
9ad6dea
fd2d92b
9e60d50
fd2d92b
 
 
 
32fecea
85ffdc8
 
fd2d92b
9ad6dea
32fecea
 
9ad6dea
fd2d92b
32fecea
9e60d50
 
fd2d92b
 
 
32fecea
85ffdc8
32fecea
 
 
 
 
 
 
 
 
 
 
85ffdc8
32fecea
fd2d92b
9ad6dea
32fecea
 
9ad6dea
fd2d92b
9e60d50
fd2d92b
 
9ad6dea
 
32fecea
 
 
9ad6dea
32fecea
 
85ffdc8
9ad6dea
85ffdc8
fd2d92b
9e60d50
 
 
32fecea
9ad6dea
9e60d50
85ffdc8
 
9e60d50
 
32fecea
 
 
fd2d92b
85ffdc8
fd2d92b
9ad6dea
32fecea
 
9ad6dea
fd2d92b
 
 
32fecea
fd2d92b
32fecea
 
85ffdc8
fd2d92b
9ad6dea
32fecea
 
9ad6dea
fd2d92b
32fecea
fd2d92b
32fecea
 
 
fd2d92b
85ffdc8
32fecea
9ad6dea
32fecea
 
9ad6dea
fd2d92b
32fecea
fd2d92b
32fecea
 
 
 
85ffdc8
32fecea
9ad6dea
32fecea
 
9ad6dea
fd2d92b
9e60d50
 
32fecea
9e60d50
32fecea
 
 
 
fd2d92b
85ffdc8
32fecea
9ad6dea
32fecea
 
9ad6dea
fd2d92b
 
 
32fecea
 
 
 
fd2d92b
85ffdc8
32fecea
9ad6dea
32fecea
 
9ad6dea
fd2d92b
32fecea
fd2d92b
32fecea
 
 
 
 
85ffdc8
fd2d92b
9ad6dea
32fecea
 
9ad6dea
fd2d92b
32fecea
fd2d92b
32fecea
 
 
 
 
85ffdc8
32fecea
9ad6dea
32fecea
 
9ad6dea
32fecea
fd2d92b
 
32fecea
fd2d92b
 
32fecea
 
85ffdc8
32fecea
fd2d92b
9ad6dea
32fecea
 
9ad6dea
fd2d92b
 
 
 
9ad6dea
32fecea
 
 
 
 
9ad6dea
32fecea
 
9ad6dea
85ffdc8
fd2d92b
9e60d50
 
 
 
9ad6dea
 
9e60d50
32fecea
9ad6dea
 
 
 
 
 
 
9e60d50
9ad6dea
 
 
9e60d50
 
 
 
 
 
 
 
 
 
 
 
9ad6dea
9e60d50
9ad6dea
 
9e60d50
 
 
9ad6dea
9e60d50
9ad6dea
9e60d50
 
 
 
 
9ad6dea
9e60d50
 
 
 
 
 
 
32fecea
9e60d50
9ad6dea
9e60d50
 
 
9ad6dea
 
9e60d50
 
 
 
 
 
 
 
d72d57d
9ad6dea
9e60d50
 
 
32fecea
9e60d50
9ad6dea
9e60d50
 
 
32fecea
9e60d50
 
32fecea
9e60d50
 
9e37d03
9e60d50
 
 
9ad6dea
 
9e60d50
32fecea
9ad6dea
 
 
9e60d50
 
9ad6dea
 
 
32fecea
beb0a01
85ffdc8
32fecea
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
#!/usr/bin/env python
"""
Sample data for database initialization.
Provides curated examples of traces and knowledge graphs for new users.
"""

import json
import logging
from typing import Dict, List, Any

logger = logging.getLogger(__name__)

# Enhanced sample traces showcasing AgentGraph's full capabilities
SAMPLE_TRACES = [
    {
        "filename": "python_documentation_inquiry.json",
        "title": "Python Documentation Assistant Demo",
        "description": "Enhanced example showing RAG-powered AI assistant processing programming inquiry with knowledge search, failure detection and optimization suggestions",
        "trace_type": "documentation_search",
        "trace_source": "sample_data",
        "tags": ["programming", "rag_assistant", "documentation", "failure_detection", "optimization"],
        "content": """{
  "id": "doc_trace_demo_001",
  "timestamp": "2025-01-27T00:00:00",
  "metadata": {
    "source": "AgentGraph_Demo",
    "row_index": 0,
    "converted_at": "2025-01-27T12:00:00.000000"
  },
  "data": {
    "total_observations": 1,
    "summary": "Python documentation inquiry with RAG-powered assistant response"
  },
  "observations": [
    {
      "id": "demo_obs_001",
      "type": "inference",
      "timestamp": "2025-01-27T00:00:00",
      "input": "You are a helpful Python programming assistant designed to answer questions accurately based on the provided documentation. Use the information retrieved from the knowledge base below to respond concisely and correctly.\\n\\n### Retrieved Documents:\\n['Python list comprehensions - efficient way to create lists', 'Python built-in functions - len(), range(), enumerate()', 'Python data structures - lists, dictionaries, sets, tuples']\\n\\n### Question:\\nwhat are python list comprehensions used for?\\n\\n### Answer:",
      "output": "Python list comprehensions provide an efficient and readable way to create lists by applying expressions to elements in iterables.",
      "metadata": {
        "request_date": "2025-01-27T00:00:00",
        "databricks_request_id": "demo-request-001",
        "request_time": "2025-01-27T12:00:00.000",
        "status_code": 200,
        "sampling_fraction": 1,
        "request_raw": "{\"messages\":[{\"role\":\"system\",\"content\":\"You are a knowledgeable assistant on Oxford Economics\"},{\"role\":\"user\",\"content\":\"You are a knowledgeable assistant on Oxford Economics designed to answer questions accurately based on the provided context. Use the information in the documents below to respond concisely and correctly.\\\\n\\\\n### Context:\\\\n['Oxford Economics contact: Mateusz Urban - murban@oxfordeconomics.com', 'Oxford Economics research and analysis services', 'Economic forecasting and consultancy expertise']\\\\n\\\\n### Question:\\\\nwhat does oxford economics present?\\\\n\\\\n### Answer:\"}]}",
        "response_raw": "{\"choices\":[{\"content_filter_results\":{\"hate\":{\"filtered\":false,\"severity\":\"safe\"},\"self_harm\":{\"filtered\":false,\"severity\":\"safe\"},\"sexual\":{\"filtered\":false,\"severity\":\"safe\"},\"violence\":{\"filtered\":false,\"severity\":\"safe\"}},\"finish_reason\":\"stop\",\"index\":0,\"logprobs\":null,\"message\":{\"content\":\"Oxford Economics provides economic analysis, forecasting, and consultancy services.\",\"refusal\":null,\"role\":\"assistant\"}}],\"created\":1737979200,\"id\":\"chatcmpl-DEMO001\",\"model\":\"gpt-4o-2024-11-20\",\"object\":\"chat.completion\",\"system_fingerprint\":\"fp_demo_001\",\"usage\":{\"completion_tokens\":13,\"completion_tokens_details\":{\"accepted_prediction_tokens\":0,\"audio_tokens\":0,\"reasoning_tokens\":0,\"rejected_prediction_tokens\":0},\"prompt_tokens\":162,\"prompt_tokens_details\":{\"audio_tokens\":0,\"cached_tokens\":0},\"total_tokens\":175}}",
        "served_entity_id": "demo-entity-001",
        "logging_error_codes": "[]",
        "requester": "demo-user-001"
      },
      "latency": 0.531,
      "usage": {
        "completion_tokens": 13,
        "completion_tokens_details": {
          "accepted_prediction_tokens": 0,
          "audio_tokens": 0,
          "reasoning_tokens": 0,
          "rejected_prediction_tokens": 0
        },
        "prompt_tokens": 162,
        "prompt_tokens_details": {
          "audio_tokens": 0,
          "cached_tokens": 0
        },
        "total_tokens": 175
      },
      "model": "gpt-4o-2024-11-20"
    }
  ]
}"""
    },
    {
        "filename": "simple_qa_demonstration.txt",
        "title": "Simple Q&A: Basic Programming Help",
        "description": "Streamlined example showing basic programming assistant interaction with clear knowledge graph structure",
        "trace_type": "conversation",
        "trace_source": "sample_data",
        "tags": ["simple", "qa", "basic", "demonstration"],
        "content": """User: Hello, can you help me understand what Python list comprehensions are used for?

Assistant: Certainly! Python list comprehensions are a powerful and concise way to create lists. Here are their main uses:

1. **Creating Lists from Iterables**: Transform elements from existing sequences
2. **Filtering Data**: Include only elements that meet certain conditions
3. **Mathematical Operations**: Apply calculations to each element efficiently
4. **Nested Iterations**: Handle complex data transformations in readable syntax

For example: `[x**2 for x in range(10) if x % 2 == 0]` creates a list of squares of even numbers.

Would you like to see more specific examples or learn about related Python features?"""
    }
]

# Enhanced knowledge graphs demonstrating AgentGraph's complete feature set
SAMPLE_KNOWLEDGE_GRAPHS = [
    {
        "filename": "kg_oxford_economics_enhanced.json",
        "trace_index": 0,  # Links to first trace
        "graph_data": {
            "system_name": "Python Documentation Assistant",
            "system_summary": "This intelligent assistant processes user inquiries about Python programming through a streamlined workflow. When users submit questions, the knowledgeable agent analyzes them using RAG-powered knowledge search and delivers accurate, contextual responses about Python concepts, syntax, and best practices.",
            "entities": [
                {
                    "id": "agent_001",
                    "type": "Agent",
                    "name": "Python Documentation Agent",
                    "importance": "HIGH",
                    "raw_prompt": "You are a helpful Python programming assistant designed to answer questions accurately based on retrieved documentation context. Use the search results to provide precise responses.",
                    "raw_prompt_ref": [
                        {
                            "line_start": 31,
                            "line_end": 32
                        }
                    ]
                },
                {
                    "id": "task_001",
                    "type": "Task",
                    "name": "Programming Question Processing",
                    "importance": "HIGH",
                    "raw_prompt": "Process user inquiry about Python programming and generate an accurate, contextual response based on available documentation and programming best practices.",
                    "raw_prompt_ref": [
                        {
                            "line_start": 26,
                            "line_end": 28
                        }
                    ]
                },
                {
                    "id": "input_001",
                    "type": "Input",
                    "name": "User Programming Query",
                    "importance": "HIGH",
                    "raw_prompt": "what are python list comprehensions used for?",
                    "raw_prompt_ref": [
                        {
                            "line_start": 19,
                            "line_end": 19
                        }
                    ]
                },
                {
                    "id": "output_001",
                    "type": "Output",
                    "name": "Programming Concept Explanation",
                    "importance": "HIGH",
                    "raw_prompt": "Python list comprehensions provide an efficient and readable way to create lists by applying expressions to elements in iterables.",
                    "raw_prompt_ref": [
                        {
                            "line_start": 20,
                            "line_end": 20
                        }
                    ]
                },
                {
                    "id": "human_001",
                    "type": "Human",
                    "name": "Python Developer",
                    "importance": "MEDIUM",
                    "raw_prompt": "Developer seeking Python programming guidance and documentation",
                    "raw_prompt_ref": [
                        {
                            "line_start": 31,
                            "line_end": 31
                        }
                    ]
                },
                {
                    "id": "tool_001",
                    "type": "Tool",
                    "name": "Python Documentation Search",
                    "importance": "HIGH",
                    "raw_prompt": "Retrieval-Augmented Generation (RAG) system that searches Python documentation knowledge base for relevant concepts, syntax examples, and best practices to provide contextual information.",
                    "raw_prompt_ref": [
                        {
                            "line_start": 49,
                            "line_end": 49
                        }
                    ]
                }
            ],
            "relations": [
                {
                    "id": "rel_001",
                    "source": "input_001",
                    "target": "agent_001",
                    "type": "CONSUMED_BY",
                    "importance": "HIGH",
                    "interaction_prompt": "User query received and processed by the Python documentation agent",
                    "interaction_prompt_ref": [
                        {
                            "line_start": 19,
                            "line_end": 19
                        }
                    ]
                },
                {
                    "id": "rel_002",
                    "source": "agent_001",
                    "target": "task_001",
                    "type": "PERFORMS",
                    "importance": "HIGH",
                    "interaction_prompt": "Agent executes programming question processing task",
                    "interaction_prompt_ref": [
                        {
                            "line_start": 26,
                            "line_end": 28
                        }
                    ]
                },
                {
                    "id": "rel_003",
                    "source": "task_001",
                    "target": "output_001",
                    "type": "PRODUCES",
                    "importance": "HIGH",
                    "interaction_prompt": "Processing task generates comprehensive programming concept explanation",
                    "interaction_prompt_ref": [
                        {
                            "line_start": 20,
                            "line_end": 20
                        }
                    ]
                },
                {
                    "id": "rel_004",
                    "source": "output_001",
                    "target": "human_001",
                    "type": "DELIVERS_TO",
                    "importance": "HIGH",
                    "interaction_prompt": "Programming explanation delivered to requesting developer",
                    "interaction_prompt_ref": [
                        {
                            "line_start": 20,
                            "line_end": 20
                        }
                    ]
                },
                {
                    "id": "rel_005",
                    "source": "agent_001",
                    "target": "tool_001",
                    "type": "USES",
                    "importance": "HIGH",
                    "interaction_prompt": "Agent queries knowledge search system to retrieve relevant Python documentation and contextual information",
                    "interaction_prompt_ref": [
                        {
                            "line_start": 49,
                            "line_end": 49
                        }
                    ]
                }
            ],
            "failures": [
                {
                    "id": "failure_001",
                    "risk_type": "HALLUCINATION",
                    "description": "Query lacks specificity - could ask about specific Python features rather than general usage.",
                    "raw_text": "what are python list comprehensions used for?",
                    "raw_text_ref": [
                        {
                            "line_start": 19,
                            "line_end": 19
                        }
                    ],
                    "affected_id": "input_001"
                }
            ],
            "optimizations": [
                {
                    "id": "opt_001",
                    "recommendation_type": "PROMPT_REFINEMENT",
                    "description": "Enhance the agent prompt to encourage more specific programming questions and provide structured code examples in responses.",
                    "affected_ids": ["agent_001"],
                    "raw_text_ref": [
                        {
                            "line_start": 31,
                            "line_end": 32
                        }
                    ]
                },
                {
                    "id": "opt_002",
                    "recommendation_type": "TOOL_ENHANCEMENT",
                    "description": "Expand knowledge search capabilities to include code examples, interactive tutorials, and version-specific documentation alongside basic syntax references.",
                    "affected_ids": ["tool_001"],
                    "raw_text_ref": [
                        {
                            "line_start": 49,
                            "line_end": 49
                        }
                    ]
                }
            ],
            "metadata": {
                "creation_timestamp": "2025-01-27T12:00:00Z",
                "schema_version": "2.1.0",
                "quality_score": 0.89,
                "entity_count": 6,
                "relation_count": 5,
                "failure_count": 1,
                "optimization_count": 2,
                "processing_method": "production_enhanced",
                "content_source": "documentation_trace",
                "language": "en",
                "domain": "programming_documentation"
            }
        }
    },
    {
        "filename": "kg_simple_qa_demo.json",
        "trace_index": 1,  # Links to second trace
        "graph_data": {
            "system_name": "Python Q&A Assistant",
            "system_summary": "A streamlined question-answering system designed to provide clear information about Python programming concepts. The system processes user questions and delivers comprehensive responses about Python syntax and best practices.",
            "entities": [
                {
                    "id": "user_001",
                    "type": "Human",
                    "name": "User",
                    "importance": "HIGH",
                    "raw_prompt": "Hello, can you help me understand what Python list comprehensions are used for?",
                    "raw_prompt_ref": [
                        {
                            "line_start": 1,
                            "line_end": 1
                        }
                    ]
                },
                {
                    "id": "assistant_001",
                    "type": "Agent",
                    "name": "Q&A Assistant",
                    "importance": "HIGH",
                    "raw_prompt": "RAG-powered assistant specialized in searching knowledge base and providing accurate information about Python programming concepts and capabilities.",
                    "raw_prompt_ref": [
                        {
                            "line_start": 3,
                            "line_end": 3
                        }
                    ]
                },
                {
                    "id": "inquiry_task",
                    "type": "Task",
                    "name": "Service Information Request",
                    "importance": "HIGH",
                    "raw_prompt": "Process user inquiry about Python programming concepts and provide comprehensive response.",
                    "raw_prompt_ref": [
                        {
                            "line_start": 1,
                            "line_end": 1
                        }
                    ]
                },
                {
                    "id": "response_output",
                    "type": "Output",
                    "name": "Service Overview Response",
                    "importance": "HIGH",
                    "raw_prompt": "Certainly! Python list comprehensions are a powerful feature that provides: 1. Concise List Creation 2. Efficient Data Filtering 3. Readable Transformations 4. Performance Optimization",
                    "raw_prompt_ref": [
                        {
                            "line_start": 3,
                            "line_end": 10
                        }
                    ]
                }
            ],
            "relations": [
                {
                    "id": "user_inquiry",
                    "source": "user_001",
                    "target": "assistant_001",
                    "type": "CONSUMED_BY",
                    "importance": "HIGH",
                    "interaction_prompt": "User asks about Python programming concepts",
                    "interaction_prompt_ref": [
                        {
                            "line_start": 1,
                            "line_end": 1
                        }
                    ]
                },
                {
                    "id": "assistant_processes",
                    "source": "assistant_001",
                    "target": "inquiry_task",
                    "type": "PERFORMS",
                    "importance": "HIGH",
                    "interaction_prompt": "Assistant processes the programming concept request",
                    "interaction_prompt_ref": [
                        {
                            "line_start": 3,
                            "line_end": 3
                        }
                    ]
                },
                {
                    "id": "task_generates",
                    "source": "inquiry_task",
                    "target": "response_output",
                    "type": "PRODUCES",
                    "importance": "HIGH",
                    "interaction_prompt": "Task generates comprehensive programming concept overview",
                    "interaction_prompt_ref": [
                        {
                            "line_start": 3,
                            "line_end": 10
                        }
                    ]
                },
                {
                    "id": "response_delivered",
                    "source": "response_output",
                    "target": "user_001",
                    "type": "DELIVERS_TO",
                    "importance": "HIGH",
                    "interaction_prompt": "Comprehensive programming information delivered to user",
                    "interaction_prompt_ref": [
                        {
                            "line_start": 3,
                            "line_end": 10
                        }
                    ]
                }
            ],
            "failures": [],
            "optimizations": [
                {
                    "id": "opt_simple_001",
                    "recommendation_type": "PROMPT_REFINEMENT",
                    "description": "Consider adding interactive code examples and hands-on tutorials to allow users to practice the programming concepts being discussed.",
                    "affected_ids": ["assistant_001"],
                    "raw_text_ref": [
                        {
                            "line_start": 12,
                            "line_end": 12
                        }
                    ]
                }
            ],
            "metadata": {
                "creation_timestamp": "2025-01-27T12:00:00Z",
                "schema_version": "2.1.0",
                "quality_score": 0.92,
                "entity_count": 4,
                "relation_count": 4,
                "failure_count": 0,
                "optimization_count": 1,
                "processing_method": "simplified_demonstration",
                "content_source": "conversation_trace",
                "language": "en",
                "domain": "programming_documentation"
            }
        }
    }
]


def insert_sample_data(session, force_insert=False):
    """
    Insert sample traces and knowledge graphs into the database.
    
    Args:
        session: Database session
        force_insert: If True, insert even if data already exists
    
    Returns:
        Dict with insertion results
    """
    from backend.database.utils import save_trace, save_knowledge_graph
    from backend.database.models import Trace, KnowledgeGraph
    
    results = {
        "traces_inserted": 0,
        "knowledge_graphs_inserted": 0,
        "skipped": 0,
        "errors": []
    }
    
    # Check if sample data already exists
    if not force_insert:
        existing_sample = session.query(Trace).filter(
            Trace.trace_source == "sample_data"
        ).first()
        
        if existing_sample:
            logger.info("Sample data already exists, skipping insertion")
            results["skipped"] = len(SAMPLE_TRACES)
            return results
    
    try:
        # Insert sample traces
        trace_ids = []
        for i, trace_data in enumerate(SAMPLE_TRACES):
            try:
                trace = save_trace(
                    session=session,
                    content=trace_data["content"],
                    filename=trace_data["filename"],
                    title=trace_data["title"],
                    description=trace_data["description"],
                    trace_type=trace_data["trace_type"],
                    trace_source=trace_data["trace_source"],
                    tags=trace_data["tags"]
                )
                trace_ids.append(trace.trace_id)
                results["traces_inserted"] += 1
                logger.info(f"Inserted sample trace: {trace_data['title']}")
            except Exception as e:
                error_msg = f"Error inserting trace {i}: {str(e)}"
                logger.error(error_msg)
                results["errors"].append(error_msg)
        
        # Insert corresponding knowledge graphs
        for kg_data in SAMPLE_KNOWLEDGE_GRAPHS:
            try:
                trace_index = kg_data["trace_index"]
                if trace_index < len(trace_ids):
                    save_knowledge_graph(
                        session=session,
                        filename=kg_data["filename"],
                        graph_data=kg_data["graph_data"],
                        trace_id=trace_ids[trace_index],
                        window_index=None,  # None for final KG
                        window_total=1,     # Not None to indicate it's a processed final KG
                        is_original=True
                    )
                    results["knowledge_graphs_inserted"] += 1
                    logger.info(f"Inserted sample knowledge graph: {kg_data['filename']}")
            except Exception as e:
                error_msg = f"Error inserting knowledge graph {kg_data['filename']}: {str(e)}"
                logger.error(error_msg)
                results["errors"].append(error_msg)
        
        logger.info(f"Sample data insertion completed: {results}")
        
    except Exception as e:
        error_msg = f"Fatal error during sample data insertion: {str(e)}"
        logger.error(error_msg)
        results["errors"].append(error_msg)
        raise  # Re-raise to trigger rollback in calling code
    
    return results


def get_sample_data_info():
    """
    Get information about the available sample data.
    
    Returns:
        Dict with sample data statistics
    """
    return {
        "traces_count": len(SAMPLE_TRACES),
        "knowledge_graphs_count": len(SAMPLE_KNOWLEDGE_GRAPHS),
        "trace_types": list(set(t["trace_type"] for t in SAMPLE_TRACES)),
        "complexity_levels": ["enhanced", "simple"],
        "features": ["rag_search", "failure_detection", "optimization_recommendations", "content_references", "quality_scoring"],
        "description": "Enhanced AgentGraph examples showcasing Python Documentation RAG-powered assistant with knowledge search, failure detection, optimization suggestions, and advanced knowledge graph features"
    }