Lecture: 6, Graph RAG and Knowledge Graphs Duration: 30 minutes Difficulty: Advanced
NetworkX.| 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) |
cd lab_05_graph_rag
python lab_05_graph_rag.py
| 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) |
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.
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)
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.
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.
knowledge_graph.html file in the lab folder.| 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. |