8 mins

Harshika Alagh

How to Build Knowledge Graphs for Your AI Agents

pia photo of the Pont du Gard aqueduct with HydraDB pixel-grid overlay

Building a knowledge graph is no longer the hard part. Making it useful for AI agents is where things get tricky.

Agents need more than connected facts. They need to find the right information, make sense of how things relate, and add or update knowledge as they work.

That means thinking beyond how a graph is built to how agents use it and how it changes over time.

In this article, we'll cover all three: graph creation, retrieval, and evolution, using SelfGraph, an open-source framework for building and maintaining knowledge graphs for AI agents.

How to create a useful knowledge graph for AI agents?

The knowledge graph lifecycle for AI agents: create, retrieve, evolve

1. Graph creation: Turning raw information into a structured graph

Most of the knowledge an agent needs already exists somewhere: documents, databases, support tickets, meeting notes, or conversations.

The first challenge is turning that information into a graph.

Take a sentence like:

Alice leads Project Atlas, which depends on the Payments API.

A knowledge graph might represent it as:

  • Alice → LEADS → Project Atlas

  • Project Atlas → DEPENDS_ON → Payments API

One sentence turned into graph structure: Alice LEADS Project Atlas DEPENDS_ON Payments API

LLMs make extracting these relationships relatively straightforward. But extraction alone doesn't guarantee a consistent graph.

For example, one document might refer to "Alice," another to "Alice Johnson," and a third to "A. Johnson." If all three refer to the same person, creating a new node for each would fragment the graph.

The same problem applies to relationships. One document might say a person "leads" a project, while another says they "manage" it.

Your system needs a way to decide whether these references mean the same thing.

This is where entity resolution and schemas become important.

Entity resolution determines whether two references point to the same real-world entity. A schema defines the kinds of entities and relationships your graph supports.

For example, you might define Person, Project, and Service as entity types, and LEADS and DEPENDS_ON as relationships.

An ontology can add meaning to these definitions through descriptions, synonyms, and related concepts.

How SelfGraph handles graph creation

SelfGraph provides a common interface for adding knowledge to a graph, whether you're starting with unstructured text or structured facts.

For unstructured text, it supports LLM-based extraction. You can also use simpler methods, such as spaCy or regex-based extraction, without making an LLM call.

This gives you control over how much processing is needed for a particular dataset.

SelfGraph also supports schemas, ontologies, and entity resolution.

You can define the entities and relationships your application expects, use synonyms to connect different terms, and identify duplicate entities before they create inconsistencies in the graph.

The goal is to move the knowledge-processing logic out of individual ingestion pipelines and into a common framework.

2. Graph retrieval: Making the graph accessible to agents

Having information stored in a graph doesn't mean an agent can easily find what it needs.

Consider the earlier question:

"Who owns the service that Project Atlas depends on?"

Answering it requires several steps. The system needs to identify Project Atlas, find the services connected to it, follow the relevant dependency, and retrieve the ownership information.

A multi-hop question answered by traversing DEPENDS_ON and OWNED_BY

A graph database can perform these traversals through queries.

But the agent shouldn't necessarily have to understand the underlying schema, generate a correct Cypher query, and decide which relationships to traverse every time it needs context.

A retrieval layer can handle that work.

It maps a question to relevant entities, follows useful relationships, and assembles the results into context the agent can use.

Retrieval also needs to account for how information is represented.

For example, a user might ask who is responsible for a service, while the graph stores the relationship as OWNED_BY. The retrieval system needs to connect the user's wording to the graph's vocabulary.

How SelfGraph handles graph retrieval

SelfGraph supports keyword-based matching, ontology-aware retrieval, and graph traversal.

It can identify relevant starting entities, follow their relationships, and return connected information along with supporting source passages.

Embeddings are optional. You can retrieve information using keyword matching and graph traversal without maintaining a separate vector store.

For applications that need semantic matching, SelfGraph also provides higher processing tiers that can use embeddings and more advanced retrieval methods.

Another capability is answerability checking.

Suppose an agent asks:

"What was Acme's advertising spend last quarter?"

The graph might contain information about Acme, its employees, and its projects, but nothing about advertising spend.

Finding the Acme entity doesn't mean the graph has enough information to answer the question.

SelfGraph can check whether the concepts in the question are represented in its ontology and identify missing terms before the agent proceeds. It's a way to give agents more information about what the graph knows and where its coverage is incomplete.

Answerability checking flowchart for the Acme advertising spend question

Exposing the graph to agents

Retrieval also needs a usable interface.

SelfGraph provides Python and TypeScript SDKs, a CLI, and an MCP server.

An application can call the SDK directly, while an MCP-compatible agent can access graph operations through tools.

This gives agents a consistent way to retrieve knowledge without having to manage the underlying database connection or construct every graph query themselves.

3. Graph evolution: Keeping knowledge up to date

Knowledge changes.

People switch teams, projects change owners, services get replaced, and new decisions can make earlier information outdated.

A knowledge graph that only supports insertion and retrieval will eventually run into problems when new facts contradict old ones.

Consider this example:

In January, Alice leads Project Atlas.

In March, Bob takes over.

If the graph simply adds another LEADS relationship, both Alice and Bob may appear to lead the project.

If it replaces Alice's relationship with Bob's, the current information becomes accurate, but the history is lost.

Neither approach is sufficient when agents need to answer questions about both the present and the past.

Append only vs overwrite vs versioned relationships when Bob takes over Project Atlas

The system needs to know when a relationship became valid, when it stopped being valid, and when the system learned about the change.

How SelfGraph handles graph evolution

SelfGraph supports versioned relationships and temporal queries.

When a new fact replaces an existing one, the older relationship can be retired rather than deleted.

For example:

  • January: Alice → LEADS → Project Atlas

  • March: Bob → LEADS → Project Atlas

A query for the current project lead can return Bob.

A historical query for February can still return Alice.

SelfGraph also tracks when changes were recorded, allowing applications to distinguish the historical state of the world from what the system knew at a particular time.

How conflicting facts are resolved depends on the configuration. You can define constraints in a schema or use LLM-assisted contradiction detection.

This matters because not every new relationship should replace an old one. A person might legitimately work on two projects, for example. The system needs rules for deciding whether relationships can coexist.

What happens when an agent writes back?

Graph evolution becomes especially important when agents are allowed to update knowledge.

Suppose an agent processes a project update and learns that the Payments API is now owned by the Platform team.

It needs to record the new relationship, identify whether an earlier ownership relationship exists, and apply the appropriate update rules.

Flowchart of what happens when an agent writes back a new fact

SelfGraph provides operations for creating and updating entities and relationships while keeping track of their history.

In a production application, you'll still need controls around what agents are allowed to write. Authentication, authorization, validation, and review policies are application responsibilities.

But the underlying knowledge-management operations no longer have to be implemented from scratch.

This makes the graph useful beyond a one-time retrieval workflow. It can become a shared knowledge source that applications and agents continue to update.

Putting it together with SelfGraph and HydraDB

So far, we've looked at graph creation, retrieval, and evolution separately. In practice, these capabilities need to work together.

A typical workflow looks like this:

  1. Ingest data: Start with text, documents, or structured facts.

  2. Create the graph: Extract entities and relationships, resolve duplicates, and apply a schema where needed.

  3. Retrieve knowledge: Find relevant entities, traverse relationships, and assemble context for the agent.

  4. Update the graph: Add new facts, handle changes to existing relationships, and preserve historical versions.

  5. Expose these operations to agents: Provide read and write access through an SDK, API, or MCP tools.

SelfGraph handles the knowledge-management operations across this workflow.

The underlying graph database still handles storage and graph queries.

For this example, we'll use HydraDB as the backend, but Selfgraph also works with Neo4j, Memgraph, FalkorDB, and Kuzu.

Architecture: agents, SDK/CLI/MCP, SelfGraph operations, and graph database backends

Getting started

Install SelfGraph:

pip install selfgraph
pip install selfgraph
pip install selfgraph
pip install selfgraph
pip install selfgraph

Then connect it to a running HydraDB instance:

from selfgraph import SelfGraph, HydraDBStore

store = HydraDBStore(
    "bolt://127.0.0.1:17687",
    auth=("neo4j", "<token>")
)
from selfgraph import SelfGraph, HydraDBStore

store = HydraDBStore(
    "bolt://127.0.0.1:17687",
    auth=("neo4j", "<token>")
)
from selfgraph import SelfGraph, HydraDBStore

store = HydraDBStore(
    "bolt://127.0.0.1:17687",
    auth=("neo4j", "<token>")
)
from selfgraph import SelfGraph, HydraDBStore

store = HydraDBStore(
    "bolt://127.0.0.1:17687",
    auth=("neo4j", "<token>")
)
from selfgraph import SelfGraph, HydraDBStore

store = HydraDBStore(
    "bolt://127.0.0.1:17687",
    auth=("neo4j", "<token>")
)

You can now initialize SelfGraph and insert structured knowledge:

async with SelfGraph(store=store) as graph:
    await graph.insert.facts({
        "entities": [
            {
                "id": "person:alice",
                "type": "Person",
                "name": "Alice"
            },
            {
                "id": "project:atlas",
                "type": "Project",
                "name": "Project Atlas"
            }
        ],
        "relations": [
            {
                "from_entity": "person:alice",
                "type": "LEADS",
                "to_entity": "project:atlas"
            }
        ]
    })

    result = await graph.retrieve(
        "Who leads Project Atlas?"
    )

    print(result.context)
async with SelfGraph(store=store) as graph:
    await graph.insert.facts({
        "entities": [
            {
                "id": "person:alice",
                "type": "Person",
                "name": "Alice"
            },
            {
                "id": "project:atlas",
                "type": "Project",
                "name": "Project Atlas"
            }
        ],
        "relations": [
            {
                "from_entity": "person:alice",
                "type": "LEADS",
                "to_entity": "project:atlas"
            }
        ]
    })

    result = await graph.retrieve(
        "Who leads Project Atlas?"
    )

    print(result.context)
async with SelfGraph(store=store) as graph:
    await graph.insert.facts({
        "entities": [
            {
                "id": "person:alice",
                "type": "Person",
                "name": "Alice"
            },
            {
                "id": "project:atlas",
                "type": "Project",
                "name": "Project Atlas"
            }
        ],
        "relations": [
            {
                "from_entity": "person:alice",
                "type": "LEADS",
                "to_entity": "project:atlas"
            }
        ]
    })

    result = await graph.retrieve(
        "Who leads Project Atlas?"
    )

    print(result.context)
async with SelfGraph(store=store) as graph:
    await graph.insert.facts({
        "entities": [
            {
                "id": "person:alice",
                "type": "Person",
                "name": "Alice"
            },
            {
                "id": "project:atlas",
                "type": "Project",
                "name": "Project Atlas"
            }
        ],
        "relations": [
            {
                "from_entity": "person:alice",
                "type": "LEADS",
                "to_entity": "project:atlas"
            }
        ]
    })

    result = await graph.retrieve(
        "Who leads Project Atlas?"
    )

    print(result.context)
async with SelfGraph(store=store) as graph:
    await graph.insert.facts({
        "entities": [
            {
                "id": "person:alice",
                "type": "Person",
                "name": "Alice"
            },
            {
                "id": "project:atlas",
                "type": "Project",
                "name": "Project Atlas"
            }
        ],
        "relations": [
            {
                "from_entity": "person:alice",
                "type": "LEADS",
                "to_entity": "project:atlas"
            }
        ]
    })

    result = await graph.retrieve(
        "Who leads Project Atlas?"
    )

    print(result.context)

For unstructured text, you can use graph.insert.text() with a configured LLM or one of SelfGraph's non-LLM extraction methods.

You can also introduce a schema, configure entity resolution, or create new relationships with timestamps as the application becomes more complex.

The advantage is that these capabilities are exposed through the same framework instead of separate ingestion, retrieval, and maintenance pipelines.

How else can you build a knowledge layer for your agents?

You don't need SelfGraph to build a knowledge layer for your agents. You can build one yourself by combining a graph database, an extraction pipeline, a retrieval framework, and a way to keep knowledge up to date.

The challenge is making all these pieces work together.

Option 1: Build your own stack

One approach is to assemble the system using existing tools.

Option 1: a build-your-own stack with glue code between five layers

This gives you control over the system, but it also means maintaining the connections between these components.

For example, when an agent writes a new fact, your system needs to determine whether the entity already exists, whether the new fact conflicts with an older one, and whether the previous relationship should be preserved.

Retrieval also has to account for those updates so agents don't accidentally use outdated information.

None of these problems is impossible to solve. But they add engineering work beyond simply creating a graph.

Option 2: Use an existing end-to-end graph framework

You can also use a framework like Zep’s Graphiti. It supports entity and relationship extraction, graph updates, temporal history, and retrieval. Rather than building each capability yourself, you can use Graphiti to maintain an evolving knowledge graph for agents.

This is closer to what SelfGraph provides than a standalone graph database or retrieval framework.

The differences come down to the architecture and how much control you need over the underlying graph.

Graphiti hands the whole job to a model. Everything you add goes through the same pipeline, and an LLM decides what the entities are, which ones are duplicates and which facts replace which. You run it on your own database.

Graphiti uses models for entity extraction, resolution, and fact reconciliation. SelfGraph lets you start with deterministic rules and use models for selected decisions.

Where the model makes decisions in Graphiti vs SelfGraph

Where SelfGraph fits

SelfGraph is useful when you want to build and maintain a structured knowledge graph without implementing the surrounding knowledge-management logic yourself.

You can use one interface to insert facts, extract relationships, query the graph, work with ontologies, and track how information changes.

You can also start without an LLM and introduce LLM-backed processing selectively rather than making it a requirement for every operation.

And because the storage layer is separate, you can work with different graph databases through the same SDK.

Explore the project and get started with SelfGraph on GitHub.

Share