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

# LangChain Agent Memory Integration with sovseal

> Wrap sovseal-sdk's store/recall as native LangChain tools in Python, or extend BaseChatMemory in TypeScript, for zero-network local memory.

<style>
  {`
      main, article, .prose {
        margin-left: 2.5cm !important;
        margin-right: 2.5cm !important;
      }
      `}
</style>

Integrating sovseal with LangChain gives your agents persistent, local-first memory without changing your chain architecture. `store`/`recall` on `sovseal-sdk` (Python) and `@sovseal/sdk` (Node) talk to the local ONEBRAIN engine over framed IPC — 0 network round-trips, so recall latency stays under 10 ms. Wrap them as a LangChain tool in Python, or as a custom `BaseChatMemory` subclass in TypeScript.

<Tabs>
  <Tab title="Python">
    ## Install dependencies

    ```bash theme={null}
    pip install langchain langchain-openai sovseal-sdk python-dotenv
    ```

    ## Expose store/recall as LangChain tools

    The example below wraps `sovseal-sdk`'s `AgentStateClient.store()`/`.recall()` directly as two `@tool`-decorated functions and runs them inside an OpenAI functions agent. No MCP server or third-party client wrapper is needed — the SDK talks to the local native host itself.

    ```python agent.py theme={null}
    import os
    import asyncio
    from dotenv import load_dotenv
    from langchain_openai import ChatOpenAI
    from langchain.agents import create_openai_functions_agent, AgentExecutor
    from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
    from langchain_core.tools import tool
    from sovseal import AgentStateClient, EngineUnavailableError

    load_dotenv()

    client = AgentStateClient()  # store/recall need no endpoint/api_key


    @tool
    def recall_memory(query: str) -> str:
        """Search stored user preferences and past decisions relevant to a query."""
        try:
            hits = client.recall(query, top_k=3)
        except EngineUnavailableError as e:
            return f"Memory engine unavailable ({e.reason}) — proceeding without recall."
        if not hits:
            return "No relevant memories found."
        return "\n".join(f"- {h['text']}" for h in hits)


    @tool
    def store_memory(content: str) -> str:
        """Store a declarative fact or preference about the user for future sessions."""
        try:
            result = client.store(content)
        except EngineUnavailableError as e:
            return f"Memory engine unavailable ({e.reason}) — not stored."
        return "stored (reinforced)" if result["reinforced"] else "stored (new)"


    async def main():
        tools = [recall_memory, store_memory]
        llm = ChatOpenAI(model="gpt-4o", temperature=0)

        prompt = ChatPromptTemplate.from_messages([
            (
                "system",
                "You are a personalized assistant. Use the recall_memory tool "
                "first to gather user preferences before answering.",
            ),
            MessagesPlaceholder(variable_name="chat_history"),
            ("human", "{input}"),
            MessagesPlaceholder(variable_name="agent_scratchpad"),
        ])

        agent = create_openai_functions_agent(llm, tools, prompt)
        agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

        # Store a preference
        await agent_executor.ainvoke({
            "input": "My favorite programming language is TypeScript. Remember that.",
            "chat_history": [],
        })

        # Recall it in a separate invocation
        response = await agent_executor.ainvoke({
            "input": "What programming language do I prefer?",
            "chat_history": [],
        })
        print("Agent Response:", response["output"])

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

    <Note>
      `store`/`recall` require the native host launcher at `~/.sovseal/native-host/run.sh`. Run `npx -y @sovseal/mcp-server` once to provision it — see [SDK Reference: Overview](/sdk-reference/overview).
    </Note>
  </Tab>

  <Tab title="TypeScript">
    ## Install dependencies

    ```bash theme={null}
    npm install langchain @sovseal/sdk @langchain/openai
    ```

    ## Implement a custom memory class

    Extend `BaseChatMemory` to call `store`/`recall` on `AgentStateClient`. `loadMemoryVariables` recalls relevant prior exchanges; `saveContext` stores the new one:

    ```typescript memory.ts theme={null}
    import {
      BaseChatMemory,
      type InputValues,
      type OutputValues,
    } from "langchain/memory";
    import { AgentStateClient, EngineUnavailableError } from "@sovseal/sdk";

    export class SovsealMemory extends BaseChatMemory {
      private client: AgentStateClient;

      constructor() {
        super();
        this.client = new AgentStateClient(); // store/recall need no endpoint/apiKey
      }

      get memoryKeys() {
        return ["history"];
      }

      async loadMemoryVariables(
        values: InputValues
      ): Promise<Record<string, unknown>> {
        try {
          const hits = await this.client.recall(String(values.input ?? ""), { topK: 3 });
          return { history: hits.map((h) => h.text).join("\n") };
        } catch (err) {
          if (err instanceof EngineUnavailableError) {
            return { history: "" }; // fail open — engine not installed/running
          }
          throw err;
        }
      }

      async saveContext(
        inputValues: InputValues,
        outputValues: OutputValues
      ): Promise<void> {
        const text = `User: ${inputValues.input}\nAssistant: ${outputValues.output}`;
        try {
          await this.client.store(text);
        } catch (err) {
          if (!(err instanceof EngineUnavailableError)) throw err;
        }
      }
    }
    ```

    Pass a `SovsealMemory` instance to any LangChain chain that accepts a `memory` parameter:

    ```typescript chain.ts theme={null}
    import { ConversationChain } from "langchain/chains";
    import { ChatOpenAI } from "@langchain/openai";
    import { SovsealMemory } from "./memory";

    const memory = new SovsealMemory();

    const chain = new ConversationChain({
      llm: new ChatOpenAI({ model: "gpt-4o" }),
      memory,
    });

    const res = await chain.call({ input: "I prefer dark mode interfaces." });
    console.log(res.response);
    ```

    <Note>
      `store`/`recall` require the native host launcher at `~/.sovseal/native-host/run.sh`. Run `npx -y @sovseal/mcp-server` once to provision it — see [SDK Reference: Overview](/sdk-reference/overview). If you need full encrypted state checkpointing (audit lineage, point-in-time rollback) rather than semantic recall, use `client.snapshot()`/`client.restore()` instead — see the [Node SDK reference](/sdk-reference/node-sdk).
    </Note>
  </Tab>
</Tabs>
