> ## Documentation Index
> Fetch the complete documentation index at: https://docs.runflow.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Workflows

> Workflow exports and API reference

## Exports

```typescript theme={null}
import {
  // V2 API (recommended)
  flow,
  FlowBuilder,

  // Workflow class
  Workflow,

  // Step helpers
  createStep,
  createAgentStep,
  createFunctionStep,
  createConnectorStep,

  // Legacy (deprecated)
  createWorkflow,
  WorkflowBuilder,
} from '@runflow-ai/sdk';
```

## `flow(config)`

Creates a new `FlowBuilder` instance. This is the recommended entry point for creating workflows.

```typescript theme={null}
const builder = flow({
  id: 'my-workflow',
  name: 'My Workflow',         // optional
  description: 'Description',  // optional
  inputSchema: z.object({ text: z.string() }),
  outputSchema: z.any(),
});
```

**Parameters:**

* `config.id` -- Unique workflow identifier
* `config.name` -- Display name (defaults to `id`)
* `config.inputSchema` -- Zod schema for input validation
* `config.outputSchema` -- Zod schema for output validation

**Returns:** `FlowBuilder`

## `FlowBuilder` Methods

### `.step(id, handler | opts)`

Add a function step.

```typescript theme={null}
// Simple handler
.step('name', async (input, ctx) => ({ result: input.value * 2 }))

// With options
.step('name', {
  handler: async (input, ctx) => ({ result: input.value * 2 }),
  outputSchema: z.object({ result: z.number() }),  // runtime validation
  when: (ctx) => ctx.results.previous.flag === true,  // conditional
  retry: { maxAttempts: 3, backoff: 'exponential', delay: 1000 },
})
```

### `.agent(id, agent, opts?)`

Add an agent step. Output is always `AgentStepResult`.

```typescript theme={null}
.agent('analyze', myAgent, {
  prompt: 'Direct prompt text',
  // or
  promptTemplate: 'Analyze: {{input.text}}',
  when: (ctx) => ctx.input.needsAnalysis,
  retry: { maxAttempts: 2, backoff: 'fixed', delay: 500 },
})
```

### `.branch(id, opts)`

Binary routing (if/else).

```typescript theme={null}
.branch('route', {
  condition: (ctx) => ctx.results.classify.urgent,
  onTrue: async (input, ctx) => ({ path: 'urgent' }),
  onFalse: async (input, ctx) => ({ path: 'normal' }),
  unwrap: true,  // default: true
})
```

`onTrue` and `onFalse` accept either a handler function or a `WorkflowStep[]` array.

### `.switch(id, opts)`

Multi-way routing.

```typescript theme={null}
.switch('route', {
  on: (ctx) => ctx.results.classify.category,
  cases: {
    billing: async (input) => ({ dept: 'billing' }),
    sales: async (input) => ({ dept: 'sales' }),
  },
  default: async (input) => ({ dept: 'general' }),
  unwrap: true,  // default: true
})
```

### `.parallel(id, steps, opts?)`

Concurrent execution.

```typescript theme={null}
.parallel('enrich', [
  createFunctionStep('a', async () => ({ a: true })),
  createFunctionStep('b', async () => ({ b: true })),
], { waitForAll: true })
```

### `.foreach(id, opts)`

Array iteration.

```typescript theme={null}
.foreach('process', {
  handler: async (item, ctx) => ({ processed: item }),
  concurrency: 5,
})
```

### `.map(transform)`

Data transformation between steps.

```typescript theme={null}
.map((output) => output.items)
```

### `.connector(id, connector, resource, action, parameters)`

Connector call.

```typescript theme={null}
.connector('create', 'hubspot', 'contacts', 'create', {
  email: '{{input.email}}',
})
```

### `.output(transform)`

Final output builder.

```typescript theme={null}
.output((results, input) => ({
  id: input.id,
  response: results.process.text,
}))
```

### `.build()`

Create the `Workflow` instance.

```typescript theme={null}
const workflow = builder.build();
const result = await workflow.execute(input);
```

## `Workflow` Instance

### `.execute(input)`

Execute the workflow with validated input.

```typescript theme={null}
const result = await workflow.execute({ text: 'hello' });
```

### `.toGraph()`

Get the workflow structure as a serializable DAG.

```typescript theme={null}
const graph = workflow.toGraph();
// { id, name, nodes: GraphNode[], edges: GraphEdge[] }
```

### `.on(event, handler)`

Listen to execution events. See [Events](/core-concepts/workflows#real-time-events).

### `.id`, `.name`, `.steps`

Read-only getters.

## Step Helpers

```typescript theme={null}
// Create an agent step for use in .branch(), .switch(), .parallel()
const step = createAgentStep('id', agent, {
  prompt: '...',
  promptTemplate: '...',
});

// Create a function step
const step = createFunctionStep('id', async (input, ctx) => {
  return { processed: true };
});

// Create a connector step
const step = createConnectorStep('id', 'hubspot', 'contacts', 'create', {
  email: '{{input.email}}',
});
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Workflow Types" icon="code" href="/api-reference/types/workflow-types">
    TypeScript type definitions
  </Card>

  <Card title="Workflows Guide" icon="diagram-project" href="/core-concepts/workflows">
    Learn workflow concepts
  </Card>
</CardGroup>
