API Reference

Complete API documentation for the RelayPlane SDK v3 fluent builder API.

relay.workflow()

Creates a new workflow builder instance. This is the entry point for defining multi-step AI workflows.

1import { relay } from "@relayplane/workflows";
2
3const workflow = relay.workflow("invoice-processor");

Parameters

  • name (string) - Unique identifier for the workflow

Returns

WorkflowBuilder<[]> - A workflow builder with no steps defined yet.

.step()

Adds a new step to the workflow. Each step represents a single AI model invocation with its configuration.

1workflow.step("extract", {
2 schema: InvoiceSchema,
3 systemPrompt: "Extract invoice data as structured JSON",
4 userPrompt: "Process this invoice: {{input.fileUrl}}",
5 retry: { maxRetries: 3, backoffMs: 1000 },
6 metadata: { priority: "high" }
7})

Parameters

  • name (string) - Unique step identifier within the workflow
  • config (StepConfig, optional) - Step configuration object

StepConfig Interface

1interface StepConfig {
2 // JSON Schema for structured output validation
3 schema?: JSONSchema;
4
5 // System prompt - sets AI behavior and context
6 systemPrompt?: string;
7
8 // User prompt template with interpolation support
9 userPrompt?: string;
10
11 // Retry configuration
12 retry?: {
13 maxRetries: number;
14 backoffMs?: number;
15 };
16
17 // Arbitrary metadata for debugging/telemetry
18 metadata?: Record;
19}

Returns

StepWith - Builder to specify the model for this step.

.with()

Specifies which AI model to use for the step. Uses the provider:model-id format.

1// OpenAI models
2.with("openai:gpt-4o")
3.with("openai:gpt-4o-mini")
4.with("openai:gpt-4o-vision")
5
6// Anthropic models
7.with("anthropic:claude-3-5-sonnet")
8.with("anthropic:claude-3-opus")
9.with("anthropic:claude-3-haiku")
10
11// Google models
12.with("google:gemini-pro")
13.with("google:gemini-pro-vision")
14
15// xAI models
16.with("xai:grok-beta")
17
18// Local models (Ollama)
19.with("ollama:llama3")
20.with("ollama:mistral")

Parameters

  • model (string) - Model identifier in provider:model-id format

Returns

StepWithModel - Builder that can add dependencies, more steps, or run the workflow.

.depends()

Declares dependencies for this step. The step will only execute after all dependencies complete. Dependencies form a DAG (Directed Acyclic Graph) enabling parallel execution of independent steps.

1// Single dependency
2.step("validate")
3.with("anthropic:claude-3-5-sonnet")
4.depends("extract")
5
6// Multiple dependencies (waits for all)
7.step("summarize")
8.with("openai:gpt-4o-mini")
9.depends("extract", "validate", "analyze")
10
11// Parallel execution example
12relay.workflow("parallel-analysis")
13 .step("sentiment").with("openai:gpt-4o-mini")
14 .step("topics").with("openai:gpt-4o-mini")
15 .step("entities").with("openai:gpt-4o-mini")
16 // All three above run in parallel
17 .step("combine")
18 .with("anthropic:claude-3-5-sonnet")
19 .depends("sentiment", "topics", "entities")
20 // Waits for all three before running

Parameters

  • ...deps (string[]) - Step names this step depends on. Must be previously defined steps (compile-time checked).

Returns

StepComplete - Builder that can add more steps or run the workflow.

Type Safety: The SDK uses phantom types to enforce that you can only depend on steps that were defined earlier in the chain. Invalid dependencies cause compile-time TypeScript errors.

.run()

Executes the workflow with the provided input. Returns a promise that resolves when all steps complete.

1const result = await workflow.run(
2 // Input data
3 { fileUrl: "https://example.com/invoice.pdf" },
4
5 // Options (optional)
6 {
7 mode: "local", // or "cloud"
8 timeout: 30000, // ms
9 metadata: { requestId: "abc123" },
10 providers: {
11 openai: { apiKey: "sk-..." },
12 anthropic: { apiKey: "sk-ant-..." }
13 }
14 }
15);

Parameters

  • input (any, optional) - Input data accessible via {{input.fieldName}} in prompts
  • options (RunOptions, optional) - Execution options

RunOptions Interface

1interface RunOptions {
2 // Execution mode: local (default) or cloud
3 mode?: "local" | "cloud";
4
5 // Per-run provider configuration overrides
6 providers?: Record;
7
8 // Timeout in milliseconds
9 timeout?: number;
10
11 // Additional metadata for this run
12 metadata?: Record;
13
14 // Abort signal for cancellation
15 signal?: AbortSignal;
16}
17
18interface ProviderConfig {
19 apiKey: string;
20 baseUrl?: string; // Custom API endpoint
21 organization?: string; // For providers that support it
22}

Returns

Promise<WorkflowResult> - The workflow execution result.

WorkflowResult

The result object returned by .run(). Contains outputs from all steps and execution metadata.

1interface WorkflowResult {
2 // Whether the workflow completed successfully
3 success: boolean;
4
5 // Step outputs indexed by step name
6 steps: Record;
7
8 // Final output from the last step
9 finalOutput?: any;
10
11 // Error information if workflow failed
12 error?: {
13 message: string;
14 stepName?: string;
15 cause?: any;
16 };
17
18 // Execution metadata
19 metadata: {
20 workflowName: string;
21 startTime: Date;
22 endTime: Date;
23 duration: number; // milliseconds
24 };
25}

Accessing Step Outputs

1const result = await workflow.run({ text: "Hello world" });
2
3if (result.success) {
4 // Access individual step outputs
5 const extracted = result.steps.extract;
6 const validated = result.steps.validate;
7 const summary = result.steps.summarize;
8
9 // Or use the final output (last step)
10 console.log(result.finalOutput);
11
12 // Check execution time
13 console.log(`Completed in ${result.metadata.duration}ms`);
14} else {
15 // Handle errors
16 console.error(`Failed at step: ${result.error?.stepName}`);
17 console.error(result.error?.message);
18}

Template Variables

Use template syntax in prompts to reference input data and outputs from previous steps.

1// Reference workflow input
2.step("analyze", {
3 userPrompt: "Analyze this document: {{input.documentUrl}}"
4})
5
6// Reference previous step output
7.step("summarize", {
8 userPrompt: `Summarize this analysis:
9
10{{analyze.output}}
11
12Focus on key findings.`
13})
14.depends("analyze")
15
16// Complex object references
17.step("format", {
18 userPrompt: `Format this data:
19
20Customer: {{extract.output.customer.name}}
21Total: {{extract.output.totalAmount}}
22Items: {{extract.output.items.length}}`
23})
24.depends("extract")

Available Variables

  • {{input.fieldName}} - Access input data fields
  • {{stepName.output}} - Access previous step's full output
  • {{stepName.output.field}} - Access nested fields from step output

relay.configure()

Sets global configuration for the SDK including provider API keys and telemetry options.

1import { relay } from "@relayplane/workflows";
2
3relay.configure({
4 providers: {
5 openai: {
6 apiKey: process.env.OPENAI_API_KEY!,
7 organization: "org-xxx" // optional
8 },
9 anthropic: {
10 apiKey: process.env.ANTHROPIC_API_KEY!
11 },
12 google: {
13 apiKey: process.env.GOOGLE_API_KEY!
14 },
15 xai: {
16 apiKey: process.env.XAI_API_KEY!
17 },
18 ollama: {
19 baseUrl: "http://localhost:11434" // default
20 }
21 },
22
23 telemetry: {
24 enabled: true,
25 apiEndpoint: "https://api.relayplane.com/telemetry",
26 apiKey: process.env.RELAYPLANE_API_KEY
27 },
28
29 cloud: {
30 enabled: true,
31 teamId: "team_xxx",
32 accessToken: process.env.RELAYPLANE_TOKEN
33 }
34});
API Key Resolution: The SDK resolves API keys in this order:
  1. 1. Per-run options (options.providers)
  2. 2. Global configuration (relay.configure())
  3. 3. Environment variables (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)

Cloud Features

RelayPlane Pro enables webhooks and scheduled execution for production workflows.

.webhook()

Configure a webhook endpoint for the workflow (cloud-only).

1workflow
2 .step("process").with("openai:gpt-4o")
3 .webhook("https://api.example.com/callback", {
4 method: "POST",
5 headers: { "X-API-Key": "secret" }
6 })
7 .run(input);

.schedule()

Schedule the workflow to run on a cron schedule (cloud-only).

1workflow
2 .step("report").with("openai:gpt-4o")
3 .schedule("0 9 * * 1-5", { // Weekdays at 9am
4 timezone: "America/New_York"
5 })
6 .run(input);

Error Handling

Handle workflow errors gracefully with try-catch and result inspection.

1try {
2 const result = await workflow.run(input);
3
4 if (!result.success) {
5 // Workflow completed but a step failed
6 console.error(`Step "${result.error?.stepName}" failed`);
7 console.error(result.error?.message);
8
9 // Access partial results from successful steps
10 if (result.steps.extract) {
11 console.log("Extract succeeded:", result.steps.extract);
12 }
13 }
14} catch (error) {
15 // Network error, invalid configuration, etc.
16 console.error("Workflow execution error:", error);
17}

Retry Configuration

Configure automatic retries for transient failures.

1.step("extract", {
2 retry: {
3 maxRetries: 3,
4 backoffMs: 1000 // Exponential backoff starting at 1s
5 }
6})

Type Safety

The SDK uses TypeScript phantom types to provide compile-time guarantees for workflow correctness.

1// This will cause a TypeScript error
2relay.workflow("test")
3 .step("first").with("openai:gpt-4o")
4 .step("second").with("openai:gpt-4o")
5 .depends("nonexistent") // Error: "nonexistent" is not a valid step name
6
7// This is correct
8relay.workflow("test")
9 .step("first").with("openai:gpt-4o")
10 .step("second").with("openai:gpt-4o")
11 .depends("first") // OK: "first" was defined earlier

See Also