zucchetti-llm-course

Lab 05: Graph RAG and Knowledge Graphs

Lecture: 6, Graph RAG and Knowledge Graphs Duration: 30 minutes Difficulty: Advanced

Objectives

Prerequisites

Requirement How to Check
Python 3.10+ python --version
Dependencies pip install openai networkx matplotlib pyvis rich python-dotenv
LLM access Ollama or DeepSeek API key (DeepSeek is recommended for JSON extraction)

Quick Start

cd lab_05_graph_rag
python lab_05_graph_rag.py

Files

File Description
lab_05_graph_rag.py Main script with TODO section
lab_05_graph_rag.ipynb Jupyter notebook version
solutions.py Graph building solution
data/clinical_notes/ 5 sample clinical notes (de-identified)

Tasks

Task 1: Information Extraction

The script uses the LLM to read clinical notes and extract a JSON array of (source, relation, target) triplets. Observe how prompt engineering forces structured output.

Task 2: Build the Knowledge Graph

Find the build_knowledge_graph() function. Implement the logic to add nodes and edges to the NetworkX directed graph based on the extracted triplets.

Hint:

G.add_edge(source, target, label=relation)

Task 3: Visualize

The script generates knowledge_graph.html. Open it in your web browser! You can drag nodes around and see how patients, diseases, and medications connect.

Task 4: Query the Graph

Observe how the script answers queries. Instead of just embedding the text, it finds the relevant entity in the graph, extracts its “1-hop neighborhood” (all connected nodes and edges), and passes that structured context to the LLM.

Expected Output

🆘 Troubleshooting

Issue Solution
JSON parsing errors Extraction is hard for smaller local models. Try DeepSeek, or use the fallback data logic.
Empty Graph Did you implement the build_knowledge_graph() TODO?
Visualization doesn’t open Open knowledge_graph.html manually in Chrome/Safari/Edge.