kaman.ai

Docs

Documentation

Guides, use cases & API reference

  • Overview
    • Getting Started
    • Platform Overview
  • Features
    • Features Overview
    • AI Assistant
    • Workflow Automation
    • Intelligent Memory
    • Data Management
    • Universal Integrations
    • Communication Channels
    • Security & Control
  • Use Cases Overview
  • Financial Services
  • Fraud Detection
  • Supply Chain
  • Technical Support
  • Software Development
  • Smart ETL
  • Data Governance
  • ESG Reporting
  • TAC Management
  • Reference
    • API Reference
  • Guides
    • Getting Started
    • Authentication
  • Endpoints
    • Workflows API
    • Tools API
    • KDL (Data Lake) API
    • OpenAI-Compatible API
    • A2A Protocol
    • Skills API
    • Knowledge Base (RAG) API
    • Communication Channels

Workflows API

Workflows are automated multi-step processes that execute a series of connected tools and functions. This guide covers how to list and execute workflows via the API.

Overview

A workflow consists of:

  • Nodes: Individual steps (tools/functions) in the workflow
  • Edges: Connections that pass data between nodes
  • Config: Execution settings like timeouts and retries

List Workflows

Returns a list of all workflows accessible to the authenticated user.

Endpoint

GET /api/agent/workflows

Parameters

ParameterTypeDescription
searchstringFilter by name or description
limitintegerMax results (default: 50)
offsetintegerPagination offset

Example

bash
curl -X GET "http://kaman.ai/api/agent/workflows?search=sales&limit=10" \
  -H "Authorization: Bearer kam_your_api_key"

Response

json
[
  {
    "id": 123,
    "name": "Sales Report Generator",
    "description": "Generates monthly sales reports",
    "created_at": "2024-01-15T10:30:00Z"
  },
  {
    "id": 124,
    "name": "Customer Data Sync",
    "description": "Syncs customer data from CRM",
    "created_at": "2024-01-10T08:00:00Z"
  }
]

Execute a Workflow

Triggers execution of the specified workflow with the provided inputs. The workflow will execute all nodes in the defined order, passing data between nodes according to the edge mappings.

Endpoint

POST /api/agent/workflows/{id}/execute

Path Parameters

ParameterTypeDescription
idintegerWorkflow ID to execute

Request Body

The request body should contain the input values required by the workflow's starting nodes.

bash
curl -X POST "http://kaman.ai/api/agent/workflows/123/execute" \
  -H "Authorization: Bearer kam_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": {
      "startDate": "2024-01-01",
      "endDate": "2024-12-31",
      "region": "APAC"
    }
  }'

Response (Success)

json
{
  "runId": "wf_123:550e8400-e29b-41d4-a716-446655440000",
  "status": "completed",
  "result": {
    "report": {
      "totalSales": 1250000,
      "growth": 15.3
    }
  },
  "executedNodes": ["fetch_data", "process", "generate_report"],
  "duration": 3450
}

Response (Human Input Needed)

Some workflows may pause to request human input:

json
{
  "error": "Human input needed",
  "fieldsNeeded": ["approvalDecision", "comments"],
  "instanceId": "wf_123:abc123"
}

Resuming an Interrupted Workflow

To continue a workflow that requested human input, include the instanceId:

bash
curl -X POST "http://kaman.ai/api/agent/workflows/123/execute" \
  -H "Authorization: Bearer kam_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "instanceId": "wf_123:abc123",
    "inputs": {
      "approvalDecision": "approved",
      "comments": "Looks good"
    }
  }'

Code Examples

TypeScript

typescript
const API_KEY = process.env.KAMAN_API_KEY;
const BASE_URL = 'http://kaman.ai';

// List workflows
async function listWorkflows(search?: string) {
  const params = search ? `?search=${encodeURIComponent(search)}` : '';
  const response = await fetch(`${BASE_URL}/api/agent/workflows${params}`, {
    headers: {
      'Authorization': `Bearer ${API_KEY}`
    }
  });
  return response.json();
}

// Execute a workflow
async function executeWorkflow(
  workflowId: number,
  inputs: Record<string, any>,
  instanceId?: string
) {
  const response = await fetch(
    `${BASE_URL}/api/agent/workflows/${workflowId}/execute`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ inputs, instanceId })
    }
  );

  const result = await response.json();

  if (result.error === 'Human input needed') {
    console.log('Workflow needs human input:', result.fieldsNeeded);
    return { needsInput: true, ...result };
  }

  return result;
}

// Example usage
const workflows = await listWorkflows('sales');
const result = await executeWorkflow(123, {
  startDate: '2024-01-01',
  endDate: '2024-12-31'
});

Python

python
import requests
import os
from typing import Optional, Dict, Any, List

class KamanWorkflows:
    def __init__(self, base_url: str):
        self.base_url = f'{base_url}/api/agent'
        self.headers = {
            'Authorization': f'Bearer {os.getenv("KAMAN_API_KEY")}',
            'Content-Type': 'application/json'
        }

    def list_workflows(self, search: Optional[str] = None, limit: int = 50) -> List[Dict]:
        params = {'limit': limit}
        if search:
            params['search'] = search

        response = requests.get(
            f'{self.base_url}/workflows',
            params=params,
            headers=self.headers
        )
        return response.json()

    def execute_workflow(
        self,
        workflow_id: int,
        inputs: Dict[str, Any],
        instance_id: Optional[str] = None
    ) -> Dict[str, Any]:
        payload = {'inputs': inputs}
        if instance_id:
            payload['instanceId'] = instance_id

        response = requests.post(
            f'{self.base_url}/workflows/{workflow_id}/execute',
            json=payload,
            headers=self.headers
        )
        result = response.json()

        if result.get('error') == 'Human input needed':
            print(f'Workflow needs input: {result["fieldsNeeded"]}')
            return {'needs_input': True, **result}

        return result

# Example usage
client = KamanWorkflows('http://kaman.ai')

# List workflows
workflows = client.list_workflows(search='sales')

# Execute a workflow
result = client.execute_workflow(123, {
    'startDate': '2024-01-01',
    'endDate': '2024-12-31'
})

Error Handling

Common Errors

StatusErrorDescription
400Human input neededWorkflow requires additional inputs (see fieldsNeeded)
400Invalid inputsMissing required input fields
401UnauthorizedInvalid or missing authentication
404Workflow not foundInvalid workflow ID
500Execution failedError during workflow execution

Error Response

json
{
  "error": "Workflow execution failed",
  "details": "Node 'fetch_data' failed: Connection timeout",
  "runId": "wf_123:abc123"
}

Best Practices

  1. Handle Interrupts: Implement handlers for human-in-the-loop workflows
  2. Store Instance IDs: Save the instanceId when a workflow needs input so you can resume later
  3. Set Timeouts: Configure appropriate timeouts on your HTTP client for long-running workflows
  4. Retry Failed Runs: Implement retry logic for transient failures

Next Steps

  • Authentication - Learn about API authentication
  • KDL API - Query data from your data lake
  • Getting Started - Quick start guide

On this page

  • Overview
  • List Workflows
  • Endpoint
  • Parameters
  • Example
  • Response
  • Execute a Workflow
  • Endpoint
  • Path Parameters
  • Request Body
  • Response (Success)
  • Response (Human Input Needed)
  • Resuming an Interrupted Workflow
  • Code Examples
  • TypeScript
  • Python
  • Error Handling
  • Common Errors
  • Error Response
  • Best Practices
  • Next Steps