Chat History & Conversation Management

⚠️ Plan Requirement
Chat history API access requires Starter plan or higher.

View plan features →

Manage conversation history, retrieve messages, and build conversation management features using the dialektai Chat History API.

When to Use This API

Use the Chat History API when you need to:

Prerequisites

Before you begin, you'll need:

  1. dialektai organization account with Starter plan or higher
  2. Organization API key (sk_*) - see API Integration Guide
  3. X-Scope-Id header - User/customer identifier for conversation tracking
ℹ️ Required Header: X-Scope-Id
All chat history endpoints require the X-Scope-Id header to identify the end-user scope. This ensures conversations are properly isolated per user.

Example: X-Scope-Id: user-123 or X-Scope-Id: customer-456

Authentication

Chat History API uses the same authentication as standard API integration:

Headers Required:

X-API-Key: sk_your_organization_key_here
X-Scope-Id: user-123
Content-Type: application/json

For details on creating organization API keys, see the API Integration Guide - Authentication.

Conversation Management

List Conversations

Get a paginated list of all conversations for a specific user.

Endpoint: GET /api/v1/chat/conversations

Query Parameters:

Parameter Type Required Default Description
limit integer No 20 Max conversations to return (max: 100)
cursor string No null Pagination cursor from previous response

Example Request:

curl -X GET "https://api.dialektai.com/api/v1/chat/conversations?limit=20" \
  -H "X-API-Key: sk_your_organization_key_here" \
  -H "X-Scope-Id: user-123"

Response:

{
  "success": true,
  "data": {
    "conversations": [
      {
        "id": "550e8400-e29b-41d4-a716-446655440000",
        "organizationId": 42,
        "scopeId": "user-123",
        "title": "Sales Analysis",
        "lastMessageAt": "2025-01-15T14:30:00Z",
        "messageCount": 12,
        "createdAt": "2025-01-15T10:00:00Z"
      }
    ],
    "cursor": "eyJpZCI6IjEyMyIsInRpbWVzdGFtcCI6MTY0NzM1MjAwMH0=",
    "hasMore": true
  }
}

Get Conversation Messages

Retrieve messages from a specific conversation or all messages for a user.

Endpoint: GET /api/v1/chat/history

Query Parameters:

Parameter Type Required Default Description
conversation_id string (UUID) No null Filter by specific conversation
limit integer No 50 Max messages to return (max: 200)
cursor string No null Pagination cursor from previous response

Example Request (Specific Conversation):

curl -X GET "https://api.dialektai.com/api/v1/chat/history?conversation_id=550e8400-e29b-41d4-a716-446655440000&limit=50" \
  -H "X-API-Key: sk_your_organization_key_here" \
  -H "X-Scope-Id: user-123"

Example Request (All User Messages):

curl -X GET "https://api.dialektai.com/api/v1/chat/history?limit=50" \
  -H "X-API-Key: sk_your_organization_key_here" \
  -H "X-Scope-Id: user-123"

Response:

{
  "success": true,
  "data": {
    "messages": [
      {
        "id": "msg-001",
        "content": "Show me top customers by revenue",
        "sender": "USER",
        "timestamp": "2025-01-15T10:05:00Z",
        "type": "text",
        "metadata": {}
      },
      {
        "id": "msg-002",
        "content": "Here are the top 10 customers by revenue...",
        "sender": "ASSISTANT",
        "timestamp": "2025-01-15T10:05:03Z",
        "type": "text",
        "metadata": {
          "query_type": "data_retrieval",
          "execution_time_ms": 1234
        }
      }
    ],
    "cursor": "eyJpZCI6Im1zZy0wMDIiLCJ0aW1lc3RhbXAiOjE2NDczNTIwMDB9",
    "hasMore": true
  }
}

Pagination

The Chat History API uses cursor-based pagination for efficient data retrieval.

How it works:

  1. Make initial request (no cursor)
  2. Check hasMore in response
  3. If hasMore: true, use cursor value in next request
  4. Repeat until hasMore: false

Example Pagination Loop (Python):

import requests

API_KEY = "sk_your_key_here"
SCOPE_ID = "user-123"

def get_all_conversations():
    """Fetch all conversations with pagination."""
    conversations = []
    cursor = None

    while True:
        url = "https://api.dialektai.com/api/v1/chat/conversations"
        params = {"limit": 20}
        if cursor:
            params["cursor"] = cursor

        response = requests.get(
            url,
            params=params,
            headers={
                "X-API-Key": API_KEY,
                "X-Scope-Id": SCOPE_ID
            }
        )

        data = response.json()["data"]
        conversations.extend(data["conversations"])

        if not data["hasMore"]:
            break

        cursor = data["cursor"]

    return conversations

# Usage
all_conversations = get_all_conversations()
print(f"Total conversations: {len(all_conversations)}")

Session-Specific Operations

Send Message to Session

Send a message to a specific conversation session (alternative to simple POST /api/v1/chat/message).

Endpoint: POST /api/v1/chat/{session_id}/message

Rate Limits:

Example Request:

curl -X POST "https://api.dialektai.com/api/v1/chat/550e8400-e29b-41d4-a716-446655440000/message" \
  -H "X-API-Key: sk_your_organization_key_here" \
  -H "X-Scope-Id: user-123" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "What were the top products last quarter?",
    "database_id": "db-uuid-here"
  }'

Response:

{
  "success": true,
  "data": {
    "message": "Based on your data, here are the top products...",
    "conversation_id": "550e8400-e29b-41d4-a716-446655440000",
    "sources": [...],
    "query_type": "data_retrieval",
    "execution_time_ms": 1456
  }
}

Get Session History

Retrieve conversation history for a specific session from PostgreSQL storage.

Endpoint: GET /api/v1/chat/{session_id}/history

Example Request:

curl -X GET "https://api.dialektai.com/api/v1/chat/550e8400-e29b-41d4-a716-446655440000/history" \
  -H "X-API-Key: sk_your_organization_key_here" \
  -H "X-Scope-Id: user-123"

Response:

{
  "success": true,
  "data": {
    "session_id": "550e8400-e29b-41d4-a716-446655440000",
    "messages": [
      {
        "role": "USER",
        "content": "Show me sales data",
        "timestamp": "2025-01-15T10:00:00Z"
      },
      {
        "role": "ASSISTANT",
        "content": "Here is your sales data...",
        "timestamp": "2025-01-15T10:00:03Z"
      }
    ],
    "organization_id": 42,
    "user_id": 123
  }
}

Delete Session

Delete a conversation session and all its messages from PostgreSQL storage.

Endpoint: DELETE /api/v1/chat/{session_id}

Example Request:

curl -X DELETE "https://api.dialektai.com/api/v1/chat/550e8400-e29b-41d4-a716-446655440000" \
  -H "X-API-Key: sk_your_organization_key_here" \
  -H "X-Scope-Id: user-123"

Response:

{
  "success": true,
  "data": {
    "message": "Session deleted successfully"
  }
}

Advanced Usage

Manually Append Messages

Programmatically add messages to conversations without going through the chat agent flow.

Endpoint: POST /api/v1/chat/message (history append)

Use Cases:

Request Body:

Parameter Type Required Description
conversation_id string (UUID) Yes Target conversation
role string Yes Message role: user, assistant, system, tool
content string Yes Message content (min 1 character)
metadata object No Optional metadata dictionary

Example Request:

curl -X POST "https://api.dialektai.com/api/v1/chat/message" \
  -H "X-API-Key: sk_your_organization_key_here" \
  -H "X-Scope-Id: user-123" \
  -H "Content-Type: application/json" \
  -d '{
    "conversation_id": "550e8400-e29b-41d4-a716-446655440000",
    "role": "user",
    "content": "What is the status of my order?",
    "metadata": {
      "source": "mobile_app",
      "app_version": "2.1.0"
    }
  }'

Response (201 Created):

{
  "success": true,
  "data": {
    "message_id": "987e6543-e21b-54d3-a456-426614174999",
    "conversation_id": "550e8400-e29b-41d4-a716-446655440000",
    "created_at": "2025-10-09T12:34:56.789Z"
  },
  "message": "Message appended successfully"
}

Message Roles:

Common Use Cases

Building a Conversation History UI

  1. List conversations with GET /api/v1/chat/conversations
  2. Display conversation list with titles and metadata
  3. Load messages when user selects conversation with GET /api/v1/chat/history?conversation_id=...
  4. Paginate through messages as user scrolls
  5. Delete conversations with DELETE /api/v1/chat/{session_id}

Conversation Search and Export

  1. Retrieve all messages with GET /api/v1/chat/history (no conversation_id)
  2. Filter and search messages in your application
  3. Export to CSV/PDF for reporting or compliance
  4. Archive old conversations to external storage

Multi-User Conversation Management

  1. Use X-Scope-Id to isolate conversations per user
  2. Create conversations for each user independently
  3. Query conversations filtered by scope ID
  4. Delete user data for GDPR compliance

Error Handling

Common Errors

Status Error Code Description Solution
400 VALIDATION_ERROR Missing or invalid parameters Check request body/params
401 UNAUTHORIZED Invalid API key Verify organization API key
403 FORBIDDEN Missing X-Scope-Id header Add X-Scope-Id header
404 NOT_FOUND Conversation/session not found Verify conversation ID exists
429 RATE_LIMIT_EXCEEDED Too many requests Implement rate limiting

Error Response Format

{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid conversation_id format",
    "details": "Expected UUID format"
  }
}

Best Practices

  1. Always include X-Scope-Id - Required for all chat history endpoints
  2. Use cursor pagination - More efficient than offset-based pagination
  3. Handle hasMore correctly - Check before making next page request
  4. Set appropriate limits - Balance between requests and payload size
  5. Implement retry logic - Handle rate limits and transient errors
  6. Clean up old conversations - Use DELETE endpoint for data hygiene
  7. Validate conversation IDs - Check for 404 errors and handle gracefully

Security Considerations

Next Steps