frontend_nyla/docs/API_ROUTES_DOCUMENTATION.md
2025-12-01 17:01:25 +01:00

14 KiB

API Routes Documentation

Overview

This documentation covers the Chat Playground and Workflow management API endpoints. These routes provide functionality for managing AI workflows, chat interactions, messages, logs, and related data.

Authentication

All endpoints require authentication via the getCurrentUser dependency, which validates the user's session/token. Rate limiting is applied at 120 requests per minute for all endpoints.


Chat Playground Routes

Base path: /api/chat/playground

1. Start Workflow

Endpoint: POST /api/chat/playground/start

Description: Starts a new workflow or continues an existing one based on the provided input.

Query Parameters:

  • workflowId (optional, string): ID of an existing workflow to continue
  • workflowMode (string, default: "Actionplan"): Workflow execution mode
    • "Actionplan": Traditional task planning workflow
    • "React": Iterative react-style processing

Request Body: UserInputRequest object containing:

{
  "input": "user's input text",
  "files": [...],  // optional file attachments
  "metadata": {...} // optional metadata
}

Response: ChatWorkflow object representing the created or continued workflow

Example Request:

POST /api/chat/playground/start?workflowMode=Actionplan
Content-Type: application/json

{
  "input": "Analyze the quarterly sales data",
  "files": [...],
  "metadata": {}
}

Example Response:

{
  "id": "wf_123456",
  "userId": "user_abc",
  "status": "running",
  "mode": "Actionplan",
  "messageIds": [...],
  "logIds": [...],
  "createdAt": 1234567890.0,
  ...
}

Use Cases:

  • User: Initiating a new AI conversation or task
  • AI: Starting automated workflow processing for scheduled tasks
  • Integration: Continuing an interrupted workflow from a previous session

2. Stop Workflow

Endpoint: POST /api/chat/playground/{workflowId}/stop

Description: Stops a running workflow, allowing graceful termination of ongoing processes.

Path Parameters:

  • workflowId (required, string): ID of the workflow to stop

Response: ChatWorkflow object with updated status

Example Request:

POST /api/chat/playground/wf_123456/stop

Example Response:

{
  "id": "wf_123456",
  "status": "stopped",
  "stoppedAt": 1234567890.0,
  ...
}

Use Cases:

  • User: Manually stopping a long-running task
  • AI: Implementing timeout mechanisms
  • System: Cleanup of abandoned workflows

3. Get Unified Chat Data

Endpoint: GET /api/chat/playground/{workflowId}/chatData

Description: Retrieves unified chat data including messages, logs, and statistics in chronological order. Supports incremental data fetching.

Path Parameters:

  • workflowId (required, string): ID of the workflow

Query Parameters:

  • afterTimestamp (optional, float): Unix timestamp to fetch only data created after this time

Response: Dictionary containing:

  • messages: Array of chat messages
  • logs: Array of log entries
  • stats: Array of statistics
  • documents: Array of attached documents
  • All sorted by _createdAt timestamp

Example Request:

GET /api/chat/playground/wf_123456/chatData?afterTimestamp=1234567800.0

Example Response:

{
  "messages": [
    {
      "id": "msg_001",
      "content": "Hello",
      "_createdAt": 1234567890.0,
      ...
    }
  ],
  "logs": [
    {
      "id": "log_001",
      "level": "info",
      "message": "Processing started",
      "_createdAt": 1234567891.0,
      ...
    }
  ],
  "stats": [...],
  "documents": [...]
}

Use Cases:

  • User: Real-time chat UI updates and polling for new data
  • AI: Monitoring workflow progress and synchronizing state
  • Mobile App: Efficient incremental data synchronization

Workflow Routes

Base path: /api/workflows

1. List All Workflows

Endpoint: GET /api/workflows/

Description: Retrieves all workflows for the currently authenticated user.

Response: Array of ChatWorkflow objects

Example Request:

GET /api/workflows/

Example Response:

[
  {
    "id": "wf_001",
    "userId": "user_abc",
    "status": "completed",
    "createdAt": 1234567890.0,
    ...
  },
  {
    "id": "wf_002",
    "userId": "user_abc",
    "status": "running",
    "createdAt": 1234567990.0,
    ...
  }
]

Use Cases:

  • User: Dashboard showing all their workflows
  • AI: Analyzing user's workflow history and patterns
  • Admin: User activity monitoring

2. Get Workflow by ID

Endpoint: GET /api/workflows/{workflowId}

Description: Retrieves detailed information about a specific workflow.

Path Parameters:

  • workflowId (required, string): ID of the workflow

Response: ChatWorkflow object

Example Request:

GET /api/workflows/wf_123456

Example Response:

{
  "id": "wf_123456",
  "userId": "user_abc",
  "status": "running",
  "mode": "Actionplan",
  "messageIds": ["msg_001", "msg_002"],
  "logIds": ["log_001", "log_002"],
  "createdAt": 1234567890.0,
  "updatedAt": 1234567990.0,
  ...
}

Use Cases:

  • User: Viewing specific workflow details
  • AI: Loading workflow state for processing
  • Debugging: Investigating workflow behavior

3. Update Workflow

Endpoint: PUT /api/workflows/{workflowId}

Description: Updates workflow properties. Requires ownership or modification permissions.

Path Parameters:

  • workflowId (required, string): ID of the workflow to update

Request Body: Dictionary with fields to update:

{
  "name": "Updated workflow name",
  "description": "Updated description",
  "tags": ["tag1", "tag2"],
  ...
}

Response: Updated ChatWorkflow object

Example Request:

PUT /api/workflows/wf_123456
Content-Type: application/json

{
  "name": "Sales Analysis Q4",
  "tags": ["sales", "analysis"]
}

Example Response:

{
  "id": "wf_123456",
  "name": "Sales Analysis Q4",
  "tags": ["sales", "analysis"],
  ...
}

Use Cases:

  • User: Renaming workflows for better organization
  • User: Adding tags and metadata
  • AI: Programmatically updating workflow metadata

4. Get Workflow Status

Endpoint: GET /api/workflows/{workflowId}/status

Description: Gets the current status of a workflow without loading all associated data.

Path Parameters:

  • workflowId (required, string): ID of the workflow

Response: ChatWorkflow object (lightweight status check)

Example Request:

GET /api/workflows/wf_123456/status

Use Response:

{
  "id": "wf_123456",
  "status": "running",
  "currentStep": "analyzing",
  "progress": 45,
  "updatedAt": 1234567990.0
}

Use Cases:

  • User: Quick status checks without loading full data
  • AI: Monitoring workflow progress
  • Mobile: Efficient polling for status updates

5. Get Workflow Logs

Endpoint: GET /api/workflows/{workflowId}/logs

Description: Retrieves logs for a workflow with support for selective data transfer.

Path Parameters:

  • workflowId (required, string): ID of the workflow

Query Parameters:

  • logId (optional, string): Log ID to fetch only newer logs (selective data transfer)

Response: Array of ChatLog objects

Example Request (All Logs):

GET /api/workflows/wf_123456/logs

Example Request (Incremental):

GET /api/workflows/wf_123456/logs?logId=log_050

Example Response:

[
  {
    "id": "log_001",
    "workflowId": "wf_123456",
    "level": "info",
    "message": "Workflow started",
    "timestamp": 1234567890.0,
    ...
  },
  {
    "id": "log_002",
    "workflowId": "wf_123456",
    "level": "warning",
    "message": "Slow response detected",
    "timestamp": 1234567900.0,
    ...
  }
]

Use Cases:

  • User: Viewing detailed execution logs for debugging
  • AI: Error analysis and troubleshooting
  • System: Audit trail and compliance

6. Get Workflow Messages

Endpoint: GET /api/workflows/{workflowId}/messages

Description: Retrieves messages for a workflow with support for selective data transfer.

Path Parameters:

  • workflowId (required, string): ID of the workflow

Query Parameters:

  • messageId (optional, string): Message ID to fetch only newer messages

Response: Array of ChatMessage objects

Example Request (All Messages):

GET /api/workflows/wf_123456/messages

Example Request (Incremental):

GET /api/workflows/wf_123456/messages?messageId=msg_100

Example Response:

[
  {
    "id": "msg_001",
    "workflowId": "wf_123456",
    "role": "user",
    "content": "Analyze the data",
    "timestamp": 1234567890.0,
    "files": [...],
    ...
  },
  {
    "id": "msg_002",
    "workflowId": "wf_123456",
    "role": "assistant",
    "content": "Processing your request...",
    "timestamp": 1234567900.0,
    ...
  }
]

Use Cases:

  • User: Viewing conversation history
  • AI: Context building for responses
  • UI: Chat interface message display

7. Delete Workflow

Endpoint: DELETE /api/workflows/{workflowId}

Description: Deletes a workflow and all its associated data (messages, logs, etc.). Requires ownership or deletion permissions.

Path Parameters:

  • workflowId (required, string): ID of the workflow to delete

Response: Dictionary with deletion confirmation

Example Request:

DELETE /api/workflows/wf_123456

Example Response:

{
  "id": "wf_123456",
  "message": "Workflow and associated data deleted successfully"
}

Use Cases:

  • User: Cleanup of old or unnecessary workflows
  • AI: Automated cleanup of expired workflows
  • Admin: Data management and compliance

8. Delete Workflow Message

Endpoint: DELETE /api/workflows/{workflowId}/messages/{messageId}

Description: Deletes a specific message from a workflow.

Path Parameters:

  • workflowId (required, string): ID of the workflow
  • messageId (required, string): ID of the message to delete

Response: Dictionary with deletion confirmation

Example Request:

DELETE /api/workflows/wf_123456/messages/msg_050

Example Response:

{
  "workflowId": "wf_123456",
  "messageId": "msg_050",
  "message": "Message deleted successfully"
}

Use Cases:

  • User: Removing sensitive or incorrect messages
  • AI: Content moderation
  • User: Editing conversation history

9. Delete File from Message

Endpoint: DELETE /api/workflows/{workflowId}/messages/{messageId}/files/{fileId}

Description: Deletes a file reference from a message within a workflow.

Path Parameters:

  • workflowId (required, string): ID of the workflow
  • messageId (required, string): ID of the message
  • fileId (required, string): ID of the file to delete

Response: Dictionary with deletion confirmation

Example Request:

DELETE /api/workflows/wf_123456/messages/msg_050/files/file_123

Example Response:

{
  "workflowId": "wf_123456",
  "messageId": "msg_050",
  "fileId": "file_123",
  "message": "File reference deleted successfully"
}

Use Cases:

  • User: Removing attached files for privacy
  • User: Fixing incorrect file uploads
  • System: Managing storage quotas

Error Handling

All endpoints may return the following HTTP status codes:

  • 200 OK: Successful request
  • 400 Bad Request: Invalid request parameters
  • 401 Unauthorized: Authentication required
  • 403 Forbidden: Insufficient permissions
  • 404 Not Found: Resource not found
  • 500 Internal Server Error: Server error

Example Error Response:

{
  "detail": "Error message describing what went wrong"
}

Best Practices

For Users:

  1. Polling Strategy: Use the afterTimestamp or logId/messageId parameters to implement efficient polling without redundant data transfer
  2. Error Handling: Always implement proper error handling and user feedback
  3. Rate Limiting: Be aware of the 120 requests/minute limit and implement exponential backoff
  4. Cleanup: Regularly delete old workflows to manage storage

For AI/Automation:

  1. Incremental Updates: Always use selective data transfer parameters to minimize bandwidth
  2. Status Checks: Use lightweight endpoints like /status for monitoring
  3. Timeout Handling: Implement proper stop logic for long-running workflows
  4. Logging: Monitor logs for debugging and performance analysis

For Developers:

  1. Caching: Cache workflow status to reduce API calls
  2. Webhooks: Consider implementing webhooks for real-time updates instead of polling
  3. Batch Operations: Group related operations to reduce network overhead
  4. Error Recovery: Implement retry logic with exponential backoff

Integration Examples

Starting a Workflow with File Upload

# Start workflow
POST /api/chat/playground/start?workflowMode=Actionplan
{
  "input": "Analyze this report",
  "files": [{"id": "file_001", "name": "report.pdf"}]
}

# Poll for updates
GET /api/chat/playground/wf_123456/chatData

# Continue polling with incremental updates
GET /api/chat/playground/wf_123456/chatData?afterTimestamp=1234567890.0

Monitoring Workflow Progress

# Start workflow
POST /api/chat/playground/start

# Check status periodically
GET /api/workflows/wf_123456/status

# Get detailed logs if status indicates issues
GET /api/workflows/wf_123456/logs

# Stop if needed
POST /api/chat/playground/wf_123456/stop

Cleanup Old Workflows

# List all workflows
GET /api/workflows/

# Filter for old/completed workflows and delete
DELETE /api/workflows/wf_old_123
DELETE /api/workflows/wf_old_124