> ## Documentation Index
> Fetch the complete documentation index at: https://metacognition-fdc534de-master.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# LangChain agents with memory

> Add Tex memory to LangChain by injecting recall before the chain or exposing recall as a tool.

There are two common ways to use Tex with LangChain.

Most chat apps should recall memory before the chain runs. Agents that choose their own steps can receive Tex as tools.

| Pattern    | When to use                                     |
| ---------- | ----------------------------------------------- |
| **Inject** | Your code recalls once per user message.        |
| **Tools**  | The model decides when to read or write memory. |

## Inject (default)

<Steps>
  <Step title="Install dependencies">
    ```bash theme={null}
    pip install tex-sdk langchain langchain-openai
    ```
  </Step>

  <Step title="Construct Tex once">
    ```python theme={null}
    import os
    from tex import Tex

    tex = Tex(
        api_key=os.environ["TEX_API_KEY"],
        base_url=os.environ["TEX_BASE_URL"],
    )
    ```
  </Step>

  <Step title="Recall → prompt → LLM → remember">
    ```python theme={null}
    from datetime import datetime, timezone
    from langchain.prompts import ChatPromptTemplate
    from langchain_openai import ChatOpenAI

    def now_iso() -> str:
        return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")

    def answer_turn(user_msg: str, session_id: str) -> str:
        hits = tex.recall(q=user_msg, session_id=session_id, top_k=5)
        memory = "\n".join(f"- {h.text}" for h in hits.hits.turns)

        prompt = ChatPromptTemplate.from_messages([
            ("system", "Relevant memory about the user:\n{memory}"),
            ("user", "{input}"),
        ])
        chain = prompt | ChatOpenAI(model="gpt-4o")

        reply = chain.invoke({"memory": memory, "input": user_msg}).content

        tex.conversations.remember(
            session_id=session_id,
            turns=[
                {"role": "user", "text": user_msg, "timestamp": now_iso()},
                {"role": "assistant", "text": reply, "timestamp": now_iso()},
            ],
        )
        return reply
    ```
  </Step>
</Steps>

## Tools

<Steps>
  <Step title="Define tools with `@tool`">
    ```python theme={null}
    import os
    from datetime import datetime, timezone
    from tex import Tex
    from langchain.tools import tool
    from langchain.agents import create_react_agent, AgentExecutor
    from langchain_openai import ChatOpenAI

    tex = Tex(api_key=os.environ["TEX_API_KEY"], base_url=os.environ["TEX_BASE_URL"])
    SESSION = "agent-1"

    def now_iso() -> str:
        return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")

    @tool
    def recall_memory(query: str) -> str:
        """Look up long-term memory; returns bullet list of statements."""
        hits = tex.recall(q=query, session_id=SESSION, top_k=5)
        if not hits.hits.turns:
            return "(no relevant memory)"
        return "\n".join(f"- {h.text}" for h in hits.hits.turns)

    @tool
    def remember_fact(text: str) -> str:
        """Persist a fact for later recall."""
        tex.conversations.remember(
            session_id=SESSION,
            turns=[{"role": "system", "text": text, "timestamp": now_iso()}],
        )
        return "remembered"
    ```
  </Step>

  <Step title="Pass tools into your agent">
    ```python theme={null}
    agent = create_react_agent(
        ChatOpenAI(model="gpt-4o"),
        tools=[recall_memory, remember_fact],
        prompt="...",  # you supply
    )

    executor = AgentExecutor(agent=agent, tools=[recall_memory, remember_fact])
    ```
  </Step>
</Steps>

<Tip>
  Add other LangChain tools to the same `tools=[...]` list. The Tex tools behave like normal tools.
</Tip>

## Compared to `BaseChatMemory`

LangChain buffers keep history in process. Tex stores memory outside the process and returns the top matches for the current question. That keeps prompts smaller and survives deploys.

<CodeGroup>
  ```python Before theme={null}
  from langchain.chains import ConversationChain
  from langchain.memory import ConversationBufferMemory

  memory = ConversationBufferMemory()
  chain = ConversationChain(llm=llm, memory=memory)
  ```

  ```python After theme={null}
  hits = tex.recall(q=user_msg, session_id=sid, top_k=5)
  prompt = stitch(hits.hits.turns, user_msg)
  answer = llm.invoke(prompt)
  tex.conversations.remember(session_id=sid, turns=[...])  # use your normal turn format
  ```
</CodeGroup>

For the migration details, continue to [Migrating from LangChain memory](/migration/from-langchain-memory).
