In this tutorial, we'll generate knowledge graphs from plain text, conversations, and multiple source documents using kg-gen. We'll start by setting up dependencies and configuring an LLM via LiteLLM, then extract entities, predicates, and relationships from simple text. As we progress, we'll work with longer passages using chunking and clustering, combine knowledge graphs from different sources, visualize graph structures, and analyze them using NetworkX. By the end, you'll have a complete workflow that turns unstructured text into an interpretable, searchable, visual, and exportable knowledge graph.
Setup and Initialization
First, install the necessary libraries:
import subprocess, sys
def pip_install(pkgs):
subprocess.run([sys.executable, "-m", "pip", "install", "-q", *pkgs], check=True)
pip_install([
"kg-gen",
"networkx>=3.1",
"pyvis",
"matplotlib",
"python-louvain",
])
Then import packages and configure the API key:
import os, json, getpass, textwrap
from collections import Counter
from kg_gen import KGGen
import networkx as nx
from pyvis.network import Network
import matplotlib.pyplot as plt
from IPython.display import HTML, IFrame, display
MODEL = "openai/gpt-4o-mini"
KEY_NAME = "OPENAI_API_KEY"
def fetch_key(name):
try:
from google.colab import userdata
v = userdata.get(name)
if v: return v
except Exception:
pass
if os.environ.get(name):
return os.environ[name]
return getpass.getpass(f"Enter {name}: ")
os.environ[KEY_NAME] = fetch_key(KEY_NAME)
kg = KGGen(model=MODEL, temperature=0.0)
print(f"✓ KGGen initialized with model={MODEL}")
Basic Extraction
Test kg-gen on a simple family relationship example:
simple_text = (
"Linda is Josh's mother. Ben is Josh's brother. "
"Andrew is Josh's father. Josh studies at Stanford University."
)
g_basic = kg.generate(input_data=simple_text, context="Family relationships")
print("Entities :", g_basic.entities)
print("Edges :", g_basic.edges)
print("Relations:")
for s, p, o in g_basic.relations:
print(f" ({s}) -[{p}]-> ({o})")
Chunking and Clustering for Long Passages
For longer text, use chunk_size and cluster=True:
big_text = textwrap.dedent("""
building machines that can perform tasks requiring human-like intelligence.
data rather than being explicitly programmed. Deep learning is a subset of
machine learning that uses multi-layer neural networks. Neural nets, also
called NNs, are inspired by the structure of the brain.
researchers in 2017. The Transformer architecture underlies modern large
language models such as GPT, Claude and Gemini. OpenAI released GPT-3 in
2020 and GPT-4 in 2023. Anthropic, founded in 2021 by former OpenAI
researchers, develops the Claude family of assistants. Google DeepMind
develops the Gemini family of models.
Stanford University hosts the Stanford AI Lab (SAIL) and the STAIR Lab.
Researchers at Stanford produced the KGGen library, which extracts
knowledge graphs from plain text using language models. KGGen relies on
DSPy for structured outputs and routes model calls through LiteLLM, which
supports providers including OpenAI, Anthropic, Google and Ollama.
""").strip()
g_big = kg.generate(
input_data=big_text,
chunk_size=800,
cluster=True,
context="History and ecosystem of modern AI",
)
print(f"Entities ({len(g_big.entities)}): {sorted(g_big.entities)}")
print(f"Edges ({len(g_big.edges)}): {sorted(g_big.edges)}")
print(f"Relations: {len(g_big.relations)}")
for s, p, o in list(g_big.relations)[:15]:
print(f" ({s}) -[{p}]-> ({o})")
Conversation Extraction
Extract relations from a conversation:
messages = [
{"role": "user", "content": "Who founded Anthropic?"},
{"role": "assistant", "content": "Anthropic was founded in 2021 by Dario Amodei and Daniela Amodei, along with other former OpenAI researchers."},
{"role": "user", "content": "And what is their main product?"},
{"role": "assistant", "content": "Anthropic's main product is Claude, a family of large language model assistants."},
]
g_chat = kg.generate(input_data=messages)
print("Relations from conversation:")
for s, p, o in g_chat.relations:
print(f" ({s}) -[{p}]-> ({o})")
Aggregating Multiple Sources
Combine graphs from multiple sources and cluster to merge related entities:
src1 = "Linda is Joe's mother. Ben is Joe's brother."
src2 = "Andrew is Joseph's father. Judy is Andrew's sister. Joseph also goes by Joe."
g_a = kg.generate(input_data=src1)
g_b = kg.generate(input_data=src2)
combined = kg.aggregate([g_a, g_b])
clustered_combined = kg.cluster(combined, context="Family relationships")
print("Entities after clustering:", clustered_combined.entities)
print("Relations after clustering:")
for r in clustered_combined.relations:
print(f" {r}")
Visualization
Use built-in visualization:
builtin_path = "kg_builtin.html"
try:
KGGen.visualize(g_big, builtin_path, open_in_browser=False)
print(f"Wrote {builtin_path}")
display(IFrame(builtin_path, width="100%", height=520))
except Exception as e:
print(f"Built-in visualize failed ({e}); we'll use the custom pyvis viz below.")
NetworkX Analytics
Convert the graph to a NetworkX MultiDiGraph and compute centrality metrics:
def kg_to_networkx(graph):
G = nx.MultiDiGraph()
for e in graph.entities:
G.add_node(e)
for s, p, o in graph.relations:
G.add_edge(s, o, label=p)
return G
G = kg_to_networkx(g_big)
print(f"Nodes: {G.number_of_nodes()} Edges: {G.number_of_edges()}")
H = nx.Graph(G)
deg_cent = nx.degree_centrality(H)
btw_cent = nx.betweenness_centrality(H)
pr_cent = nx.pagerank(nx.DiGraph(G)) if G.number_of_edges() else {}
def top(d, k=8):
return sorted(d.items(), key=lambda x: -x[1])[:k]
print("\nTop entities by degree centrality:")
for n, v in top(deg_cent):
print(f" {n:35s} {v:.3f}")
print("\nTop entities by betweenness:")
for n, v in top(btw_cent):
print(f" {n:35s} {v:.3f}")
This workflow provides a powerful way to extract structured knowledge from unstructured text, analyze relationships, and visualize the results.