Waterflai
  • Welcome to Waterflai
  • Getting Started
    • Concepts
    • Quickstart
  • Providers
    • Providers Overview
    • Providers setup
    • AI models
    • Choose the right models
  • Knowledge
    • Knowledge Overview
    • Knowledge connectors
    • Knowledge collections
  • Studio
    • Studio Overview
    • Studio Builders
      • Light Builder
      • Dream Builder
      • Workflow Builder
      • Flow components (nodes)
        • Input Node
        • Output Node
        • LLM model Node
        • Multimodal LLM Node
        • Dall-E 2 (image generation) Node
        • Dall-E 3 (image generation) Node
        • Sora video generation Node
        • Text-to-Speech (TTS) Node
        • Speech-to-Text (STT) Node
        • OCR Node
        • Agent Node
        • Reranker Node
        • Knowledge retrieval Node
        • Vector store insert Node
        • Vector store record delete Node
        • Gitbook loader
        • Notion Database Node
        • Figma Node
        • Webpage scraper Node
        • Sitemap Scraper Node
        • API Request Node
        • Document metadata extraction Node
        • Document metadata update Node
        • Character splitter Node
        • HTML splitter Node
        • Markdown Splitter
        • Calculator tool Node
        • Text as tool Node
        • Knowledge retrieval tool Node
        • Conditional Node
        • Iteration loop Node
      • Testing and Debugging
    • Publishing
    • Integration with API
    • Embedding in website
  • Analytics
    • Analytics Overview
    • Dashboards
    • Logs
  • Administration
    • Organization users
    • Workspace
    • Security and permissions
  • Troubleshooting
    • Support
Powered by GitBook
On this page
  • Waterflai API Documentation
  • API Overview
  • Managing API Keys
  • API Endpoints
  • Content Types and Message Handling
  • File Handling
  • Code Examples
  • Best Practices
  • Troubleshooting
  1. Studio

Integration with API

Waterflai API Documentation

This comprehensive guide explains how to integrate your Waterflai chatbots with external applications using our API. You'll learn how to manage API keys, understand different endpoints, handle various content types, and implement best practices for integration.

API Overview

Waterflai provides different API endpoints based on your chatbot type:

  • Simple Chatbots: OpenAI-compatible endpoint for basic chat interactions

  • Dream Builder (Chatflows): Specialized endpoints for complex conversational flows

  • Workflow Builder: Dedicated endpoints for automated workflow execution

Managing API Keys

API keys are essential for authenticating your requests to the Waterflai API. Here's how to manage them:

Viewing API Keys

  1. In the Studio page, click the "API Keys" button

  2. A modal will open, displaying a list of your existing API keys

  3. Each key shows its name and the actual key value

Creating a New API Key

  1. Click the "API Keys" button, then select "New API Key" from the dropdown

  2. In the Create API Key modal:

    • Enter a name for your new key

    • Click "Create API Key"

  3. The new key will be displayed. Copy it immediately, as you won't be able to see it again

Important: Store your API key securely. It won't be displayed again after you close the modal.

Deleting an API Key

  1. In the API Keys list, click the trash icon next to the key you want to delete

  2. Confirm the deletion in the popup

Note: Deleting an API key will immediately revoke access for any applications using that key.

API Endpoints

Dream Builder (Chatflow) Endpoints

Execute Chatflow

  • Endpoint: POST https://api.waterflai.ai/execute_chatflow/{chatflow_id}/execute

  • Purpose: Execute a chatflow and receive the complete response

  • Headers:

    Authorization: Bearer YOUR_API_KEY_HERE
    Content-Type: application/json
  • Request Body (option 1: string message):

    {
      "input_data": {
        "query": "Your message here",
        "custom_input": "..."
      }
    }
  • {
      "input_data": {
        "query": [
          {
            "role": "assistant",
            "content": "Initial message from the assistant"
          },
          {
            "role": "user",
            "content": "User message here"
          }
        ],
        "custom_input": "..."
      }
    }

  • Response Format:

    {
      "model": "chatflow_id",
      "choices": [
        {
          "index": 0,
          "message": {
            "role": "assistant",
            "content": "Response content"
          }
        }
      ],
      "usage": {
        "prompt_tokens": 0,
        "completion_tokens": 0,
        "total_tokens": 0
      }
    }

Stream Execute Chatflow

  • Endpoint: POST https://api.waterflai.ai/execute_chatflow/{chatflow_id}/stream_execute

  • Purpose: Execute a chatflow with real-time streaming updates (adequat for long time execution flows)

  • Headers: Same as non-streaming endpoint

  • Request Body: Same as non-streaming endpoint

  • Response: Server-Sent Events (SSE) stream with the following events:

    {
      "type": "execution_started",
      "timestamp": "2025-02-11T14:34:08.678088"
    }
    {
      "type": "node_started",
      "node_id": "inputNodeType-19d7",
      "node_label": "Input",
      "node_type": "inputNodeType",
      "timestamp": "2025-02-11T14:34:08.681607"
    }
    {
      "type": "node_completed",
      "node_id": "inputNodeType-19d7",
      "node_label": "Input",
      "node_type": "inputNodeType",
      "timestamp": "2025-02-11T14:34:08.687736"
    }
    {
      "type": "execution_completed",
      "final_output": {
        "query": "Hello.",
        "response": "Response content"
      }
    }

Workflow Builder Endpoints

Execute Workflow

  • Endpoint: POST https://api.waterflai.ai/execute_workflow/{workflow_id}/execute

  • Purpose: Execute a workflow and receive the complete response

  • Headers: Same as chatflow endpoints

  • Request Body (option 1: string message):

    {
      "input_data": {
        "query": "Your message here",
        "custom_input": "..."
      }
    }
  • {
      "input_data": {
        "query": [
          {
            "role": "assistant",
            "content": "Initial message from the assistant"
          },
          {
            "role": "user",
            "content": "User message here"
          }
        ],
        "custom_input": "..."
      }
    }
  • Response: JSON object containing workflow execution results

Stream Execute Workflow

  • Endpoint: POST https://api.waterflai.ai/execute_workflow/{workflow_id}/stream_execute

  • Purpose: Execute a workflow with streaming updates

  • Headers: Same as non-streaming endpoint

  • Request Body: Same as non-streaming endpoint

  • Response: SSE stream with execution updates

Content Types and Message Handling

Text Messages

For simple text messages, use a string directly:

{
  "role": "user",
  "content": "Hello, how can you help me today?"
}

Image Messages

For messages containing images, use the multimodal content format with base64-encoded images:

{
  "role": "user",
  "content": [
    {
      "type": "text",
      "text": "What can you tell me about this image?"
    },
    {
      "type": "image_url",
      "image_url": {
        "data": "data:image/jpeg;filename=photo.jpg;base64,/9j/4AAQSkZJRg..."
      }
    }
  ]
}

Mixed Content Messages

You can combine multiple content types in a single message:

{
  "role": "user",
  "content": [
    {
      "type": "text",
      "text": "I found these two diagrams. Can you compare them?"
    },
    {
      "type": "image_url",
      "image_url": {
        "data": "data:image/png;filename=diagram1.png;base64,iVBORw0KGgoAAAANSU..."
      }
    },
    {
      "type": "image_url",
      "image_url": {
        "data": "data:image/png;filename=diagram2.png;base64,iVBORw0KGgoAAAANSU..."
      }
    }
  ]
}

File Handling

Text Files

Upload text files using base64-encoded data with metadata:

data:[MIME type];filename=[filename];base64,[encoded content]

Examples:

# For PDF files
data:application/pdf;filename=document.pdf;base64,JVBERi0xLjcKCjEgMCBvYmo...

# For PPTX
data:application/vnd.openxmlformats-officedocument.presentationml.presentation;filename=document.pdf;base64,JVBERi0xLjcKCjEgMCBvYmo...

Image Files

Two options for image files:

  1. Base64-encoded data:

data:image/jpeg;filename=photo.jpg;base64,/9j/4AAQSkZJRg...
  1. Direct URL:

{
  "type": "image_url",
  "image_url": {
    "url": "https://example.com/image.jpg"
  }
}

Code Examples

Python

import requests

api_key = 'YOUR_API_KEY_HERE'
headers = {
    'Authorization': f'Bearer {api_key}',
    'Content-Type': 'application/json'
}

# Regular execution
data = {
    'input_data': {
      'query': 'Hello, how are you?'
    }
}

response = requests.post(
    'https://api.waterflai.ai/execute_chatflow/CHATFLOW_ID/execute',
    json=data,
    headers=headers
)
print(response.json()['choices'][0]['message']['content'])

# Streaming execution
def handle_stream():
    response = requests.post(
        'https://api.waterflai.ai/execute_chatflow/CHATFLOW_ID/stream_execute',
        json=data,
        headers=headers,
        stream=True
    )
    
    for line in response.iter_lines():
        if line:
            print(line.decode('utf-8'))

# File handling
def convert_file_to_base64(file_path):
    import base64
    with open(file_path, 'rb') as file:
        return base64.b64encode(file.read()).decode('utf-8')

JavaScript

// Regular execution
const response = await fetch('https://api.waterflai.ai/execute_chatflow/CHATFLOW_ID/execute', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY_HERE',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    input_data: { query: 'Hello, how are you?' }
  })
});

const data = await response.json();
console.log(data.choices[0].message.content);

// Streaming execution
const eventSource = new EventSource('https://api.waterflai.ai/execute_chatflow/CHATFLOW_ID/stream_execute', {
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY_HERE'
  }
});

eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log(data);
};

// File handling helper
const convertFileToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      if (typeof reader.result === 'string') {
        if (file.type.startsWith('image/')) {
          resolve(`data:${file.type};base64,${reader.result.split(',')[1]}`);
        } else {
          resolve(`data:${file.type};filename=${file.name};base64,${reader.result.split(',')[1]}`);
        }
      } else {
        reject(new Error('Failed to convert file to base64'));
      }
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
};

Best Practices

Security

  1. Store API keys securely and never expose them in client-side code

  2. Regularly rotate API keys

  3. Monitor API usage for suspicious activity

Performance

  1. Use streaming endpoints for real-time updates (and for long duration flow execution to avoid Timeout error)

  2. Implement proper timeout handling

  3. Cache responses when appropriate

Troubleshooting

Common Issues

  1. Authentication Errors

    • Verify API key is valid and active

    • Check Authorization header format

    • Verify proper encoding of the Authorization header

  2. Request Format Errors

    • Validate JSON structure

    • Verify required fields are present

    • Ensure proper encoding of special characters

  3. File Upload Issues

    • Check file format support

    • Ensure proper base64 encoding

    • Validate file metadata format

PreviousPublishingNextEmbedding in website

Last updated 2 months ago

Request Body (option 2: list of messages, see for more detail on message types):

Request Body (option 2: list of messages, see for more detail on message types):

below
below