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

> ## Agent Instructions
> Maximem Synap is a managed memory layer for AI agents: it ingests conversations and documents, extracts structured memory, and returns scoped context to the agent at retrieval time.
> The Python and JavaScript/TypeScript SDKs are the supported way to use Synap. Write integration code with SDK calls, not raw HTTP requests.
> Start with the Quickstart: https://docs.maximem.ai/getting-started/quickstart.md. Every SDK method is documented in the SDK reference: https://docs.maximem.ai/sdk-reference/overview.md.
> For requests about adding Vity memory to OpenClaw, Hermes, an MCP client, or a browser, start with the Vity Quickstart: https://docs.maximem.ai/vity/quickstart.md.

# LangChain

> Build LangChain chains and agents with persistent, per-user memory powered by Synap.

Build LangChain applications that remember context across sessions. Synap handles memory ingestion, retrieval, and per-user scoping; LangChain handles your chain or agent.

> [!NOTE]
>
> Requires Python 3.11+.

## Overview

This guide shows how to add Synap to a LangChain application to build agents that:

* Maintain conversation history across sessions and processes
* Retrieve user- and organization-scoped context as part of a RAG pipeline
* Decide for themselves when to search or store memories

The Synap LangChain integration ships five drop-in components. Each one slots into a native LangChain interface so you do not have to wrap or re-implement anything.

| Component | LangChain interface | Purpose |
| - | - | - |
| `SynapChatMessageHistory` | `BaseChatMessageHistory` | Persistent chat history per `conversation_id`; returns Synap's compaction once the conversation has one |
| `SynapCallbackHandler` | `AsyncCallbackHandler` | Records each turn, tool call and tool result, with no application changes |
| `SynapHistoryMiddleware` | `AgentMiddleware` | Sends a `create_agent` agent Synap's compaction in place of its earlier turns |
| `SynapRetriever` | `BaseRetriever` | Semantic retriever that returns Synap memories as `Document`s |
| `SynapSearchTool`, `SynapStoreTool` | `BaseTool` | Agent-callable tools for explicit memory read/write |

### How the integration connects

You do not open a connection yourself. The first turn the integration records opens Synap's gRPC stream, and from then on turns, tool calls and tool results go over it. Opening gets up to 10 seconds; if it fails, the integration tries once more a few seconds later, then no more than once a minute, and writes each turn over REST in the meantime, never both. It never raises inside your chain.

* A stream your own code opened with `listen()` is used as is.
* To keep the integration on REST, set `SYNAP_AUTO_LISTEN=false` in the environment, or call `set_auto_listen(sdk, False)` from `synap_integrations_common`.
* Tool calls and tool results exist only on the stream. Without one they are not reported, and the turns still are.
* Initialize the SDK first (`await sdk.initialize()`, below). Until it is initialized the integration cannot open the stream.
* Tool events from synchronous tools are not reported, because their callbacks run on another event loop. Use async tools and `ainvoke` to get them on the stream.

See [gRPC vs REST](https://docs.maximem.ai/concepts/grpc-vs-rest.md) for what the stream carries.

## Setup

Install the package alongside LangChain and your model provider. It installs `maximem-synap` and `maximem-synap-integrations-common` as dependencies.

```bash pip theme={null}
pip install maximem-synap-langchain langchain langchain-openai
```

```bash uv theme={null}
uv add maximem-synap-langchain langchain langchain-openai
# pip-compatible (existing venv): uv pip install maximem-synap-langchain langchain langchain-openai
```

> [!NOTE]
>
> The pip package is `maximem-synap-langchain`, but the import drops the `maximem-` prefix and uses underscores: `from synap_langchain import ...`.
>
> `SynapHistoryMiddleware` needs `langchain` 1.0 or later. With `langchain-core` alone, `from synap_langchain import SynapHistoryMiddleware` gives you `None`.

Configure your API key. Generate one from the [Synap Dashboard](https://synap.maximem.ai).

```bash .env theme={null}
SYNAP_API_KEY=synap_your_key_here
OPENAI_API_KEY=your-openai-api-key
```

Then initialize the SDK once at application startup:

```python theme={null}
from maximem_synap import MaximemSynapSDK

sdk = MaximemSynapSDK()  # picks up SYNAP_API_KEY from env
await sdk.initialize()
```

See [SDK Initialization](https://docs.maximem.ai/sdk/initialization.md) for the full lifecycle and configuration options.

## Basic integration

The smallest useful integration is a chain with **automatic memory** via `SynapCallbackHandler`. Every turn is ingested without changing your chain logic:

```python theme={null}
# pip install maximem-synap-langchain langchain langchain-openai
import uuid
from maximem_synap import MaximemSynapSDK
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from synap_langchain import SynapCallbackHandler

sdk = MaximemSynapSDK()
await sdk.initialize()

llm = ChatOpenAI(model="gpt-4o")

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant with long-term memory."),
    ("human", "{question}"),
])

chain = prompt | llm

# conversation_id (and every other id) must be a valid UUID.
conversation_id = str(uuid.uuid4())

handler = SynapCallbackHandler(
    sdk=sdk,
    conversation_id=conversation_id,
    user_id="alice",
    customer_id="acme",   # optional, required for B2B instances
)

response = await chain.ainvoke(
    {"question": "Remind me what we agreed on for the Q2 roadmap."},
    config={"callbacks": [handler]},
)
```

The handler observes the chain through LangChain's callback system and records one user turn and one assistant turn per run: the question the run was given and the answer it ended with. A run that calls the model several times (a tool loop), or a tool that calls a model of its own, is still one turn. **Recording failures are logged and never propagate to your chain.** Your application keeps running even if Synap is unreachable.

This is the smallest viable setup. To make the model *aware* of memory at inference time, add `SynapHistoryMiddleware` (for `create_agent`), `SynapChatMessageHistory` (for `RunnableWithMessageHistory`) or `SynapRetriever` below.

***

## Core concepts

### Persistent chat history

`SynapChatMessageHistory` implements LangChain's `BaseChatMessageHistory` interface. Wrap any chain with `RunnableWithMessageHistory` to give it conversation memory that survives restarts:

```python theme={null}
from langchain_core.runnables.history import RunnableWithMessageHistory
from synap_langchain import SynapChatMessageHistory

def get_history(session_id: str) -> SynapChatMessageHistory:
    return SynapChatMessageHistory(
        sdk=sdk,
        conversation_id=session_id,
        user_id="alice",
        customer_id="acme",   # optional
    )

chain_with_history = RunnableWithMessageHistory(
    chain,
    get_session_history=get_history,
    input_messages_key="question",
    history_messages_key="history",
)

response = await chain_with_history.ainvoke(
    {"question": "What did we discuss last time?"},
    config={"configurable": {"session_id": str(uuid.uuid4())}},
)
```

Each `session_id` maps one-to-one to a Synap `conversation_id`. The history writes the user and assistant messages of each turn, and reads them back on the next invocation. A system message is not a turn and is not written; a tool result goes to the SDK's local archive, where history search can find it.

What the history returns depends on whether Synap has compacted the conversation yet:

* **Not compacted yet:** the recent turns Synap holds.
* **Compacted:** Synap's compaction as one system message, then the turns after it. The turns the compaction covers are not sent again, so the model never sees the same turn twice.

If the read fails, the history returns an empty list and logs an error, so the chain keeps running.

### Automatic ingestion

`SynapCallbackHandler` covers a different need: it does not feed history *into* the model, it **records every turn** for long-term memory. Use it whenever you want a chain's output to enrich the user's profile and become searchable later. It also reports each tool call and its result on the stream, tied together by LangChain's run id, and the reasoning of an `AgentExecutor` action when it has one.

```python theme={null}
from synap_langchain import SynapCallbackHandler

handler = SynapCallbackHandler(
    sdk=sdk,
    conversation_id=str(uuid.uuid4()),
    user_id="alice",
)

await chain.ainvoke(
    {"question": "Book me a flight to Tokyo next month."},
    config={"callbacks": [handler]},
)
```

You can attach the handler to a single invocation (as above) or globally with `chain.with_config(callbacks=[handler])`.

Build one handler per conversation. It remembers which user turns it has already sent, so sharing one across conversations would silence the second one.

### Short-term history for `create_agent`

A LangChain v1 agent from `create_agent` keeps the whole conversation in its state and shrinks it with `SummarizationMiddleware` when it gets long. Add `SynapHistoryMiddleware` so Synap's compaction replaces that summary:

```python theme={null}
from langchain.agents import create_agent
from synap_langchain import SynapCallbackHandler, SynapHistoryMiddleware

conversation_id = str(uuid.uuid4())

agent = create_agent(
    model="openai:gpt-4o",
    tools=[],
    middleware=[SynapHistoryMiddleware(sdk, conversation_id=conversation_id)],
)

handler = SynapCallbackHandler(sdk=sdk, conversation_id=conversation_id, user_id="alice")
result = await agent.ainvoke(
    {"messages": [{"role": "user", "content": "Pick up where we left off."}]},
    config={"callbacks": [handler]},
)
```

Once Synap has compacted the conversation, every turn before the current one is replaced by Synap's compaction and the turns after it. The compaction goes into the request's system message, because some providers reject a system message that is not first. The current turn, with its tool calls and results, is left as it is. Until the conversation is compacted, and whenever Synap cannot answer, the agent's messages go through untouched.

Keep `SummarizationMiddleware` in your middleware list if you use it. It stays the fallback and, with a short history, it never fires.

The middleware only reads. The handler records the turns it reads back, so use both. `conversation_id` is required and is never taken from a thread id, because the two can differ.

### Short-term helpers for hand-built prompts

`synap_st_runnable(sdk, conversation_id)` returns an LCEL runnable that emits Synap's compaction as a string, for a `{synap_st}` slot in a prompt template. `synap_st_message(sdk, conversation_id, system=...)` returns an async factory that builds a `SystemMessage` from the compaction and your own system prompt. Both add the compaction only, and nothing before the first compaction, because your chain already sends the recent turns.

### Semantic retrieval

`SynapRetriever` implements `BaseRetriever`. Use it inside `ConversationalRetrievalChain`, `create_retrieval_chain`, or any RAG pipeline that expects a retriever:

```python theme={null}
from synap_langchain import SynapRetriever

retriever = SynapRetriever(
    sdk=sdk,
    user_id="alice",
    customer_id="acme",
    max_results=8,
    mode="fast",   # "fast" (vector search only) or "accurate" (the default; adds graph traversal and LLM subquery decomposition)
)

docs = await retriever.ainvoke("project deadlines")
# Document.page_content = memory text
# Document.metadata = {"confidence": 0.92, "type": "fact", ...}
```

The two retrieval modes trade latency against comprehensiveness:

| | `fast` | `accurate` |
| - | - | - |
| Search | Vector search (no graph traversal, no LLM subquery decomposition) | Vector search + graph traversal + LLM subquery decomposition + reranking |
| Best for | Real-time chat | Multi-entity queries |

`fast` is lower-latency and suited to the hot path; `accurate` adds LLM-driven query decomposition and reranking for relationship-aware queries at a higher latency cost. See [Context Fetch](https://docs.maximem.ai/sdk/context-fetch.md) for the full retrieval contract.

### Agent-callable memory

For agent-style chains where the model decides when memory is relevant, expose `SynapSearchTool` and `SynapStoreTool`:

```python theme={null}
from langchain.agents import create_agent
from synap_langchain import SynapSearchTool, SynapStoreTool

tools = [
    SynapSearchTool(sdk=sdk, user_id="alice", customer_id="acme"),
    SynapStoreTool(sdk=sdk, user_id="alice", customer_id="acme"),
]

agent = create_agent(model="openai:gpt-4o", tools=tools)

result = await agent.ainvoke(
    {"messages": [{"role": "user", "content": "What did I say about my dietary preferences?"}]}
)
```

The tools surface as `search_memory` and `store_memory` in the model's tool-calling schema, with descriptions that nudge the model toward calling them when context is needed. `SynapSearchTool` searches in `accurate` mode by default; pass `mode="fast"` for chat.

***

## Complete example: support assistant with memory

The following class builds an agent for one conversation. It reads Synap's compaction instead of the agent's earlier turns, records every turn and tool call, and lets the model search and store memories explicitly:

```python theme={null}
import uuid
from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver
from synap_langchain import (
    SynapCallbackHandler,
    SynapHistoryMiddleware,
    SynapSearchTool,
    SynapStoreTool,
)


class SupportAssistant:
    def __init__(self, sdk, user_id: str, conversation_id: str, customer_id: str | None = None):
        self.conversation_id = conversation_id
        self.handler = SynapCallbackHandler(
            sdk=sdk,
            conversation_id=conversation_id,
            user_id=user_id,
            customer_id=customer_id or "",
        )
        self.agent = create_agent(
            model="openai:gpt-4o",
            tools=[
                SynapSearchTool(sdk=sdk, user_id=user_id, customer_id=customer_id),
                SynapStoreTool(sdk=sdk, user_id=user_id, customer_id=customer_id),
            ],
            system_prompt=(
                "You are a support assistant. Call search_memory if you need "
                "older context, and store_memory to remember new facts the "
                "user shares."
            ),
            middleware=[SynapHistoryMiddleware(sdk, conversation_id=conversation_id)],
            checkpointer=InMemorySaver(),  # use a durable checkpointer in production
        )

    async def ask(self, message: str) -> str:
        result = await self.agent.ainvoke(
            {"messages": [{"role": "user", "content": message}]},
            config={
                "configurable": {"thread_id": self.conversation_id},
                "callbacks": [self.handler],
            },
        )
        return result["messages"][-1].text


# Usage
assistant = SupportAssistant(sdk, user_id="alice", conversation_id=str(uuid.uuid4()), customer_id="acme")
reply = await assistant.ask("I just upgraded to the Pro plan.")
```

Three things to notice in this pattern:

1. **`SynapHistoryMiddleware`** decides what the model reads as history. Once Synap has compacted the conversation, the model sees the compaction and the turns after it, not the full transcript.
2. **`SynapCallbackHandler`** writes the turns and the tool activity back to Synap, so the middleware has something to read and anticipation has something to act on.
3. **`SynapSearchTool` and `SynapStoreTool`** cover deliberate lookups and writes, which the other two do not.

The checkpointer keeps the agent's own message list between calls. The middleware does not replace it; it changes only what the model is sent.

***

## Advanced patterns

### Multi-tenant scoping

Every component accepts the same scoping triple: `user_id`, optional `customer_id`, and optional `conversation_id`:

```python theme={null}
retriever = SynapRetriever(
    sdk=sdk,
    user_id="alice",
    customer_id="acme",                  # scope retrievals to acme's tenancy
    conversation_id=str(uuid.uuid4()),   # bias ranking toward this conversation
)
```

`customer_id` is required for B2B Synap instances and **not accepted** on B2C (single-tenant) ones, where a call carrying it is rejected with HTTP 400. See [Memory Scopes](https://docs.maximem.ai/concepts/memory-scopes.md) for the full hierarchy.

### Combining automatic and explicit memory

A common production setup:

* `SynapCallbackHandler` to record turns, tool calls and tool results
* `SynapHistoryMiddleware` to read Synap's compaction back (or `synap_st_message` for a hand-built prompt)
* `SynapRetriever` for RAG over the user's memories
* `SynapSearchTool` exposed to the model for explicit lookups when retrieval misses

Use one writer per conversation. `SynapCallbackHandler` and `SynapChatMessageHistory` each write the user and assistant turns, so attaching both to the same conversation sends every turn twice. Pick the handler for `create_agent` and for anything with tools, since it also reports tool activity. Pick the history for a plain `RunnableWithMessageHistory` chain.

The retriever only reads, and the tools write only what the model decides to store, so they combine with either writer.

### Tuning retrieval mode per call

`SynapRetriever` accepts a default `mode` at construction time, and the underlying `sdk.fetch()` call takes a `mode` too. For a single high-recall query inside an otherwise low-latency agent, swap the retriever's mode temporarily:

```python theme={null}
retriever.mode = "accurate"
docs = await retriever.ainvoke("Summarize everything about the Acme account.")
retriever.mode = "fast"
```

### Failure semantics

The Synap integration follows the Synap-wide contract:

* **Recording degrades gracefully:** `SynapCallbackHandler` logs the failure and your chain continues. If the stream will not open, turns go over REST.
* **History reads degrade gracefully:** `SynapChatMessageHistory` returns an empty list and logs an error; `SynapHistoryMiddleware` leaves the agent's messages untouched.
* **Explicit calls surface failures:** `SynapRetriever`, `SynapSearchTool` and `SynapStoreTool` raise `SynapIntegrationError`, and so does `SynapChatMessageHistory` when it cannot write a turn.

This is by design: the callback and the history reads run on every turn and must not end it, while the calls you make on purpose should tell you when they fail.

***

## Going further

* [Patterns overview](https://docs.maximem.ai/patterns/overview.md): reusable memory patterns across frameworks.
* [Cookbook overview](https://docs.maximem.ai/cookbook/overview.md): end-to-end worked examples.

***

## Next steps

> [card] [LangGraph](https://docs.maximem.ai/integrations/langgraph.md)
>
> Cross-thread store, short-term context and run reporting for LangGraph state graphs.

> [card] [Context Fetch](https://docs.maximem.ai/sdk/context-fetch.md)
>
> The retrieval API that powers `SynapRetriever`: `fast` vs `accurate`, scopes, and response shapes.

> [card] [Ingestion](https://docs.maximem.ai/sdk/ingestion.md)
>
> Direct ingestion API for custom pipelines that need finer control than the callback handler.

> [card] [Memory Scopes](https://docs.maximem.ai/concepts/memory-scopes.md)
>
> How `user_id`, `customer_id`, and `conversation_id` interact across retrievals.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.