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
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=falsein the environment, or callset_auto_listen(sdk, False)fromsynap_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
ainvoketo get them on the stream.
Setup
Install the package alongside LangChain and your model provider. It installsmaximem-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..env
Basic integration
The smallest useful integration is a chain with automatic memory viaSynapCallbackHandler. Every turn is ingested without changing your chain logic:
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:
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.
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.
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:
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:
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, exposeSynapSearchTool and SynapStoreTool:
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:SynapHistoryMiddlewaredecides 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.SynapCallbackHandlerwrites the turns and the tool activity back to Synap, so the middleware has something to read and anticipation has something to act on.SynapSearchToolandSynapStoreToolcover deliberate lookups and writes, which the other two do not.
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:SynapCallbackHandlerto record turns, tool calls and tool resultsSynapHistoryMiddlewareto read Synap’s compaction back (orsynap_st_messagefor a hand-built prompt)SynapRetrieverfor RAG over the user’s memoriesSynapSearchToolexposed to the model for explicit lookups when retrieval misses
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:
SynapCallbackHandlerlogs the failure and your chain continues. If the stream will not open, turns go over REST. - History reads degrade gracefully:
SynapChatMessageHistoryreturns an empty list and logs an error;SynapHistoryMiddlewareleaves the agent’s messages untouched. - Explicit calls surface failures:
SynapRetriever,SynapSearchToolandSynapStoreToolraiseSynapIntegrationError, and so doesSynapChatMessageHistorywhen it cannot write a turn.
Going further
- Patterns overview: reusable memory patterns across frameworks.
- Cookbook overview: end-to-end worked examples.
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.