LaserData Cloud
Laser SDK

Laser SDK

Complete workflow and memory programs to copy, then agents, sessions, state, and messages on one log, in TypeScript, Rust, Python, and Go

View as Markdownllms.txt

Download the complete programs for https://docs.laserdata.com/laser-sdk/typescript.txt, https://docs.laserdata.com/laser-sdk/rust.txt, https://docs.laserdata.com/laser-sdk/python.txt, https://docs.laserdata.com/laser-sdk/go.txt.

Laser SDK gives agents and services durable workflows, long-term memory, sessions, and messaging on one log, in TypeScript, Rust, Python, and Go. The workflow and memory programs below are complete and need no edits once the package is installed, because they connect with LASER_CONNECTION_STRING. Each prints JSON. LaserData publishes it under Apache-2.0 on PyPI as laser-sdk (https://pypi.org/project/laser-sdk/), on npm as @laserdata/laser-sdk, and on crates.io as laser-sdk, with the source at https://github.com/laserdata/laser-sdk. Install the Python package with python -m pip install laser-sdk.

Durable workflow with @ls.workflow and @ls.step decorators

A durable workflow is a function whose steps are recorded: Python decorates functions with @ls.step and @ls.workflow, TypeScript wraps them with step() and workflow(), and Rust passes closures to run_with.

The complete TypeScript workflow program, saved as main.mts: three steps, the workflow function, and one line that prints the outcome.

// npm install @laserdata/laser-sdk tsx
// Run with: npx tsx main.mts
// Needs only LASER_CONNECTION_STRING. No server to start when it is set.
import { setTimeout as sleep } from "node:timers/promises"
import { step, workflow } from "@laserdata/laser-sdk"

const ingest = step("ingest", () => "frames from sat-7")
const analyze = step("analyze", async (frames: string) => {
  await sleep(1000)
  return `analyzed ${frames}`
})
const report = step("report", (analysis: string) => `report on ${analysis}`)

const pipeline = workflow("pipeline", async () => report(await analyze(await ingest())))

const run = await pipeline.run()
console.log(JSON.stringify({ status: run.status, steps: run.completedSteps, report: run.value }))

The complete Rust workflow program, saved as src/main.rs: three steps inside run_with and one line that prints the outcome.

// cargo add laser-sdk
// cargo add tokio --features macros,rt-multi-thread,time
// 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 std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), LaserError> {
    let laser = Laser::connect_env().await?;
    let run = laser
        .workflow("pipeline")
        .run_with(async |run| {
            let frames: String = run
                .step("ingest", async || Ok("frames from sat-7".to_owned()))
                .await?;
            let analysis: String = run
                .step("analyze", async || {
                    tokio::time::sleep(Duration::from_secs(1)).await;
                    Ok(format!("analyzed {frames}"))
                })
                .await?;
            run.step("report", async || Ok(format!("report on {analysis}")))
                .await
        })
        .await?;
    let report = serde_json::json!({
        "status": run.status,
        "steps": run.completed_steps,
        "report": run.json::<String>("report")?,
    });
    println!("{report}");
    laser.close().await
}

The complete Python workflow program, saved as main.py: three steps, the workflow function, and one line that prints the outcome.

# python -m pip install laser-sdk
# Needs only LASER_CONNECTION_STRING. No server to start when it is set.
import json
import time

import laser_sdk as ls


@ls.step
def ingest():
    return "frames from sat-7"


@ls.step
def analyze(frames):
    time.sleep(1)
    return f"analyzed {frames}"


@ls.step
def report(analysis):
    return f"report on {analysis}"


@ls.workflow
def pipeline():
    return report(analyze(ingest()))


run = pipeline.run()
print(json.dumps({"status": run.status, "steps": run.completed_steps, "report": run.value}))

The complete Go workflow 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"
    "fmt"
    "os"
    "time"

    "github.com/laserdata/laser-sdk/foreign/go/laser"
    "github.com/laserdata/laser-sdk/foreign/go/wire"
)

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) error {
    client, err := laser.ConnectEnv(ctx)
    if err != nil {
        return err
    }
    defer client.Close()
    if client.DefaultStream() == "" {
        client = client.WithDefaultStream("pipeline")
    }
    source, err := wire.NewAgentID("pipeline")
    if err != nil {
        return err
    }
    outcome, err := laser.RunWith(ctx, client.Workflow(source, wire.AgentSessions), pipeline)
    if err != nil {
        return err
    }
    return json.NewEncoder(os.Stdout).Encode(map[string]any{
        "status": outcome.Status, "steps": outcome.CompletedSteps, "report": json.RawMessage(outcome.Value),
    })
}

func pipeline(ctx context.Context, run *laser.WorkflowRun) (string, error) {
    frames, err := laser.RunStep(ctx, run, "ingest", func(context.Context) (string, error) {
        return "frames from sat-7", nil
    })
    if err != nil {
        return "", err
    }
    analysis, err := laser.RunStep(ctx, run, "analyze", func(context.Context) (string, error) {
        time.Sleep(time.Second)
        return "analyzed " + frames, nil
    })
    if err != nil {
        return "", err
    }
    return laser.RunStep(ctx, run, "report", func(context.Context) (string, error) {
        return "report on " + analysis, nil
    })
}

Python prints this, TypeScript prints it without the spaces, and Rust and Go order the keys by name:

{"status": "completed", "steps": ["ingest", "analyze", "report"], "report": "report on analyzed frames from sat-7"}

run() connects with LASER_CONNECTION_STRING, runs the steps, and returns the outcome: status, completed_steps (TypeScript: completedSteps) in the order the steps finished, value, which is what the workflow function returned, and run_id. A step takes and returns JSON values. Resuming a stopped run and steps that agents run are at https://docs.laserdata.com/laser-sdk/workflow.

Install and connect

The program connects with LASER_CONNECTION_STRING. With that variable set, it needs no Docker and no local server. A workflow function connects with it when it runs, with no connect call in the program. The memory program connects with Laser.connect_env(). If the check prints configured, run it unchanged.

Save a program as main.mts and run it with npx tsx main.mts. The package is ES modules only, so a .ts file needs "type": "module" in the project's package.json.

npm install @laserdata/laser-sdk tsx  # complete programs: https://docs.laserdata.com/laser-sdk/typescript.txt
echo "${LASER_CONNECTION_STRING:+configured}"  # prints configured when the variable is set

Workflows, memory, and sessions are in the crate's default features.

cargo add laser-sdk  # complete programs: https://docs.laserdata.com/laser-sdk/rust.txt
echo "${LASER_CONNECTION_STRING:+configured}"  # prints configured when the variable is set
cargo add tokio --features macros,rt-multi-thread,time
cargo add serde_json

The package imports as laser_sdk.

python -m pip install laser-sdk  # complete programs: https://docs.laserdata.com/laser-sdk/python.txt
echo "${LASER_CONNECTION_STRING:+configured}"  # prints configured when the variable is set

Use Go 1.25 or later. From your Go module, install the client and save a complete program as main.go. Run it with go run ..

go get github.com/laserdata/laser-sdk/foreign/go/laser@latest
echo "${LASER_CONNECTION_STRING:+configured}"  # prints configured when the variable is set

Without LASER_CONNECTION_STRING

This applies only when the check above prints a blank line. connect_env() then raises ConfigError, which names the variable. Where a connection string comes from is at https://docs.laserdata.com/laser-sdk/connect.

Long-term memory: complete program that corrects a fact

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
}

It prints this on every run:

{
  "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"]
}

In Python, pass conversation and user as keyword arguments. Every memory call is awaited. remember returns the new fact's ID. Pass it to supersede(old_id, text, ...) to replace that fact across conversations. Recall returns MemoryItem objects. For named items, forgetting, and recall by meaning, see https://docs.laserdata.com/laser-sdk/memory.

Sessions

The complete session program records a model call, a tool call, and state, reads the session back, and continues it in a new process. It is at https://docs.laserdata.com/laser-sdk/session.

An agent and a caller

The triage agent advertises the resolve-ticket capability and replies to each request. The caller sends a request to whichever agent has that capability and waits for the reply. Both run on plain Apache Iggy and read the connection string from LASER_CONNECTION_STRING.

import { Agent, AgentId, AgentTopic, Laser, TopicRetention, agentMessageBody, routeToCapable } from "@laserdata/laser-sdk"

await using root = await Laser.connectEnv()
const laser = root.withDefaultStream("support")
await laser.bootstrap(1, TopicRetention.expireAfter(86_400_000))

await using triage = Agent.builder()
  .id(AgentId.new("triage"))
  .listenOn(AgentTopic.Sessions)
  .respondOn(AgentTopic.Sessions)
  .capabilities([{ skillId: "resolve-ticket" }])
  .handler({ handle: (_message, ctx) => ctx.respond(new TextEncoder().encode("on it")) })
  .build()
  .spawn(laser)
await triage.ready()

const result = await laser
  .contract(routeToCapable("resolve-ticket", { kind: "any" }))
  .from(AgentId.new("support-desk"))
  .payload(new TextEncoder().encode("ticket #42 is stuck"))
  .inboxRoute({ kind: "fixed", topic: AgentTopic.Sessions })
  .send()
if (result.kind === "completed") console.log(new TextDecoder().decode(agentMessageBody(result.reply)))
use laser_sdk::prelude::full::*;
use laser_sdk::wire::agent::CapabilityDescriptor;
use std::time::Duration;

struct Triage;

impl AgentHandler for Triage {
    async fn handle(&self, _message: &AgentMessage, ctx: &AgentCtx<'_>) -> Result<(), LaserError> {
        ctx.respond("on it").await
    }
}

#[tokio::main]
async fn main() -> Result<(), LaserError> {
    let laser = Laser::connect_env().await?.with_default_stream("support");
    laser.bootstrap(1, TopicRetention::expire_after(Duration::from_secs(86_400))).await?;

    let mut triage = Agent::builder()
        .id("triage".parse()?)
        .listen_on(AgentTopic::Sessions)
        .respond_on(AgentTopic::Sessions)
        .capabilities(vec![CapabilityDescriptor { skill_id: "resolve-ticket".into(), ..Default::default() }])
        .handler(Triage)
        .build()
        .spawn(laser.clone());
    triage.ready().await?;

    let result = laser
        .contract(Router::to_capable("resolve-ticket", RoutePolicy::Any))
        .from("support-desk".parse()?)
        .payload("ticket #42 is stuck")
        .inbox_route(InboxRoute::Fixed(AgentTopic::Sessions))
        .send()
        .await?;
    if let Contract::Completed(reply) = result {
        println!("{}", String::from_utf8_lossy(reply.body()));
    }
    triage.shutdown().await
}
import asyncio
import laser_sdk as ls

SESSIONS = ls.AgentTopic.Sessions

async def handle(ctx, message):
    await ctx.respond(b"on it")

async def main():
    laser = (await ls.Laser.connect_env()).with_default_stream("support")
    await laser.bootstrap(1, ls.TopicRetention.expire_after(86_400_000))

    triage = laser.spawn_agent("triage", SESSIONS, handle, respond_on=SESSIONS, capabilities=["resolve-ticket"])
    await triage.ready()

    result = await laser.contract("resolve-ticket", b"ticket #42 is stuck", source="support-desk", fixed_inbox=SESSIONS)
    if isinstance(result, ls.Contract.Completed):
        print(bytes(result[0].body()).decode())
    await triage.shutdown()
    await laser.close()

asyncio.run(main())
package main

import (
    "context"
    "fmt"
    "os"
    "time"

    "github.com/laserdata/laser-sdk/foreign/go/laser"
    "github.com/laserdata/laser-sdk/foreign/go/wire"
)

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) error {
    root, err := laser.ConnectEnv(ctx)
    if err != nil {
        return err
    }
    defer root.Close()
    client := root.WithDefaultStream("support")
    if err := client.Bootstrap(ctx, 1, laser.ExpireAfter(24*time.Hour)); err != nil {
        return err
    }
    triage, err := wire.NewAgentID("triage")
    if err != nil {
        return err
    }
    desk, err := wire.NewAgentID("support-desk")
    if err != nil {
        return err
    }

    options := laser.SpawnOptions{
        RuntimeOptions: laser.RuntimeOptions{Topic: wire.AgentSessions, RespondOn: wire.AgentSessions},
        Capabilities:   []wire.CapabilityDescriptor{{SkillID: "resolve-ticket"}},
    }
    handle, err := client.SpawnAgent(ctx, triage, options, laser.HandlerFunc(
        func(ctx context.Context, message *laser.AgentMessage, agent *laser.AgentCtx) error {
            return agent.Respond(ctx, []byte("on it"))
        },
    ))
    if err != nil {
        return err
    }
    defer handle.Shutdown(context.WithoutCancel(ctx))
    if err := handle.Ready(ctx); err != nil {
        return err
    }

    result, err := client.Contract(laser.ToCapable("resolve-ticket", laser.RouteAny), wire.AgentSessions).
        InboxRoute(laser.FixedInbox(wire.AgentSessions)).From(desk).
        Payload([]byte("ticket #42 is stuck")).Send(ctx)
    if err != nil {
        return err
    }
    if result.State == laser.ContractCompleted {
        fmt.Println(string(result.Reply.Envelope.Body))
    }
    return nil
}

The request and the reply are messages on the agent.sessions topic, so they stay on the log after the program exits. The runnable agent example adds a deadline and pickup tracking. The Quickstart walks through a first program step by step.

What you can build

You needUseNeeds Laser Stack or Cloud
Agents that find each other by capability, send requests, and get repliesAgentsNo
A workflow of agent steps that resumes after a crash without repeating finished stepsWorkflowsNo
A recorded unit of work with model calls, tool calls, state, and a final statusSessionsOnly for the session index and timelines
Facts an agent remembers and recalls across conversations, and corrects when they changeMemoryOnly for the managed memory view
Keyed state with compare-and-swap, expiry, and branchesKey-value stateYes
Queries over your messages that stay up to date, and a feed of what changedQueries and views, ChangesYes
A stream where each consumer receives only the records it asked forFiltersYes

Where to go next

Packages are on npm, crates.io, and PyPI. Source and issues are at github.com/laserdata/laser-sdk. Context7 serves these docs as /websites/laserdata and the SDK source as /laserdata/laser-sdk.

On this page