> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/getzep/graphiti/llms.txt
> Use this file to discover all available pages before exploring further.

# Knowledge Graphs

> Understanding knowledge graphs and how Graphiti uses them for AI memory

## What is a Knowledge Graph?

A knowledge graph is a network of interconnected facts represented as **triplets**—each consisting of two entities (nodes) and their relationship (edge). For example, the fact *"Kendra loves Adidas shoes"* becomes:

* **Source Node**: Kendra (entity)
* **Edge**: loves (relationship)
* **Target Node**: Adidas shoes (entity)

Knowledge graphs enable AI agents to reason about complex, interconnected information by representing it as a queryable network rather than isolated documents.

## The Graphiti Approach

While traditional knowledge graphs have been used extensively for information retrieval, Graphiti introduces a unique approach tailored for AI agents:

### Autonomous Graph Building

Graphiti autonomously constructs knowledge graphs from unstructured and structured data without requiring manual schema definition. When you add an episode (a unit of information), Graphiti:

1. **Extracts entities** using LLMs to identify people, places, organizations, and custom entity types
2. **Identifies relationships** between entities with semantic meaning
3. **Resolves duplicates** by detecting when new information refers to existing entities
4. **Updates the graph** incrementally without batch recomputation

### Temporal Awareness

Unlike traditional static graphs, Graphiti maintains a **temporal dimension**:

```python theme={null}
class EntityEdge(Edge):
    fact: str  # The relationship described as a fact
    valid_at: datetime | None  # When the fact became true
    invalid_at: datetime | None  # When the fact stopped being true
    expired_at: datetime | None  # When the edge was superseded
```

This enables:

* Point-in-time queries: "Who was the Attorney General in 2015?"
* Tracking evolving relationships: "When did Alice start working at Acme Corp?"
* Handling contradictions: New information can invalidate old facts without deletion

<Note>
  Graphiti tracks both when facts occurred in the real world (`valid_at`/`invalid_at`) and when they were ingested into the system (`created_at`/`expired_at`). This **bi-temporal model** is crucial for accurate historical reasoning.
</Note>

## Graph Structure

A Graphiti knowledge graph consists of several node and edge types:

### Node Types

| Type              | Purpose                        | Example                                          |
| ----------------- | ------------------------------ | ------------------------------------------------ |
| **EntityNode**    | Represents real-world entities | People, places, organizations, concepts          |
| **EpisodicNode**  | Stores raw input data          | Chat messages, documents, JSON data              |
| **CommunityNode** | Groups related entities        | Topic clusters discovered through graph analysis |
| **SagaNode**      | Organizes sequential episodes  | Conversation threads, event sequences            |

### Edge Types

| Type                            | Connects           | Purpose                              |
| ------------------------------- | ------------------ | ------------------------------------ |
| **EntityEdge** (RELATES\_TO)    | Entity → Entity    | Semantic relationships with facts    |
| **EpisodicEdge** (MENTIONS)     | Episode → Entity   | Links raw data to extracted entities |
| **CommunityEdge** (HAS\_MEMBER) | Community → Entity | Membership in topic clusters         |
| **HasEpisodeEdge**              | Saga → Episode     | Saga membership                      |
| **NextEpisodeEdge**             | Episode → Episode  | Sequential ordering                  |

## Knowledge Representation Example

Consider this episode:

```python theme={null}
await graphiti.add_episode(
    name="Career Update",
    episode_body="Kamala Harris is the Attorney General of California. "
                 "She was previously the district attorney for San Francisco.",
    source=EpisodeType.text,
    reference_time=datetime.now(timezone.utc),
)
```

Graphiti extracts:

**Entities**:

* Node: "Kamala Harris" (Person)
* Node: "California" (Location)
* Node: "San Francisco" (Location)
* Node: "Attorney General" (Position)
* Node: "District Attorney" (Position)

**Relationships**:

* Edge: Kamala Harris → holds position → Attorney General
  * Fact: "Kamala Harris is the Attorney General of California"
* Edge: Kamala Harris → previously held → District Attorney
  * Fact: "She was previously the district attorney for San Francisco"

**Episode Link**:

* EpisodicEdge: "Career Update" → mentions → "Kamala Harris"

## Why Graphiti vs Traditional Approaches

### vs. RAG (Retrieval-Augmented Generation)

Traditional RAG systems retrieve document chunks based on semantic similarity. Graphiti goes further:

* **Structured relationships**: Instead of text chunks, retrieve specific facts with context
* **Graph traversal**: Find related information by following edges
* **Temporal queries**: Filter by when facts were true, not just when documents were created
* **Contradiction handling**: Automatically invalidates outdated information

### vs. GraphRAG

| Aspect                | GraphRAG                      | Graphiti                          |
| --------------------- | ----------------------------- | --------------------------------- |
| **Data Handling**     | Batch-oriented                | Continuous, incremental           |
| **Primary Use**       | Static document summarization | Dynamic data management           |
| **Retrieval**         | Sequential LLM summarization  | Hybrid semantic + keyword + graph |
| **Temporal Handling** | Basic timestamps              | Bi-temporal tracking              |
| **Query Latency**     | Seconds to tens of seconds    | Sub-second                        |
| **Custom Types**      | No                            | Yes, via Pydantic models          |

## Real-Time Incremental Updates

One of Graphiti's key advantages is real-time processing:

```python theme={null}
# Add new information instantly
result = await graphiti.add_episode(
    name="Latest News",
    episode_body="Kamala Harris became Vice President in January 2021.",
    reference_time=datetime(2021, 1, 20, tzinfo=timezone.utc),
)

# Graphiti automatically:
# 1. Recognizes "Kamala Harris" as an existing entity
# 2. Creates a new relationship for the VP role
# 3. Invalidates the Attorney General edge (expired_at = 2021-01-20)
# 4. Makes the new information immediately searchable
```

<Tip>
  Graphiti's incremental updates make it ideal for AI agents that need to maintain accurate, up-to-date knowledge without costly batch reprocessing.
</Tip>

## Hybrid Search

Graphiti combines three search methods for comprehensive retrieval:

1. **Semantic search**: Vector similarity on embedded facts and entity names
2. **Keyword search**: BM25 full-text search for precise term matching
3. **Graph traversal**: Navigate relationships to find connected information

```python theme={null}
# Hybrid search example
results = await graphiti.search(
    "Who was California's Attorney General before becoming VP?",
    center_node_uuid=kamala_node.uuid,  # Focus on related entities
    num_results=10
)
```

## Group IDs for Multi-Tenancy

Graphiti supports partitioning graphs by `group_id`, enabling:

* **Multi-user applications**: Separate knowledge graphs per user
* **Organizational hierarchies**: Team-level or project-level graphs
* **Access control**: Query only the groups a user has permission for

```python theme={null}
# Add episode to a specific group
await graphiti.add_episode(
    name="User Message",
    episode_body="Alice started working on Project Phoenix",
    group_id="user_123",
    reference_time=datetime.now(timezone.utc),
)

# Search within a group
results = await graphiti.search(
    "What is Alice working on?",
    group_ids=["user_123"]
)
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Temporal Model" icon="clock" href="/concepts/temporal-model">
    Learn about Graphiti's bi-temporal data model
  </Card>

  <Card title="Episodes" icon="book" href="/concepts/episodes">
    Understand episodes as units of information
  </Card>

  <Card title="Nodes and Edges" icon="diagram-project" href="/concepts/nodes-and-edges">
    Explore the graph schema in detail
  </Card>

  <Card title="Communities" icon="users" href="/concepts/communities">
    Discover community detection for topic clustering
  </Card>
</CardGroup>
