Essentials

Build a Graph

Learn how to build a knowledge graph from a text file and export it to Neo4j, TTL, and CQL formats.

The full code for this example is available on GitHub.

Perseus gives you the tools to transform unstructured text into a queryable knowledge graph. This allows you to build smarter AI applications by turning raw information into structured, context-aware memory that your agents can reliably use.

What You'll Learn

In this tutorial, you'll learn how to:

  • Build a knowledge graph from a plain text file.
  • Enrich the graph with an ontology and custom metadata.
  • Export the graph to multiple formats, including Neo4j, TTL, and CQL.

Example Use Case: Analyzing a Biography

In this example, we'll take a simple text file containing a short biography of Marie Curie and use the Perseus SDK to extract structured information and load it into a graph database.

Prerequisites

Before running this example, ensure you have followed the installation guide to set up your environment and obtain the necessary API keys.


Code Walkthrough

Build a Knowledge Graph

The simplest way to create a graph is to call the perseus_client.build_graph() function with a list of file paths. This function processes each file and returns a list of KnowledgeGraph objects.

For more details on the build_graph method, refer to the Python API.

import perseus_client

# Build a graph from a single text file
knowledge_graphs = perseus_client.build_graph(
    file_paths=["assets/sample.txt"],
)

if knowledge_graphs:
    kg = knowledge_graphs[0]
    print(f"Successfully built graph with {len(kg.entities)} entities.")

Enrich with an Ontology and Metadata

You can add structure and context to your graph by providing an ontology and custom metadata during the build process.

  • Ontology: An ontology file (e.g., in .ttl format) defines the schema of your graph—the types of entities and relations that can exist.
  • Metadata: A dictionary of custom key-value pairs that will be attached to every node and relationship in the graph. This is useful for tracking data provenance, versioning, or other contextual information.
import os
import perseus_client

custom_metadata = {
    "source_file": os.path.basename("assets/sample.txt"),
    "processing_date": "2026-03-10",
    "version": "1.0",
}

knowledge_graphs = perseus_client.build_graph(
    file_paths=["assets/sample.txt"],
    ontology_path="assets/ontology.ttl",
    metadata=custom_metadata,
)

Export the Graph

Once a KnowledgeGraph object is created, you can export it to various formats. The SDK provides convenient methods to save the graph to local files or directly to a graph database like Neo4j.

For more details on the methods to export or save your graph, refer to the Python API.

# Assuming 'kg' is a KnowledgeGraph object

kg.save_ttl("./output/graph.ttl")
kg.save_cql("./output/graph.cql")
kg.save_to_neo4j()
kg.save_to_falkordb()