> ## 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.

# Adding Episodes

> Learn how to add episodes to your knowledge graph using text and JSON formats

Episodes are the primary units of information in Graphiti. Each episode represents a discrete piece of content that Graphiti processes to extract entities and relationships.

## Episode Types

Graphiti supports three episode types:

* `EpisodeType.text` - Plain text content like meeting notes or articles
* `EpisodeType.json` - Structured JSON data
* `EpisodeType.message` - Conversation messages with speaker patterns

## Adding a Single Episode

<Steps>
  <Step title="Import dependencies">
    ```python theme={null}
    from datetime import datetime, timezone
    from graphiti_core import Graphiti
    from graphiti_core.nodes import EpisodeType
    ```
  </Step>

  <Step title="Initialize Graphiti">
    ```python theme={null}
    graphiti = Graphiti(
        uri="bolt://localhost:7687",
        user="neo4j",
        password="password"
    )
    ```
  </Step>

  <Step title="Add a text episode">
    ```python theme={null}
    await graphiti.add_episode(
        name="Meeting Notes Q4",
        episode_body="Alice reviewed the mobile app redesign progress. Bob presented the engineering timeline.",
        source=EpisodeType.text,
        source_description="Q4 planning meeting",
        reference_time=datetime.now(timezone.utc)
    )
    ```

    The `reference_time` parameter specifies when this information was valid, enabling temporal queries.
  </Step>
</Steps>

## Adding JSON Episodes

For structured data, use `EpisodeType.json` and serialize your data:

```python theme={null}
import json

product_data = {
    "name": "Wool Runners",
    "material": "SuperLight Wool",
    "color": "Dark Grey",
    "technology": "SuperLight Foam"
}

await graphiti.add_episode(
    name="Product Catalog Entry",
    episode_body=json.dumps(product_data),
    source=EpisodeType.json,
    source_description="Product database",
    reference_time=datetime.now(timezone.utc)
)
```

## Adding Message Episodes

For conversations, use `EpisodeType.message`:

```python theme={null}
conversation = """User: I need help setting up a development environment.
Assistant: I can help with that. Which cloud provider are you using?
User: We're using AWS with PostgreSQL and Redis."""

await graphiti.add_episode(
    name="Support Chat 2024-01-15",
    episode_body=conversation,
    source=EpisodeType.message,
    source_description="Customer support conversation",
    reference_time=datetime.now(timezone.utc)
)
```

## Episode Parameters

| Parameter            | Type          | Required | Description                                  |
| -------------------- | ------------- | -------- | -------------------------------------------- |
| `name`               | `str`         | Yes      | Unique identifier for the episode            |
| `episode_body`       | `str`         | Yes      | The content (plain text or JSON string)      |
| `source`             | `EpisodeType` | Yes      | Type of episode (text, json, or message)     |
| `source_description` | `str`         | Yes      | Description of where this data came from     |
| `reference_time`     | `datetime`    | Yes      | When this information was valid              |
| `group_id`           | `str`         | No       | Graph partition identifier                   |
| `uuid`               | `str`         | No       | Custom UUID (auto-generated if not provided) |
| `entity_types`       | `dict`        | No       | Custom entity type definitions               |
| `edge_types`         | `dict`        | No       | Custom relationship type definitions         |
| `update_communities` | `bool`        | No       | Whether to update community summaries        |

## Advanced Options

### Group IDs for Multi-Tenancy

Use `group_id` to partition your graph for different users or contexts:

```python theme={null}
await graphiti.add_episode(
    name="User Session",
    episode_body="User completed checkout process",
    source=EpisodeType.text,
    source_description="Analytics event",
    reference_time=datetime.now(timezone.utc),
    group_id="user_12345"  # Isolate data per user
)
```

### Custom Entity Types

Define custom entity types to extract domain-specific information:

```python theme={null}
from pydantic import BaseModel, Field

class Person(BaseModel):
    """A human person"""
    first_name: str | None = Field(description="First name")
    last_name: str | None = Field(description="Last name")
    occupation: str | None = Field(description="Work occupation")

await graphiti.add_episode(
    name="Team Meeting",
    episode_body="Sarah Johnson, the lead engineer, presented the roadmap.",
    source=EpisodeType.text,
    source_description="Meeting notes",
    reference_time=datetime.now(timezone.utc),
    entity_types={"Person": Person}
)
```

See the [Custom Entities](/guides/custom-entities) guide for more details.

### Updating Communities

Communities are clusters of related entities. Enable automatic community updates:

```python theme={null}
result = await graphiti.add_episode(
    name="Episode 5",
    episode_body="Content about related topics",
    source=EpisodeType.text,
    source_description="Source",
    reference_time=datetime.now(timezone.utc),
    update_communities=True  # Regenerate community summaries
)

print(f"Communities updated: {len(result.communities)}")
```

## Episode Results

The `add_episode` method returns an `AddEpisodeResults` object:

```python theme={null}
result = await graphiti.add_episode(...)

print(f"Episode UUID: {result.episode.uuid}")
print(f"Entities extracted: {len(result.nodes)}")
print(f"Relationships extracted: {len(result.edges)}")
print(f"Communities: {len(result.communities)}")

# Access extracted entities
for node in result.nodes:
    print(f"Entity: {node.name} - {node.summary}")

# Access relationships
for edge in result.edges:
    print(f"Fact: {edge.fact}")
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Sequential Processing" icon="list-ol">
    Add episodes sequentially, not in parallel. Each episode builds on the context of previous ones.
  </Card>

  <Card title="Descriptive Names" icon="tag">
    Use clear, unique names for episodes to make them easy to identify later.
  </Card>

  <Card title="Accurate Timestamps" icon="clock">
    Set `reference_time` to when the information was valid, not when you're processing it.
  </Card>

  <Card title="Source Descriptions" icon="book">
    Provide meaningful source descriptions to track data provenance.
  </Card>
</CardGroup>

## Dense Content Handling

Graphiti automatically detects and chunks dense content (like cost reports with many entities):

```python theme={null}
# This dense JSON will be automatically chunked
aws_costs = {
    "report_type": "AWS Cost Breakdown",
    "services": [
        {"name": "Amazon S3", "cost": 2487.97},
        {"name": "Amazon RDS", "cost": 1071.74},
        # ... many more services
    ]
}

await graphiti.add_episode(
    name="AWS Cost Report",
    episode_body=json.dumps(aws_costs),
    source=EpisodeType.json,
    source_description="Monthly cost breakdown",
    reference_time=datetime.now(timezone.utc)
)
# Graphiti automatically chunks this into multiple LLM calls
```

Chunking is controlled by environment variables:

* `CHUNK_MIN_TOKENS` - Minimum tokens before considering chunking (default: 1000)
* `CHUNK_DENSITY_THRESHOLD` - Entity density threshold (default: 0.15)
* `CHUNK_TOKEN_SIZE` - Target size per chunk (default: 3000)

## Error Handling

```python theme={null}
try:
    result = await graphiti.add_episode(
        name="Example",
        episode_body="Content here",
        source=EpisodeType.text,
        source_description="Example source",
        reference_time=datetime.now(timezone.utc)
    )
except Exception as e:
    print(f"Failed to add episode: {e}")
    # Handle error appropriately
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Bulk Operations" icon="layer-group" href="/guides/bulk-operations">
    Learn how to add multiple episodes efficiently
  </Card>

  <Card title="Searching" icon="magnifying-glass" href="/guides/searching">
    Query your knowledge graph to retrieve information
  </Card>

  <Card title="Custom Entities" icon="shapes" href="/guides/custom-entities">
    Define domain-specific entity types
  </Card>
</CardGroup>
