Workflows
Durable workflow: decorate functions with @ls.step and @ls.workflow, record each finished step on the log, resume after a restart without repeating finished steps, and route steps to agents
The complete programs on this page are plain text, one language each, at https://docs.laserdata.com/md/python/laser-sdk/workflow.md, https://docs.laserdata.com/md/typescript/laser-sdk/workflow.md, https://docs.laserdata.com/md/rust/laser-sdk/workflow.md, and https://docs.laserdata.com/md/go/laser-sdk/workflow.md.
A durable workflow is a function whose steps are recorded on the log. Python decorates functions with @ls.step and @ls.workflow, TypeScript wraps them with step() and workflow(), and Rust passes closures to run_with. Each step that finishes is written to the agent.workflow_journal topic, so a run that stops part way continues from the first step that did not finish. Workflows run on plain Apache Iggy, Laser Stack, and LaserData Cloud.
If you know Temporal, a step is what Temporal calls an activity, and there is no separate activity type.
Use a workflow when a job has several dependent steps and must survive a restart, such as ingest, then analyze, then report. For a single request and reply, send the request to the agent directly.
Quick example
This program runs a three-step durable workflow in its own process. Each step is a function, the workflow function calls them in order, and analyze waits one second before it returns. The program prints the run's status, the finished steps in order, and the workflow's value as JSON.
The program connects with LASER_CONNECTION_STRING. With that variable set, it needs no Docker and no local server. Without it, the resolve block below connects with a LaserData API key.
npm install @laserdata/laser-sdk tsx
echo "${LASER_CONNECTION_STRING:+configured}" # prints configured when the variable is setcargo 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_jsonpython -m pip install laser-sdk
echo "${LASER_CONNECTION_STRING:+configured}" # prints configured when the variable is set
python -c "import laser_sdk; print(laser_sdk.__version__)" # prints the installed versionUse 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 setThe 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() 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. status is completed for every returned outcome, because a failed run raises the step's error instead. Calling the workflow as a function, pipeline(), returns the value alone. In Python an async def workflow is awaited, and its steps can be async def too. The run creates its stream and its topics on the first write, so the program needs no bootstrap.
How a run is recorded
- A step takes and returns what JSON holds: an object, a list, text, a number, a boolean, or null. A step call returns the value as JSON decodes it, on a first run and on a resumed one alike, so a Python tuple comes back as a list. A value JSON cannot hold is refused with the step's name.
- A step is recorded under its name as its label. A second call of the same step in one run is recorded as
name#2, the third asname#3.completed_stepslists these labels, andoutcome.json(label)reads one step's value (Rust:run.json::<T>(label)). - The run is recorded on the client's default stream, else on the stream
LASER_STREAMnames, else on a stream named after the workflow,pipelinehere. The run creates the stream when it is missing. - The stream stays after the run, so the journal is there for a resume. Delete it with
laser.stream("pipeline").delete()when you no longer need it. - Each run has a run ID. Resuming with it returns the recorded value of every finished step without calling the step again and runs the rest. Pass the workflow's arguments again, because the journal does not hold them.
- A resumed step call finds its record by the step's name and its arguments. A call with the same arguments returns the recorded value, and a call with other arguments runs as a new call. Rust's
run.steptakes no arguments, so its calls take the records of their label in call order. - When the workflow function returns, no new step starts. A step still running then has 5 seconds to finish and be recorded. A step that takes longer is not recorded and runs again on a resume.
| TypeScript | Rust | Python | |
|---|---|---|---|
| Run and get the outcome | await pipeline.run() | laser.workflow("pipeline").run_with(...) | pipeline.run() |
| Resume a run | await pipeline.resume(runId) | laser.workflow("pipeline").run_id(run_id).run_with(...) | pipeline.resume(run_id) |
| Run on a client you hold | pipeline.bind(laser).run() | The client the workflow was made on | pipeline.bind(laser).run() |
| Name the stream | workflow(name, fn, { stream }) | laser.with_default_stream(stream) | @ls.workflow(stream=...) |
A workflow function connects with LASER_CONNECTION_STRING and closes its connection when the run ends. A bound one uses your client and leaves it open.
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.
The builder: steps that agents run, verifiers, compensation, and budgets
A workflow function runs every step in your process. Use the builder when a step is a request to an agent that offers a capability, when a step needs a verifier or a compensation, or when the run needs a budget. Both forms write the same journal and resume the same way. The workflow reference lists every builder option.
Steps in your process
With the builder a step is declared with its label and the labels it runs after, and its body reads the earlier outputs as bytes. This program runs on a scratch stream with a unique name and deletes that stream at the end, so it leaves nothing to clean up.
The same pipeline with the builder, 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 { setTimeout as sleep } from "node:timers/promises"
import { Laser } from "@laserdata/laser-sdk"
const decode = (bytes?: Uint8Array) => new TextDecoder().decode(bytes)
await using root = await Laser.connectEnv()
await using scratch = await root.scratchStream("workflow")
const outcome = await scratch.laser
.workflow("pipeline")
.stepLocal("ingest", () => "frames from sat-7")
.stepLocal("analyze", async ({ outputs }) => {
await sleep(1000)
return `analyzed ${decode(outputs.get("ingest"))}`
})
.after("ingest")
.stepLocal("report", ({ outputs }) => `report on ${decode(outputs.get("analyze"))}`)
.after("analyze")
.run()
console.log(
JSON.stringify({
run_id: outcome.runId.toString(),
status: outcome.status,
completed_steps: outcome.completedSteps,
report: outcome.text("report")
})
)The same pipeline with the builder, saved as src/main.rs.
// cargo add laser-sdk
// cargo add tokio --features macros,rt-multi-thread,time
// cargo add serde --features derive
// cargo add serde_json
// cargo add async-trait
// Needs only LASER_CONNECTION_STRING, which connect_env() reads. No server to start when it is set.
use laser_sdk::prelude::*;
use serde::Serialize;
use std::time::Duration;
#[derive(Serialize)]
struct Report {
run_id: String,
status: SessionStatus,
completed_steps: Vec<String>,
report: Option<String>,
}
struct Analyze;
#[async_trait::async_trait]
impl StepFn for Analyze {
async fn build(&self, context: &StepContext<'_>) -> Result<Vec<u8>, LaserError> {
let ingested = context.outputs.get("ingest").cloned().unwrap_or_default();
tokio::time::sleep(Duration::from_secs(1)).await;
Ok([b"analyzed ".to_vec(), ingested].concat())
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let root = Laser::connect_env().await?;
let scratch = root.scratch_stream("workflow").await?;
let result = run_pipeline(scratch.laser()).await;
scratch.delete().await?;
let outcome = result?;
let report = Report {
run_id: outcome.run_id.to_string(),
report: outcome.text("report"),
status: outcome.status,
completed_steps: outcome.completed_steps,
};
println!("{}", serde_json::to_string(&report)?);
Ok(())
}
async fn run_pipeline(laser: &Laser) -> Result<WorkflowOutcome, LaserError> {
laser
.workflow("pipeline")
.step_local("ingest", |_: &StepContext<'_>| {
b"frames from sat-7".to_vec()
})
.step_local("analyze", Analyze)
.after("ingest")
.step_local("report", |context: &StepContext<'_>| {
let analyzed = context.outputs.get("analyze").cloned().unwrap_or_default();
[b"report on ".to_vec(), analyzed].concat()
})
.after("analyze")
.run()
.await
}A closure step is synchronous and returns Vec<u8>, so an async closure does not compile. A step that awaits is a type that implements StepFn, passed in place of the closure, as Analyze is.
The same pipeline with the builder, 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
async def analyze(outputs):
await asyncio.sleep(1)
return b"analyzed " + outputs["ingest"]
async def main():
async with await ls.Laser.connect_env() as root:
async with root.scratch_stream("workflow") as scratch:
outcome = await (
scratch.laser.workflow("pipeline")
.step("ingest", run=lambda outputs: "frames from sat-7")
.step("analyze", after=["ingest"], run=analyze)
.step(
"report",
after=["analyze"],
run=lambda outputs: b"report on " + outputs["analyze"],
)
.run()
)
print(
json.dumps(
{
"run_id": outcome.run_id,
"status": outcome.status,
"completed_steps": outcome.completed_steps,
"report": outcome.text("report"),
}
)
)
asyncio.run(main())The same pipeline with the builder, saved as main.go.
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 {
root, err := laser.ConnectEnv(ctx)
if err != nil {
return err
}
defer root.Close()
scratch, err := root.ScratchStream(ctx, "workflow")
if err != nil {
return err
}
defer scratch.Delete(context.WithoutCancel(ctx))
pipeline, err := wire.NewAgentID("pipeline")
if err != nil {
return err
}
job := scratch.Laser().Workflow(pipeline, wire.AgentSessions)
job.StepLocal("ingest", func(context.Context, map[string][]byte) ([]byte, error) {
return []byte("frames from sat-7"), nil
})
job.StepLocal("analyze", func(_ context.Context, outputs map[string][]byte) ([]byte, error) {
time.Sleep(time.Second)
return append([]byte("analyzed "), outputs["ingest"]...), nil
}).After("ingest")
job.StepLocal("report", func(_ context.Context, outputs map[string][]byte) ([]byte, error) {
return append([]byte("report on "), outputs["analyze"]...), nil
}).After("analyze")
outcome, err := job.Run(ctx)
if err != nil {
return err
}
report, _ := outcome.Text("report")
return json.NewEncoder(os.Stdout).Encode(struct {
RunID string `json:"run_id"`
Status wire.SessionStatus `json:"status"`
CompletedSteps []string `json:"completed_steps"`
Report string `json:"report"`
}{outcome.RunID.String(), outcome.Status, outcome.CompletedSteps, report})
}The output looks like this in every language, with your own run ID. Python separates the fields with a space:
{"run_id":"01JD3W8Q4M6V2X9TQK7R5N1B0C","status":"completed","completed_steps":["ingest","analyze","report"],"report":"report on analyzed frames from sat-7"}A step body gets outputs, the earlier steps' outputs by label, each as bytes (Uint8Array in TypeScript, Vec<u8> in Rust), and returns its own output as text or bytes. In Python it is a plain function or a coroutine, in TypeScript a plain or async function, and in Rust a closure or a type that implements StepFn. It runs inside the step deadline, 30 seconds unless you set one. status is completed for every returned outcome, because a failed, canceled, or over-budget run raises an error instead. completed_steps (TypeScript: completedSteps) lists the finished steps in the order the journal recorded them, outputs holds each step's output as bytes, and text(label) returns one as text. The run creates the journal and session topics on its first write, so the program needs no bootstrap. The scratch stream is deleted with the journal and every other topic when its scope ends. To keep the journal so a run can resume, use a named stream, as in Resume a stopped run. To delete a stream yourself, call laser.stream(name).delete().
Run steps on agents
A step can also be a request to an agent that offers a capability, so the work runs in another process or on another machine. This program starts one worker agent and runs the same three-step pipeline against it on the named stream telemetry. To resume a run, set RUN_ID to the run ID it printed. Local and routed steps mix in one workflow. The program keeps the stream so a run can resume. Delete it when you are done with laser.stream("telemetry").delete().
// npm install @laserdata/laser-sdk tsx
// Run with: npx tsx main.mts
import {
Agent,
AgentId,
AgentTopic,
ConversationId,
Laser,
TopicRetention,
WorkflowBudget,
agentMessageBody,
routeToCapable
} from "@laserdata/laser-sdk"
const text = new TextEncoder()
const decode = (bytes: Uint8Array) => new TextDecoder().decode(bytes)
const step = () => routeToCapable("telemetry-step", { kind: "any" })
await using root = await Laser.connectEnv()
const laser = root.withDefaultStream("telemetry")
await laser.bootstrap(1, TopicRetention.expireAfter(86_400_000))
await using worker = Agent.builder()
.id(AgentId.new("telemetry-worker"))
.listenOn(AgentTopic.Sessions)
.respondOn(AgentTopic.Sessions)
.capabilities([{ skillId: "telemetry-step" }])
.ackOnPickup()
.handler({
handle: (message, ctx) =>
ctx.respond(text.encode(`done: ${decode(agentMessageBody(message))}`))
})
.build()
.spawn(laser)
await worker.ready()
let workflow = laser
.workflow("telemetry-pipeline")
.inboxRoute({ kind: "fixed", topic: AgentTopic.Sessions })
.budget(WorkflowBudget.unlimited().invocations(6).wallClock(60_000))
if (process.env.RUN_ID) workflow = workflow.runId(ConversationId.parse(process.env.RUN_ID))
const outcome = await workflow
.step("ingest", step(), () => text.encode("ingest frames from sat-7"))
.step("analyze", step(), ({ outputs }) =>
text.encode(`analyze ${decode(outputs.get("ingest") ?? new Uint8Array())}`)
)
.after("ingest")
.step("report", step(), ({ outputs }) =>
text.encode(`report ${decode(outputs.get("analyze") ?? new Uint8Array())}`)
)
.after("analyze")
.run()
const report = decode(outcome.outputs.get("report") ?? new Uint8Array())
console.log(`Run ${outcome.runId.toString()} finished: ${report}`)// cargo add laser-sdk
// cargo add tokio --features macros,rt-multi-thread
use laser_sdk::prelude::full::*;
use laser_sdk::wire::agent::CapabilityDescriptor;
use std::time::Duration;
struct Worker;
impl AgentHandler for Worker {
async fn handle(&self, message: &AgentMessage, ctx: &AgentCtx<'_>) -> Result<(), LaserError> {
let task = String::from_utf8_lossy(message.body());
ctx.respond(format!("done: {task}")).await
}
}
#[tokio::main]
async fn main() -> Result<(), LaserError> {
let laser = Laser::connect_env().await?.with_default_stream("telemetry");
laser
.bootstrap(1, TopicRetention::expire_after(Duration::from_secs(86_400)))
.await?;
let mut worker = Agent::builder()
.id("telemetry-worker".parse()?)
.listen_on(AgentTopic::Sessions)
.respond_on(AgentTopic::Sessions)
.capabilities(vec![CapabilityDescriptor {
skill_id: "telemetry-step".to_owned(),
..Default::default()
}])
.ack_on_pickup(true)
.handler(Worker)
.build()
.spawn(laser.clone());
worker.ready().await?;
let step = || Router::to_capable("telemetry-step", RoutePolicy::Any);
let mut workflow = laser
.workflow("telemetry-pipeline")
.inbox_route(InboxRoute::Fixed(AgentTopic::Sessions))
.budget(WorkflowBudget::unlimited().invocations(6).wall_clock(Duration::from_secs(60)));
if let Ok(run_id) = std::env::var("RUN_ID") {
workflow = workflow.run_id(run_id.parse()?);
}
let outcome = workflow
.step("ingest", step(), |_ctx: &StepContext<'_>| b"ingest frames from sat-7".to_vec())
.step("analyze", step(), |ctx: &StepContext<'_>| {
let ingested = ctx.outputs.get("ingest").cloned().unwrap_or_default();
[b"analyze ".to_vec(), ingested].concat()
})
.after("ingest")
.step("report", step(), |ctx: &StepContext<'_>| {
let analyzed = ctx.outputs.get("analyze").cloned().unwrap_or_default();
[b"report ".to_vec(), analyzed].concat()
})
.after("analyze")
.run()
.await?;
let report = outcome.outputs.get("report").cloned().unwrap_or_default();
println!(
"Run {} finished: {}",
outcome.run_id,
String::from_utf8_lossy(&report)
);
worker.shutdown().await
}import asyncio
import os
import laser_sdk as ls
async def work(ctx, message):
await ctx.respond(b"done: " + bytes(message.body()))
async def main():
async with await ls.Laser.connect_env() as root:
laser = root.with_default_stream("telemetry")
await laser.bootstrap(1, ls.TopicRetention.expire_after(86_400_000))
async with laser.spawn_agent(
"telemetry-worker",
ls.AgentTopic.Sessions,
work,
respond_on=ls.AgentTopic.Sessions,
capabilities=["telemetry-step"],
ack_on_pickup=True,
):
workflow = laser.workflow("telemetry-pipeline", fixed_inbox=ls.AgentTopic.Sessions)
workflow.budget(ls.WorkflowBudget.unlimited().invocations(6).wall_clock(60_000))
if os.environ.get("RUN_ID"):
workflow.run_id(os.environ["RUN_ID"])
workflow.step(
"ingest",
to_capable="telemetry-step",
build=lambda outputs: b"ingest frames from sat-7",
)
workflow.step(
"analyze",
to_capable="telemetry-step",
after=["ingest"],
build=lambda outputs: b"analyze " + outputs["ingest"],
)
workflow.step(
"report",
to_capable="telemetry-step",
after=["analyze"],
build=lambda outputs: b"report " + outputs["analyze"],
)
outcome = await workflow.run()
report = bytes(outcome.outputs["report"]).decode()
print(f"Run {outcome.run_id} finished: {report}")
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(), 2*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("telemetry")
if err := client.Bootstrap(ctx, 1, laser.ExpireAfter(24*time.Hour)); err != nil {
return err
}
worker, err := wire.NewAgentID("telemetry-worker")
if err != nil {
return err
}
pipeline, err := wire.NewAgentID("telemetry-pipeline")
if err != nil {
return err
}
options := laser.SpawnOptions{
RuntimeOptions: laser.RuntimeOptions{Topic: wire.AgentSessions, RespondOn: wire.AgentSessions, AckOnPickup: true},
Capabilities: []wire.CapabilityDescriptor{{SkillID: "telemetry-step"}},
}
handle, err := client.SpawnAgent(ctx, worker, options, laser.HandlerFunc(
func(ctx context.Context, message *laser.AgentMessage, agent *laser.AgentCtx) error {
return agent.Respond(ctx, append([]byte("done: "), message.Body()...))
},
))
if err != nil {
return err
}
defer handle.Shutdown(context.WithoutCancel(ctx))
if err := handle.Ready(ctx); err != nil {
return err
}
step := laser.ToCapable("telemetry-step", laser.RouteAny)
job := client.Workflow(pipeline, wire.AgentSessions).
InboxRoute(laser.FixedInbox(wire.AgentSessions)).
Budget(laser.WorkflowBudget{}.WithInvocations(6).WithWallClock(time.Minute))
if text := os.Getenv("RUN_ID"); text != "" {
id, err := wire.ParseID(text)
if err != nil {
return err
}
job = job.RunID(wire.ConversationID{ID: id})
}
job.Step("ingest", step, func(context.Context, map[string][]byte) ([]byte, error) {
return []byte("ingest frames from sat-7"), nil
})
job.Step("analyze", step, func(_ context.Context, outputs map[string][]byte) ([]byte, error) {
return append([]byte("analyze "), outputs["ingest"]...), nil
}).After("ingest")
job.Step("report", step, func(_ context.Context, outputs map[string][]byte) ([]byte, error) {
return append([]byte("report "), outputs["analyze"]...), nil
}).After("analyze")
outcome, err := job.Run(ctx)
if err != nil {
return err
}
fmt.Printf("Run %s finished: %s\n", outcome.RunID, outcome.Outputs["report"])
return nil
}The output looks like this, with your own run ID. Each step's reply wraps the request it got:
Run 01JD3W8Q4M6V2X9TQK7R5N1B0C finished: done: report done: analyze done: ingest frames from sat-7Common mistakes
- One connection advertises one agent. A second agent spawned on the same connection fails with
PresenceConflictError(connection already advertises agent ...). In Python,async with laser.spawn_agent(...)andready()report it asagent stopped before ready, andshutdown()then raises thePresenceConflictError. Serve every step from one agent whose handler reads the request, as the example does, or open one connection per agent. - A worker replies on the topic it responds on. Without one, the agent refuses
ack_on_pickupwithack_on_pickup requires respond_on, or a step fails because the agent has no respond_on topic configured. Set it when you build the agent:respond_onin Python,respondOnin TypeScript,respond_onin Rust. - In Python,
message.body()is a method that returns the task body.message.payloadis the whole encoded message, so decoding it as text fails. - A step function called outside a workflow function is refused with an error that names both ways out: call it inside a workflow function, or call its
fnfor the plain function. - In Python, a thread does not inherit its workflow, so a step called on a new thread is refused as a call outside a workflow. Run the step with
asyncio.to_thread(step, ...), or hand the threadcontextvars.copy_context().runwith the step as its first argument.
Resume a stopped run
Every run has a run ID. The run writes each finished step to agent.workflow_journal under that ID, so a run resumes only on a stream that outlives the process, not on a scratch stream. When the process stops between steps, start it again on the same stream with the same run ID: pipeline.resume(run_id) for a workflow function, run_id on the builder, as the agent program above does with RUN_ID:
- A step recorded as finished does not run again. Its stored output feeds the next step.
- A step that runs in your process and stopped before its finished record runs again, so it runs at least once.
- A step that was sent but has no recorded reply is answered by its reply when one landed. Otherwise it is sent again with the same idempotency key. A worker can drop a duplicate while its deduplication record still exists. The default in-memory deduplication window does not survive every worker restart, so the handler must tolerate redelivery.
- A step copy that a worker dropped because its deadline had passed never ran, so it does not stop the resent step from running. That holds on a worker that refills its deduplication window on restart too, unless its warm dedup policy is
all. - When the worker's process stopped too, the streaming server keeps that worker's partitions until it ends the stopped process's session, 36 seconds or more after the stop with default server settings. A run resumed sooner can fail with a
timed_outstep error. Resume it again with the same run ID and the step runs once. - A run whose journal was cut by topic retention fails with a journal truncated error instead of running every step again.
The journal records what the workflow did. An agent that changes something outside the log, such as a payment or an email, still needs its own protection against doing it twice. Make the step exclusive and use a fenced write, or key the external call with the request's idempotency key.
When a step fails
In a workflow function, a step that raises ends the run as failed and the same error reaches the caller unchanged. The steps that finished stay recorded, so a resume runs the failed step and what follows.
A step fails when its agent does not reply before the step deadline (30 seconds unless you set one), when the reply is an error, or when a verifier rejects the output. A step in your process fails when its body runs past the deadline, and an error its body raises comes back unchanged. The run then fails with a step failed error that names the run, the step, and the reason, and for a timed-out step also the target and the deadline in milliseconds. Steps that already finished run their compensations in reverse order. Only a timed_out failure is worth retrying as is.
| Error | Rust | TypeScript and Python | What to do |
|---|---|---|---|
| Step failed | LaserError::StepFailed | StepFailedError | Read the reason, fix the agent or the input, resume with the same run ID |
| Budget exceeded | LaserError::BudgetExceeded | BudgetExceededError | Raise the budget, or split the run |
| Journal truncated | LaserError::JournalTruncated | JournalTruncatedError | Start a new run, and keep the journal topic longer than your longest run |
| No capable agent | LaserError::NoCapableAgent | NoCapableAgentError | Start an agent that offers the capability and wait for ready(), then resume with the same run ID |
When no agent offers the capability a step asks for, the run fails at once with the no capable agent error instead of waiting for the step deadline. Start the agents first and wait for ready(), as the example does.
Next steps
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
Sessions
Record every agent interaction as a durable session you can inspect, replay, resume after a restart, and control