BeClaude
Guide2026-05-06

Building Knowledge Graphs from Unstructured Text with Claude

Learn how to use Claude to extract entities and relations from unstructured documents, resolve duplicates, and build queryable knowledge graphs — no training data required.

Quick Answer

This guide shows you how to use Claude to extract typed entities and relations from unstructured text, resolve duplicate mentions (e.g., 'NASA' vs 'National Aeronautics and Space Administration'), build an in-memory graph, and answer multi-hop questions — all without training data or complex NLP pipelines.

Knowledge GraphsEntity ResolutionStructured OutputsClaude APIMulti-hop Reasoning

Building Knowledge Graphs from Unstructured Text with Claude

You have a pile of unstructured documents and need to answer questions that span them — "who works with people who worked on project X", "which vendors are connected to this incident". No single document contains the answer. RAG retrieval won't chain the facts for you. You need a knowledge graph: entities as nodes, typed relations as edges, so that multi-hop reasoning becomes graph traversal.

Building one used to mean training a named-entity recognizer on your domain, training a relation classifier, writing entity-resolution heuristics, and maintaining all three as your data shifted. With Claude, each of those stages becomes a prompt.

What You'll Learn

By the end of this guide you will be able to:

  • Use structured outputs to extract typed entities and subject–predicate–object triples from arbitrary text with no training data
  • Apply Claude-driven entity resolution to collapse surface-form variants into canonical nodes, replacing brittle string-similarity heuristics
  • Assemble and query an in-memory graph, and run multi-hop questions by serializing subgraphs back to Claude
  • Measure extraction quality with precision/recall against a gold set and reason about the cost/quality tradeoff between Haiku and Sonnet
Everything runs in memory with no database. The techniques transfer directly to Neo4j, Neptune, or a Postgres adjacency table when you need to scale.

Prerequisites

  • Python 3.11+
  • Anthropic API key (get one here)
  • Basic familiarity with graphs (nodes, edges, traversal)

Setup

We use two models. Haiku handles the high-volume, schema-constrained extraction work where speed and cost matter more than nuance. Sonnet handles entity resolution and summarization, where the model needs to weigh conflicting evidence across documents.

import anthropic
from pydantic import BaseModel, Field
from typing import List, Optional

client = anthropic.Anthropic()

HAIKU = "claude-3-haiku-20240307" SONNET = "claude-3-sonnet-20240229"

Building a Corpus

We need a handful of documents that talk about overlapping entities, so that entity resolution has real work to do. The Apollo program is a good test bed: six short Wikipedia summaries that all mention NASA, the Moon, several astronauts, and a launch vehicle — but each article names them slightly differently.

We fetch summaries from the Wikipedia REST API rather than full articles to keep token costs low. For a production pipeline you would chunk full documents; the extraction logic is identical.

import requests

def fetch_wikipedia_summary(title): url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{title}" response = requests.get(url) response.raise_for_status() return response.json()["extract"]

documents = { "Apollo 11": fetch_wikipedia_summary("Apollo 11"), "Neil Armstrong": fetch_wikipedia_summary("Neil Armstrong"), "Buzz Aldrin": fetch_wikipedia_summary("Buzz Aldrin"), "Saturn V": fetch_wikipedia_summary("Saturn V"), "NASA": fetch_wikipedia_summary("NASA"), "Moon": fetch_wikipedia_summary("Moon"), }

Entity and Relation Extraction

Classical NER tags spans of text with labels (PERSON, ORG, LOC). Classical relation extraction then classifies pairs of spans into relation types. Both traditionally require labeled training data per domain.

We collapse both stages into a single Claude call per document. The key is structured outputs: we define the output shape as a Pydantic model and pass it to client.messages.parse(). Claude's response is guaranteed to validate against that schema and comes back as a typed Python object — no regex parsing, no JSON decode errors, no defensive isinstance checks.

class Entity(BaseModel):
    name: str = Field(description="The entity name as it appears in the text")
    type: str = Field(description="Entity type: PERSON, ORGANIZATION, LOCATION, EVENT, etc.")
    description: str = Field(description="A one-line description for disambiguation")

class Relation(BaseModel): subject: str = Field(description="The subject entity name") predicate: str = Field(description="The relation type (e.g., 'worked_on', 'launched', 'commanded')") object: str = Field(description="The object entity name")

class Extraction(BaseModel): entities: List[Entity] relations: List[Relation]

def extract_from_document(title, text): prompt = f"""Extract all entities and their relations from the following text about {title}.

Entities should be people, organizations, locations, events, missions, vehicles, or other notable concepts. Relations should be meaningful connections between entities.

Text: {text}""" response = client.messages.parse( model=HAIKU, max_tokens=2000, messages=[{"role": "user", "content": prompt}], response_model=Extraction ) return response

Extract from all documents

all_extractions = {} for title, text in documents.items(): all_extractions[title] = extract_from_document(title, text)

Let's look at what was extracted. Notice how the same real-world entity appears under different surface forms across documents — this is the entity resolution problem we solve next.

Entity Resolution

The raw extraction gives us overlapping mentions: "NASA" and "National Aeronautics and Space Administration", "Neil Armstrong" and "Armstrong", possibly "the Moon" and "Moon". If we build a graph directly from this, we get a fractured mess where the same concept is split across disconnected nodes.

Traditional approaches use string similarity (edit distance, Jaccard on tokens) plus blocking rules. That works for typos but fails on "Edwin Aldrin" vs "Buzz Aldrin" — two names with zero character overlap that refer to the same person.

We instead ask Claude to cluster entities of each type, using the one-line descriptions from extraction as disambiguation context. The descriptions matter: "Armstrong — first person to walk on the Moon" and "Armstrong — jazz trumpeter" have the same name but should not merge.

def resolve_entities(extractions):
    # Collect all unique entity names with their descriptions
    entity_map = {}
    for doc_title, extraction in extractions.items():
        for entity in extraction.entities:
            if entity.name not in entity_map:
                entity_map[entity.name] = entity
    
    # Group by type for resolution
    by_type = {}
    for entity in entity_map.values():
        by_type.setdefault(entity.type, []).append(entity)
    
    alias_to_canonical = {}
    
    for entity_type, entities in by_type.items():
        if len(entities) < 2:
            alias_to_canonical[entities[0].name] = entities[0].name
            continue
        
        # Build a prompt for Sonnet to cluster
        entity_list = "\n".join([f"- {e.name}: {e.description}" for e in entities])
        prompt = f"""Group the following {entity_type} entities into clusters where they refer to the same real-world entity.

Entities: {entity_list}

For each cluster, provide:

  • The canonical name (most recognizable form)
  • The list of aliases that map to it
Return as JSON: {{ "clusters": [{{"canonical": "...", "aliases": ["..."]}}] }}""" response = client.messages.parse( model=SONNET, max_tokens=1000, messages=[{"role": "user", "content": prompt}], response_model=... # Define a ClusterList model ) for cluster in response.clusters: for alias in cluster.aliases: alias_to_canonical[alias] = cluster.canonical return alias_to_canonical

Two failure modes to watch for. First, any raw name Claude leaves out of every cluster silently disappears from the graph — a production resolver should fall back to a single-element cluster for unmatched names so nothing is lost. Second, the resolver can over-merge: a specific mission like "Gemini 12" may get folded into the broader "Project Gemini" because the descriptions overlap. The first loses nodes, the second loses precision. Both are worth spot-checking.

Assembling the Graph

With a clean alias map, we rewrite every relation endpoint to its canonical form and load the result into NetworkX. We use a MultiDiGraph because two entities can be connected by several distinct predicates ("launched from" and "operated by"), and direction matters ("Armstrong commanded Apollo 11" is not the same edge as "Apollo 11 commanded Armstrong").

Each node carries its type, the source document it came from, and the original surface form for traceability.

import networkx as nx

def build_graph(extractions, alias_map): G = nx.MultiDiGraph() for doc_title, extraction in extractions.items(): for entity in extraction.entities: canonical = alias_map.get(entity.name, entity.name) G.add_node(canonical, type=entity.type, source=doc_title, original=entity.name) for relation in extraction.relations: subj = alias_map.get(relation.subject, relation.subject) obj = alias_map.get(relation.object, relation.object) G.add_edge(subj, obj, predicate=relation.predicate, source=doc_title) return G

graph = build_graph(all_extractions, alias_to_canonical)

Querying the Graph with Multi-hop Questions

Now we can answer questions that require chaining facts across documents. The approach: serialize the relevant subgraph back to Claude and let it reason over the structured context.

def query_graph(question, graph):
    # Serialize a subgraph around entities mentioned in the question
    # (In production, you'd use embedding similarity to find relevant nodes)
    
    # Simple approach: serialize the full graph for small graphs
    nodes_str = "\n".join([f"- {n} ({d['type']})" for n, d in graph.nodes(data=True)])
    edges_str = "\n".join([f"- {u} --[{d['predicate']}]--> {v}" for u, v, d in graph.edges(data=True)])
    
    prompt = f"""Given this knowledge graph:

Nodes: {nodes_str}

Edges: {edges_str}

Answer the following question by traversing the graph: {question}

Provide your reasoning step by step.""" response = client.messages.create( model=SONNET, max_tokens=1000, messages=[{"role": "user", "content": prompt}] ) return response.content[0].text

Example multi-hop question

answer = query_graph("Which astronauts worked on projects that used the Saturn V?", graph) print(answer)

Measuring Quality

To trust your graph, you need to measure extraction quality. Create a gold set of expected entities and relations for a sample of documents, then compute precision and recall against Claude's output.

def evaluate_extraction(gold_entities, gold_relations, extracted):
    gold_entity_set = set(gold_entities)
    extracted_entity_set = set(e.name for e in extracted.entities)
    
    true_positives = gold_entity_set & extracted_entity_set
    precision = len(true_positives) / len(extracted_entity_set) if extracted_entity_set else 0
    recall = len(true_positives) / len(gold_entity_set) if gold_entity_set else 0
    
    return {"precision": precision, "recall": recall, "f1": 2  precision  recall / (precision + recall) if (precision + recall) else 0}

Track these metrics across model choices. Haiku is 3-5x cheaper per extraction but may miss nuanced relations. Sonnet catches more but costs more. For many applications, a Haiku-first pass with Sonnet re-extraction on low-confidence documents is the sweet spot.

Key Takeaways

  • No training data needed: Claude replaces traditional NER and relation classification pipelines with a single structured output prompt per document, eliminating the need for domain-specific labeled data.
  • Entity resolution via LLM reasoning: Claude's ability to understand context (e.g., "Buzz Aldrin" vs "Edwin Aldrin") outperforms string-similarity heuristics for resolving entity variants.
  • Multi-hop reasoning becomes graph traversal: By serializing subgraphs back to Claude, you can answer questions that span multiple documents — something RAG alone struggles with.
  • Cost/quality tradeoffs matter: Use Haiku for high-volume extraction where speed and cost are priorities, and Sonnet for entity resolution and complex reasoning where accuracy is critical.
  • Always measure and validate: Track precision/recall against a gold set, and watch for failure modes like missing entities (unmatched names) or over-merging (overly broad clusters).