# AI Workflows

> Build multi-step AI pipelines with sequential and parallel execution using the Stack0 SDK.

Build multi-step AI pipelines with sequential and parallel execution, variable passing between steps, and webhook notifications. Supports Anthropic, OpenAI, Gemini, Replicate, and more.

## Create a Workflow

Define a multi-step AI pipeline with dependencies:

create-workflow.tsCopy

```
import { Stack0 } from '@stack0/sdk' const stack0 = new Stack0({  apiKey: process.env.STACK0_API_KEY!}) const workflow = await stack0.workflows.create({  projectSlug: 'my-project',  slug: 'content-pipeline',  name: 'Content Generation Pipeline',  description: 'Generate blog posts with AI',  steps: [    {      id: 'generate-outline',      type: 'llm',      name: 'Generate Outline',      provider: 'anthropic',      model: 'claude-3-5-sonnet-20241022',      prompt: 'Create an outline for a blog post about {{topic}}',      outputVariable: 'outline',    },    {      id: 'write-content',      type: 'llm',      name: 'Write Content',      provider: 'openai',      model: 'gpt-4o',      prompt: 'Write a blog post based on this outline:\n\n{{steps.generate-outline.output}}',      dependsOn: ['generate-outline'],      outputVariable: 'content',    },  ],  variables: {    topic: { type: 'string', required: true },  },})
```

## Run a Workflow

Execute a workflow with input variables:

run-workflow.tsCopy

```
// Start workflow execution (async)const run = await stack0.workflows.run({  projectSlug: 'my-project',  workflowId: 'workflow_abc123',  variables: {    topic: 'AI in Healthcare',  },  webhook: {    url: 'https://yourapp.com/webhook',    secret: 'your-webhook-secret',  },  metadata: {    userId: 'user_123',  },}) console.log('Run ID:', run.id)console.log('Status:', run.status)
```

## Run and Wait

Execute a workflow and automatically wait for completion:

run-and-wait.tsCopy

```
const result = await stack0.workflows.runAndWait({  projectSlug: 'my-project',  workflowId: 'workflow_abc123',  variables: {    topic: 'AI in Healthcare',  },}, {  pollInterval: 2000,  timeout: 120000,}) console.log('Status:', result.status)console.log('Output:', result.output)console.log('Duration:', result.totalDurationMs, 'ms')console.log('Credits used:', result.creditsUsed)
```

## Step Types

Available step types for building workflows:

| Type | Description | Providers |
| --- | --- | --- |
| llm | Text generation with AI models | Anthropic, OpenAI, Gemini |
| image | Image generation | Replicate, Stack0 |
| video | Video generation | Replicate, Kling |
| audio | Audio generation | ElevenLabs, Replicate |
| code | Execute custom code | - |
| http | Make HTTP requests | - |
| transform | Transform data between steps | - |
| condition | Conditional branching | - |
| loop | Iterate over arrays | - |

## LLM Step Configuration

Configure text generation steps with AI models:

llm-step.tsCopy

```
{  id: 'generate-summary',  type: 'llm',  name: 'Summarize Content',  provider: 'anthropic', // 'anthropic' | 'openai' | 'gemini'  model: 'claude-3-5-sonnet-20241022',  prompt: 'Summarize this content: {{content}}',  systemPrompt: 'You are a helpful assistant that creates concise summaries.',  temperature: 0.7,  maxTokens: 4096,  responseFormat: 'text', // 'text' | 'json'  dependsOn: ['previous-step'],  outputVariable: 'summary',}
```

## Image Generation Step

Generate images with AI models:

image-step.tsCopy

```
{  id: 'generate-image',  type: 'image',  name: 'Generate Hero Image',  provider: 'replicate',  model: 'stability-ai/sdxl',  prompt: 'A futuristic city at sunset, high detail, photorealistic',  width: 1024,  height: 1024,  outputVariable: 'heroImage',}
```

## HTTP Step

Make HTTP requests to external APIs:

http-step.tsCopy

```
{  id: 'fetch-data',  type: 'http',  name: 'Fetch External Data',  method: 'POST',  url: 'https://api.example.com/data',  headers: {    'Authorization': 'Bearer {{apiKey}}',    'Content-Type': 'application/json',  },  body: {    query: '{{searchQuery}}',  },  outputVariable: 'externalData',}
```

## Variable Interpolation

Use `{{variable}}` syntax to reference variables and step outputs:

variable-interpolation.tsCopy

```
// Reference input variablesprompt: 'Write about {{topic}}' // Reference step outputsprompt: 'Expand on: {{steps.generate-outline.output}}' // Reference nested dataprompt: 'Use this title: {{steps.generate-metadata.output.title}}' // Reference arraysprompt: 'Process these items: {{steps.fetch-data.output.items}}'
```

## Get Run Status

Check the status of a workflow run:

get-run-status.tsCopy

```
const run = await stack0.workflows.getRun({  projectSlug: 'my-project',  id: 'run_xyz789',}) console.log('Status:', run.status)console.log('Progress:', `${run.completedSteps}/${run.totalSteps}`) // Check individual step statesfor (const [stepId, state] of Object.entries(run.stepStates)) {  console.log(`${stepId}: ${state.status}`)  if (state.error) {    console.log(`  Error: ${state.error}`)  }}
```

## List Runs

Query workflow runs with filters:

list-runs.tsCopy

```
const { items, total, hasMore } = await stack0.workflows.listRuns({  projectSlug: 'my-project',  workflowId: 'workflow_abc123', // Optional: filter by workflow  status: 'completed', // 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'  limit: 50,  offset: 0,}) for (const run of items) {  console.log(`[${run.status}] ${run.id}`)  console.log(`  Duration: ${run.totalDurationMs}ms`)  console.log(`  Credits: ${run.creditsUsed}`)}
```

## Cancel Run

Cancel a running workflow:

cancel-run.tsCopy

```
await stack0.workflows.cancelRun({  projectSlug: 'my-project',  id: 'run_xyz789',})
```

## Manage Workflows

List, update, and delete workflows:

manage-workflows.tsCopy

```
// List workflowsconst { workflows } = await stack0.workflows.list({  projectSlug: 'my-project',  limit: 20,}) // Get a specific workflowconst workflow = await stack0.workflows.get({  projectSlug: 'my-project',  id: 'workflow_abc123',}) // Update a workflowawait stack0.workflows.update({  projectSlug: 'my-project',  id: 'workflow_abc123',  name: 'Updated Pipeline Name',  isActive: true,}) // Delete a workflowawait stack0.workflows.delete({  projectSlug: 'my-project',  id: 'workflow_abc123',})
```

## Webhook Events

Configure webhooks to receive workflow notifications:

webhook-payload.jsonCopy

```
// Webhook payload example{  "event": "run.completed",  "timestamp": "2025-01-15T10:30:00Z",  "data": {    "id": "run_xyz789",    "workflowId": "workflow_abc123",    "status": "completed",    "output": {      "outline": "1. Introduction...",      "content": "AI is transforming..."    },    "totalDurationMs": 12500,    "creditsUsed": 15  }} // Available events:// - run.started// - run.completed// - run.failed// - step.completed
```

### Related

[Workflows API Reference](https://www.stack0.dev/docs/api-reference/workflows)[AI Extraction](https://www.stack0.dev/docs/sdk/extraction)[Error Handling](https://www.stack0.dev/docs/errors)

---

Source: https://www.stack0.dev/docs/sdk/workflows
llms.txt: https://www.stack0.dev/llms.txt
Sitemap: https://www.stack0.dev/sitemap.xml
Documentation: https://www.stack0.dev/docs
OpenAPI spec: https://www.stack0.dev/openapi.json
MCP server: https://api.stack0.dev/mcp
