Memory
Long-term agent memory: remember facts about a user, supersede a fact that changed in a later conversation, recall the current facts from any agent, and trace each one back to the log
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/typescript/laser-sdk/memory.md, https://docs.laserdata.com/md/rust/laser-sdk/memory.md, and https://docs.laserdata.com/md/go/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 below connects with a LaserData API key.
The complete TypeScript memory program, saved as main.mts.
// npm install @laserdata/laser-sdk tsx
// Run with: npx tsx main.mts
// Needs only LASER_CONNECTION_STRING, which connectEnv() reads. No server to start when it is set.
import { ConversationId, Laser, memoryItemText } from "@laserdata/laser-sdk"
const user = "user-42"
const query = "Where does the user live, and what should I know before booking dinner?"
await using root = await Laser.connectEnv()
await using scratch = await root.scratchStream("memory")
const memory = scratch.laser.memory("assistant")
// Conversation 1: the user shares three facts.
const first = ConversationId.new()
const city = await memory.remember("Lives in Gdansk").scope(first).user(user).send()
await memory.remember("Allergic to peanuts").scope(first).user(user).send()
await memory.remember("Prefers a window seat").scope(first).user(user).send()
// Conversation 2: the user moved. supersede stores the new fact and forgets the old one.
const second = ConversationId.new()
await memory.supersede(city, "Lives in Lisbon").scope(second).user(user).send()
// Recall for the user across every conversation.
const facts = await memory.recall().user(user).semantic(query).limit(10).fetch()
console.log(JSON.stringify({ user, query, facts: facts.map(memoryItemText) }, null, 2))The complete Rust memory program, saved as src/main.rs. Memory is in the agent feature, and kv makes recall read the managed memory view as the TypeScript and Python clients do. Both are default features.
// cargo add laser-sdk
// cargo add tokio --features macros,rt-multi-thread
// cargo add serde --features derive
// cargo add serde_json
// Needs only LASER_CONNECTION_STRING, which connect_env() reads. No server to start when it is set.
use laser_sdk::prelude::*;
use serde::Serialize;
const USER: &str = "user-42";
const QUERY: &str = "Where does the user live, and what should I know before booking dinner?";
#[derive(Serialize)]
struct Recall {
user: &'static str,
query: &'static str,
facts: Vec<String>,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let root = Laser::connect_env().await?;
let scratch = root.scratch_stream("memory").await?;
let result = correct_and_recall(scratch.laser()).await;
scratch.delete().await?;
println!("{}", serde_json::to_string_pretty(&result?)?);
Ok(())
}
async fn correct_and_recall(laser: &Laser) -> Result<Recall, LaserError> {
let memory = laser.memory("assistant");
// Conversation 1: the user shares three facts.
let first = ConversationId::new();
let city = memory
.remember("Lives in Gdansk")
.scope(first)
.user(USER)
.send()
.await?;
memory
.remember("Allergic to peanuts")
.scope(first)
.user(USER)
.send()
.await?;
memory
.remember("Prefers a window seat")
.scope(first)
.user(USER)
.send()
.await?;
// Conversation 2: the user moved. supersede stores the new fact and forgets the old one.
let second = ConversationId::new();
memory
.supersede(city, "Lives in Lisbon")
.scope(second)
.user(USER)
.send()
.await?;
// Recall for the user across every conversation.
let facts = memory
.recall(None)
.user(USER)
.semantic(QUERY)
.limit(10)
.fetch()
.await?;
Ok(Recall {
user: USER,
query: QUERY,
facts: facts.iter().map(MemoryItem::text).collect(),
})
}The complete Python memory program, saved as main.py.
# 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 complete Go memory program, saved as main.go.
// go get github.com/laserdata/laser-sdk/foreign/go/laser@latest
// Needs only LASER_CONNECTION_STRING, which ConnectEnv reads. No server to start when it is set.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"time"
"github.com/laserdata/laser-sdk/foreign/go/laser"
)
const (
user = "user-42"
query = "Where does the user live, and what should I know before booking dinner?"
)
type recall struct {
User string `json:"user"`
Query string `json:"query"`
Facts []string `json:"facts"`
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
if err := run(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(ctx context.Context) (err error) {
root, err := laser.ConnectEnv(ctx)
if err != nil {
return err
}
defer func() { err = errors.Join(err, root.Close()) }()
scratch, err := root.ScratchStream(ctx, "memory")
if err != nil {
return err
}
result, err := correctAndRecall(ctx, scratch.Laser())
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
if err = errors.Join(err, scratch.Delete(cleanup)); err != nil {
return err
}
printed, err := json.MarshalIndent(result, "", " ")
if err != nil {
return err
}
fmt.Println(string(printed))
return nil
}
func correctAndRecall(ctx context.Context, client *laser.Laser) (recall, error) {
memory := client.Memory("assistant")
// Conversation 1: the user shares three facts.
first := laser.NewConversationID()
shared := memory.For(laser.MemoryScope{User: user, Conversation: &first})
city, err := shared.Remember(ctx, laser.MemoryFact, []byte("Lives in Gdansk"))
if err != nil {
return recall{}, err
}
for _, fact := range []string{"Allergic to peanuts", "Prefers a window seat"} {
if _, err := shared.Remember(ctx, laser.MemoryFact, []byte(fact)); err != nil {
return recall{}, err
}
}
// Conversation 2: the user moved. Supersede stores the new fact and forgets the old one.
second := laser.NewConversationID()
moved := memory.For(laser.MemoryScope{User: user, Conversation: &second})
if _, err := moved.Supersede(ctx, city, laser.MemoryFact, []byte("Lives in Lisbon")); err != nil {
return recall{}, err
}
// Recall for the user across every conversation.
items, err := memory.For(laser.MemoryScope{User: user}).
Recall(ctx, laser.MemoryQuery{Query: query, Strategy: laser.RecallSemantic, Limit: 10})
if err != nil {
return recall{}, err
}
facts := make([]string, 0, len(items))
for _, item := range items {
facts = append(facts, item.Text())
}
return recall{User: user, Query: query, Facts: facts}, nil
}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:
{
"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 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.
// Paste after the imports. It sets LASER_CONNECTION_STRING from LD_API_KEY when it is not set.
const API_URL = process.env.LD_API_URL ?? "https://api.laserdata.cloud"
async function laserdata(url: string): Promise<any> {
const headers = { "ld-api-key": process.env.LD_API_KEY ?? "", "user-agent": "laserdata-docs-example" }
const response = await fetch(url, { headers })
if (!response.ok) throw new Error(`GET ${url} answered ${response.status}: ${await response.text()}`)
// IDs are 64-bit integers, so keep each number JavaScript cannot hold exactly as its source text.
return JSON.parse(await response.text(), (_key, value, context?: { source?: string }) =>
typeof value === "number" && !Number.isSafeInteger(value) ? context?.source : value
)
}
async function connectionString(): Promise<string> {
const [tenant] = await laserdata(`${API_URL}/tenants`)
const deployments: any[] = []
for (let page = 1, totalPages = 1; page <= totalPages; page++) {
const reply = await laserdata(`${API_URL}/tenants/${tenant.id}/deployments?results=100&page=${page}`)
deployments.push(...reply.items)
totalPages = reply.total_pages
}
const wanted = process.env.LD_DEPLOYMENT
const matches = deployments.filter(
(deployment) => !wanted || deployment.name === wanted || String(deployment.id) === wanted
)
if (matches.length !== 1) {
const visible = deployments.map((deployment) => `${deployment.name} (${deployment.id})`).join(", ")
console.error(`Set LD_DEPLOYMENT to the name or ID of one deployment. Visible: ${visible || "none"}`)
process.exit(1)
}
const [deployment] = matches
if (!deployment.supervisor_url) throw new Error(`Deployment ${deployment.name} has no supervisor_url yet`)
const credentials = await laserdata(`${deployment.supervisor_url}/deployments/${deployment.id}/credentials`)
return credentials.connection_string
}
process.env.LASER_CONNECTION_STRING ||= await connectionString()// cargo add reqwest --features json
// cargo add serde_json
// Add these two functions, then connect with Laser::connect(&connection_string().await?) in main.
use serde_json::Value;
async fn laserdata(client: &reqwest::Client, url: &str) -> Result<Value, Box<dyn std::error::Error>> {
let key = std::env::var("LD_API_KEY")?;
let response = client.get(url).header("ld-api-key", key).header("user-agent", "laserdata-docs-example").send().await?;
let status = response.status();
if !status.is_success() {
return Err(format!("GET {url} answered {status}: {}", response.text().await?).into());
}
Ok(response.json().await?)
}
async fn connection_string() -> Result<String, Box<dyn std::error::Error>> {
if let Ok(value) = std::env::var("LASER_CONNECTION_STRING") {
return Ok(value);
}
let api_url = std::env::var("LD_API_URL").unwrap_or_else(|_| "https://api.laserdata.cloud".to_owned());
let client = reqwest::Client::new();
let tenants = laserdata(&client, &format!("{api_url}/tenants")).await?;
let mut deployments = Vec::new();
for page in 1_u64.. {
let url = format!("{api_url}/tenants/{}/deployments?results=100&page={page}", tenants[0]["id"]);
let reply = laserdata(&client, &url).await?;
deployments.extend(reply["items"].as_array().cloned().unwrap_or_default());
if page >= reply["total_pages"].as_u64().unwrap_or(0) {
break;
}
}
let wanted = std::env::var("LD_DEPLOYMENT").ok();
let matches: Vec<&Value> = deployments
.iter()
.filter(|deployment| wanted.as_deref().is_none_or(|wanted| deployment["name"] == wanted || deployment["id"].to_string() == wanted))
.collect();
let [deployment] = matches.as_slice() else {
let visible: Vec<String> = deployments.iter().map(|deployment| format!("{} ({})", deployment["name"].as_str().unwrap_or_default(), deployment["id"])).collect();
eprintln!("Set LD_DEPLOYMENT to the name or ID of one deployment. Visible: {}", visible.join(", "));
std::process::exit(1);
};
let supervisor_url = deployment["supervisor_url"].as_str().ok_or("The deployment has no supervisor_url yet")?;
let credentials = laserdata(&client, &format!("{supervisor_url}/deployments/{}/credentials", deployment["id"])).await?;
Ok(credentials["connection_string"].as_str().ok_or("The credentials answer has no connection_string")?.to_owned())
}# 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()// Add these functions and the imports they use, then call resolveConnection(ctx) as the first line of run.
// It sets LASER_CONNECTION_STRING from LD_API_KEY when it is not set.
// Imports: context, encoding/json, fmt, io, net/http, os, strings.
type deployment struct {
ID json.Number `json:"id"`
Name string `json:"name"`
SupervisorURL string `json:"supervisor_url"`
}
func laserdata(ctx context.Context, url string, into any) error {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
request.Header.Set("ld-api-key", os.Getenv("LD_API_KEY"))
request.Header.Set("user-agent", "laserdata-docs-example")
response, err := http.DefaultClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
body, _ := io.ReadAll(response.Body)
return fmt.Errorf("GET %s answered %d: %s", url, response.StatusCode, body)
}
return json.NewDecoder(response.Body).Decode(into)
}
func connectionString(ctx context.Context) (string, error) {
apiURL := os.Getenv("LD_API_URL")
if apiURL == "" {
apiURL = "https://api.laserdata.cloud"
}
var tenants []struct {
ID json.Number `json:"id"`
}
if err := laserdata(ctx, apiURL+"/tenants", &tenants); err != nil {
return "", err
}
if len(tenants) == 0 {
return "", fmt.Errorf("the API key reads no organization")
}
var deployments []deployment
for page, totalPages := 1, 1; page <= totalPages; page++ {
var reply struct {
Items []deployment `json:"items"`
TotalPages int `json:"total_pages"`
}
url := fmt.Sprintf("%s/tenants/%s/deployments?results=100&page=%d", apiURL, tenants[0].ID, page)
if err := laserdata(ctx, url, &reply); err != nil {
return "", err
}
deployments = append(deployments, reply.Items...)
totalPages = reply.TotalPages
}
wanted := os.Getenv("LD_DEPLOYMENT")
var matches []deployment
var visible []string
for _, candidate := range deployments {
visible = append(visible, fmt.Sprintf("%s (%s)", candidate.Name, candidate.ID))
if wanted == "" || wanted == candidate.Name || wanted == candidate.ID.String() {
matches = append(matches, candidate)
}
}
if len(matches) != 1 {
if len(visible) == 0 {
visible = []string{"none"}
}
fmt.Fprintf(os.Stderr, "Set LD_DEPLOYMENT to the name or ID of one deployment. Visible: %s\n", strings.Join(visible, ", "))
os.Exit(1)
}
chosen := matches[0]
if chosen.SupervisorURL == "" {
return "", fmt.Errorf("deployment %s has no supervisor_url yet", chosen.Name)
}
var credentials struct {
ConnectionString string `json:"connection_string"`
}
url := fmt.Sprintf("%s/deployments/%s/credentials", chosen.SupervisorURL, chosen.ID)
if err := laserdata(ctx, url, &credentials); err != nil {
return "", err
}
return credentials.ConnectionString, nil
}
func resolveConnection(ctx context.Context) error {
if os.Getenv("LASER_CONNECTION_STRING") != "" {
return nil
}
value, err := connectionString(ctx)
if err != nil {
return err
}
return os.Setenv("LASER_CONNECTION_STRING", value)
}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 allow, and a connect from any other address times out naming the Iggy server to accept the connection. Agent access shows how to admit an address, and 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.
const memory = laser.memory("users")
await memory.set("ada/plan", JSON.stringify({ tier: "free" }))
await memory.set("ada/plan", JSON.stringify({ tier: "pro" }))
const current = await memory.fetchFolded("ada/plan")
console.log(current ? new TextDecoder().decode(current) : "no value")let memory = laser.memory("users");
memory.set("ada/plan", br#"{"tier":"free"}"#.to_vec()).await?;
memory.set("ada/plan", br#"{"tier":"pro"}"#.to_vec()).await?;
match memory.fetch_folded("ada/plan").await? {
Some(current) => println!("{}", String::from_utf8_lossy(¤t)),
None => println!("no value"),
}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")memory := client.Memory("users")
if err := memory.Set(ctx, "ada/plan", []byte(`{"tier":"free"}`)); err != nil {
return err
}
if err := memory.Set(ctx, "ada/plan", []byte(`{"tier":"pro"}`)); err != nil {
return err
}
current, found, err := memory.FetchFolded(ctx, "ada/plan")
if err != nil {
return err
}
if found {
fmt.Println(string(current))
} else {
fmt.Println("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 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 four 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 shows MemoryHandler, which remembers every message an agent handles.
import { AgentId } from "@laserdata/laser-sdk"
const triage = AgentId.new("triage")
await memory.remember("Disk alerts on node-7 are noise").scope(conversation).agent(triage).send()
const notes = await memory.recall(conversation).agent(triage).fetch()let triage: AgentId = "triage".parse()?;
memory
.remember("Disk alerts on node-7 are noise")
.scope(conversation)
.agent(triage.clone())
.send()
.await?;
let notes = memory.recall(conversation).agent(triage).fetch().await?;await memory.remember(
"Disk alerts on node-7 are noise",
conversation=conversation,
agent="triage",
)
notes = await memory.recall(conversation=conversation, agent="triage")scoped := memory.For(laser.MemoryScope{Agent: &triage, Conversation: &conversation})
if _, err := scoped.Remember(ctx, laser.MemoryFact, []byte("Disk alerts on node-7 are noise")); err != nil {
return err
}
notes, err := scoped.Recall(ctx, laser.MemoryQuery{})
if err != nil {
return err
}
fmt.Println(len(notes), "notes")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.
import { MemoryBackend } from "@laserdata/laser-sdk"
const runbooks = laser.memoryWith("runbooks", MemoryBackend.Vector, embedder)
await runbooks.remember("Gateway latency spikes mean the db pool is exhausted").scope(conversation).send()
const hits = await runbooks.recall(conversation).semantic("gateway is slow").limit(3).fetch()let runbooks = laser.memory_with("runbooks", MemoryBackend::Vector).embedder(embedder);
runbooks
.remember("Gateway latency spikes mean the db pool is exhausted")
.scope(conversation)
.send()
.await?;
let hits = runbooks.recall(conversation).semantic("gateway is slow").limit(3).fetch().await?;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)vector, err := client.MemoryWith("runbooks", laser.MemoryBackendVector)
if err != nil {
return err
}
runbooks := vector.Embedder(embedder).For(laser.MemoryScope{Conversation: &conversation})
fact := []byte("Gateway latency spikes mean the db pool is exhausted")
if _, err := runbooks.Remember(ctx, laser.MemoryFact, fact); err != nil {
return err
}
hits, err := runbooks.Recall(ctx, laser.MemoryQuery{Strategy: laser.RecallSemantic, Query: "gateway is slow", Limit: 3})
if err != nil {
return err
}
for _, hit := range hits {
fmt.Println(hit.Text())
}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, 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
fetchread the managed view on Laser Stack and LaserData Cloud. With Iggy alone, which serves no view, they fold the memory topic in your process, asfoldedrecall andfetch_foldedalways 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
fetchon 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. - On log memory,
semanticandhybridrank every item by the words it shares with the query plus its feedback weight.keywordis 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")addressesstream:<stream>/support. Without a default stream, memory calls fail withNoStreamError. - In Rust, memory needs the
agentfeature, and reading the managed view also needskv, whichmanagedincludes. Withoutkv, default recall andfetchfold the topic.