Octopodas
    All Posts
    Tutorials·Dec 8, 2025·6 min read

    How to Give Your AI Agent Memory in 5 Minutes (With Code)

    Share
    How to Give Your AI Agent Memory in 5 Minutes (With Code)

    Every AI agent you've ever built has the same dirty secret. It forgets everything the moment the session ends. You spent an hour teaching it about your project, your preferences, your customers. Close the terminal. Open it again. Gone. Like the conversation never happened.

    I've watched developers waste weeks building hacky workarounds for this. Dumping conversations into text files. Stuffing JSON into system prompts until the context window explodes. Writing custom SQLite wrappers that break the moment two agents need to share data.

    There's a faster way. Five minutes. Real code. Let's go.

    The problem in 30 seconds

    Build an agent with LangChain. Have a great conversation. The agent learns your name, your project details, your preferences. Ask it to remember something important. Now restart the script. Ask it what your name is. It has no idea.

    This isn't a bug. It's how every agent framework works by default. LangChain, CrewAI, AutoGen, OpenAI Agents SDK. All of them. Session ends, state dies. The frameworks are built for reasoning and tool use. Nobody built the memory layer. So we did.

    Step 1: Install

    bash
    pip install octopoda langchain langchain-openai

    Get a free API key at octopodas.com/signup. Takes 30 seconds.

    Step 2: Connect memory

    python
    from octopoda import Octopoda
    import os
     
    memory = Octopoda(api_key=os.getenv("OCTOPODA_API_KEY"))
    agent = memory.agent("my-assistant")

    Two lines. Your agent now has a persistent brain.

    Step 3: Remember things

    python
    agent.write("user:name", "Alex, frontend developer at BrightPath")
    agent.write("user:preference", "Prefers React over Vue, concise answers")
    agent.write("project:current", "Building a dashboard with Next.js and Supabase")

    These memories persist forever. Restart your script, restart your computer, come back next week. They're still there.

    Step 4: Recall by meaning

    This is the part that changes everything. You don't need to remember exact keys:

    python
    results = agent.search("what framework does the user like")
    Semantic search
    That query doesn't match the exact words "Prefers React over Vue" but it finds it anyway because the meanings are related. Your agent can think "what do I know about this person's preferences?" and find the right information even if it was stored with completely different words.

    Step 5: Wire it into your agent

    Here's a complete LangChain agent with persistent memory:

    python
    from dotenv import load_dotenv
    load_dotenv()
     
    from langchain_openai import ChatOpenAI
    from langchain.agents import tool, AgentExecutor, create_react_agent
    from langchain.prompts import PromptTemplate
    from octopoda import Octopoda
    import os
     
    llm = ChatOpenAI(model="gpt-4", temperature=0)
    memory = Octopoda(api_key=os.getenv("OCTOPODA_API_KEY"))
    brain = memory.agent("my-assistant")
     
    @tool
    def remember(key_and_value: str) -> str:
    """Store information in long-term memory. Format: key|||value"""
    try:
    key, value = key_and_value.split("|||")
    brain.write(key.strip(), value.strip())
    return f"Remembered: {key.strip()}"
    except:
    return "Error: use format key|||value"
     
    @tool
    def search_memory(query: str) -> str:
    """Search memory by meaning to find relevant information."""
    try:
    results = brain.search(query, limit=3)
    if not results:
    return "Nothing relevant in memory."
    output = ""
    for r in results:
    output += f"{r.get('key', '?')}: {r.get('value', '')}\n"
    return output
    except:
    return "Memory search failed."
     
    tools = [remember, search_memory]
     
    prompt = PromptTemplate.from_template("""
    You are a helpful assistant with persistent memory.
    When the user shares important info, store it with the remember tool.
    Before answering personal questions, search your memory first.
     
    Tools: {tools}
    Tool names: {tool_names}
    Question: {input}
    {agent_scratchpad}
    """)
     
    agent = create_react_agent(llm, tools, prompt)
    executor = AgentExecutor(agent=agent, tools=tools, verbose=True, max_iterations=8)
     
    while True:
    user_input = input("You: ")
    if user_input.lower() in ["quit", "exit"]:
    break
    result = executor.invoke({"input": user_input})
    print(f"Agent: {result['output']}\n")

    Run it. Tell it your name. Tell it what you're working on. Close the terminal. Run it again. Ask it who you are. It remembers.

    What you get beyond basic memory

    Versioning
    Every change tracked with timestamps
    Shared Memory
    Multiple agents read/write the same space
    Conflict Detection
    Flags contradictions automatically

    Plus loop detection that catches when your agent gets stuck repeating the same pattern, and a real dashboard where you can browse every memory, see version history, check agent health, and read the full audit trail.

    Where this matters

    Memory sounds like a nice feature until you realise how many things break without it. A customer support agent that asks "what's your name?" for the fifteenth time. A research agent that searches for the same information every session. A personal assistant that doesn't know your schedule preferences despite you explaining them three times.

    Every one of those is a memory problem. Every one is fixed by those two lines of code at the top.

    Get started
    pip install octopoda. Give your agent a brain. Come back tomorrow and it'll still know who you are.

    Start monitoring your agents

    Persistent memory, loop detection, crash recovery and audit trails — open source, runs locally.

    pip install octopoda
    Octopoda featured on There's an AI for That