Skip to main content
Build LangChain applications that remember context across sessions. Synap handles memory ingestion, retrieval, and per-user scoping; LangChain handles your chain or agent.
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.

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 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.
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.
.env
Then initialize the SDK once at application startup:
See SDK Initialization 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:
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:
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.
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:
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:
The two retrieval modes trade latency against comprehensiveness: 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 for the full retrieval contract.

Agent-callable memory

For agent-style chains where the model decides when memory is relevant, expose SynapSearchTool and SynapStoreTool:
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:
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:
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 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:

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


Next steps

LangGraph

Cross-thread store, short-term context and run reporting for LangGraph state graphs.

Context Fetch

The retrieval API that powers SynapRetriever: fast vs accurate, scopes, and response shapes.

Ingestion

Direct ingestion API for custom pipelines that need finer control than the callback handler.

Memory Scopes

How user_id, customer_id, and conversation_id interact across retrievals.