How to Build Document Knowledge Graphs with Large Language Models: A Practical Guide

    This guide walks through an end-to-end pipeline for turning unstructured documents into queryable knowledge graphs using large language models (LLMs). It covers the fundamentals of knowledge graphs and SPO triples, then breaks down each stage of the pipeline: text preprocessing and chunking, LLM-based extraction of entities, relationships, and document metadata, entity normalization and deduplication, graph construction and persistence, and querying and visualization. It also addresses practical engineering concerns such as hallucination control, cost management, quality measurement, incremental updates, and reliable structured output. The emphasis is on the engineering details—chunking strategy, prompt design, entity normalization, and quality validation—that ultimately determine whether a document knowledge graph succeeds.

    1. Why Turn Text into a Knowledge Graph

    Most of the information we deal with every day exists as unstructured text—reports, articles, biographies, meeting notes. The biggest problem with this data is that it is “not queryable.” You cannot run a single SQL query to ask “which elements did a person discover during their lifetime, and which later research did those elements influence?” The value of information depends largely on its queryability, reasonability, and visualizability.

    The Knowledge Graph (KG) is a structured way of representing data designed to solve exactly this problem. It reorganizes fragmented text in the language of graphs, so that a computer can not only “read” each sentence but also understand the complex connections between entities. The rise of large language models (LLMs) has dramatically lowered the barrier and cost of “automatically extracting structured knowledge from text,” providing an engineerable path for building document-level knowledge graphs.

    2. Core Concepts: Reading the Language of Knowledge Graphs

    A knowledge graph is essentially a database that expresses information as a network, built from two basic elements:

    • Nodes / Entities: Represent concepts, people, places, organizations, and similar things in the real world. Every unique subject or object in the graph can become a node.
    • Edges / Relationships: Represent relationships or interactions between entities, carrying both direction and a label that describes the relationship.

    The most basic unit of abstraction is the SPO triple (Subject-Predicate-Object):

    Element Role Graph Component Example
    Subject (S) The subject of the statement Node Marie Curie
    Predicate (P) The relationship connecting subject and object Edge Label discovered
    Object (O) The object of the statement Node radium

    The triple (Marie Curie, discovered, radium) is a single piece of directed, labeled knowledge. The entire pipeline exists to let the LLM help us identify and extract these triples from massive amounts of text in bulk, accurately, and in structured form, and then further generate document metadata that can be used for classification and retrieval.

    It is worth noting that early industry practice typically used supervised, discriminative models for relation extraction. These methods performed reasonably well on training datasets or well-structured text, but generalized poorly. Once the domain changed or the corpus became less standardized, performance dropped noticeably. The zero-shot/few-shot generalization ability of LLMs precisely fills this gap.

    3. End-to-End Pipeline Overview

    The whole pipeline can be abstracted as a “smelting” chain for data:

    1. Raw documents → text extraction & cleaning → smart chunking → LLM entity/relation extraction →
    2. metadata generation → triple normalization & deduplication → graph construction & persistence → query & visualization

    Let’s break down the key implementation at each stage.

    4. Step 1: Text Preprocessing and Chunking

    Raw documents (especially PDFs) often carry headers, footers, tables of contents, garbled text, and layout noise, so cleaning is required first. More importantly, LLM context windows are limited, so long documents must be split into semantically complete chunks. Otherwise, entity relationships that span sections will be cut off.

    1. def split_into_chunks(text: str, chunk_size: int = 1000, overlap: int = 100):
    2. """
    3. Split text using a sliding window over characters; overlap keeps
    4. semantics continuous across chunks.
    5. In practice, you can replace this with sentence- or paragraph-based
    6. splitting to obtain better semantic boundaries.
    7. """
    8. chunks, start = [], 0
    9. while start < len(text):
    10. chunks.append(text[start:start + chunk_size])
    11. start += chunk_size - overlap
    12. return chunks

    Chunking quality directly determines the upper bound of downstream extraction: chunks that are too large dilute key information and increase the probability of hallucination; chunks that are too small fragment semantics and lose context. You need to tune this repeatedly based on the document type.

    5. Step 2: Generating Entities, Relationships, and Metadata with an LLM

    This is the core of the entire pipeline. We have the LLM perform structured extraction on each text chunk and output a unified JSON format. The key here is constraining the output structure with a carefully designed prompt and providing clear examples, to reduce the instability that comes from the model improvising freely.

    1. EXTRACTION_PROMPT = """
    2. You are a knowledge extraction assistant. From the text below, extract
    3. all SPO triples, and summarize the topic tags and a one-sentence summary
    4. of the text.
    5. Output strictly in the following JSON format, with no extra text:
    6. {{
    7. "triples": [
    8. {{"subject": "", "predicate": "", "object": ""}}
    9. ],
    10. "keywords": [],
    11. "summary": ""
    12. }}
    13. Text:
    14. {chunk}
    15. """
    16. def extract_from_chunk(llm_client, chunk: str) -> dict:
    17. prompt = EXTRACTION_PROMPT.format(chunk=chunk)
    18. response = llm_client.chat(prompt, temperature=0) # low temperature improves determinism
    19. return parse_json(response) # on parse failure, retry or apply a fallback

    Beyond triples, the same batch of calls can conveniently generate document metadata: topic keywords, a one-sentence summary, document classification, and the times and places involved. On one hand, this metadata builds multi-dimensional indexes for documents; on the other, it attaches as node/edge properties to the graph, greatly enhancing retrieval capability.

    A practical recommendation is to implement retry and validation for responses that fail to parse or have missing fields, and to retain the raw responses for traceability. The stability of structured extraction often matters more to final quality than the choice of model.

    6. Step 3: Normalization and Deduplication

    The same entity may appear with different expressions across text chunks—for example, “Marie Curie,” “Mary Curie,” and “M. Curie.” If unhandled, the graph will be littered with duplicate nodes, breaking connectivity. This is why an Entity Normalization stage is needed:

    1. def normalize_graph(triples):
    2. # 1. Unify entity names (alias mapping table + LLM to judge coreference)
    3. # 2. Unify relation label naming and direction
    4. # 3. Deduplicate identical triples
    5. seen, result = set(), []
    6. alias = {"M. Curie": "Marie Curie", "Mary Curie": "Marie Curie"}
    7. for t in triples:
    8. s = alias.get(t["subject"], t["subject"])
    9. o = alias.get(t["object"], t["object"])
    10. key = (s, t["predicate"], o)
    11. if key not in seen:
    12. seen.add(key)
    13. result.append({"subject": s, "predicate": t["predicate"], "object": o})
    14. return result

    Coreference resolution is one of the decisive factors in knowledge graph quality. In engineering, you can combine an alias dictionary, edit distance, and asking the LLM to judge “whether these two expressions refer to the same entity” to make a comprehensive decision.

    7. Step 4: Graph Construction and Persistence

    The normalized triples can then be loaded into a graph data structure. You can first validate the logic in an in-memory graph structure, and then consider persisting to a graph database or relational storage:

    1. def build_graph(all_triples):
    2. graph = {}
    3. for t in all_triples:
    4. s, p, o = t["subject"], t["predicate"], t["object"]
    5. graph.setdefault(s, []).append((p, o)) # directed adjacency list
    6. graph.setdefault(o, []) # ensure objects also become nodes
    7. return graph

    In real deployments, if the graph is large and requires frequent multi-hop queries, it is typically persisted to a graph database or handled with a combination of object storage + an indexing service; for small and medium-scale scenarios, an in-memory graph or relational tables are entirely sufficient. The choice of storage layer should follow the query patterns and data scale, rather than blindly pursuing a complex architecture.

    8. Step 5: Query, Reasoning, and Visualization

    The value of a graph ultimately shows up in its use. With an adjacency structure in place, you can answer questions that text alone cannot:

    1. def related_entities(graph, entity):
    2. """Return all relationships and neighbors directly connected to an entity"""
    3. return graph.get(entity, [])
    4. # Example: query all triples related to "Marie Curie"
    5. print(related_entities(graph, "Marie Curie"))

    For visualization, mapping nodes to dots and relationships to connecting lines—combined with zoom, drag, and color-coding by category—lets people intuitively grasp the network structure among people, events, and concepts. For developers, an interactive graph view that can highlight paths often reveals the patterns behind the data better than any static chart.

    9. Engineering Practices and Common Challenges

    To actually put this pipeline into production, you still need to pay attention to several easily overlooked yet highly impactful issues:

    • Hallucination control: LLMs may extract triples that do not exist in the source text. The countermeasure is to require the model to output source evidence snippets and perform traceability checks, keeping only triples whose provenance can be located in the original text.
    • Cost and control: Full extraction involves a huge number of calls. You can control costs through filter-then-extract (using rules or a lightweight model to filter out irrelevant passages first), batched/merged calls, and caching results for repeated chunks.
    • Measurable quality: Define a sampled evaluation set for precision and recall of extraction results, and establish regression tests, to avoid the “fix one problem, another pops up” cycle every time a prompt is changed.
    • Incremental updates: Document sets keep growing, so the graph should be designed from the start to support incremental merging and version management of triples, rather than rebuilding everything each time.
    • Reliable structured output: JSON parsing failures are the norm, so be sure to implement schema validation, retry on failure, and fallback strategies.

    10. Conclusion

    Turning unstructured text into a knowledge graph is essentially a data “smelting” pipeline of text → structured triples → graph. Large language models have transformed entity and relation extraction from a “supervised learning task requiring large amounts of annotation” into an engineering problem that can start “as soon as you design a good prompt,” dramatically lowering the barrier to adoption. What truly determines success is not how powerful the model is, but whether chunking strategy, prompt design, entity normalization, and quality validation—these engineering details—are solid. Polish these stages well, and knowledge sleeping in the ocean of documents can be transformed into living assets that are queryable, reason-able, and visualizable.