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";23const 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 validation3 schema?: JSONSchema;45 // System prompt - sets AI behavior and context6 systemPrompt?: string;78 // User prompt template with interpolation support9 userPrompt?: string;1011 // Retry configuration12 retry?: {13 maxRetries: number;14 backoffMs?: number;15 };1617 // Arbitrary metadata for debugging/telemetry18 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 models2.with("openai:gpt-4o")3.with("openai:gpt-4o-mini")4.with("openai:gpt-4o-vision")56// Anthropic models7.with("anthropic:claude-3-5-sonnet")8.with("anthropic:claude-3-opus")9.with("anthropic:claude-3-haiku")1011// Google models12.with("google:gemini-pro")13.with("google:gemini-pro-vision")1415// xAI models16.with("xai:grok-beta")1718// Local models (Ollama)19.with("ollama:llama3")20.with("ollama:mistral")Parameters
- •
model(string) - Model identifier inprovider:model-idformat
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 dependency2.step("validate")3.with("anthropic:claude-3-5-sonnet")4.depends("extract")56// Multiple dependencies (waits for all)7.step("summarize")8.with("openai:gpt-4o-mini")9.depends("extract", "validate", "analyze")1011// Parallel execution example12relay.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 parallel17 .step("combine")18 .with("anthropic:claude-3-5-sonnet")19 .depends("sentiment", "topics", "entities")20 // Waits for all three before runningParameters
- •
...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.
.run()
Executes the workflow with the provided input. Returns a promise that resolves when all steps complete.
1const result = await workflow.run(2 // Input data3 { fileUrl: "https://example.com/invoice.pdf" },45 // Options (optional)6 {7 mode: "local", // or "cloud"8 timeout: 30000, // ms9 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 cloud3 mode?: "local" | "cloud";45 // Per-run provider configuration overrides6 providers?: Record; 78 // Timeout in milliseconds9 timeout?: number;1011 // Additional metadata for this run12 metadata?: Record; 1314 // Abort signal for cancellation15 signal?: AbortSignal;16}1718interface ProviderConfig {19 apiKey: string;20 baseUrl?: string; // Custom API endpoint21 organization?: string; // For providers that support it22}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 successfully3 success: boolean;45 // Step outputs indexed by step name6 steps: Record; 78 // Final output from the last step9 finalOutput?: any;1011 // Error information if workflow failed12 error?: {13 message: string;14 stepName?: string;15 cause?: any;16 };1718 // Execution metadata19 metadata: {20 workflowName: string;21 startTime: Date;22 endTime: Date;23 duration: number; // milliseconds24 };25}Accessing Step Outputs
1const result = await workflow.run({ text: "Hello world" });23if (result.success) {4 // Access individual step outputs5 const extracted = result.steps.extract;6 const validated = result.steps.validate;7 const summary = result.steps.summarize;89 // Or use the final output (last step)10 console.log(result.finalOutput);1112 // Check execution time13 console.log(`Completed in ${result.metadata.duration}ms`);14} else {15 // Handle errors16 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 input2.step("analyze", {3 userPrompt: "Analyze this document: {{input.documentUrl}}"4})56// Reference previous step output7.step("summarize", {8 userPrompt: `Summarize this analysis:910{{analyze.output}}1112Focus on key findings.`13})14.depends("analyze")1516// Complex object references17.step("format", {18 userPrompt: `Format this data:1920Customer: {{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";23relay.configure({4 providers: {5 openai: {6 apiKey: process.env.OPENAI_API_KEY!,7 organization: "org-xxx" // optional8 },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" // default20 }21 },2223 telemetry: {24 enabled: true,25 apiEndpoint: "https://api.relayplane.com/telemetry",26 apiKey: process.env.RELAYPLANE_API_KEY27 },2829 cloud: {30 enabled: true,31 teamId: "team_xxx",32 accessToken: process.env.RELAYPLANE_TOKEN33 }34});- 1. Per-run options (
options.providers) - 2. Global configuration (
relay.configure()) - 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).
1workflow2 .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).
1workflow2 .step("report").with("openai:gpt-4o")3 .schedule("0 9 * * 1-5", { // Weekdays at 9am4 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);34 if (!result.success) {5 // Workflow completed but a step failed6 console.error(`Step "${result.error?.stepName}" failed`);7 console.error(result.error?.message);89 // Access partial results from successful steps10 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 1s5 }6})Type Safety
The SDK uses TypeScript phantom types to provide compile-time guarantees for workflow correctness.
1// This will cause a TypeScript error2relay.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 name67// This is correct8relay.workflow("test")9 .step("first").with("openai:gpt-4o")10 .step("second").with("openai:gpt-4o")11 .depends("first") // OK: "first" was defined earlierSee Also
- •Quickstart Guide - Get started in 5 minutes
- •Core Concepts - Understand workflows, steps, and dependencies
- •Providers Guide - Configure OpenAI, Anthropic, and more
- •Invoice Processor Example - Complete production example