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

# Relay Workflow Integration

> Execute Relay workflows for automated business process management

## Overview

Integrate Relay workflows with AgentFlow to automate business processes with AI-powered decision making. Relay combines workflow automation with human-in-the-loop approvals and AI assistance.

***

## Prerequisites

<CardGroup cols={2}>
  <Card title="Relay Account" icon="cloud">
    Sign up at [relay.app](https://relay.app)
  </Card>

  <Card title="API Access" icon="key">
    Generate API key from Relay settings
  </Card>

  <Card title="Workflow Created" icon="diagram-project">
    Build workflow with API trigger
  </Card>

  <Card title="AgentFlow Admin" icon="user-shield">
    Admin access required
  </Card>
</CardGroup>

***

## Step 1: Setup Relay Workflow

### Create New Workflow

1. Log in to [Relay.app](https://relay.app)
2. Click **Create Workflow**
3. Name: `AgentFlow Automation`
4. Description: `Process requests from AgentFlow chat`

### Add API Trigger

<Steps>
  <Step title="Select Trigger Type">
    * Click **Add Trigger**
    * Choose **API / Webhook**
    * Select **When API call is received**
  </Step>

  <Step title="Configure Trigger">
    * **Method**: POST
    * **Authentication**: API Key
    * Click **Generate API Key**
    * Copy the API key and webhook URL
  </Step>

  <Step title="Define Input Schema">
    ```json theme={null}
    {
      "message": "string",
      "user_id": "string",
      "timestamp": "string",
      "context": "object"
    }
    ```
  </Step>
</Steps>

### Build Workflow Logic

Add steps to process the request:

<Steps>
  <Step title="Parse Input">
    **Set Variables** step:

    ```
    message = {{trigger.message}}
    user_id = {{trigger.user_id}}
    timestamp = {{trigger.timestamp}}
    ```
  </Step>

  <Step title="AI Processing">
    **AI Assist** step:

    * Prompt: "Analyze this message: {{message}}"
    * Model: GPT-4
    * Output: analysis\_result
  </Step>

  <Step title="Conditional Logic">
    **Condition** step:

    ```
    If analysis_result.priority === "high"
      → Route to urgent path
    Else
      → Route to standard path
    ```
  </Step>

  <Step title="Execute Actions">
    * Update database
    * Send notifications
    * Call external APIs
    * Log to systems
  </Step>

  <Step title="Return Response">
    **API Response** step:

    ```json theme={null}
    {
      "data": {
        "execution_result": "{{workflow.output}}",
        "status": "success",
        "workflow_id": "{{workflow.id}}"
      }
    }
    ```
  </Step>
</Steps>

### Publish Workflow

1. Click **Test Workflow** with sample data
2. Verify all steps execute correctly
3. Click **Publish**
4. Note the workflow ID and API endpoint

***

## Step 2: Create AI Connection in AgentFlow

### Manual Setup

1. **Admin Dashboard** → **AI Models** → **Add Model**

2. Basic information:
   * **Name**: `Relay Business Automation`
   * **Model ID**: `relay-workflow-executor`
   * **Description**: `Automated business processes via Relay`

3. API Configuration:
   * **Endpoint**: `https://api.relay.app/v1/workflows/{{workflow_id}}/execute`
   * **Method**: POST

4. Headers:
   ```json theme={null}
   {
     "Authorization": "Bearer {{relay_api_key}}",
     "Content-Type": "application/json",
     "X-Relay-Version": "2024-01"
   }
   ```

5. Request schema:
   ```json theme={null}
   {
     "workflow_id": "{{workflow_id}}",
     "trigger_type": "webhook",
     "input_data": {
       "message": "{{message}}",
       "user_id": "{{user_id}}",
       "timestamp": "{{timestamp}}",
       "context": "{{context}}"
     },
     "execution_options": {
       "async": false,
       "timeout": 300,
       "retry_policy": "exponential_backoff",
       "max_retries": 3
     }
   }
   ```

6. Response path: `data.execution_result`

7. **Save**

***

## Step 3: Import via YAML

### YAML Configuration

Create `relay-workflow-config.yaml`:

```yaml theme={null}
name: "Relay Workflow Automation"
model_id: "relay-workflow-executor"
description: "Execute Relay workflows for automated business process management"
endpoint: "https://api.relay.app/v1/workflows/{{workflow_id}}/execute"
method: "POST"

headers:
  Authorization: "Bearer {{relay_api_key}}"
  Content-Type: "application/json"
  X-Relay-Version: "2024-01"

request_schema:
  workflow_id: "{{workflow_id}}"
  trigger_type: "webhook"
  input_data:
    message: "{{message}}"
    user_id: "{{user_id}}"
    timestamp: "{{timestamp}}"
    context: "{{context}}"
  execution_options:
    async: false
    timeout: 300
    retry_policy: "exponential_backoff"
    max_retries: 3

response_path: "data.execution_result"

message_format:
  preset: "custom"
  mapping:
    role:
      source: "role"
      target: "input_data.user_role"
      transform: "lowercase"
    content:
      source: "content"
      target: "input_data.message_content"
      transform: "none"
    timestamp:
      source: "timestamp"
      target: "input_data.timestamp"
      transform: "iso8601"
    context:
      source: "context"
      target: "input_data.additional_context"
      transform: "json_stringify"
  customFields:
    - name: "relay_metadata"
      value:
        platform: "relay"
        version: "2024-01"
        execution_type: "webhook"
        environment: "production"
      type: "object"
    - name: "workflow_settings"
      value:
        timeout: 300
        retry_policy: "exponential_backoff"
        max_retries: 3
        async_execution: false
      type: "object"

suggestion_prompts:
  - "Create a workflow for automated customer onboarding process"
  - "Set up a workflow for inventory management and reorder alerts"
  - "Build a workflow for employee performance review automation"
  - "Create a workflow for automated invoice processing and approval"
  - "Set up a workflow for lead scoring and CRM updates"
```

### Import Process

1. Replace placeholders with actual values
2. **Admin Dashboard** → **AI Models** → **Import Model**
3. Upload YAML file
4. Enter Relay API key
5. **Import**

***

## Step 4: Assign to Group

1. **Admin Dashboard** → **Groups**
2. Select group (e.g., "Operations Team")
3. **Manage Models** → Enable **Relay Workflow**
4. Set limits:
   * **Daily executions**: 1000
   * **Priority**: High
   * **Approval required**: No (or Yes for sensitive operations)
5. **Save Changes**

***

## Step 5: Use in Chat

### Trigger Workflows

1. **Chat Interface** → **New Conversation**
2. Select **Relay Workflow** model
3. Send message to execute workflow

### Example Scenarios

<CodeGroup>
  ```text Customer Onboarding theme={null}
  Start onboarding for new customer: Sarah Johnson, Company: TechCorp, Plan: Enterprise, Start Date: 2024-02-01
  ```

  ```text Approval Request theme={null}
  Request approval for $15,000 marketing campaign budget for Q2 social media ads
  ```

  ```text Inventory Alert theme={null}
  Check inventory levels for Product SKU-12345 and reorder if below 100 units
  ```

  ```text Performance Review theme={null}
  Schedule performance review for employee ID: EMP-789, Manager: John Doe, Due: Next Friday
  ```
</CodeGroup>

***

## Advanced Workflow Features

### Human-in-the-Loop Approvals

Relay's unique feature: Add approval steps

<Steps>
  <Step title="Add Approval Step">
    * Click **Add Step** → **Request Approval**
    * Configure approvers
    * Set approval conditions
  </Step>

  <Step title="Configure Approval">
    ```json theme={null}
    {
      "approvers": ["manager@company.com", "cfo@company.com"],
      "require_all": false,
      "timeout": "24h",
      "message": "Approve {{request_details}}"
    }
    ```
  </Step>

  <Step title="Handle Response">
    * **If Approved** → Continue workflow
    * **If Rejected** → Send notification and end
    * **If Timeout** → Escalate to admin
  </Step>
</Steps>

### AI-Powered Decision Making

Use Relay's AI capabilities:

```javascript theme={null}
// AI Assist step
{
  "prompt": "Analyze this request and determine priority level",
  "input": "{{trigger.message}}",
  "model": "gpt-4",
  "output_format": {
    "priority": "string",
    "reasoning": "string",
    "recommended_action": "string"
  }
}
```

### Multi-App Workflows

Connect multiple services:

<Steps>
  <Step title="CRM Integration">
    Salesforce → Search/Create contact
  </Step>

  <Step title="Communication">
    Slack → Send notification
  </Step>

  <Step title="Document Management">
    Google Drive → Create folder & files
  </Step>

  <Step title="Project Management">
    Asana → Create tasks
  </Step>

  <Step title="Analytics">
    Airtable → Log execution
  </Step>
</Steps>

***

## Workflow Templates

### 1. Customer Onboarding

```yaml theme={null}
Trigger: API Call
Steps:
  1. Parse customer data
  2. Create CRM record (Salesforce)
  3. Generate welcome email (SendGrid)
  4. Create Google Workspace account
  5. Setup project in Asana
  6. Assign to success manager
  7. Schedule kickoff call (Calendly)
  8. Send summary to team (Slack)
Response: Onboarding status
```

### 2. Invoice Approval Workflow

```yaml theme={null}
Trigger: API Call
Steps:
  1. Parse invoice details
  2. Validate against PO (Database)
  3. AI Review for anomalies
  4. If > $10k → Request CFO approval
  5. If approved → Process payment (Stripe)
  6. Update accounting system (QuickBooks)
  7. Send confirmation (Email)
  8. Archive in Google Drive
Response: Payment status
```

### 3. Lead Qualification

```yaml theme={null}
Trigger: API Call
Steps:
  1. Extract lead information
  2. Enrich data (Clearbit)
  3. AI Scoring (GPT-4)
  4. If score > 80:
     - Add to CRM (high priority)
     - Alert sales team (Slack)
     - Schedule follow-up (Calendly)
  5. Else:
     - Add to nurture campaign (HubSpot)
  6. Log in database
Response: Lead score & next steps
```

***

## Error Handling

### Retry Logic

Relay automatically retries failed steps:

```yaml theme={null}
retry_policy:
  max_attempts: 3
  backoff_strategy: exponential
  initial_delay: 1000  # ms
  max_delay: 30000     # ms
```

### Error Notifications

Configure alerts for failures:

```yaml theme={null}
error_handling:
  on_failure:
    - send_slack_alert:
        channel: "#ops-alerts"
        message: "Workflow {{workflow.name}} failed: {{error.message}}"
    - send_email:
        to: "admin@company.com"
        subject: "Workflow Error"
    - log_to_database:
        table: "workflow_errors"
```

### Fallback Actions

Define fallback behavior:

```javascript theme={null}
// Condition step
if (step.failed) {
  // Execute fallback
  return {
    action: "fallback",
    notify: "admin",
    message: "Primary action failed, using fallback"
  };
}
```

***

## Monitoring & Analytics

### Execution Dashboard

View in Relay:

* **Runs**: All workflow executions
* **Status**: Success/Failed/Running
* **Duration**: Execution time
* **Logs**: Detailed step logs

### AgentFlow Analytics

Track performance:

1. **Analytics Dashboard** → **Model Usage**
2. Filter by Relay workflows
3. Monitor:
   * Success rate
   * Average response time
   * Error patterns
   * Usage trends

### Custom Metrics

Export data for analysis:

```javascript theme={null}
// At end of workflow
{
  "metrics": {
    "execution_time": "{{workflow.duration}}",
    "steps_completed": "{{workflow.steps_count}}",
    "user_id": "{{input.user_id}}",
    "outcome": "{{workflow.result}}"
  }
}
```

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Workflow Not Triggered">
    **Check**:

    * API key is valid
    * Workflow is published (not draft)
    * Endpoint URL is correct
    * Request format matches schema

    **Debug**: View execution log in Relay dashboard
  </Accordion>

  <Accordion title="Step Failure">
    **Common causes**:

    * Invalid credentials for integrated app
    * API rate limit exceeded
    * Timeout on long-running operation
    * Data format mismatch

    **Fix**: Check step logs and adjust configuration
  </Accordion>

  <Accordion title="Approval Timeout">
    **Issue**: Approvers didn't respond in time

    **Solutions**:

    * Increase timeout duration
    * Add more approvers
    * Set up escalation path
    * Enable reminder notifications
  </Accordion>

  <Accordion title="Response Not Received">
    **Check**:

    * API Response step is configured
    * Response format matches expected schema
    * No errors in previous steps

    **Fix**: Test workflow manually in Relay
  </Accordion>
</AccordionGroup>

***

## Security & Compliance

### API Key Management

<Steps>
  <Step title="Generate Keys">
    Create separate keys for different environments:

    * Development
    * Staging
    * Production
  </Step>

  <Step title="Rotate Regularly">
    Update keys every 90 days
  </Step>

  <Step title="Monitor Usage">
    Track API calls for anomalies
  </Step>

  <Step title="Revoke Compromised Keys">
    Immediately disable if breach suspected
  </Step>
</Steps>

### Data Privacy

* **Encryption**: All data encrypted in transit (TLS 1.3)
* **Storage**: Encrypted at rest (AES-256)
* **Retention**: Configure data retention policies
* **Compliance**: GDPR, SOC 2, HIPAA ready

### Access Control

Implement least privilege:

```yaml theme={null}
permissions:
  workflow_execution:
    - role: admin
      access: full
    - role: user
      access: execute_only
    - role: viewer
      access: read_logs
```

***

## Best Practices

<CardGroup cols={2}>
  <Card title="Workflow Design" icon="diagram-project">
    Keep workflows focused and modular
  </Card>

  <Card title="Error Handling" icon="shield-halved">
    Always add try-catch and fallbacks
  </Card>

  <Card title="Testing" icon="vial">
    Test thoroughly with edge cases
  </Card>

  <Card title="Documentation" icon="book">
    Document purpose and data flow
  </Card>

  <Card title="Version Control" icon="code-branch">
    Version workflows for rollback capability
  </Card>

  <Card title="Monitoring" icon="chart-line">
    Set up alerts for critical workflows
  </Card>

  <Card title="Performance" icon="gauge">
    Optimize for speed and efficiency
  </Card>

  <Card title="Security" icon="lock">
    Regular security audits
  </Card>
</CardGroup>

***

## Relay vs Other Platforms

| Feature         | Relay        | n8n           | Make.com      |
| --------------- | ------------ | ------------- | ------------- |
| Human Approvals | ✅ Built-in   | ❌ Manual      | ⚠️ Limited    |
| AI Assistance   | ✅ Native     | ⚠️ Via API    | ⚠️ Via API    |
| Visual Builder  | ✅            | ✅             | ✅             |
| Self-Hosted     | ❌            | ✅             | ❌             |
| Pricing         | Per workflow | Per execution | Per operation |
| Free Tier       | ✅ Limited    | ✅ 5 workflows | ✅ 1K ops      |

***

## Next Steps

<CardGroup cols={2}>
  <Card title="LangChain Agents" icon="brain" href="/examples/langchain-agent">
    Build AI agents with tools
  </Card>

  <Card title="Cloud Functions" icon="cloud" href="/examples/cloud-run-function">
    Serverless automation
  </Card>

  <Card title="OpenAI Assistants" icon="robot" href="/examples/openai-agent-builder">
    Advanced AI agents
  </Card>

  <Card title="Analytics" icon="chart-simple" href="/analytics/usage-metrics">
    Monitor workflow performance
  </Card>
</CardGroup>
