> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cognee.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# LangGraph

> Add persistent memory to LangGraph agents with Cognee.

Give your [LangGraph](https://langchain-ai.github.io/langgraph/) agents persistent semantic memory that survives across sessions. Store data in cognee's knowledge graph and retrieve it via natural language—no manual state management required.

## Why Use This Integration

* **Cross-Session Memory**: Context persists across agent instances and conversation sessions
* **Semantic Recall**: Retrieve information using natural language queries
* **Session Isolation**: Multi-tenant support with per-user data separation
* **Drop-in tools**: `add_tool` and `search_tool` work with LangGraph agents out of the box

## Installation

```bash theme={null}
pip install cognee-integration-langgraph
```

## Quick Start

Before using the integration, configure your environment variables:

```bash theme={null}
export OPENAI_API_KEY="your-openai-api-key-here"    # for LangGraph
export LLM_API_KEY="your-openai-api-key-here"       # for cognee
export LLM_MODEL="gpt-4o-mini"
```

Add memory tools to your LangGraph agent. Tools are built per session and the agent must be invoked asynchronously with `ainvoke()`:

```python theme={null}
import asyncio
from langchain.agents import create_agent
from langchain_core.messages import HumanMessage
from cognee_integration_langgraph import get_sessionized_cognee_tools

async def main():
    # Build sessionized memory tools (omit the arg to auto-generate a session ID)
    add_tool, search_tool = get_sessionized_cognee_tools("user-123")

    # Create an agent with memory
    agent = create_agent(
        "openai:gpt-4o-mini",
        tools=[add_tool, search_tool],
    )

    # Store and retrieve information (note: must use await with .ainvoke())
    response = await agent.ainvoke({
        "messages": [
            HumanMessage(content="Remember: I like pizza and coding in Python")
        ]
    })
    print(response["messages"][-1].content)

if __name__ == "__main__":
    asyncio.run(main())
```

## Tools

`get_sessionized_cognee_tools(session_id=None, include_persist_tool=False, user=None)` returns the memory tools:

| Tool                    | Description                                                                                                                                       |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `add_tool`              | Stores data in the knowledge base (`data`, optional `node_set`)                                                                                   |
| `search_tool`           | Retrieves stored information with natural language (`query_text`, optional `session_id`, `query_type`); defaults to `SearchType.GRAPH_COMPLETION` |
| `persist_sessions_tool` | Promotes conversation sessions into the permanent graph (`session_ids`); returned only when `include_persist_tool=True`                           |

## Session Management

Pass a `session_id` to isolate memory per user or organization:

```python theme={null}
# User-specific memory
user_tools = get_sessionized_cognee_tools(session_id="user_123")

# Org-specific memory
org_tools = get_sessionized_cognee_tools(session_id="org_acme")

# Generate a unique session automatically
auto_tools = get_sessionized_cognee_tools()  # Uses a UUID-based session ID
```

<Info>
  Session isolation is implemented by scoping data with `node_set=[session_id]` for `add_tool`, and injecting the `session_id` into `search_tool`. Data added outside a session forms separate clusters.
</Info>

## How It Works

1. **Add Tool**: Stores data in cognee's knowledge graph with embeddings
2. **Search Tool**: Retrieves relevant information via cognee's recall pipeline
3. **Auto-Processing**: cognee extracts entities, relationships, and context automatically
4. **Session Scoping**: Data is organized by session clusters but globally accessible

## Use Cases

<AccordionGroup>
  <Accordion title="Knowledge Accumulation">
    Build domain knowledge incrementally over multiple sessions:

    ```python theme={null}
    # Add knowledge from sessions
    for doc in knowledge_base:
        await agent.ainvoke({"messages": [HumanMessage(content=f"Learn: {doc}")]})

    # Query across all
    response = await agent.ainvoke({
        "messages": [HumanMessage(content="Find information about contract terms")]
    })
    ```
  </Accordion>

  <Accordion title="Context-Aware Assistance">
    Maintain user context across work sessions:

    ```python theme={null}
    # Monday
    await agent.ainvoke({"messages": [HumanMessage(content="Debugging payment flow")]})

    # Wednesday
    await agent.ainvoke({"messages": [HumanMessage(content="What was I debugging?")]})
    ```
  </Accordion>

  <Accordion title="Multi-Tenant Applications">
    Isolate data per user/organization while sharing global knowledge:

    ```python theme={null}
    # Per-user isolation
    add_tool, search_tool = get_sessionized_cognee_tools(session_id=user_id)
    agent = create_agent("openai:gpt-4o-mini", tools=[add_tool, search_tool])
    ```
  </Accordion>
</AccordionGroup>

***

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/topoteretes/cognee-integrations/tree/main/integrations/langgraph">
    View source code and examples
  </Card>

  <Card title="Examples" icon="book" href="https://github.com/topoteretes/cognee-integrations/tree/main/integrations/langgraph/examples">
    Runnable example scripts
  </Card>
</CardGroup>
