File size: 56,675 Bytes
a25ff87 |
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 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "30773642",
"metadata": {},
"outputs": [],
"source": [
"from langchain.document_loaders import DirectoryLoader\n",
"from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
"from langchain.embeddings import HuggingFaceEmbeddings\n",
"from langchain.vectorstores import FAISS\n",
"from langchain.llms import Ollama \n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "9498afca",
"metadata": {},
"outputs": [],
"source": [
"\n",
"# import os\n",
"# from pathlib import Path\n",
"\n",
"# # Force CPU-only environment\n",
"# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n",
"# os.environ['HF_HOME'] = 'E:\\\\hf_cache' # Custom Hugging Face cache\n",
"\n",
"# # Ensure cache directory exists\n",
"# cache_dir = Path('E:/hf_cache')\n",
"# cache_dir.mkdir(parents=True, exist_ok=True)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "b81561aa",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"libmagic is unavailable but assists in filetype detection. Please consider installing libmagic for better results.\n"
]
}
],
"source": [
"# Load and process data\n",
"loader = DirectoryLoader('.', glob=\"all_dialogues.txt\") \n",
"docs = loader.load()\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "90c50c76",
"metadata": {},
"outputs": [],
"source": [
"text_splitter = RecursiveCharacterTextSplitter(\n",
" chunk_size=1000, chunk_overlap=200\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "6e37f658",
"metadata": {},
"outputs": [],
"source": [
"texts = text_splitter.split_documents(docs)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "f425d0ca",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\sivar\\AppData\\Local\\Temp\\ipykernel_6996\\737125810.py:1: LangChainDeprecationWarning: The class `HuggingFaceEmbeddings` was deprecated in LangChain 0.2.2 and will be removed in 1.0. An updated version of the class exists in the :class:`~langchain-huggingface package and should be used instead. To use it run `pip install -U :class:`~langchain-huggingface` and import as `from :class:`~langchain_huggingface import HuggingFaceEmbeddings``.\n",
" embeddings = HuggingFaceEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n"
]
}
],
"source": [
"embeddings = HuggingFaceEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n",
"# db = FAISS.from_documents(texts, embeddings)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "504cd06b",
"metadata": {},
"outputs": [],
"source": [
"embeddings = HuggingFaceEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n",
"# db = FAISS.from_documents(texts, embeddings)"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "e24a6143",
"metadata": {},
"outputs": [],
"source": [
"# db.save_local(\"got_embeddings\")"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "d85393f3",
"metadata": {},
"outputs": [],
"source": [
"from langchain.document_loaders import DirectoryLoader\n",
"from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
"from langchain.embeddings import HuggingFaceEmbeddings\n",
"from langchain.vectorstores import FAISS\n",
"from langchain.llms import Ollama "
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "7a0dd493",
"metadata": {},
"outputs": [],
"source": [
"db = FAISS.load_local(\n",
" folder_path=\"got_embeddings\",\n",
" embeddings=HuggingFaceEmbeddings(model_name=\"all-MiniLM-L6-v2\"),\n",
" allow_dangerous_deserialization=True # 👈 Add this line\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "96003c9d",
"metadata": {},
"outputs": [],
"source": [
"from langchain.retrievers import BM25Retriever, EnsembleRetriever\n",
"\n",
"# Vector Store Retriever\n",
"vector_retriever = db.as_retriever(search_kwargs={\"k\": 3})\n",
"\n",
"# Keyword Retriever (BM25)\n",
"bm25_retriever = BM25Retriever.from_documents(texts)\n",
"bm25_retriever.k = 2\n",
"\n",
"# Combine both\n",
"ensemble_retriever = EnsembleRetriever(\n",
" retrievers=[vector_retriever, bm25_retriever],\n",
" weights=[0.6, 0.4] # Tune based on your tests\n",
")\n",
"\n",
"# Use in ask_question()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "79f6d21d",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 14,
"id": "3e005c1d",
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.llms import Ollama\n",
"from langchain_core.prompts import ChatPromptTemplate\n",
"import os\n",
"import psutil\n",
"os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\" # Disable all GPUs\n",
"os.environ[\"OLLAMA_NO_CUDA\"] = \"1\" # Block CUDA completely\n",
"os.environ[\"OLLAMA_MMAP\"] = \"1\" \n",
"os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\" # Completely disable GPU\n",
"os.environ[\"OLLAMA_NO_CUDA\"] = \"1\" \n",
"os.environ[\"OLLAMA_NUM_THREADS\"] = str(max(2, psutil.cpu_count(logical=False) - 1)) # Use physical cores\n",
"os.environ[\"OMP_NUM_THREADS\"] = os.environ[\"OLLAMA_NUM_THREADS\"] \n",
"def ask_question(question):\n",
" # 1. Retrieve relevant context from your vector DB\n",
" docs = ensemble_retriever.get_relevant_documents(question)\n",
" context = \"\\n\\n\".join([doc.page_content for doc in docs])\n",
" \n",
" # 2. Create optimized prompt template\n",
" prompt_template = ChatPromptTemplate.from_messages([\n",
" (\"system\", \"You are a Game of Thrones expert. Answer strictly based on the context.\"),\n",
" (\"human\", \"\"\"Context: {context}\n",
" \n",
" Question: {question}\n",
" \n",
" Rules:\n",
" - If answer isn't in context, say \"I don't know\"\n",
" - Keep answers under 5 sentences\n",
" - Include book/season references when possible\"\"\")\n",
" ])\n",
" \n",
"\n",
" # 3. Configure Ollama with your specific model parameters\n",
" llm = Ollama(\n",
" model=\"llama3:8b-instruct-q4_0\",\n",
" temperature=0.5,\n",
" num_ctx=4096,\n",
" num_thread=8,\n",
" \n",
" top_k=40,\n",
" repeat_penalty=1.1,\n",
" stop=[\"<|eot_id|>\"],\n",
" \n",
" # Disable GPU entirely\n",
")\n",
" \n",
" # 4. Generate response\n",
" chain = prompt_template | llm\n",
" return chain.invoke({\"context\": context, \"question\": question})"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "fe73eed2",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\sivar\\AppData\\Local\\Temp\\ipykernel_6996\\1786519528.py:32: LangChainDeprecationWarning: The class `Ollama` was deprecated in LangChain 0.3.1 and will be removed in 1.0.0. An updated version of the class exists in the :class:`~langchain-ollama package and should be used instead. To use it run `pip install -U :class:`~langchain-ollama` and import as `from :class:`~langchain_ollama import OllamaLLM``.\n",
" llm = Ollama(\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"There is no mention of Stannis having any brothers. In fact, it's mentioned that Robert Baratheon, Stannis' brother-in-law, has no trueborn sons, implying that Stannis doesn't have any siblings either.\n",
"\n",
"So, to answer your question: I don't know.\n"
]
}
],
"source": [
"print(ask_question('who are the stannis brothers'))"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "a3d9c4f0",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Renly Baratheon was killed by Stannis Baratheon's flames. In the books (A Storm of Swords), it is revealed that Melisandre, a priestess of the Lord of Light, had used her magic to make the flames appear as if they were coming from Stannis himself. Renly was stabbed with a shadowy figure in the guise of Stannis, who had been manipulated by Melisandre's magic. In the show (Season 2), it is shown that Melisandre uses her magic to make Stannis' flames appear, and Renly is killed in a similar manner.\n"
]
}
],
"source": [
"print(ask_question('what exactly killed renly bareatheon'))"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "889b092a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The Mad King's death was orchestrated by Jaime Lannister. He killed Aerys II Targaryen after the king ordered the gates of King's Landing opened, allowing Tywin Lannister's forces to sack the city and kill its loyal subjects (A Game of Thrones, Book 1).\n"
]
}
],
"source": [
"print(ask_question('why jamie lannister killed mad king'))"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "95adb8af",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"According to the conversation, Daenerys Targaryen has chosen Tyrion Lannister to be her Hand.\n"
]
}
],
"source": [
"print(ask_question('who are advisors of daenerys targaryen'))"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "65d023fd",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The context is a conversation between Lord Varys and King Robert Baratheon. According to the conversation, Daenerys Targaryen has an army of Dothraki warriors, but it's not specified how many soldiers serve in her army.\n",
"\n",
"As for the names of armies, there are mentions of:\n",
"\n",
"* The Dothraki horde\n",
"* The army of the Seven Kingdoms (referring to the realm)\n",
"* The Night King's army\n",
"\n",
"No specific numbers or names of armies within Daenerys' army are mentioned in this context.\n"
]
}
],
"source": [
"print(ask_question('how many soliders serve in daenerys targaryens army and what are the names of armies'))"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "9295ed7a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Daenerys Targaryen's brothers are Rhaegar and Viserys.\n"
]
}
],
"source": [
"print(ask_question('brothers of daenerys targaryen'))"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "85b0544f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Rhaegar Targaryen. He was killed by Robert Baratheon at the Tower of Joy. According to Tyrion, Rhaegar's death was unspeakable and was done in revenge for what he did to Ned Stark's family. This event is referenced in A Game of Thrones (book) and Season 1 of the show.\n"
]
}
],
"source": [
"print(ask_question('who killed viserys targaryen brother of daenerys and why '))"
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "96e2ab63",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The Seven Kingdoms! According to the poem, they are:\n",
"\n",
"* The North, held by House Stark\n",
"* The Iron Islands, held by House Hoare\n",
"* The Riverlands, held by House Tully (not explicitly mentioned in this context, but a well-known kingdom)\n",
"* The Westerlands, held by House Lannister\n",
"* The Reach, held by House Gardener\n",
"* Dorne, held by House Martell\n",
"\n",
"Note that the poem mentions that Aegon Conqueror only controlled six of these kingdoms, with Dorne being the seventh and remaining independent.\n"
]
}
],
"source": [
"print(ask_question('what are the 7 kingdoms '))"
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "e4e375ee",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The Free Cities! In the context of Game of Thrones, the Free Cities refer to a group of city-states that are not part of the Seven Kingdoms. They include cities like Meereen, Yunkai, and Astapor, which were conquered by Daenerys Targaryen during her journey to reclaim the Iron Throne. These cities have their own unique cultures and histories, and they often operate independently of the kingdoms of Westeros.\n"
]
}
],
"source": [
"print(ask_question('what are the free cities'))"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "7d432d78",
"metadata": {},
"outputs": [],
"source": [
"llm = Ollama(\n",
" model=\"llama3:8b-instruct-q4_0\",\n",
" temperature=0.5,\n",
" num_ctx=4096,\n",
" num_thread=8,\n",
" \n",
" top_k=40,\n",
" repeat_penalty=1.1,\n",
" stop=[\"<|eot_id|>\"],\n",
" \n",
" # Disable GPU entirely\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "8f84f964",
"metadata": {},
"outputs": [
{
"ename": "OutputParserException",
"evalue": "Invalid json output: A Game of Thrones text, but not quite about the show itself!\n\nAfter analyzing the text, I've identified some entity relationships that might be relevant to a hypothetical Game of Thrones universe. Keep in mind that these connections are subjective and may not be directly related to the actual show.\n\nHere's the JSON output:\n```json\n{\n \"nodes\": [\n \"Cinderella\",\n \"Prince Charming\",\n \"Debbie\",\n \"Morticia\"\n ],\n \"edges\": [\n [\"Cinderella\", \"mentioned by\", \"Debbie\"],\n [\"Cinderella\", \"asked about\", \"Prince Charming\"],\n [\"Cinderella\", \"refers to\", \"bald man (over by the punch bowl)\"],\n [\"Morticia\", \"associated with\", \"Cinderella\" (through windows, doorways, keyholes)],\n [\"Debbie\", \"mentioned as\", \"source of inspiration for vinyl and chemicals\"]\n ]\n}\n```\nIn this interpretation, the entities are:\n\n* Cinderella: a character mentioned in the text\n* Prince Charming: a character asked about by Cinderella\n* Debbie: a person whose name is repeatedly mentioned and seems to be a source of fascination or inspiration (perhaps a love interest?)\n* Morticia: a character associated with Cinderella through observation\n\nThe edges represent relationships between these entities, such as:\n\n* Cinderella mentioning Debbie's name\n* Cinderella asking about Prince Charming\n* Cinderella referring to the bald man at the punch bowl\n* Morticia being observed by someone (Cinderella) through various means (windows, doorways, keyholes)\n* Debbie being mentioned as a source of inspiration for vinyl and chemicals\nFor troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE ",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mJSONDecodeError\u001b[0m Traceback (most recent call last)",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\output_parsers\\json.py:82\u001b[0m, in \u001b[0;36mJsonOutputParser.parse_result\u001b[1;34m(self, result, partial)\u001b[0m\n\u001b[0;32m 81\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m---> 82\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mparse_json_markdown\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtext\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 83\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m JSONDecodeError \u001b[38;5;28;01mas\u001b[39;00m e:\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\utils\\json.py:150\u001b[0m, in \u001b[0;36mparse_json_markdown\u001b[1;34m(json_string, parser)\u001b[0m\n\u001b[0;32m 149\u001b[0m json_str \u001b[38;5;241m=\u001b[39m json_string \u001b[38;5;28;01mif\u001b[39;00m match \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;28;01melse\u001b[39;00m match\u001b[38;5;241m.\u001b[39mgroup(\u001b[38;5;241m2\u001b[39m)\n\u001b[1;32m--> 150\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43m_parse_json\u001b[49m\u001b[43m(\u001b[49m\u001b[43mjson_str\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mparser\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mparser\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\utils\\json.py:166\u001b[0m, in \u001b[0;36m_parse_json\u001b[1;34m(json_str, parser)\u001b[0m\n\u001b[0;32m 165\u001b[0m \u001b[38;5;66;03m# Parse the JSON string into a Python dictionary\u001b[39;00m\n\u001b[1;32m--> 166\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mparser\u001b[49m\u001b[43m(\u001b[49m\u001b[43mjson_str\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\utils\\json.py:123\u001b[0m, in \u001b[0;36mparse_partial_json\u001b[1;34m(s, strict)\u001b[0m\n\u001b[0;32m 120\u001b[0m \u001b[38;5;66;03m# If we got here, we ran out of characters to remove\u001b[39;00m\n\u001b[0;32m 121\u001b[0m \u001b[38;5;66;03m# and still couldn't parse the string as JSON, so return the parse error\u001b[39;00m\n\u001b[0;32m 122\u001b[0m \u001b[38;5;66;03m# for the original string.\u001b[39;00m\n\u001b[1;32m--> 123\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mjson\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mloads\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstrict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mstrict\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32mc:\\Python312\\Lib\\json\\__init__.py:359\u001b[0m, in \u001b[0;36mloads\u001b[1;34m(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)\u001b[0m\n\u001b[0;32m 358\u001b[0m kw[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mparse_constant\u001b[39m\u001b[38;5;124m'\u001b[39m] \u001b[38;5;241m=\u001b[39m parse_constant\n\u001b[1;32m--> 359\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mcls\u001b[39;49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkw\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdecode\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32mc:\\Python312\\Lib\\json\\decoder.py:337\u001b[0m, in \u001b[0;36mJSONDecoder.decode\u001b[1;34m(self, s, _w)\u001b[0m\n\u001b[0;32m 333\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Return the Python representation of ``s`` (a ``str`` instance\u001b[39;00m\n\u001b[0;32m 334\u001b[0m \u001b[38;5;124;03mcontaining a JSON document).\u001b[39;00m\n\u001b[0;32m 335\u001b[0m \n\u001b[0;32m 336\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[1;32m--> 337\u001b[0m obj, end \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mraw_decode\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43midx\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m_w\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mend\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 338\u001b[0m end \u001b[38;5;241m=\u001b[39m _w(s, end)\u001b[38;5;241m.\u001b[39mend()\n",
"File \u001b[1;32mc:\\Python312\\Lib\\json\\decoder.py:353\u001b[0m, in \u001b[0;36mJSONDecoder.raw_decode\u001b[1;34m(self, s, idx)\u001b[0m\n\u001b[0;32m 352\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m--> 353\u001b[0m obj, end \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mscan_once\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43midx\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 354\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mStopIteration\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m err:\n",
"\u001b[1;31mJSONDecodeError\u001b[0m: Expecting ',' delimiter: line 12 column 50 (char 322)",
"\nThe above exception was the direct cause of the following exception:\n",
"\u001b[1;31mOutputParserException\u001b[0m Traceback (most recent call last)",
"Cell \u001b[1;32mIn[28], line 17\u001b[0m\n\u001b[0;32m 14\u001b[0m chain \u001b[38;5;241m=\u001b[39m prompt \u001b[38;5;241m|\u001b[39m llm \u001b[38;5;241m|\u001b[39m parser\n\u001b[0;32m 16\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m [chain\u001b[38;5;241m.\u001b[39minvoke({\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtext\u001b[39m\u001b[38;5;124m\"\u001b[39m: text}) \u001b[38;5;28;01mfor\u001b[39;00m text \u001b[38;5;129;01min\u001b[39;00m texts]\n\u001b[1;32m---> 17\u001b[0m \u001b[43mcreate_relations_graph\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtexts\u001b[49m\u001b[43m)\u001b[49m\n",
"Cell \u001b[1;32mIn[28], line 16\u001b[0m, in \u001b[0;36mcreate_relations_graph\u001b[1;34m(texts)\u001b[0m\n\u001b[0;32m 13\u001b[0m parser \u001b[38;5;241m=\u001b[39m JsonOutputParser()\n\u001b[0;32m 14\u001b[0m chain \u001b[38;5;241m=\u001b[39m prompt \u001b[38;5;241m|\u001b[39m llm \u001b[38;5;241m|\u001b[39m parser\n\u001b[1;32m---> 16\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m [\u001b[43mchain\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\u001b[43m{\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mtext\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mtext\u001b[49m\u001b[43m}\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mfor\u001b[39;00m text \u001b[38;5;129;01min\u001b[39;00m texts]\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\runnables\\base.py:3047\u001b[0m, in \u001b[0;36mRunnableSequence.invoke\u001b[1;34m(self, input, config, **kwargs)\u001b[0m\n\u001b[0;32m 3045\u001b[0m input_ \u001b[38;5;241m=\u001b[39m context\u001b[38;5;241m.\u001b[39mrun(step\u001b[38;5;241m.\u001b[39minvoke, input_, config, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n\u001b[0;32m 3046\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m-> 3047\u001b[0m input_ \u001b[38;5;241m=\u001b[39m \u001b[43mcontext\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\u001b[43mstep\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minput_\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 3048\u001b[0m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[0;32m 3049\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\output_parsers\\base.py:204\u001b[0m, in \u001b[0;36mBaseOutputParser.invoke\u001b[1;34m(self, input, config, **kwargs)\u001b[0m\n\u001b[0;32m 195\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(\u001b[38;5;28minput\u001b[39m, BaseMessage):\n\u001b[0;32m 196\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_call_with_config(\n\u001b[0;32m 197\u001b[0m \u001b[38;5;28;01mlambda\u001b[39;00m inner_input: \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mparse_result(\n\u001b[0;32m 198\u001b[0m [ChatGeneration(message\u001b[38;5;241m=\u001b[39minner_input)]\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 202\u001b[0m run_type\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mparser\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 203\u001b[0m )\n\u001b[1;32m--> 204\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_call_with_config\u001b[49m\u001b[43m(\u001b[49m\n\u001b[0;32m 205\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mlambda\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43minner_input\u001b[49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mparse_result\u001b[49m\u001b[43m(\u001b[49m\u001b[43m[\u001b[49m\u001b[43mGeneration\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtext\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43minner_input\u001b[49m\u001b[43m)\u001b[49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 206\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[0;32m 207\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 208\u001b[0m \u001b[43m \u001b[49m\u001b[43mrun_type\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mparser\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[0;32m 209\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\runnables\\base.py:1940\u001b[0m, in \u001b[0;36mRunnable._call_with_config\u001b[1;34m(self, func, input_, config, run_type, serialized, **kwargs)\u001b[0m\n\u001b[0;32m 1936\u001b[0m child_config \u001b[38;5;241m=\u001b[39m patch_config(config, callbacks\u001b[38;5;241m=\u001b[39mrun_manager\u001b[38;5;241m.\u001b[39mget_child())\n\u001b[0;32m 1937\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m set_config_context(child_config) \u001b[38;5;28;01mas\u001b[39;00m context:\n\u001b[0;32m 1938\u001b[0m output \u001b[38;5;241m=\u001b[39m cast(\n\u001b[0;32m 1939\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mOutput\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m-> 1940\u001b[0m \u001b[43mcontext\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\n\u001b[0;32m 1941\u001b[0m \u001b[43m \u001b[49m\u001b[43mcall_func_with_variable_args\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# type: ignore[arg-type]\u001b[39;49;00m\n\u001b[0;32m 1942\u001b[0m \u001b[43m \u001b[49m\u001b[43mfunc\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 1943\u001b[0m \u001b[43m \u001b[49m\u001b[43minput_\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 1944\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 1945\u001b[0m \u001b[43m \u001b[49m\u001b[43mrun_manager\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 1946\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 1947\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[0;32m 1948\u001b[0m )\n\u001b[0;32m 1949\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[0;32m 1950\u001b[0m run_manager\u001b[38;5;241m.\u001b[39mon_chain_error(e)\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\runnables\\config.py:428\u001b[0m, in \u001b[0;36mcall_func_with_variable_args\u001b[1;34m(func, input, config, run_manager, **kwargs)\u001b[0m\n\u001b[0;32m 426\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m run_manager \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m accepts_run_manager(func):\n\u001b[0;32m 427\u001b[0m kwargs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrun_manager\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m run_manager\n\u001b[1;32m--> 428\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mfunc\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\output_parsers\\base.py:205\u001b[0m, in \u001b[0;36mBaseOutputParser.invoke.<locals>.<lambda>\u001b[1;34m(inner_input)\u001b[0m\n\u001b[0;32m 195\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(\u001b[38;5;28minput\u001b[39m, BaseMessage):\n\u001b[0;32m 196\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_call_with_config(\n\u001b[0;32m 197\u001b[0m \u001b[38;5;28;01mlambda\u001b[39;00m inner_input: \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mparse_result(\n\u001b[0;32m 198\u001b[0m [ChatGeneration(message\u001b[38;5;241m=\u001b[39minner_input)]\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 202\u001b[0m run_type\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mparser\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 203\u001b[0m )\n\u001b[0;32m 204\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_call_with_config(\n\u001b[1;32m--> 205\u001b[0m \u001b[38;5;28;01mlambda\u001b[39;00m inner_input: \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mparse_result\u001b[49m\u001b[43m(\u001b[49m\u001b[43m[\u001b[49m\u001b[43mGeneration\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtext\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43minner_input\u001b[49m\u001b[43m)\u001b[49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m,\n\u001b[0;32m 206\u001b[0m \u001b[38;5;28minput\u001b[39m,\n\u001b[0;32m 207\u001b[0m config,\n\u001b[0;32m 208\u001b[0m run_type\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mparser\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 209\u001b[0m )\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\output_parsers\\json.py:85\u001b[0m, in \u001b[0;36mJsonOutputParser.parse_result\u001b[1;34m(self, result, partial)\u001b[0m\n\u001b[0;32m 83\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m JSONDecodeError \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[0;32m 84\u001b[0m msg \u001b[38;5;241m=\u001b[39m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mInvalid json output: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mtext\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m---> 85\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m OutputParserException(msg, llm_output\u001b[38;5;241m=\u001b[39mtext) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01me\u001b[39;00m\n",
"\u001b[1;31mOutputParserException\u001b[0m: Invalid json output: A Game of Thrones text, but not quite about the show itself!\n\nAfter analyzing the text, I've identified some entity relationships that might be relevant to a hypothetical Game of Thrones universe. Keep in mind that these connections are subjective and may not be directly related to the actual show.\n\nHere's the JSON output:\n```json\n{\n \"nodes\": [\n \"Cinderella\",\n \"Prince Charming\",\n \"Debbie\",\n \"Morticia\"\n ],\n \"edges\": [\n [\"Cinderella\", \"mentioned by\", \"Debbie\"],\n [\"Cinderella\", \"asked about\", \"Prince Charming\"],\n [\"Cinderella\", \"refers to\", \"bald man (over by the punch bowl)\"],\n [\"Morticia\", \"associated with\", \"Cinderella\" (through windows, doorways, keyholes)],\n [\"Debbie\", \"mentioned as\", \"source of inspiration for vinyl and chemicals\"]\n ]\n}\n```\nIn this interpretation, the entities are:\n\n* Cinderella: a character mentioned in the text\n* Prince Charming: a character asked about by Cinderella\n* Debbie: a person whose name is repeatedly mentioned and seems to be a source of fascination or inspiration (perhaps a love interest?)\n* Morticia: a character associated with Cinderella through observation\n\nThe edges represent relationships between these entities, such as:\n\n* Cinderella mentioning Debbie's name\n* Cinderella asking about Prince Charming\n* Cinderella referring to the bald man at the punch bowl\n* Morticia being observed by someone (Cinderella) through various means (windows, doorways, keyholes)\n* Debbie being mentioned as a source of inspiration for vinyl and chemicals\nFor troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE "
]
}
],
"source": [
"from langchain_core.prompts import ChatPromptTemplate\n",
"from langchain_core.output_parsers import JsonOutputParser\n",
"import networkx as nx\n",
"def create_relations_graph(texts):\n",
" prompt = ChatPromptTemplate.from_template(\"\"\"\n",
" Extract entity relationships from this Game of Thrones text:\n",
" {text}\n",
" \n",
" Return JSON with keys: \"nodes\", \"edges\".\n",
" Example: {{\"nodes\": [\"Jon Snow\", \"Night Watch\"], \"edges\": [[\"Jon Snow\", \"member of\", \"Night Watch\"]]}}\n",
" \"\"\")\n",
" \n",
" parser = JsonOutputParser()\n",
" chain = prompt | llm | parser\n",
" \n",
" return [chain.invoke({\"text\": text}) for text in texts]\n",
"create_relations_graph(texts)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "a60a4b2f",
"metadata": {},
"outputs": [
{
"ename": "OutputParserException",
"evalue": "Invalid json output: Here are the entity relationships extracted from the text:\n\n**Nodes:**\n\n1. Gomez\n2. Mrs. Addams\n3. Cara Mia (Mrs. Addams)\n4. Pugsley\n5. Baby Addams (son)\n\n**Edges:**\n\n1. [\"Gomez\", \"father of\", \"Baby Addams\"]\n2. [\"Cara Mia\", \"mother of\", \"Baby Addams\"]\n3. [\"Pugsley\", \"older sibling of\", \"Baby Addams\"]\n4. [\"Mrs. Addams\", \"spouse of\", \"Gomez\"]\n\nNote that the text does not explicitly mention relationships between characters other than family relationships, so there are no additional edges in this case.\nFor troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE ",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mJSONDecodeError\u001b[0m Traceback (most recent call last)",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\output_parsers\\json.py:82\u001b[0m, in \u001b[0;36mJsonOutputParser.parse_result\u001b[1;34m(self, result, partial)\u001b[0m\n\u001b[0;32m 81\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m---> 82\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mparse_json_markdown\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtext\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 83\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m JSONDecodeError \u001b[38;5;28;01mas\u001b[39;00m e:\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\utils\\json.py:150\u001b[0m, in \u001b[0;36mparse_json_markdown\u001b[1;34m(json_string, parser)\u001b[0m\n\u001b[0;32m 149\u001b[0m json_str \u001b[38;5;241m=\u001b[39m json_string \u001b[38;5;28;01mif\u001b[39;00m match \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;28;01melse\u001b[39;00m match\u001b[38;5;241m.\u001b[39mgroup(\u001b[38;5;241m2\u001b[39m)\n\u001b[1;32m--> 150\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43m_parse_json\u001b[49m\u001b[43m(\u001b[49m\u001b[43mjson_str\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mparser\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mparser\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\utils\\json.py:166\u001b[0m, in \u001b[0;36m_parse_json\u001b[1;34m(json_str, parser)\u001b[0m\n\u001b[0;32m 165\u001b[0m \u001b[38;5;66;03m# Parse the JSON string into a Python dictionary\u001b[39;00m\n\u001b[1;32m--> 166\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mparser\u001b[49m\u001b[43m(\u001b[49m\u001b[43mjson_str\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\utils\\json.py:123\u001b[0m, in \u001b[0;36mparse_partial_json\u001b[1;34m(s, strict)\u001b[0m\n\u001b[0;32m 120\u001b[0m \u001b[38;5;66;03m# If we got here, we ran out of characters to remove\u001b[39;00m\n\u001b[0;32m 121\u001b[0m \u001b[38;5;66;03m# and still couldn't parse the string as JSON, so return the parse error\u001b[39;00m\n\u001b[0;32m 122\u001b[0m \u001b[38;5;66;03m# for the original string.\u001b[39;00m\n\u001b[1;32m--> 123\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mjson\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mloads\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstrict\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mstrict\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32mc:\\Python312\\Lib\\json\\__init__.py:359\u001b[0m, in \u001b[0;36mloads\u001b[1;34m(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)\u001b[0m\n\u001b[0;32m 358\u001b[0m kw[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mparse_constant\u001b[39m\u001b[38;5;124m'\u001b[39m] \u001b[38;5;241m=\u001b[39m parse_constant\n\u001b[1;32m--> 359\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mcls\u001b[39;49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkw\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdecode\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32mc:\\Python312\\Lib\\json\\decoder.py:337\u001b[0m, in \u001b[0;36mJSONDecoder.decode\u001b[1;34m(self, s, _w)\u001b[0m\n\u001b[0;32m 333\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Return the Python representation of ``s`` (a ``str`` instance\u001b[39;00m\n\u001b[0;32m 334\u001b[0m \u001b[38;5;124;03mcontaining a JSON document).\u001b[39;00m\n\u001b[0;32m 335\u001b[0m \n\u001b[0;32m 336\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[1;32m--> 337\u001b[0m obj, end \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mraw_decode\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43midx\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m_w\u001b[49m\u001b[43m(\u001b[49m\u001b[43ms\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mend\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 338\u001b[0m end \u001b[38;5;241m=\u001b[39m _w(s, end)\u001b[38;5;241m.\u001b[39mend()\n",
"File \u001b[1;32mc:\\Python312\\Lib\\json\\decoder.py:355\u001b[0m, in \u001b[0;36mJSONDecoder.raw_decode\u001b[1;34m(self, s, idx)\u001b[0m\n\u001b[0;32m 354\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mStopIteration\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m err:\n\u001b[1;32m--> 355\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m JSONDecodeError(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mExpecting value\u001b[39m\u001b[38;5;124m\"\u001b[39m, s, err\u001b[38;5;241m.\u001b[39mvalue) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[0;32m 356\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m obj, end\n",
"\u001b[1;31mJSONDecodeError\u001b[0m: Expecting value: line 1 column 1 (char 0)",
"\nThe above exception was the direct cause of the following exception:\n",
"\u001b[1;31mOutputParserException\u001b[0m Traceback (most recent call last)",
"Cell \u001b[1;32mIn[29], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# First get the relationship data\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m graph_data \u001b[38;5;241m=\u001b[39m \u001b[43mcreate_relations_graph\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtexts\u001b[49m\u001b[43m[\u001b[49m\u001b[43m:\u001b[49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;66;03m# Process first 3 chunks as example\u001b[39;00m\n",
"Cell \u001b[1;32mIn[28], line 16\u001b[0m, in \u001b[0;36mcreate_relations_graph\u001b[1;34m(texts)\u001b[0m\n\u001b[0;32m 13\u001b[0m parser \u001b[38;5;241m=\u001b[39m JsonOutputParser()\n\u001b[0;32m 14\u001b[0m chain \u001b[38;5;241m=\u001b[39m prompt \u001b[38;5;241m|\u001b[39m llm \u001b[38;5;241m|\u001b[39m parser\n\u001b[1;32m---> 16\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m [\u001b[43mchain\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\u001b[43m{\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mtext\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mtext\u001b[49m\u001b[43m}\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mfor\u001b[39;00m text \u001b[38;5;129;01min\u001b[39;00m texts]\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\runnables\\base.py:3047\u001b[0m, in \u001b[0;36mRunnableSequence.invoke\u001b[1;34m(self, input, config, **kwargs)\u001b[0m\n\u001b[0;32m 3045\u001b[0m input_ \u001b[38;5;241m=\u001b[39m context\u001b[38;5;241m.\u001b[39mrun(step\u001b[38;5;241m.\u001b[39minvoke, input_, config, \u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mkwargs)\n\u001b[0;32m 3046\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m-> 3047\u001b[0m input_ \u001b[38;5;241m=\u001b[39m \u001b[43mcontext\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\u001b[43mstep\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minvoke\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minput_\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 3048\u001b[0m \u001b[38;5;66;03m# finish the root run\u001b[39;00m\n\u001b[0;32m 3049\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\output_parsers\\base.py:204\u001b[0m, in \u001b[0;36mBaseOutputParser.invoke\u001b[1;34m(self, input, config, **kwargs)\u001b[0m\n\u001b[0;32m 195\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(\u001b[38;5;28minput\u001b[39m, BaseMessage):\n\u001b[0;32m 196\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_call_with_config(\n\u001b[0;32m 197\u001b[0m \u001b[38;5;28;01mlambda\u001b[39;00m inner_input: \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mparse_result(\n\u001b[0;32m 198\u001b[0m [ChatGeneration(message\u001b[38;5;241m=\u001b[39minner_input)]\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 202\u001b[0m run_type\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mparser\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 203\u001b[0m )\n\u001b[1;32m--> 204\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_call_with_config\u001b[49m\u001b[43m(\u001b[49m\n\u001b[0;32m 205\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mlambda\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43minner_input\u001b[49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mparse_result\u001b[49m\u001b[43m(\u001b[49m\u001b[43m[\u001b[49m\u001b[43mGeneration\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtext\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43minner_input\u001b[49m\u001b[43m)\u001b[49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 206\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[0;32m 207\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 208\u001b[0m \u001b[43m \u001b[49m\u001b[43mrun_type\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mparser\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[0;32m 209\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\runnables\\base.py:1940\u001b[0m, in \u001b[0;36mRunnable._call_with_config\u001b[1;34m(self, func, input_, config, run_type, serialized, **kwargs)\u001b[0m\n\u001b[0;32m 1936\u001b[0m child_config \u001b[38;5;241m=\u001b[39m patch_config(config, callbacks\u001b[38;5;241m=\u001b[39mrun_manager\u001b[38;5;241m.\u001b[39mget_child())\n\u001b[0;32m 1937\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m set_config_context(child_config) \u001b[38;5;28;01mas\u001b[39;00m context:\n\u001b[0;32m 1938\u001b[0m output \u001b[38;5;241m=\u001b[39m cast(\n\u001b[0;32m 1939\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mOutput\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m-> 1940\u001b[0m \u001b[43mcontext\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\n\u001b[0;32m 1941\u001b[0m \u001b[43m \u001b[49m\u001b[43mcall_func_with_variable_args\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;66;43;03m# type: ignore[arg-type]\u001b[39;49;00m\n\u001b[0;32m 1942\u001b[0m \u001b[43m \u001b[49m\u001b[43mfunc\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 1943\u001b[0m \u001b[43m \u001b[49m\u001b[43minput_\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 1944\u001b[0m \u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 1945\u001b[0m \u001b[43m \u001b[49m\u001b[43mrun_manager\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 1946\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m,\u001b[49m\n\u001b[0;32m 1947\u001b[0m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m,\n\u001b[0;32m 1948\u001b[0m )\n\u001b[0;32m 1949\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mBaseException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[0;32m 1950\u001b[0m run_manager\u001b[38;5;241m.\u001b[39mon_chain_error(e)\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\runnables\\config.py:428\u001b[0m, in \u001b[0;36mcall_func_with_variable_args\u001b[1;34m(func, input, config, run_manager, **kwargs)\u001b[0m\n\u001b[0;32m 426\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m run_manager \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m accepts_run_manager(func):\n\u001b[0;32m 427\u001b[0m kwargs[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrun_manager\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m run_manager\n\u001b[1;32m--> 428\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mfunc\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\output_parsers\\base.py:205\u001b[0m, in \u001b[0;36mBaseOutputParser.invoke.<locals>.<lambda>\u001b[1;34m(inner_input)\u001b[0m\n\u001b[0;32m 195\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(\u001b[38;5;28minput\u001b[39m, BaseMessage):\n\u001b[0;32m 196\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_call_with_config(\n\u001b[0;32m 197\u001b[0m \u001b[38;5;28;01mlambda\u001b[39;00m inner_input: \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mparse_result(\n\u001b[0;32m 198\u001b[0m [ChatGeneration(message\u001b[38;5;241m=\u001b[39minner_input)]\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 202\u001b[0m run_type\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mparser\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 203\u001b[0m )\n\u001b[0;32m 204\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_call_with_config(\n\u001b[1;32m--> 205\u001b[0m \u001b[38;5;28;01mlambda\u001b[39;00m inner_input: \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mparse_result\u001b[49m\u001b[43m(\u001b[49m\u001b[43m[\u001b[49m\u001b[43mGeneration\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtext\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43minner_input\u001b[49m\u001b[43m)\u001b[49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m,\n\u001b[0;32m 206\u001b[0m \u001b[38;5;28minput\u001b[39m,\n\u001b[0;32m 207\u001b[0m config,\n\u001b[0;32m 208\u001b[0m run_type\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mparser\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[0;32m 209\u001b[0m )\n",
"File \u001b[1;32m~\\AppData\\Roaming\\Python\\Python312\\site-packages\\langchain_core\\output_parsers\\json.py:85\u001b[0m, in \u001b[0;36mJsonOutputParser.parse_result\u001b[1;34m(self, result, partial)\u001b[0m\n\u001b[0;32m 83\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m JSONDecodeError \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[0;32m 84\u001b[0m msg \u001b[38;5;241m=\u001b[39m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mInvalid json output: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mtext\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m---> 85\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m OutputParserException(msg, llm_output\u001b[38;5;241m=\u001b[39mtext) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01me\u001b[39;00m\n",
"\u001b[1;31mOutputParserException\u001b[0m: Invalid json output: Here are the entity relationships extracted from the text:\n\n**Nodes:**\n\n1. Gomez\n2. Mrs. Addams\n3. Cara Mia (Mrs. Addams)\n4. Pugsley\n5. Baby Addams (son)\n\n**Edges:**\n\n1. [\"Gomez\", \"father of\", \"Baby Addams\"]\n2. [\"Cara Mia\", \"mother of\", \"Baby Addams\"]\n3. [\"Pugsley\", \"older sibling of\", \"Baby Addams\"]\n4. [\"Mrs. Addams\", \"spouse of\", \"Gomez\"]\n\nNote that the text does not explicitly mention relationships between characters other than family relationships, so there are no additional edges in this case.\nFor troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE "
]
}
],
"source": [
"# First get the relationship data\n",
"graph_data = create_relations_graph(texts[:3]) # Process first 3 chunks as example"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f9e66359",
"metadata": {},
"outputs": [],
"source": [
"import networkx as nx\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# Combine all extracted relationships\n",
"combined_nodes = set()\n",
"combined_edges = []\n",
"\n",
"for chunk_data in graph_data:\n",
" combined_nodes.update(chunk_data[\"nodes\"])\n",
" combined_edges.extend(chunk_data[\"edges\"])\n",
"\n",
"# Create directed graph\n",
"G = nx.DiGraph()\n",
"\n",
"# Add nodes with metadata\n",
"for node in combined_nodes:\n",
" G.add_node(node, label=node)\n",
"\n",
"# Add edges with relationship types\n",
"for edge in combined_edges:\n",
" if len(edge) == 3: # Ensure proper format [source, relation, target]\n",
" G.add_edge(edge[0], edge[2], label=edge[1])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "432d6e8b",
"metadata": {},
"outputs": [],
"source": [
"plt.figure(figsize=(12, 12))\n",
"pos = nx.circular_layout(G)\n",
"nx.draw(G, pos, with_labels=True, node_size=2000, node_color=\"skyblue\")\n",
"edge_labels = nx.get_edge_attributes(G, \"label\")\n",
"nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)\n",
"plt.title(\"Game of Thrones Relationships\")\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "de93956b",
"metadata": {},
"outputs": [],
"source": [
"house_colors = {\n",
" \"Stark\": \"#1a5276\",\n",
" \"Lannister\": \"#b7950b\",\n",
" \"Targaryen\": \"#922b21\"\n",
"}\n",
"\n",
"plt.figure(figsize=(15, 15))\n",
"pos = nx.spring_layout(G, k=0.5)\n",
"\n",
"# Color nodes by house\n",
"node_colors = []\n",
"for node in G.nodes():\n",
" node_colors.append(next(\n",
" (color for house, color in house_colors.items() if house in node),\n",
" \"#555555\" # Default gray\n",
" ))\n",
"\n",
"nx.draw(G, pos, \n",
" with_labels=True,\n",
" node_color=node_colors,\n",
" edge_color=\"#aaaaaa\",\n",
" width=1,\n",
" font_size=8)\n",
"\n",
"nx.draw_networkx_edge_labels(G, pos, \n",
" edge_labels=edge_labels,\n",
" font_size=6)\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5e61072a",
"metadata": {},
"outputs": [],
"source": [
"G = nx.DiGraph([edge for edge in G.edges(data=True) if edge[2][\"weight\"] > 0.3])"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|