Skip to main content

Chat API

The Chat API allows you to send questions and receive AI-generated answers with citations from your documents.

Endpoints

MethodEndpointDescription
POST/api/ai/chatSend a message, get a complete response
POST/api/ai/chat/streamSend a message, get a streaming response

Send Chat Message

Authorization
string
required
API key with ApiKey prefix
X-External-Org-Id
string
required
Your client’s organization identifier
X-External-User-Id
string
required
The user making the request
X-External-Roles
string
required
JSON array of user’s roles for access control

Request Body

message
string
required
The question to ask
conversationId
string
Optional. Continue an existing conversation
documentIds
array
Optional. Limit search to specific documents
folderIds
array
Optional. Limit search to specific folders

Example Request

curl -X POST https://api.docbit.ai/api/ai/chat \
  -H "Authorization: ApiKey sk_yourpartner_abc123..." \
  -H "X-External-Org-Id: acme" \
  -H "X-External-User-Id: user-456" \
  -H "X-External-Roles: [\"employee\", \"hr\"]" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "What is the vacation policy?",
    "conversationId": null
  }'

Response

{
  "conversationId": "550e8400-e29b-41d4-a716-446655440000",
  "content": "According to the Employee Handbook, full-time employees receive 15 days of paid vacation per year. Vacation days accrue monthly and can be carried over to the next year, up to a maximum of 5 days.",
  "citations": [
    {
      "documentId": "doc-abc123",
      "documentTitle": "Employee Handbook",
      "page": 12,
      "section": "Time Off Policies",
      "excerpt": "Full-time employees are entitled to 15 days of paid vacation annually..."
    }
  ],
  "confidence": "High"
}

Response Fields

FieldTypeDescription
conversationIdstringID for follow-up questions
contentstringThe AI-generated answer
citationsarraySource references
confidencestringHigh, Medium, or Low

Citation Object

FieldTypeDescription
documentIdstringDocument identifier
documentTitlestringDocument name
pageintegerPage number (if available)
sectionstringSection heading (if available)
excerptstringRelevant text snippet

Stream Chat Response

For real-time responses, use the streaming endpoint. Responses are delivered via Server-Sent Events (SSE).

Example Request

curl -X POST https://api.docbit.ai/api/ai/chat/stream \
  -H "Authorization: ApiKey sk_yourpartner_abc123..." \
  -H "X-External-Org-Id: acme" \
  -H "X-External-User-Id: user-456" \
  -H "X-External-Roles: [\"employee\"]" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{"message": "Summarize the benefits package"}'

SSE Events

The stream emits these event types: Token Event - Individual tokens as they’re generated:
data: {"token": "According"}

data: {"token": " to"}

data: {"token": " the"}
Done Event - Final response with metadata:
data: {"conversationId": "...", "citations": [...], "confidence": "High"}
Error Event - If an error occurs:
data: {"error": "Rate limit exceeded"}

JavaScript Example

async function streamChat(message) {
  const response = await fetch('https://api.docbit.ai/api/ai/chat/stream', {
    method: 'POST',
    headers: {
      'Authorization': `ApiKey ${API_KEY}`,
      'X-External-Org-Id': 'acme',
      'X-External-User-Id': 'user-456',
      'X-External-Roles': '["employee"]',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ message })
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let fullResponse = '';

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    
    const chunk = decoder.decode(value);
    const lines = chunk.split('\n');
    
    for (const line of lines) {
      if (line.startsWith('data: ')) {
        const data = JSON.parse(line.slice(6));
        
        if (data.token) {
          fullResponse += data.token;
          process.stdout.write(data.token);
        } else if (data.citations) {
          console.log('\n\nCitations:', data.citations);
        }
      }
    }
  }
}

Follow-Up Questions

To continue a conversation, include the conversationId from the previous response:
{
  "message": "How do I request time off?",
  "conversationId": "550e8400-e29b-41d4-a716-446655440000"
}
The AI will have context from the previous messages in the conversation.

Scoped Queries

Limit searches to specific documents or folders:

By Document IDs

{
  "message": "What does this say about overtime?",
  "documentIds": ["doc-abc123", "doc-def456"]
}

By Folder IDs

{
  "message": "What are the HR policies?",
  "folderIds": ["folder-hr-001"]
}

Error Responses

StatusErrorDescription
400Message is requiredEmpty or missing message
400Missing required headerRequired header not provided
401Invalid API keyAuthentication failed
404Conversation not foundInvalid conversationId
429Rate limit exceededToo many requests
See Error Codes for complete error documentation.