BeClaude
Guide2026-04-30

Building Knowledge Graphs from Unstructured Text with Claude

Learn how to use Claude to extract entities and relations from unstructured documents, resolve duplicates, and query a knowledge graph — no training data required.

Quick Answer

This guide shows how to use Claude's structured outputs to extract entities and relations from text, resolve duplicate mentions with AI-driven clustering, build an in-memory graph with NetworkX, and answer multi-hop questions — all without labeled training data.

knowledge graphentity extractionstructured outputsentity resolutionClaude API

Introduction

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(api_key="your-api-key")

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.

import requests

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

documents = [ fetch_wikipedia_summary("Apollo 11"), fetch_wikipedia_summary("Neil Armstrong"), fetch_wikipedia_summary("Buzz Aldrin"), fetch_wikipedia_summary("Saturn V"), fetch_wikipedia_summary("NASA"), fetch_wikipedia_summary("Moon landing") ]

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.

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 canonical name of the entity")
    type: str = Field(description="Entity type: PERSON, ORG, LOC, MISSION, VEHICLE, or OTHER")
    description: str = Field(description="One-line context from the document")

class Relation(BaseModel): subject: str = Field(description="Name of the subject entity") predicate: str = Field(description="Relation type, e.g. 'commanded', 'launched', 'part_of'") object: str = Field(description="Name of the object entity")

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

def extract_from_text(text: str) -> Extraction: response = client.messages.parse( model="claude-3-haiku-20240307", max_tokens=2000, system="You are a knowledge graph extraction system. Extract all entities and their relations from the text.", messages=[{"role": "user", "content": text}], response_model=Extraction ) return response

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.

from typing import Dict, List

def resolve_entities(entities: List[Entity]) -> Dict[str, str]: """Returns a mapping from surface form to canonical name.""" # Group entities by type for focused resolution by_type = {} for e in entities: by_type.setdefault(e.type, []).append(e) alias_to_canonical = {} for etype, group in by_type.items(): # Prepare the list for Claude entity_list = "\n".join([f"- {e.name}: {e.description}" for e in group]) prompt = f"""Given these {etype} entities, cluster those that refer to the same real-world entity. For each cluster, choose the best canonical name. Return a mapping from each original name to its canonical name.

Entities: {entity_list}

Return as JSON: {{"mappings": [{{"original": "...", "canonical": "..."}}]}}""" response = client.messages.parse( model="claude-3-sonnet-20240229", max_tokens=1000, messages=[{"role": "user", "content": prompt}], response_model=dict ) for mapping in response["mappings"]: alias_to_canonical[mapping["original"]] = mapping["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, because alias_to_canonical has no entry for it — 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 in the output below.

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, and the original surface forms as attributes.

import networkx as nx

def build_graph(extractions: List[Extraction], alias_map: Dict[str, str]) -> nx.MultiDiGraph: G = nx.MultiDiGraph() for extraction in extractions: for entity in extraction.entities: canonical = alias_map.get(entity.name, entity.name) G.add_node(canonical, type=entity.type, description=entity.description) 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) return G

Querying the Graph

Now the real power emerges. To answer multi-hop questions like "Which astronauts worked on Apollo 11?", we can traverse the graph programmatically. But for more complex reasoning, we serialize the relevant subgraph back to Claude.

def query_graph(graph: nx.MultiDiGraph, question: str) -> str:
    # Serialize a subgraph around entities mentioned in the question
    # For simplicity, we serialize the whole graph (small scale)
    nodes = list(graph.nodes(data=True))
    edges = list(graph.edges(data=True))
    
    graph_text = "Nodes:\n"
    for node, attrs in nodes:
        graph_text += f"- {node} ({attrs.get('type', 'unknown')}): {attrs.get('description', '')}\n"
    
    graph_text += "\nEdges:\n"
    for u, v, attrs in edges:
        graph_text += f"- {u} --[{attrs['predicate']}]--> {v}\n"
    
    prompt = f"""Given this knowledge graph, answer the question.

{graph_text}

Question: {question}

Answer concisely based only on the graph.""" response = client.messages.create( model="claude-3-sonnet-20240229", max_tokens=500, messages=[{"role": "user", "content": prompt}] ) return response.content[0].text

Example usage:

# After building the graph from Apollo documents
graph = build_graph(all_extractions, alias_map)
answer = query_graph(graph, "Which astronauts were part of Apollo 11?")
print(answer)  # "Neil Armstrong (commander), Buzz Aldrin (lunar module pilot), Michael Collins (command module pilot)"

Measuring Quality

To trust your graph in production, you need to measure extraction quality. Create a small gold set of documents with manually annotated entities and relations, then compare Claude's output against it.

def evaluate_extraction(gold_entities: List[str], gold_relations: List[tuple], 
                        extracted_entities: List[str], extracted_relations: List[tuple]):
    gold_entity_set = set(gold_entities)
    extracted_entity_set = set(extracted_entities)
    
    true_positives = len(gold_entity_set & extracted_entity_set)
    precision = true_positives / len(extracted_entity_set) if extracted_entity_set else 0
    recall = true_positives / len(gold_entity_set) if gold_entity_set else 0
    f1 = 2  precision  recall / (precision + recall) if (precision + recall) > 0 else 0
    
    return {"precision": precision, "recall": recall, "f1": f1}

Track these metrics across your corpus to understand the cost/quality tradeoff between Haiku (faster, cheaper, slightly lower quality) and Sonnet (slower, more expensive, higher quality).

Key Takeaways

  • No training data needed: Claude's structured outputs let you extract entities and relations with a single prompt, replacing traditional NER and relation classification pipelines.
  • AI-driven entity resolution beats heuristics: Claude can resolve "Buzz Aldrin" and "Edwin Aldrin" as the same entity using context, where string similarity fails.
  • Graph + LLM = powerful querying: By serializing subgraphs back to Claude, you can answer complex multi-hop questions that span multiple documents.
  • Watch for failure modes: Unclustered entities silently disappear, and over-merging can reduce precision. Always fall back to single-element clusters and spot-check results.
  • Measure what matters: Track precision, recall, and F1 against a gold set to understand quality and make informed model choices between Haiku and Sonnet.