# Memory

Code on this page is in Python. The same page in [TypeScript](https://docs.laserdata.com/md/typescript/laser-sdk/memory.md), [Rust](https://docs.laserdata.com/md/rust/laser-sdk/memory.md), or with every language at https://docs.laserdata.com/md/laser-sdk/memory.md.

The complete programs on this page are plain text, one language each, at [https://docs.laserdata.com/md/python/laser-sdk/memory.md](https://docs.laserdata.com/md/python/laser-sdk/memory.md), [https://docs.laserdata.com/md/typescript/laser-sdk/memory.md](https://docs.laserdata.com/md/typescript/laser-sdk/memory.md), and [https://docs.laserdata.com/md/rust/laser-sdk/memory.md](https://docs.laserdata.com/md/rust/laser-sdk/memory.md).

Memory stores facts your agents learn, such as a user's preferences or the fix that closed an incident. Any agent that opens the same namespace can recall them. Every change is a record on the log, so you can see who wrote a fact, when, and from which message.

## Correct a fact in a later conversation

This program keeps long-term memory for one user. In a first conversation the user shares three facts. In a second conversation the user moves, and `supersede` replaces the old city with the new one. A recall for the user across every conversation then returns the current facts only, and the program prints them as JSON. It runs on a scratch stream with a unique name and deletes that stream at the end, so it leaves nothing to clean up.

The program connects with `LASER_CONNECTION_STRING`. With that variable set, it needs no Docker and no local server. `echo "${LASER_CONNECTION_STRING:+configured}"` prints `configured` when the variable is set and a blank line when it is not. Without it, the [resolve block](#run-it-with-an-api-key) below connects with a LaserData API key.

The complete Python memory program, saved as `main.py`.

```python
# python -m pip install laser-sdk
# Needs only LASER_CONNECTION_STRING, which connect_env() reads. No server to start when it is set.
import asyncio
import json

import laser_sdk as ls

USER = "user-42"
QUERY = "Where does the user live, and what should I know before booking dinner?"


async def main():
    async with await ls.Laser.connect_env() as root:
        async with root.scratch_stream("memory") as scratch:
            memory = scratch.laser.memory("assistant")

            # Conversation 1: the user shares three facts.
            first = ls.new_conversation_id()
            city = await memory.remember("Lives in Gdansk", conversation=first, user=USER)
            await memory.remember("Allergic to peanuts", conversation=first, user=USER)
            await memory.remember("Prefers a window seat", conversation=first, user=USER)

            # Conversation 2: the user moved. supersede stores the new fact and forgets the old one.
            second = ls.new_conversation_id()
            await memory.supersede(city, "Lives in Lisbon", conversation=second, user=USER)

            # Recall for the user across every conversation.
            facts = await memory.recall(user=USER, semantic=QUERY, limit=10)
            print(
                json.dumps(
                    {"user": USER, "query": QUERY, "facts": [fact.text() for fact in facts]},
                    indent=2,
                )
            )


asyncio.run(main())
```

The program prints the three current facts, and `Lives in Gdansk` is gone. No fact shares a word with this query, so they come back newest first:

```json
{
  "user": "user-42",
  "query": "Where does the user live, and what should I know before booking dinner?",
  "facts": ["Lives in Lisbon", "Prefers a window seat", "Allergic to peanuts"]
}
```

`supersede(old_id, fact)` stores the new fact under the scope you give it, then forgets the old ID in every conversation, so no later recall of that user returns it. It returns the new fact's ID. If it fails between the two writes, both facts remain, so no fact is lost. A recall that names the user and no conversation reads every conversation of that user. A recall right after a write on the same connection waits until the memory view shows that write, so it never returns the fact you just replaced. A `semantic` query on log memory ranks every fact of the scope by the share of the query's words it contains, newest first among equals, and returns up to `limit`. It drops nothing, so `Allergic to peanuts` comes back although it shares no word with the query.

In Python the scope is keyword arguments on the call: `await memory.remember(text, conversation=first, user="user-42")`, `await memory.supersede(city, text, conversation=second, user="user-42")`, and `await memory.recall(user="user-42", semantic=query, limit=10)`. A conversation ID comes from `ls.new_conversation_id()`, and any other string is refused. TypeScript and Rust build the same call as a chain that ends in `.send()` or `.fetch()`.

`laser.memory(namespace)` returns the handle at once, and each of its calls returns an awaitable. `remember` and `supersede` resolve to the new fact's ID, and `recall` to a list of `MemoryItem`, each with `text()` and `id` (TypeScript: `memoryItemText(item)` and `item.id`). In Python, `memory_topic(topic)` is the one memory factory that returns an awaitable, because it creates its topic first.

The memory topic `agent.memory` is created on the first write, so the program needs no `bootstrap`. The default recall reads the managed memory view of [Laser Stack](/laser-sdk/laser-stack) and LaserData Cloud. On plain Apache Iggy, which serves no view, the same recall reads the memory topic in your process, so the program runs there unchanged.

The scratch stream is deleted with every topic and record in it when its scope ends. To keep the facts, open a named stream with `with_default_stream("support")` (TypeScript: `withDefaultStream`) instead. To delete a stream yourself, call `laser.stream(name).delete()`.

## Run it with an API key

With a LaserData API key in `LD_API_KEY` instead of a connection string, add this block to the program. It turns the key into the connection string in three calls: the key's organization from `/tenants`, the deployments the key can read from `/tenants/{tenant_id}/deployments`, and the login from the deployment's `/credentials`. Set `LD_DEPLOYMENT` to the deployment's name or ID when the key sees more than one deployment. The block then exits and lists the ones it sees. The key's role needs `deployment:read` and `deployment:credentials:read` on the deployment's environment. The block keeps the connection string in memory and never prints it.

```python
# Paste after the imports. It sets LASER_CONNECTION_STRING from LD_API_KEY when it is not set.
import json
import os
import urllib.request

API_URL = os.environ.get("LD_API_URL", "https://api.laserdata.cloud")


def laserdata(url):
    # The API's edge protection refuses urllib's default User-Agent with 403 and error code 1010.
    headers = {"ld-api-key": os.environ["LD_API_KEY"], "user-agent": "laserdata-docs-example"}
    with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=30) as response:
        return json.load(response)


def connection_string():
    tenant_id = laserdata(f"{API_URL}/tenants")[0]["id"]
    deployments, page, total_pages = [], 1, 1
    while page <= total_pages:
        reply = laserdata(f"{API_URL}/tenants/{tenant_id}/deployments?results=100&page={page}")
        deployments += reply["items"]
        page, total_pages = page + 1, reply["total_pages"]
    wanted = os.environ.get("LD_DEPLOYMENT")
    matches = [deployment for deployment in deployments if not wanted or wanted in (deployment["name"], str(deployment["id"]))]
    if len(matches) != 1:
        visible = ", ".join(f"{deployment['name']} ({deployment['id']})" for deployment in deployments)
        raise SystemExit(f"Set LD_DEPLOYMENT to the name or ID of one deployment. Visible: {visible or 'none'}")
    deployment = matches[0]
    if not deployment.get("supervisor_url"):
        raise SystemExit(f"Deployment {deployment['name']} has no supervisor_url yet")
    credentials = laserdata(f"{deployment['supervisor_url']}/deployments/{deployment['id']}/credentials")
    return credentials["connection_string"]


if not os.environ.get("LASER_CONNECTION_STRING"):
    os.environ["LASER_CONNECTION_STRING"] = connection_string()
```

The block calls nothing else: it never changes access rules and never needs `info:read`. A Free deployment admits every address, so the program connects at once. A paid deployment admits only the addresses its [access rules](/networking/access-rules) allow, and a connect from any other address times out naming `the Iggy server to accept the connection`. [Agent access](/agents#the-network-path) shows how to admit an address, and [When no deployment exists](/agents#when-no-deployment-exists) shows how to create one.

## Update a fact

A named item keeps one current value under a key. Write the key again to replace the value, for example a user's current plan. Every write stays on the memory topic, so the earlier value remains in the history. Any process that opens the same namespace reads the current value, after a restart too.

```python
memory = laser.memory("users")
await memory.set("ada/plan", json.dumps({"tier": "free"}))
await memory.set("ada/plan", json.dumps({"tier": "pro"}))

current = await memory.fetch_folded("ada/plan")
print(current.decode() if current is not None else "no value")
```

The code prints `{"tier":"pro"}`. `fetch_folded` (TypeScript: `fetchFolded`) reads and folds the memory log in your process, so it works on plain Apache Iggy. On Laser Stack and LaserData Cloud, `fetch` reads the managed view without folding the full history locally. The managed view can lag behind a new write while the backend processes it. `update(key, patch)` changes some fields of a JSON value, and `remove(key)` deletes the item. Keys select data but do not protect it. Anyone who can read the stream can read every key, so keep different customers in different deployments or streams with their own credentials. [Named items](/laser-sdk/advanced/memory#named-items) covers the details.

## Forget a fact

`remember` returns the new item's ID, and every recalled item carries its `id`. `forget(id)` writes a tombstone, so the item and any older copy of it stop appearing while the topic keeps the history. A forget that names a conversation removes the item from that conversation only, in every client, so name the conversation the item was remembered in, or no conversation to remove it everywhere. To replace a fact, use `supersede`, which does both writes in one call.

## Share facts across agents

Agents share memory by opening the same namespace on the same stream, in any of the three languages. Each item records the conversation, agent, user, and application it belongs to. Set them when you remember and narrow by them when you recall. A field you leave out widens the read, so a recall without a user returns every user's items. [Agents](/laser-sdk/fabric) shows `MemoryHandler`, which remembers every message an agent handles.

```python
await memory.remember(
    "Disk alerts on node-7 are noise",
    conversation=conversation,
    agent="triage",
)

notes = await memory.recall(conversation=conversation, agent="triage")
```

## Recall by meaning

The vector backend ranks items by how close they are to a question. You supply the embedding function, usually a call to an embedding model. Vector items live in process memory, so use this for working memory inside one agent.

```python
runbooks = laser.memory_with("runbooks", "vector", embedder=embed)
await runbooks.remember(
    "Gateway latency spikes mean the db pool is exhausted",
    conversation=conversation,
)

hits = await runbooks.recall(conversation=conversation, semantic="gateway is slow", limit=3)
```

## Trace a fact back to the log

Each item recalled from log memory carries `source`, the stream, topic, partition, and offset of the record it came from. Inside a [session](/laser-sdk/session), `linked_memory()` (TypeScript: `linkedMemory`) also stamps each new item with the record the session was handling and the agent that wrote it.

## Reweight a fact

`improve` adds a feedback weight that moves an item up or down in later recalls. Remembering a forgotten item again brings it back. For a value you look up by name, such as the current plan, use `set(key, body)` and `fetch(key)` instead of a recall.

## Good to know

* Default recall and `fetch` read the managed view on Laser Stack and LaserData Cloud. With Iggy alone, which serves no view, they fold the memory topic in your process, as `folded` recall and `fetch_folded` always do. Keep one handle for folded reads, because it reads only new records on each call.
* A default recall waits until the managed view shows the writes this connection made, for up to 10 seconds, then fails with a retryable timeout. Writes from another connection show once the view catches up in the background.
* After the managed backend on a node restarts, default recall and `fetch` on that node wait while its memory folds replay the topic. A fold that applies nothing for 30 seconds stops holding them, and recall then serves the view folded so far, which can miss newer items until the fold moves again. See [Reads after a restart](/laser-sdk/advanced/memory#reads-after-a-restart).
* On log memory, `semantic` and `hybrid` rank every item by the words it shares with the query plus its feedback weight. `keyword` is a filter that drops an item sharing no word. The vector backend ranks by meaning.
* Namespaces are scoped to the default stream, so `laser.memory("support")` addresses `stream:<stream>/support`. Without a default stream, memory calls fail with `NoStreamError`.
* In Rust, memory needs the `agent` feature, and reading the managed view also needs `kv`, which `managed` includes. Without `kv`, default recall and `fetch` fold the topic.

- [Memory in depth](/laser-sdk/advanced/memory): Recall modes, lineage, named items, context blocks, consolidation, and custom backends
- [Context](/laser-sdk/context): Memory and messages for one conversation
- [Graph](/laser-sdk/graph): Relationships between the things your agents know
- [Recall example](https://github.com/laserdata/laser-sdk/tree/main/examples/rust/src/recall): Runnable remember, recall, improve, and forget in Rust, Python, and TypeScript

Source: https://docs.laserdata.com/laser-sdk/memory
