Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Fix semantic extraction pipeline errors and enhance LLM JSON parsing

KaifAhmad1ef0797e03e57
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
index 0059b45b..0a1081f8 100644
--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
@@ -55,9 +55,32 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 36,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Note: you may need to restart the kernel to use updated packages.\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~gno (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~lotly (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",
+ "WARNING: Ignoring invalid distribution ~ython-socketio (c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"
+ ]
+ }
+ ],
"source": [
"# Install Semantica and all required dependencies\n",
"%pip install -qU semantica networkx matplotlib plotly pandas faiss-cpu beautifulsoup4 groq sentence-transformers\n"
@@ -84,9 +107,25 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 37,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\threading.py:986: ResourceWarning: unclosed file <_io.BufferedWriter name=3>\n",
+ " del self._target, self._args, self._kwargs\n",
+ "ResourceWarning: Enable tracemalloc to get the object allocation traceback\n",
+ "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\threading.py:986: ResourceWarning: unclosed file <_io.BufferedReader name=4>\n",
+ " del self._target, self._args, self._kwargs\n",
+ "ResourceWarning: Enable tracemalloc to get the object allocation traceback\n",
+ "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\threading.py:986: ResourceWarning: unclosed file <_io.BufferedReader name=5>\n",
+ " del self._target, self._args, self._kwargs\n",
+ "ResourceWarning: Enable tracemalloc to get the object allocation traceback\n"
+ ]
+ }
+ ],
"source": [
"# Core imports will be added in cells where they're first used\n",
"import os\n",
@@ -104,13 +143,13 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 38,
"metadata": {},
"outputs": [],
"source": [
"# Set up API keys\n",
"# Note: In production, use environment variables: export GROQ_API_KEY=\"your-key\"\n",
- "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"your-groq-api-key-here\")\n"
+ "os.environ[\"GROQ_API_KEY\"] = os.getenv(\"GROQ_API_KEY\", \"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\")\n"
]
},
{
@@ -129,7 +168,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 39,
"metadata": {},
"outputs": [],
"source": [
@@ -181,9 +220,27 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 40,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Configuration complete. Semantica initialized.\n",
+ " - Embedding dimension: 384\n",
+ " - Vector store backend: FAISS\n",
+ " - Knowledge graph backend: NetworkX\n"
+ ]
+ }
+ ],
"source": [
"from semantica.core import Semantica, ConfigManager\n",
"from semantica.vector_store import VectorStore\n",
@@ -221,7 +278,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 41,
"metadata": {},
"outputs": [],
"source": [
@@ -269,9 +326,17 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 42,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Foundation data saved to skincare_base.json\n"
+ ]
+ }
+ ],
"source": [
"# Save foundation data to JSON file\n",
"with open(\"skincare_base.json\", \"w\") as f:\n",
@@ -291,9 +356,19 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 43,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Phase 0.1 Complete. Seeded 3 primary nodes and 1 relationships.\n",
+ " - Foundation graph created successfully\n",
+ " - Seed data will be merged with extracted data in Phase 4\n"
+ ]
+ }
+ ],
"source": [
"from semantica.seed import SeedDataManager\n",
"\n",
@@ -335,7 +410,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
@@ -355,9 +430,17 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 45,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Ingestion components initialized.\n"
+ ]
+ }
+ ],
"source": [
"from semantica.ingest import FeedIngestor, WebIngestor, FileIngestor\n",
"from semantica.normalize import TextNormalizer\n",
@@ -385,9 +468,23 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 46,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Ingesting from RSS/Atom feeds...\n",
+ " Processing: https://makeupandbeautyblog.com/feed\n",
+ " Successfully ingested 3 items\n",
+ " Processing: https://www.drbaileyskincare.com/blogs/blog.atom\n",
+ " Successfully ingested 3 items\n",
+ "\n",
+ "Total feed items ingested: 6\n"
+ ]
+ }
+ ],
"source": [
"# Define feed URLs\n",
"feed_urls = [\n",
@@ -424,9 +521,34 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 47,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Ingesting from web pages...\n",
+ " Processing: https://en.wikipedia.org/wiki/Retinol\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "URL https://en.wikipedia.org/wiki/Retinol blocked by robots.txt\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ " Warning: Failed to ingest https://en.wikipedia.org/wiki/Retinol: URL blocked by robots.txt: https://en.wikipedia.org/wiki/Retinol\n",
+ "\n",
+ "Total web pages ingested: 6\n"
+ ]
+ }
+ ],
"source": [
"# Define web URLs to ingest\n",
"web_urls = [\n",
@@ -458,9 +580,23 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 48,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Ingesting from local files...\n",
+ " Processing: expert_skincare_guide.txt\n",
+ " Warning: Failed to ingest expert_skincare_guide.txt: 'FileObject' object is not iterable\n",
+ " Processing: data/sample_graphrag_paper.txt\n",
+ " Warning: Failed to ingest data/sample_graphrag_paper.txt: 'FileObject' object is not iterable\n",
+ "\n",
+ "Total local files processed: 6\n"
+ ]
+ }
+ ],
"source": [
"# Define local files to ingest\n",
"local_files = [\n",
@@ -501,9 +637,23 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 49,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Normalizing content...\n",
+ "\n",
+ "Phase 1 Complete. Ingested 6 documents from multiple sources.\n",
+ " - Feed items: 2 feeds processed\n",
+ " - Web pages: 1 URLs processed\n",
+ " - Local files: 2 files processed\n",
+ " - Total normalized documents: 6\n"
+ ]
+ }
+ ],
"source": [
"# Normalize all ingested content\n",
"print(\"Normalizing content...\")\n",
@@ -546,7 +696,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 50,
"metadata": {},
"outputs": [],
"source": [
@@ -565,9 +715,19 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 51,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "EntityAwareChunker initialized.\n",
+ " - Chunk size: 1000 characters\n",
+ " - Overlap: 200 characters\n"
+ ]
+ }
+ ],
"source": [
"from semantica.split import EntityAwareChunker\n",
"\n",
@@ -592,9 +752,27 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 52,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Chunking documents...\n",
+ " Document 1: 2 chunks created\n",
+ " Document 2: 2 chunks created\n",
+ " Document 3: 2 chunks created\n",
+ " Document 4: 17 chunks created\n",
+ " Document 5: 26 chunks created\n",
+ " Document 6: 24 chunks created\n",
+ "\n",
+ "Phase 2 Complete. Generated 73 semantic chunks.\n",
+ " - Average chunk size: 2071 characters\n",
+ " - Total chunks: 73\n"
+ ]
+ }
+ ],
"source": [
"# Chunk all normalized documents\n",
"all_chunks = []\n",
@@ -636,7 +814,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 53,
"metadata": {},
"outputs": [],
"source": [
@@ -647,7 +825,7 @@
" TripletExtractor,\n",
" EventDetector,\n",
" CoreferenceResolver\n",
- ")\n"
+ ")"
]
},
{
@@ -661,9 +839,22 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 54,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "All extractors initialized successfully.\n",
+ " - NER Extractor: Ready\n",
+ " - Relation Extractor: Ready\n",
+ " - Triplet Extractor: Ready\n",
+ " - Event Detector: Ready\n",
+ " - Coreference Resolver: Ready\n"
+ ]
+ }
+ ],
"source": [
"from semantica.semantic_extract import NERExtractor, RelationExtractor\n",
"\n",
@@ -718,9 +909,17 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 55,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Results container initialized.\n"
+ ]
+ }
+ ],
"source": [
"# Container for all extraction results\n",
"combined_results = {\n",
@@ -749,9 +948,157 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 56,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Extracting semantic information from chunks...\n",
+ "Processing 10 chunks...\n",
+ "\n",
+ "Chunk 1/10:\n",
+ " Extracting entities...\n",
+ " Found 0 entities\n",
+ " Skipping relationship extraction (no entities found)\n",
+ " Extracting triplets...\n",
+ "DEBUG: Entity map keys: ['href=\"https://makeupandbeautyblog.com', 'monday', '2/', 'beauty blog', '893', 'december-15-2025-610x763.jpg', '5px;max', '100%', 'https://makeupandbeautyblog.com/wp-content/uploads/2025/12/mbb-monday-poll-december-15-2025-768x960.jpg 768w', 'https://makeupandbeautyblog.com/wp-content/uploads/2025/12/mbb-monday-poll-december-15-2025.jpg 1000w']\n",
+ " Found 0 triplets\n",
+ " Detecting events...\n",
+ " Found 0 events\n",
+ "\n",
+ "Chunk 2/10:\n",
+ " Extracting entities...\n",
+ " Found 8 entities\n",
+ " Extracting relationships...\n",
+ " Found 0 relationships\n",
+ " Extracting triplets...\n",
+ "DEBUG: Entity map keys: ['jo malone', 'laneige', 'ulta', 'trader joe', 'monday', '2007', 'makeup and beauty blog', 'makeup and beauty blog | makeup reviews, swatches and how-to makeup']\n",
+ " Found 27 triplets\n",
+ " Detecting events...\n",
+ " Found 1 events\n",
+ "\n",
+ "Chunk 3/10:\n",
+ " Extracting entities...\n",
+ " Found 7 entities\n",
+ " Extracting relationships...\n",
+ " Found 9 relationships\n",
+ " Extracting triplets...\n",
+ "DEBUG: Entity map keys: ['makeup and beauty blog', 'monday poll', 'vol. 892', 'monday morning', '2007']\n",
+ " Found 7 triplets\n",
+ " Detecting events...\n",
+ " Found 0 events\n",
+ "\n",
+ "Chunk 4/10:\n",
+ " Extracting entities...\n",
+ " Found 10 entities\n",
+ " Extracting relationships...\n",
+ " Found 9 relationships\n",
+ " Extracting triplets...\n",
+ "DEBUG: Entity map keys: ['holiday shopping', 'mbb', 'makeup and beauty blog', 'makeup reviews, swatches and how-to makeup', 'makeup and beauty blog monday poll, vol. 892', 'makeupandbeautyblog.com']\n",
+ " Found 10 triplets\n",
+ " Detecting events...\n",
+ " Found 3 events\n",
+ "\n",
+ "Chunk 5/10:\n",
+ " Extracting entities...\n",
+ " Found 9 entities\n",
+ " Extracting relationships...\n",
+ " Found 10 relationships\n",
+ " Extracting triplets...\n",
+ "DEBUG: Entity map keys: ['makeup and beauty blog', 'monday poll', 'vol. 891', 'hawaii', 'lanikai', '2024', '2025', 'makeup and beauty blog monday poll', '2007']\n",
+ " Found 14 triplets\n",
+ " Detecting events...\n",
+ " Found 0 events\n",
+ "\n",
+ "Chunk 6/10:\n",
+ " Extracting entities...\n",
+ " Found 9 entities\n",
+ " Extracting relationships...\n",
+ " Found 0 relationships\n",
+ " Extracting triplets...\n",
+ "DEBUG: Entity map keys: ['my upper lip', 'a friend of mine', 'cavallo point', 'sausalito', 'rosie', 'marnie', 'makeup and beauty blog', 'makeup reviews, swatches and how-to makeup']\n",
+ " Found 9 triplets\n",
+ " Detecting events...\n",
+ " Found 3 events\n",
+ "\n",
+ "Chunk 7/10:\n",
+ " Extracting entities...\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "LLM entity extraction failed: Failed to parse JSON from Groq response: Failed to parse extracted JSON: Expecting ',' delimiter: line 280 column 70 (char 19586)\n",
+ "Raw snippet: [\n",
+ " {\"text\": \"I\", \"label\": \"PERSON\", \"start\": 0, \"...\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ " Found 0 entities\n",
+ " Skipping relationship extraction (no entities found)\n",
+ " Extracting triplets...\n",
+ "DEBUG: Entity map keys: ['the treatment options and products to control rosacea</h2>', 'over 35 years', '#', '10px', 'rosacea skincare', 'li><a', '4', 'href=\"https://drbaileyskincare.com', 'therapy skincare kit', 'step rosacea skincare', 'calming zinc', 'the rosacea therapy kit).</li>', 'li aria', 'li aria-level=\"2\">alternatively', 'sodium sulfacetamide sulfur', 'gentle foaming facial cleanser</a>', 'li aria-level=\"2\">in', 'height=\"340', 'alt=\"extremely gentle foaming facial cleanser']\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "LLM triplet extraction failed: Failed to parse JSON from Groq response: Failed to parse extracted JSON: Expecting ',' delimiter: line 218 column 104 (char 27090)\n",
+ "Raw snippet: [\n",
+ " {\"subject\": \"rosacea\", \"predicate\": \"has_treat...\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ " Found 0 triplets\n",
+ " Detecting events...\n",
+ " Found 0 events\n",
+ "\n",
+ "Chunk 8/10:\n",
+ " Extracting entities...\n",
+ " Found 8 entities\n",
+ " Extracting relationships...\n",
+ " Found 7 relationships\n",
+ " Extracting triplets...\n",
+ "DEBUG: Entity map keys: ['dr. bailey', 'green tea antioxidant skin therapy', 'rosacea therapy skin care kit', 'benzoyl peroxide cream', \"dr. bailey's skincare\"]\n",
+ " Found 7 triplets\n",
+ " Detecting events...\n",
+ " Found 0 events\n",
+ "\n",
+ "Chunk 9/10:\n",
+ " Extracting entities...\n",
+ " Found 8 entities\n",
+ " Extracting relationships...\n",
+ " Found 10 relationships\n",
+ " Extracting triplets...\n",
+ "DEBUG: Entity map keys: ['rosacea', 'facial dandruff', 'calming zinc soap', 'green tea antioxidant skin therapy', 'clotrimazole', \"dr. bailey's skincare\", 'rosacea medical treatments: creams, topical & oral medications, and procedures', 'dr. bailey']\n",
+ " Found 13 triplets\n",
+ " Detecting events...\n",
+ " Found 0 events\n",
+ "\n",
+ "Chunk 10/10:\n",
+ " Extracting entities...\n",
+ " Found 10 entities\n",
+ " Extracting relationships...\n",
+ " Found 9 relationships\n",
+ " Extracting triplets...\n",
+ "DEBUG: Entity map keys: ['dr. bailey', 'daily moisturizing face cream', \"dr. bailey's skincare\", 'omega enriched face booster oil', 'sea buckthorn', 'castor seed oil']\n",
+ " Found 8 triplets\n",
+ " Detecting events...\n",
+ " Found 0 events\n",
+ "\n"
+ ]
+ }
+ ],
"source": [
"# Process first 10 chunks to avoid rate limits\n",
"print(\"Extracting semantic information from chunks...\")\n",
@@ -802,7 +1149,7 @@
" # Step 3: Triplet Extraction\n",
" print(f\" Extracting triplets...\")\n",
" try:\n",
- " triplets = triplet_ext.extract(txt, entities=entities if entities else None)\n",
+ " triplets = triplet_ext.extract_triplets(txt, entities=entities if entities else None)\n",
" \n",
" for t in triplets:\n",
" combined_results[\"triplets\"].append({\n",
@@ -822,7 +1169,7 @@
" \n",
" for evt in events:\n",
" combined_results[\"events\"].append({\n",
- " \"type\": evt.type,\n",
+ " \"type\": evt.event_type,\n",
" \"text\": evt.text,\n",
" \"participants\": evt.participants\n",
" })\n",
@@ -879,9 +1226,38 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 59,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "============================================================\n",
+ "Phase 3 Complete - Extraction Summary\n",
+ "============================================================\n",
+ "Entities extracted: 69\n",
+ "Relationships extracted: 54\n",
+ "Triplets extracted: 95\n",
+ "Events detected: 7\n",
+ "============================================================\n",
+ "\n",
+ "Sample entities:\n",
+ " - Jo Malone (ORG)\n",
+ " - Laneige (ORG)\n",
+ " - Ulta (ORG)\n",
+ " - Trader Joe (ORG)\n",
+ " - Monday (DATE)\n",
+ "\n",
+ "Sample relationships:\n",
+ " - Makeup and Beauty Blog --[publishes]--> Monday Poll\n",
+ " - Makeup and Beauty Blog --[posts]--> Monday Poll\n",
+ " - Makeup and Beauty Blog --[has been posting]--> Monday Poll\n",
+ " - Monday Poll --[has been posted]--> Makeup and Beauty Blog\n",
+ " - Monday Poll --[is published on]--> Makeup and Beauty Blog\n"
+ ]
+ }
+ ],
"source": [
"# Display extraction summary\n",
"print(\"=\" * 60)\n",
@@ -938,9 +1314,21 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 60,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Building knowledge graph...\n",
+ "Initial graph statistics:\n",
+ " - Entities: 20\n",
+ " - Relationships: 54\n",
+ " - Metadata: {'num_entities': 20, 'num_relationships': 54, 'temporal_enabled': False, 'timestamp': '2025-12-23T23:19:22.955279', 'entity_resolution_applied': True}\n"
+ ]
+ }
+ ],
"source": [
"from semantica.kg import GraphBuilder\n",
"\n",
@@ -972,9 +1360,24 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 63,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Resolving entities (deduplication)...\n",
+ " Method: Semantic similarity matching\n",
+ " Threshold: 0.85 (85% similarity)\n",
+ "\n",
+ "Entity resolution complete:\n",
+ " - Original entities: 20\n",
+ " - Resolved entities: 20\n",
+ " - Entities merged: 0\n"
+ ]
+ }
+ ],
"source": [
"from semantica.kg import EntityResolver\n",
"\n",
@@ -989,7 +1392,6 @@
"# Resolve entities using semantic method\n",
"resolved_entities = resolver.resolve_entities(\n",
" kg.get('entities', []), \n",
- " method=\"semantic\"\n",
")\n",
"\n",
"# Create final graph with resolved entities\n",
@@ -1015,9 +1417,24 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 64,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Analyzing graph structure...\n",
+ "\n",
+ "Graph structure metrics:\n",
+ " - Graph density: 0.0000\n",
+ " - Connected components: 0\n",
+ " - Average degree: 0.00\n",
+ " - Total nodes: 0\n",
+ " - Total edges: 0\n"
+ ]
+ }
+ ],
"source": [
"from semantica.kg import GraphAnalyzer\n",
"\n",
@@ -1051,9 +1468,24 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 65,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Calculating centrality measures...\n",
+ "\n",
+ "Top 5 entities by degree centrality:\n",
+ " 1. Makeup and Beauty Blog: 0.3571\n",
+ " 2. Dr. Bailey's Skincare: 0.3214\n",
+ " 3. Dr. Bailey: 0.2143\n",
+ " 4. Green Tea Antioxidant Skin Therapy: 0.1786\n",
+ " 5. Omega Enriched Face Booster Oil: 0.1429\n"
+ ]
+ }
+ ],
"source": [
"from semantica.kg import CentralityCalculator\n",
"\n",
@@ -1063,21 +1495,19 @@
"print(\"Calculating centrality measures...\")\n",
"\n",
"# Calculate degree centrality (simplest and most common)\n",
- "degree_centrality = centrality_calc.calculate_degree_centrality(kg_final)\n",
- "\n",
- "if degree_centrality:\n",
- " # Get top entities by degree centrality\n",
- " top_entities = sorted(\n",
- " degree_centrality.items(), \n",
- " key=lambda x: x[1], \n",
- " reverse=True\n",
- " )[:5]\n",
- " \n",
+ "# This returns a dictionary containing 'centrality', 'rankings', etc.\n",
+ "result = centrality_calc.calculate_degree_centrality(kg_final)\n",
+ "\n",
+ "if result and \"rankings\" in result:\n",
+ " # Use the pre-computed rankings (highest scores first)\n",
+ " top_entities = result[\"rankings\"][:5]\n",
+ "\n",
" print(f\"\\nTop 5 entities by degree centrality:\")\n",
- " for rank, (entity_id, score) in enumerate(top_entities, 1):\n",
- " print(f\" {rank}. {entity_id}: {score:.4f}\")\n",
+ " for rank, item in enumerate(top_entities, 1):\n",
+ " # item['node'] is the entity ID, item['score'] is the normalized score\n",
+ " print(f\" {rank}. {item['node']}: {item['score']:.4f}\")\n",
"else:\n",
- " print(\" No centrality data available\")\n"
+ " print(\" No centrality data available\")"
]
},
{
@@ -1094,23 +1524,43 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 66,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Detecting communities...\n",
+ " Method: Louvain algorithm (greedy modularity optimization)\n",
+ "\n",
+ "Community detection results:\n",
+ " - Total communities found: 6\n",
+ " - Community 1: 10 entities\n",
+ " Sample entities: 2025, Makeup and Beauty Blog Monday Poll, Makeup and Beauty Blog\n",
+ " - Community 2: 8 entities\n",
+ " Sample entities: Benzoyl Peroxide Cream, Omega Enriched Face Booster Oil, Rosacea Medical Treatments: Creams, Topical & Oral Medications, and Procedures\n",
+ " - Community 3: 5 entities\n",
+ " Sample entities: Rosacea Therapy Skin Care Kit, Green Tea Antioxidant Skin Therapy, rosacea\n"
+ ]
+ }
+ ],
"source": [
"# Initialize CommunityDetector\n",
+ "from semantica.kg import CommunityDetector\n",
"community_detector = CommunityDetector()\n",
"\n",
"print(\"Detecting communities...\")\n",
"print(\" Method: Louvain algorithm (greedy modularity optimization)\")\n",
"\n",
"# Detect communities using Louvain algorithm\n",
- "communities = community_detector.detect_communities(\n",
+ "result = community_detector.detect_communities(\n",
" kg_final, \n",
" method=\"louvain\"\n",
")\n",
"\n",
- "if communities:\n",
+ "if result and \"communities\" in result:\n",
+ " communities = result[\"communities\"]\n",
" print(f\"\\nCommunity detection results:\")\n",
" print(f\" - Total communities found: {len(communities)}\")\n",
" \n",
@@ -1136,9 +1586,26 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 67,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "============================================================\n",
+ "Phase 4 Complete - Knowledge Graph Summary\n",
+ "============================================================\n",
+ "Final graph contains:\n",
+ " - Entities: 20\n",
+ " - Relationships: 54\n",
+ " - Graph density: 0.0000\n",
+ " - Connected components: 0\n",
+ " - Communities: 6\n",
+ "============================================================\n"
+ ]
+ }
+ ],
"source": [
"print(\"=\" * 60)\n",
"print(\"Phase 4 Complete - Knowledge Graph Summary\")\n",
@@ -1177,9 +1644,20 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 68,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Preparing texts for embedding...\n",
+ " - Total chunks to embed: 73\n",
+ " - Embedding model: all-MiniLM-L6-v2\n",
+ " - Expected dimension: 384\n"
+ ]
+ }
+ ],
"source": [
"# Prepare texts for embedding generation\n",
"print(\"Preparing texts for embedding...\")\n",
@@ -1192,9 +1670,37 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 69,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "fastembed not available. Install with: pip install fastembed. Using fallback embedding method.\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Generating embeddings...\n",
+ "Embeddings generated successfully:\n",
+ " - Total embeddings: 73\n"
+ ]
+ },
+ {
+ "ename": "ValueError",
+ "evalue": "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
+ "Cell \u001b[1;32mIn[69], line 7\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mEmbeddings generated successfully:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 6\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m - Total embeddings: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlen\u001b[39m(embeddings)\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m----> 7\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m - Embedding dimension: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlen\u001b[39m(embeddings[\u001b[38;5;241m0\u001b[39m])\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mif\u001b[39;00m\u001b[38;5;250m \u001b[39membeddings\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01melse\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;241m0\u001b[39m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n",
+ "\u001b[1;31mValueError\u001b[0m: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
+ ]
+ }
+ ],
"source": [
"# Generate embeddings using the configured embedding generator\n",
"print(\"Generating embeddings...\")\n",
@@ -1216,9 +1722,18 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 70,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Preparing metadata...\n",
+ " - Metadata entries created: 73\n"
+ ]
+ }
+ ],
"source": [
"# Create metadata for each vector\n",
"metadata_list = []\n",
@@ -1246,9 +1761,32 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 71,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Storing vectors in vector store...\n",
+ "\n",
+ "Phase 5 Complete. Vector store populated successfully.\n",
+ " - Vectors stored: 73\n",
+ " - Vector store backend: FAISS\n"
+ ]
+ },
+ {
+ "ename": "ValueError",
+ "evalue": "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
+ "Cell \u001b[1;32mIn[71], line 8\u001b[0m\n\u001b[0;32m 6\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m - Vectors stored: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlen\u001b[39m(embeddings)\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 7\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m - Vector store backend: FAISS\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m----> 8\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m - Embedding dimension: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlen\u001b[39m(embeddings[\u001b[38;5;241m0\u001b[39m])\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mif\u001b[39;00m\u001b[38;5;250m \u001b[39membeddings\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01melse\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;241m0\u001b[39m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 9\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m - Ready for similarity search\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n",
+ "\u001b[1;31mValueError\u001b[0m: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"
+ ]
+ }
+ ],
"source": [
"# Store vectors in FAISS vector store\n",
"print(\"Storing vectors in vector store...\")\n",
@@ -1286,7 +1824,7 @@
},
{
"cell_type": "code",
- "execution_count": null,
+ "execution_count": 72,
"metadata": {},
"outputs": [],
"source": [
@@ -1310,9 +1848,21 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 73,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Initializing AgentContext for GraphRAG...\n",
+ "AgentContext initialized successfully.\n",
+ " - Graph expansion: Enabled\n",
+ " - Max expansion hops: 2\n",
+ " - Hybrid alpha: 0.6 (60% graph, 40% vector)\n"
+ ]
+ }
+ ],
"source": [
"from semantica.context import AgentContext\n",
"\n",
@@ -1344,9 +1894,20 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 74,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "LLM provider initialized.\n",
+ " - Provider: Groq\n",
+ " - Model: llama-3.1-70b-versatile\n",
+ " - Ready for answer generation\n"
+ ]
+ }
+ ],
"source": [
"# Initialize LLM provider for answer generation\n",
"llm_provider = create_provider(\"groq\", model=\"llama-3.1-70b-versatile\")\n",
@@ -1368,9 +1929,19 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 75,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "EntityLinker initialized.\n",
+ " - Knowledge graph: Linked\n",
+ " - Ready for entity resolution in queries\n"
+ ]
+ }
+ ],
"source": [
"# Initialize EntityLinker\n",
"linker = EntityLinker(knowledge_graph=kg_final)\n",
@@ -1389,9 +1960,21 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 76,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "======================================================================\n",
+ "GRAPH RAG QUERY PROCESSING\n",
+ "======================================================================\n",
+ "Query: What ingredients synergize with Retinol to prevent irritation?\n",
+ "\n"
+ ]
+ }
+ ],
"source": [
"# Define the user query\n",
"user_query = \"What ingredients synergize with Retinol to prevent irritation?\"\n",
@@ -1413,9 +1996,24 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 77,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Retrieving context using hybrid search...\n",
+ " - Vector search: Finding semantically similar chunks\n",
+ " - Graph traversal: Following entity relationships\n",
+ " - Max results: 5\n",
+ " - Graph expansion: Enabled (2 hops)\n",
+ "\n",
+ "Retrieved 1 context results.\n",
+ "\n"
+ ]
+ }
+ ],
"source": [
"# Retrieve context using hybrid retrieval\n",
"print(\"Retrieving context using hybrid search...\")\n",
@@ -1447,9 +2045,25 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 78,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "======================================================================\n",
+ "MULTI-HOP CONTEXT DISCOVERED\n",
+ "======================================================================\n",
+ "\n",
+ "Result 1:\n",
+ " Content: ...\n",
+ " Relevance Score: 0.7722\n",
+ "\n",
+ "======================================================================\n"
+ ]
+ }
+ ],
"source": [
"if context_results:\n",
" print(\"=\" * 70)\n",
@@ -1492,9 +2106,25 @@
},
{
"cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
+ "execution_count": 79,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "======================================================================\n",
+ "GENERATING FINAL ANSWER\n",
+ "======================================================================\n",
+ "Using LLM to synthesize answer from retrieved context...\n",
+ "\n",
+ "Warning: LLM generation failed: Error code: 400 - {'error': {'message': 'The model `llama-3.1-70b-versatile` has been decommissioned and is no longer supported. Please refer to https://console.groq.com/docs/deprecations for a recommendation on which model to use instead.', 'type': 'invalid_request_error', 'code': 'model_decommissioned'}}\n",
+ "\n",
+ "However, we successfully retrieved relevant context using GraphRAG!\n",
+ "The context above can be used to answer the query manually.\n"
+ ]
+ }
+ ],
"source": [
"if context_results:\n",
" # Combine all retrieved context\n",
@@ -1696,8 +2326,22 @@
}
],
"metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
"language_info": {
- "name": "python"
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.9"
}
},
"nbformat": 4,
diff --git a/cookbook/use_cases/advanced_rag/skincare_base.json b/cookbook/use_cases/advanced_rag/skincare_base.json
index 6f11beb5..f662ca1d 100644
--- a/cookbook/use_cases/advanced_rag/skincare_base.json
+++ b/cookbook/use_cases/advanced_rag/skincare_base.json
@@ -1 +1,38 @@
-{"entities": [{"id": "hyaluronic_acid", "name": "Hyaluronic Acid", "type": "Ingredient", "properties": {"role": "Humectant"}}, {"id": "retinol", "name": "Retinol", "type": "Ingredient", "properties": {"role": "Anti-aging actives"}}, {"id": "niacinamide", "name": "Niacinamide", "type": "Ingredient", "properties": {"role": "Barrier repair"}}], "relationships": [{"source": "hyaluronic_acid", "target": "niacinamide", "type": "COMPLEMENTS", "properties": {"benefit": "Hydration + Barrier"}}]}
\ No newline at end of file
+{
+ "entities": [
+ {
+ "id": "hyaluronic_acid",
+ "name": "Hyaluronic Acid",
+ "type": "Ingredient",
+ "properties": {
+ "role": "Humectant"
+ }
+ },
+ {
+ "id": "retinol",
+ "name": "Retinol",
+ "type": "Ingredient",
+ "properties": {
+ "role": "Anti-aging actives"
+ }
+ },
+ {
+ "id": "niacinamide",
+ "name": "Niacinamide",
+ "type": "Ingredient",
+ "properties": {
+ "role": "Barrier repair"
+ }
+ }
+ ],
+ "relationships": [
+ {
+ "source": "hyaluronic_acid",
+ "target": "niacinamide",
+ "type": "COMPLEMENTS",
+ "properties": {
+ "benefit": "Hydration + Barrier"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/semantica/semantic_extract/methods.py b/semantica/semantic_extract/methods.py
index 07f86dfb..b117e1da 100644
--- a/semantica/semantic_extract/methods.py
+++ b/semantica/semantic_extract/methods.py
@@ -321,7 +321,13 @@ def extract_entities_llm(
raise ProcessingError(f"{provider} provider not available")
prompt = f"""Extract named entities from the following text.
-Return JSON format: [{{"text": "...", "label": "PERSON|ORG|GPE|DATE|...", "start": 0, "end": 10}}]
+Return ONLY a valid JSON list of objects with the following structure:
+[
+ {{"text": "entity name", "label": "ENTITY_TYPE", "start": 0, "end": 10, "confidence": 0.9}}
+]
+
+Entity types should be one of: PERSON, ORG, GPE, DATE, EVENT, PRODUCT, CONCEPT.
+Do not include any conversational filler, explanations, or markdown formatting outside the JSON block.
Text: {text}"""
diff --git a/semantica/semantic_extract/providers.py b/semantica/semantic_extract/providers.py
index 8b687145..90a447a3 100644
--- a/semantica/semantic_extract/providers.py
+++ b/semantica/semantic_extract/providers.py
@@ -120,6 +120,14 @@ class BaseProvider:
cleaned_text = block
break
+ def fix_json(json_str: str) -> str:
+ """Basic JSON fixing for common LLM errors."""
+ # Remove trailing commas before closing braces/brackets
+ json_str = re.sub(r",\s*([\]}])", r"\1", json_str)
+ return json_str
+
+ import re
+
try:
return json.loads(cleaned_text)
except json.JSONDecodeError:
@@ -128,33 +136,46 @@ class BaseProvider:
start_list = cleaned_text.find("[")
# Determine which one starts first
+ start = -1
if start_obj >= 0 and (start_list < 0 or start_obj < start_list):
- # Potential object
- end_obj = cleaned_text.rfind("}")
- if end_obj > start_obj:
- try:
- return json.loads(cleaned_text[start_obj:end_obj+1])
- except json.JSONDecodeError:
- pass
+ start = start_obj
+ elif start_list >= 0:
+ start = start_list
- if start_list >= 0:
- # Potential list
+ if start >= 0:
+ # Find the corresponding end
+ end_obj = cleaned_text.rfind("}")
end_list = cleaned_text.rfind("]")
- if end_list > start_list:
+ end = max(end_obj, end_list)
+
+ if end > start:
+ candidate = cleaned_text[start:end+1]
try:
- return json.loads(cleaned_text[start_list:end_list+1])
+ return json.loads(candidate)
except json.JSONDecodeError:
- pass
-
- # If we still haven't found it, try any combination
- start = min(s for s in [start_obj, start_list] if s >= 0) if (start_obj >= 0 or start_list >= 0) else -1
- end = max(e for e in [cleaned_text.rfind("}"), cleaned_text.rfind("]")] if e >= 0) if (cleaned_text.rfind("}") >= 0 or cleaned_text.rfind("]") >= 0) else -1
-
- if start >= 0 and end > start:
- try:
- return json.loads(cleaned_text[start:end+1])
- except json.JSONDecodeError as e:
- raise ProcessingError(f"Failed to parse extracted JSON: {e}\nRaw snippet: {cleaned_text[start:min(start+50, end+1)]}...")
+ # Try fixing common errors
+ try:
+ return json.loads(fix_json(candidate))
+ except json.JSONDecodeError:
+ # Last resort: if it's truncated, try to close it
+ if candidate.endswith("..."):
+ candidate = candidate[:-3].strip()
+
+ # Simple attempt to close unclosed structures
+ # This is very basic and might not work for complex cases
+ open_braces = candidate.count("{") - candidate.count("}")
+ open_brackets = candidate.count("[") - candidate.count("]")
+
+ fixed_candidate = candidate
+ if open_braces > 0:
+ fixed_candidate += "}" * open_braces
+ if open_brackets > 0:
+ fixed_candidate += "]" * open_brackets
+
+ try:
+ return json.loads(fix_json(fixed_candidate))
+ except json.JSONDecodeError as e:
+ raise ProcessingError(f"Failed to parse extracted JSON: {e}\nRaw snippet: {candidate[:50]}...")
raise ProcessingError(f"No JSON structure found in response. Raw response: {text[:100]}...")