{"slug": "automating-knowledge-graph-population-extracting-entities-and-triples-from-text", "title": "Automating Knowledge Graph Population: Extracting Entities and Triples from Unstructured Text with an LLM", "summary": "A tutorial published on Machine Learning Mastery details a pipeline that uses a local Llama 3.2 model served through Ollama to extract SPOC (Subject-Predicate-Object-Context) quads from unstructured Wikipedia text and load them into the Quadstore knowledge graph database for Graph-RAG retrieval. The workflow runs in Google Colab or a local Python IDE, requires installing the wikipedia and requests libraries, and relies on few-shot prompting with Llama 3.2's JSON output mode to convert narrative text into structured relationships.", "body_md": "In this article, you will learn how to automatically extract structured knowledge from raw text and populate a knowledge graph with SPOC quads using a local LLM via Ollama.\n\nTopics we will cover include:\n\n- How to set up Ollama with the Llama 3.2 model to run a free, local LLM for structured data extraction.\n- How to design a robust extraction pipeline that converts unstructured Wikipedia text into SPOC (Subject-Predicate-Object-Context) quads using few-shot prompting and JSON output mode.\n- How to load the extracted quads into a QuadStore knowledge graph, ready for use in a Graph-RAG retrieval pipeline.\n\n## Introduction\n\nThe recent article on [Building a Deterministic 3-Tiered Graph-RAG System](https://machinelearningmastery.com/beyond-vector-search-building-a-deterministic-3-tiered-graph-rag-system/) shows how a hierarchical, graph-based architecture can tackle the issue of hallucinations in standard vector information retrieval.\n\nThat article leveraged [Quadstore](https://github.com/mmmayo13/quadstore), a lightweight knowledge graph database implemented in Python, to teach LLMs to respect ground-truth facts, thereby ensuring factual accuracy and deterministic retrieval conflict resolution in applications like RAG systems.\n\nA critical question remains, though: where does the factual graph knowledge come from? This article helps close the loop, showing a free, fully automated approach to extract entities and build SPOC quads (Subject-Predicate-Object-Context) from raw text such as Wikipedia pages. We will do this with the help of a local, free LLM from Ollama. Once these quads are built, we will illustrate how to directly populate the Quadstore.\n\n## Prerequisites and Setup\n\nThe workflow shown in this article is designed to run seamlessly both in a Google Colab notebook and in your local Python IDE. If you choose the latter, you will need to manually install **Ollama** on your computer first, along with pulling the **Llama 3.2** model locally.\n\nIn Google Colab, you can set up Ollama and get Llama 3.2 for your open session using these commands:\n\n```\n!apt-get update -qq && apt-get install -y -qq zstd\n!curl -fsSL https://ollama.com/install.sh | sh\n\n12\n\n!apt-get update -qq && apt-get install -y -qq zstd!curl -fsSL https://ollama.com/install.sh | sh\n```\n\nEither way, you will need to install these two libraries as well:\n\n```\n!pip install wikipedia requests\n\n1\n\n!pip install wikipedia requests\n```\n\nLlama 3.2 is a lightweight, free model. Its API is configured to strictly operate in JSON input/output mode, a mandatory standard for reliable data extraction. Using `subprocess`, we can start the Ollama server as a background process and pull our target model:\n\n``` python\nimport subprocess\nimport time\n\n# 1. Starting the Ollama server in the background\nprint(\"Starting Ollama server...\")\nprocess = subprocess.Popen([\"ollama\", \"serve\"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\ntime.sleep(3) # Give the server a moment to start\n\n# 2. Pulling the Llama 3.2 model (this may take a minute or two on Colab)\nprint(\"Pulling Llama 3.2...\")\nsubprocess.run([\"ollama\", \"pull\", \"llama3.2\"])\nprint(\"Model ready!\")\n\n123456789101112\n\nimport subprocessimport time # 1. Starting the Ollama server in the backgroundprint(\"Starting Ollama server...\")process = subprocess.Popen([\"ollama\", \"serve\"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)time.sleep(3) # Give the server a moment to start # 2. Pulling the Llama 3.2 model (this may take a minute or two on Colab)print(\"Pulling Llama 3.2...\")subprocess.run([\"ollama\", \"pull\", \"llama3.2\"])print(\"Model ready!\")\n```\n\n## Automated Knowledge Graph Population\n\nLet’s look at the process of constructing our knowledge graph from a source of raw text. We will convert narrative text into strictly modeled relationships that extend classical RDF triples of the form `(Subject, Predicate, Object)` by adding a fourth dimension: the context. This is useful for tracking where a fact comes from and whether it is true or not.\n\nA triple like `(\"LeBron James\", \"plays_for\", \"Lakers\")` thus becomes `(\"LeBron James\", \"plays_for\", \"Lakers\", \"NBA_2023_Roster\")`.\n\nFirst, we will create a small, simulated `QuadStore` engine that mimics the framework used in the related article this one follows up on. If you are working in a notebook, run this code in a separate cell to generate a `quadstore.py` file in your workspace on the fly:\n\n``` python\n%%writefile quadstore.py\nclass QuadStore:\n    def __init__(self):\n        # Using a simple list to store the facts for our lightweight implementation\n        self.quads = []\n\n    def add(self, subject, predicate, obj, context):\n        \"\"\"Adds a new SPOC quad to the knowledge graph.\"\"\"\n        quad = (subject, predicate, obj, context)\n        if quad not in self.quads:\n            self.quads.append(quad)\n\n    def query(self, subject=None, predicate=None, obj=None, context=None):\n        \"\"\"Queries the graph. Returns a list of quads that match the provided criteria.\"\"\"\n        results = []\n        for q_sub, q_pred, q_obj, q_ctx in self.quads:\n            if (subject is None or subject == q_sub) and \\\n               (predicate is None or predicate == q_pred) and \\\n               (obj is None or obj == q_obj) and \\\n               (context is None or context == q_ctx):\n                results.append((q_sub, q_pred, q_obj, q_ctx))\n        return results\n\n1234567891011121314151617181920212223\n\n%%writefile quadstore.py class QuadStore:    def __init__(self):        # Using a simple list to store the facts for our lightweight implementation        self.quads = []     def add(self, subject, predicate, obj, context):        \"\"\"Adds a new SPOC quad to the knowledge graph.\"\"\"        quad = (subject, predicate, obj, context)        if quad not in self.quads:            self.quads.append(quad)     def query(self, subject=None, predicate=None, obj=None, context=None):        \"\"\"Queries the graph. Returns a list of quads that match the provided criteria.\"\"\"        results = []        for q_sub, q_pred, q_obj, q_ctx in self.quads:            if (subject is None or subject == q_sub) and \\               (predicate is None or predicate == q_pred) and \\               (obj is None or obj == q_obj) and \\               (context is None or context == q_ctx):                results.append((q_sub, q_pred, q_obj, q_ctx))        return results\n```\n\nA file containing exactly the above code will be created, and we will refer to it later on just like any other Python module, to demonstrate how to load our created knowledge graph into our mock Graph-RAG system.\n\nBack to the main process: we will now pull some raw text from Wikipedia using the namesake API. The `auto_suggest=False` option ensures we correctly fetch the right article name from Wikipedia without automated corrections that may cause a crash.\n\n``` python\nimport wikipedia\n\nprint(\"Fetching Wikipedia summary...\")\n# Disabling auto_suggest to prevent the library from renaming \"Turing\" to \"tuning\"\nwiki_page = wikipedia.page(\"Alan Turing\", auto_suggest=False)\ntext_content = wiki_page.summary\n\n# We'll just take the first two paragraphs of the Wikipedia page to keep extraction fast\nparagraphs = text_content.split('\\n')[:2]\nshort_text = \" \".join(paragraphs)\n\nprint(f\"Extracted {len(short_text)} characters of text ready for processing.\")\n\n123456789101112\n\nimport wikipedia print(\"Fetching Wikipedia summary...\")# Disabling auto_suggest to prevent the library from renaming \"Turing\" to \"tuning\"wiki_page = wikipedia.page(\"Alan Turing\", auto_suggest=False)text_content = wiki_page.summary # We'll just take the first two paragraphs of the Wikipedia page to keep extraction fastparagraphs = text_content.split('\\n')[:2]short_text = \" \".join(paragraphs) print(f\"Extracted {len(short_text)} characters of text ready for processing.\")\n```\n\nOutput:\n\n```\nFetching Wikipedia summary...\nExtracted 1244 characters of text ready for processing.\n\n12\n\nFetching Wikipedia summary...Extracted 1244 characters of text ready for processing.\n```\n\nNow comes the core of the entire workflow: the robust extraction engine, modeled by the following function that:\n\n- Works with the target LLM’s formatting engine to extract structured data in the form of quads. To do this, we use few-shot examples as part of the prompt sent to the LLM.\n- Post-processes the LLM output to extract a list of facts and build a list of quads accordingly.\n\n``` python\nimport json\nimport requests\n\ndef extract_spoc_quads_final(text, context_label, model=\"llama3.2\"):\n    # To abide by Llama3.2's output mode, we ask for a JSON object with a \"facts\" key\n    prompt = f\"\"\"\n    You are an expert data extraction algorithm. Extract atomic facts from the text.\n    You must output a valid JSON object containing a single key called \"facts\".\n    The value of \"facts\" must be an array of objects.\n    \n    Example output format:\n    {{\n      \"facts\": [\n        {{\"subject\": \"LeBron James\", \"predicate\": \"plays_for\", \"object\": \"Lakers\"}},\n        {{\"subject\": \"Lakers\", \"predicate\": \"based_in\", \"object\": \"Los Angeles\"}}\n      ]\n    }}\n    \n    Text to process:\n    {text}\n    \"\"\"\n    \n    payload = {\n        \"model\": model,\n        \"prompt\": prompt,\n        \"format\": \"json\",\n        \"stream\": False,\n        \"temperature\": 0.0 \n    }\n    \n    try:\n        response = requests.post('http://localhost:11434/api/generate', json=payload)\n        response.raise_for_status()\n        \n        raw_llm_text = response.json()['response']\n        parsed_json = json.loads(raw_llm_text)\n        \n        # Looking specifically for the \"facts\" array\n        triples = parsed_json.get(\"facts\", [])\n        \n        # Fallback: If the LLM still used a different key, grab the first list we find\n        if not triples and isinstance(parsed_json, dict):\n            for key, value in parsed_json.items():\n                if isinstance(value, list):\n                    triples = value\n                    break\n                    \n        quads = []\n        for t in triples:\n            if not isinstance(t, dict): continue\n            \n            # Converting keys to lowercase to catch \"Subject\" vs \"subject\"\n            normalized_t = {str(k).lower().strip(): str(v).strip() for k, v in t.items()}\n            \n            if all(k in normalized_t for k in ('subject', 'predicate', 'object')):\n                quads.append({\n                    \"subject\": normalized_t['subject'],\n                    \"predicate\": normalized_t['predicate'],\n                    \"object\": normalized_t['object'],\n                    \"context\": context_label\n                })\n        return quads\n        \n    except Exception as e:\n        print(f\"Extraction failed: {e}\")\n        return []\n\n123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566\n\nimport jsonimport requests def extract_spoc_quads_final(text, context_label, model=\"llama3.2\"):    # To abide by Llama3.2's output mode, we ask for a JSON object with a \"facts\" key    prompt = f\"\"\"    You are an expert data extraction algorithm. Extract atomic facts from the text.    You must output a valid JSON object containing a single key called \"facts\".    The value of \"facts\" must be an array of objects.        Example output format:    {{      \"facts\": [        {{\"subject\": \"LeBron James\", \"predicate\": \"plays_for\", \"object\": \"Lakers\"}},        {{\"subject\": \"Lakers\", \"predicate\": \"based_in\", \"object\": \"Los Angeles\"}}      ]    }}        Text to process:    {text}    \"\"\"        payload = {        \"model\": model,        \"prompt\": prompt,        \"format\": \"json\",        \"stream\": False,        \"temperature\": 0.0     }        try:        response = requests.post('http://localhost:11434/api/generate', json=payload)        response.raise_for_status()                raw_llm_text = response.json()['response']        parsed_json = json.loads(raw_llm_text)                # Looking specifically for the \"facts\" array        triples = parsed_json.get(\"facts\", [])                # Fallback: If the LLM still used a different key, grab the first list we find        if not triples and isinstance(parsed_json, dict):            for key, value in parsed_json.items():                if isinstance(value, list):                    triples = value                    break                            quads = []        for t in triples:            if not isinstance(t, dict): continue                        # Converting keys to lowercase to catch \"Subject\" vs \"subject\"            normalized_t = {str(k).lower().strip(): str(v).strip() for k, v in t.items()}                        if all(k in normalized_t for k in ('subject', 'predicate', 'object')):                quads.append({                    \"subject\": normalized_t['subject'],                    \"predicate\": normalized_t['predicate'],                    \"object\": normalized_t['object'],                    \"context\": context_label                })        return quads            except Exception as e:        print(f\"Extraction failed: {e}\")        return []\n```\n\nAll that remains is running the pipeline to extract, view, and make use of our newly created quads, which will constitute our knowledge graph.\n\n```\nprint(\"Beginning extraction (this takes a few seconds on a Colab T4 GPU)...\\n\")\n\nextracted_quads = extract_spoc_quads_final(\n    text=short_text, \n    context_label=\"Wikipedia_Alan_Turing\"\n)\n\n# Viewing the results\nfor quad in extracted_quads:\n    print(f\"S: {quad['subject']:<20} | P: {quad['predicate']:<15} | O: {quad['object']:<25} | C: {quad['context']}\")\n\n12345678910\n\nprint(\"Beginning extraction (this takes a few seconds on a Colab T4 GPU)...\\n\") extracted_quads = extract_spoc_quads_final(    text=short_text,     context_label=\"Wikipedia_Alan_Turing\") # Viewing the resultsfor quad in extracted_quads:    print(f\"S: {quad['subject']:<20} | P: {quad['predicate']:<15} | O: {quad['object']:<25} | C: {quad['context']}\")\n```\n\nResults:\n\n```\nBeginning extraction (this takes a few seconds on a Colab T4 GPU)...\n\nS: Alan Mathison Turing | P: was             | O: an English mathematician, computer scientist, logician, cryptanalyst, philosopher and theoretical biologist | C: Wikipedia_Alan_Turing\nS: Alan Mathison Turing | P: was born        | O: in London                 | C: Wikipedia_Alan_Turing\nS: Alan Mathison Turing | P: was raised      | O: in southern England       | C: Wikipedia_Alan_Turing\nS: Alan Mathison Turing | P: graduated from  | O: King's College, Cambridge | C: Wikipedia_Alan_Turing\nS: Alan Mathison Turing | P: earned          | O: a doctorate degree from Princeton University | C: Wikipedia_Alan_Turing\nS: Alan Mathison Turing | P: worked for      | O: the Government Code and Cypher School at Bletchley Park | C: Wikipedia_Alan_Turing\nS: Alan Mathison Turing | P: led             | O: Hut 8, the section responsible for German naval cryptanalysis | C: Wikipedia_Alan_Turing\nS: Alan Mathison Turing | P: devised techniques for | O: speeding the breaking of German ciphers | C: Wikipedia_Alan_Turing\nS: Alan Mathison Turing | P: played a crucial role in | O: cracking intercepted messages that enabled the Allies to defeat the Axis powers | C: Wikipedia_Alan_Turing\nS: Alan Mathison Turing | P: is              | O: widely considered to be the father of theoretical computer science | C: Wikipedia_Alan_Turing\nS: Alan Mathison Turing | P: was             | O: influential in the development of theoretical computer science | C: Wikipedia_Alan_Turing\n\n12345678910111213\n\nBeginning extraction (this takes a few seconds on a Colab T4 GPU)... S: Alan Mathison Turing | P: was             | O: an English mathematician, computer scientist, logician, cryptanalyst, philosopher and theoretical biologist | C: Wikipedia_Alan_TuringS: Alan Mathison Turing | P: was born        | O: in London                 | C: Wikipedia_Alan_TuringS: Alan Mathison Turing | P: was raised      | O: in southern England       | C: Wikipedia_Alan_TuringS: Alan Mathison Turing | P: graduated from  | O: King's College, Cambridge | C: Wikipedia_Alan_TuringS: Alan Mathison Turing | P: earned          | O: a doctorate degree from Princeton University | C: Wikipedia_Alan_TuringS: Alan Mathison Turing | P: worked for      | O: the Government Code and Cypher School at Bletchley Park | C: Wikipedia_Alan_TuringS: Alan Mathison Turing | P: led             | O: Hut 8, the section responsible for German naval cryptanalysis | C: Wikipedia_Alan_TuringS: Alan Mathison Turing | P: devised techniques for | O: speeding the breaking of German ciphers | C: Wikipedia_Alan_TuringS: Alan Mathison Turing | P: played a crucial role in | O: cracking intercepted messages that enabled the Allies to defeat the Axis powers | C: Wikipedia_Alan_TuringS: Alan Mathison Turing | P: is              | O: widely considered to be the father of theoretical computer science | C: Wikipedia_Alan_TuringS: Alan Mathison Turing | P: was             | O: influential in the development of theoretical computer science | C: Wikipedia_Alan_Turing\n```\n\nFrom just two paragraphs of Alan Turing’s Wikipedia article, we extracted around 11 facts, structured as quads. Note that the exact number may vary slightly due to the non-deterministic behavior of the LLM.\n\nWe wrap up by seeing how to add these facts into the `QuadStore` object:\n\n``` python\nfrom quadstore import QuadStore\n\nfacts_qs = QuadStore()\n\nfor quad in extracted_quads:\n    facts_qs.add(\n        quad[\"subject\"], \n        quad[\"predicate\"], \n        quad[\"object\"], \n        quad[\"context\"]\n    )\n\nprint(f\"Successfully loaded {len(extracted_quads)} automated facts into the Graph RAG system!\")\n\n12345678910111213\n\nfrom quadstore import QuadStore facts_qs = QuadStore() for quad in extracted_quads:    facts_qs.add(        quad[\"subject\"],         quad[\"predicate\"],         quad[\"object\"],         quad[\"context\"]    ) print(f\"Successfully loaded {len(extracted_quads)} automated facts into the Graph RAG system!\")\n```\n\nOutput:\n\n```\nSuccessfully loaded 11 automated facts into the Graph RAG system!\n\n1\n\nSuccessfully loaded 11 automated facts into the Graph RAG system!\n```\n\n## Conclusion\n\nThis article closed the loop on our [deterministic 3-tiered Graph-RAG architecture](https://machinelearningmastery.com/beyond-vector-search-building-a-deterministic-3-tiered-graph-rag-system/) by showing how to build a knowledge graph consisting of facts extracted directly from unstructured text in the form of quads — all from scratch. You can now integrate this knowledge into your retrieval pipeline to help eliminate issues like LLM hallucinations.", "url": "https://wpnews.pro/news/automating-knowledge-graph-population-extracting-entities-and-triples-from-text", "canonical_source": "https://machinelearningmastery.com/automating-knowledge-graph-population-extracting-entities-and-triples-from-unstructured-text-with-an-llm/", "published_at": "2026-09-29 12:00:20+00:00", "updated_at": "2026-09-29 14:47:20.871278+00:00", "lang": "en", "topics": ["large-language-models", "ai-tools", "structured-data", "ai-infrastructure", "natural-language-processing"], "entities": ["Ollama", "Llama 3.2", "Quadstore", "Machine Learning Mastery", "Google Colab", "Wikipedia", "Graph-RAG"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/automating-knowledge-graph-population-extracting-entities-and-triples-from-text", "markdown": "https://wpnews.pro/news/automating-knowledge-graph-population-extracting-entities-and-triples-from-text.md", "text": "https://wpnews.pro/news/automating-knowledge-graph-population-extracting-entities-and-triples-from-text.txt", "jsonld": "https://wpnews.pro/news/automating-knowledge-graph-population-extracting-entities-and-triples-from-text.jsonld"}}