LaserData Cloud
Laser SDK

Quickstart

Install the SDK, run a durable workflow, and have one agent answer another

View as Markdownllms.txt

Each task below has one complete program in TypeScript, Rust, Python, and Go, and the Laser SDK overview opens with the first two. With LASER_CONNECTION_STRING set, a program runs as it is, and there is no server to start. The steps below start one for local development.

TaskComplete program
A durable workflow of functions decorated with @ls.step and @ls.workflow, one step waiting a secondStep 3 below, and Workflows
Long-term memory that corrects a fact and recalls the current facts for a userMemory
A recorded session with a model call, a tool call, and state, resumed in a new processSessions
One agent answers anotherStep 4 below

This page runs a durable workflow, then gets two agents talking. One agent handles a request, a caller sends it one, and the caller prints the reply. Then the same exchange runs inside a recorded session. Pick Rust, Python, TypeScript, or Go in the tabs. Your choice carries across the SDK docs.

1. Start a target

With LASER_CONNECTION_STRING exported, skip this step: every program on this page runs as it is.

Every step on this page works on any of these targets:

  • Laser Stack runs Laser Streams and the managed backend on your machine. Use it for local development.
  • LaserData Cloud gives you a connection string for the deployment admin ld-admin on the Credentials tab of your deployment. A Free deployment starts with an access rule that admits every address. For a paid deployment, or when that rule was deleted, add a rule for your client's public IP first, or the connect times out. With only an API key, resolve the connection string from the key in three calls.
  • Plain Apache Iggy runs messaging, agents, and sessions. Managed features such as queries and key-value state return Unsupported.

To start Laser Stack:

git clone https://github.com/laserdata/laser-stack
cd laser-stack
./scripts/up

The script waits for Iggy and the managed backend, then prints a LASER_CONNECTION_STRING export. Copy it into your shell. For Cloud or your own Iggy server, export that server's connection string the same way:

export LASER_CONNECTION_STRING='iggy:laser@127.0.0.1:8090'

Laser Stack covers requirements, persistence, and troubleshooting. Connect covers connection strings, tokens, and TLS.

2. Install the SDK

The program connects with LASER_CONNECTION_STRING. With that variable set, it needs no Docker and no local server.

npm install @laserdata/laser-sdk tsx
echo "${LASER_CONNECTION_STRING:+configured}"  # prints configured when the variable is set

Requires Node.js 22.14 or later. Save a program as main.mts to use top-level await. Run it with npx tsx main.mts.

cargo add laser-sdk
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

Requires Rust 1.100.0 or later. Agents, workflows, memory, sessions, and key-value state are in the default features. Add managed for queries and the other managed features.

python -m pip install laser-sdk
echo "${LASER_CONNECTION_STRING:+configured}"  # prints configured when the variable is set

Requires Python 3.10 or later. With uv, run uv pip install laser-sdk instead.

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

3. Run a durable workflow

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 program connects with LASER_CONNECTION_STRING when it runs, with no connect call in it.

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

Each completed step is journaled, so a stopped run resumes without running a finished step again. Workflows covers resuming a run and steps that agents run.

4. Have one agent answer another

The program connects, creates the agent topics on a stream named quickstart, and starts an agent called triage. Then a caller called intake sends triage a request and prints the reply.

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

const text = new TextEncoder()
const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes)

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

await using triage = Agent.builder()
  .id(AgentId.new("triage"))
  .listenOn(AgentTopic.Sessions)
  .respondOn(AgentTopic.Sessions)
  .handler({
    handle: (message, ctx) =>
      ctx.respond(text.encode(`triaged: ${decode(agentMessageBody(message))}`))
  })
  .build()
  .spawn(laser)
await triage.ready()

const outcome = await laser
  .contract(routeTo(AgentId.new("triage")))
  .from(AgentId.new("intake"))
  .payload(text.encode("disk full on node-7"))
  .inboxRoute({ kind: "fixed", topic: AgentTopic.Sessions })
  .send()

if (outcome.kind === "completed") {
  console.log(decode(agentMessageBody(outcome.reply)))
} else {
  console.log(`no reply: ${outcome.kind}`)
}
use laser_sdk::prelude::full::*;
use std::time::Duration;

struct Triage;

impl AgentHandler for Triage {
    async fn handle(&self, message: &AgentMessage, ctx: &AgentCtx<'_>) -> Result<(), LaserError> {
        let ticket = String::from_utf8_lossy(message.body());
        ctx.respond(format!("triaged: {ticket}")).await
    }
}

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

    let mut triage = Agent::builder()
        .id("triage".parse()?)
        .listen_on(AgentTopic::Sessions)
        .respond_on(AgentTopic::Sessions)
        .handler(Triage)
        .build()
        .spawn(laser.clone());
    triage.ready().await?;

    let outcome = laser
        .contract(Router::to("triage".parse()?))
        .from("intake".parse()?)
        .payload("disk full on node-7")
        .inbox_route(InboxRoute::Fixed(AgentTopic::Sessions))
        .send()
        .await?;

    match outcome {
        Contract::Completed(reply) => println!("{}", String::from_utf8_lossy(reply.body())),
        other => println!("no reply: {other:?}"),
    }
    triage.shutdown().await
}
import asyncio

import laser_sdk as ls


async def handle(ctx, message):
    ticket = bytes(message.body()).decode()
    await ctx.respond(f"triaged: {ticket}".encode())


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

        async with laser.spawn_agent(
            "triage",
            ls.AgentTopic.Sessions,
            handle,
            respond_on=ls.AgentTopic.Sessions,
        ):
            outcome = await laser.contract(
                None,
                b"disk full on node-7",
                agent="triage",
                source="intake",
                fixed_inbox=ls.AgentTopic.Sessions,
            )

        if isinstance(outcome, ls.Contract.Completed):
            print(bytes(outcome[0].body()).decode())
        else:
            print(f"no reply: {outcome!r}")


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("quickstart")
    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
    }
    intake, err := wire.NewAgentID("intake")
    if err != nil {
        return err
    }

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

    outcome, err := client.Contract(laser.To(triage), wire.AgentSessions).
        InboxRoute(laser.FixedInbox(wire.AgentSessions)).From(intake).
        Payload([]byte("disk full on node-7")).Send(ctx)
    if err != nil {
        return err
    }
    if outcome.State == laser.ContractCompleted {
        fmt.Println(string(outcome.Reply.Envelope.Body))
    } else {
        fmt.Println("no reply:", outcome.State)
    }
    return nil
}

The program prints:

triaged: disk full on node-7

What each part does:

  • bootstrap creates the agent topics on the stream, one partition each, and keeps agent.sessions records for one day. It is safe to run again.
  • ready() waits until the agent reads its topic, so the request cannot arrive before it listens. Python's async with waits for you.
  • contract sends one request to one agent and waits for the answer, 30 seconds by default. It ends as completed, failed, not consumed, or timed out.
  • The fixed inbox sends the request to agent.sessions, where triage listens. Without it, the SDK looks up the agent's inbox from live presence, which needs an agent that advertises capabilities and a server that serves presence.

5. Record the exchange as a session

A session is one unit of work with a start, an end, and every record in between, kept on the log. Open a session as intake, send the request inside it, end the session, and read it back. Replace the request in step 4 with this code.

import { sessionTurnText } from "@laserdata/laser-sdk"

const { session } = await laser.sessions().start().agent(AgentId.new("intake")).begin()

await laser
  .contract(routeTo(AgentId.new("triage")))
  .from(AgentId.new("intake"))
  .payload(text.encode("disk full on node-7"))
  .inboxRoute({ kind: "fixed", topic: AgentTopic.Sessions })
  .conversation(session.conversation)
  .send()
await session.end()

for (const turn of await session.context()) {
  console.log(turn.display, turn.display === "agent.message" ? sessionTurnText(turn) : "")
}
let (session, _lease) = laser
    .sessions()
    .start()
    .agent("intake".parse::<AgentId>()?)
    .begin()
    .await?;

laser
    .contract(Router::to("triage".parse()?))
    .from("intake".parse()?)
    .payload("disk full on node-7")
    .inbox_route(InboxRoute::Fixed(AgentTopic::Sessions))
    .conversation(session.conversation())
    .send()
    .await?;
session.end().await?;

for turn in session.context().await? {
    let kind: &str = turn.display.into();
    match kind {
        "agent.message" => println!("{kind}: {}", turn.text()),
        _ => println!("{kind}"),
    }
}
session, _lease = await laser.sessions().start().agent("intake").begin()

await laser.contract(
    None,
    b"disk full on node-7",
    agent="triage",
    source="intake",
    fixed_inbox=ls.AgentTopic.Sessions,
    conversation=session.conversation,
)
await session.end()

for turn in await session.context():
    print(turn.display, turn.text() if turn.display == "agent.message" else "")
session := client.Sessions().Start().As(intake)
_, lease, err := session.Begin(ctx)
if err != nil {
    return err
}
defer lease.Release()

if _, err := client.Contract(laser.To(triage), wire.AgentSessions).
    InboxRoute(laser.FixedInbox(wire.AgentSessions)).From(intake).
    Conversation(session.Conversation()).
    Payload([]byte("disk full on node-7")).Send(ctx); err != nil {
    return err
}
if _, err := session.Complete(ctx, "request answered"); err != nil {
    return err
}

turns, err := session.Context(ctx)
if err != nil {
    return err
}
for _, turn := range turns {
    if turn.Display == wire.DisplayAgentMessage {
        fmt.Println(turn.Display, turn.Text())
    } else {
        fmt.Println(turn.Display)
    }
}

The program prints the session as it was recorded:

session.started
agent.message disk full on node-7
agent.message triaged: disk full on node-7
session.completed

The request and the reply carry the session ID as their conversation, so context() returns them with the session's start and end. This works on plain Apache Iggy, because the SDK reads the records back from agent.sessions. Laser Stack and LaserData Cloud also index sessions, which adds listing, status, and timeline reads across the stream. Sessions shows both.

6. Publish and read your own messages

Agents use ordinary topics underneath. To publish your own records, such as telemetry or support tickets, and read them back by offset, follow Messages.

Next

On this page