> ## Documentation Index
> Fetch the complete documentation index at: https://60db.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Chat

> Generate AI responses using our Small Language Model (SLM) with support for streaming, text correction, and function calling

## Request

### Headers

<ParamField header="Authorization" type="string" required>
  Bearer token with your API key
</ParamField>

<ParamField header="Content-Type" type="string" required>
  application/json
</ParamField>

### Body - Direct Messages Mode (OpenAI Compatible)

<ParamField body="model" type="string" default="qcall/slm-3b-int4">
  The model to use for completion
</ParamField>

<ParamField body="messages" type="array" required>
  Array of message objects with `role` and `content`
</ParamField>

<ParamField body="stream" type="boolean" default="true">
  Enable streaming response (Server-Sent Events)
</ParamField>

<ParamField body="top_k" type="number" default="20">
  Top-k sampling parameter for response generation
</ParamField>

<ParamField body="chat_template_kwargs" type="object">
  Template configuration options
</ParamField>

<ParamField body="chat_template_kwargs.enable_thinking" type="boolean" default="false">
  Enable thinking mode in the model
</ParamField>

<ParamField body="tool" type="array">
  Array of tool/function definitions for function calling
</ParamField>

### Body - Enhanced Text Correction Mode

<ParamField body="text" type="string" required>
  The text to correct/improve
</ParamField>

<ParamField body="dictionary" type="array">
  Array of term-replacement pairs for custom corrections
</ParamField>

<ParamField body="dictionary[].term" type="string">
  The term to find and replace
</ParamField>

<ParamField body="dictionary[].replacement" type="string">
  The replacement text
</ParamField>

<ParamField body="style" type="object">
  Style configuration for text correction
</ParamField>

<ParamField body="style.tone" type="string">
  Tone to apply (e.g., "professional", "casual", "friendly")
</ParamField>

<ParamField body="style.autoCapitalize" type="boolean">
  Automatically capitalize sentences
</ParamField>

<ParamField body="style.autoPunctuate" type="boolean">
  Add proper punctuation
</ParamField>

<ParamField body="style.useContractions" type="boolean">
  Whether to use contractions (false to expand them)
</ParamField>

<ParamField body="style.expandAbbreviations" type="boolean">
  Expand abbreviations to full form
</ParamField>

<ParamField body="appContext" type="string">
  Application context (e.g., "email", "chat", "document")
</ParamField>

<ParamField body="save_chat" type="boolean" default="true">
  Save conversation to chat history
</ParamField>

<ParamField body="chat_id" type="string">
  Existing chat ID to continue conversation
</ParamField>

## Response

<ResponseField name="choices" type="array">
  Array of completion choices
</ResponseField>

<ResponseField name="choices[0].message" type="object">
  The generated message with role and content
</ResponseField>

<ResponseField name="choices[0].delta" type="object">
  Streaming delta with incremental content (stream mode only)
</ResponseField>

<ResponseField name="chat_id" type="string">
  ID of the chat session (for new chats)
</ResponseField>

<ResponseField name="usage" type="object">
  Token usage information
</ResponseField>

<ResponseField name="usage.total_tokens" type="number">
  Total tokens used in the request
</ResponseField>

<ResponseField name="response_time_ms" type="number">
  Response time in milliseconds
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  # Direct Messages Mode (OpenAI Compatible)
  curl --location 'https://api.60db.ai/v1/chat/completions' \
  --header 'Content-Type: application/json' \
  --data '{
    "model": "qcall/slm-3b-int4",
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "How are you? How can I improve my English communication?"
      }
    ],
    "top_k": 20,
    "chat_template_kwargs": {
      "enable_thinking": false
    },
    "stream": true
  }'
  ```

  ```bash cURL theme={null}
  # With Function Calling (Tools)
  curl --location 'https://api.60db.ai/v1/chat/completions' \
  --header 'Content-Type: application/json' \
  --data '{
    "model": "qcall/slm-3b-int4",
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "What'\''s the weather like in San Francisco?"
      }
    ],
    "stream": true,
    "tool": [
      {
        "name": "get_weather",
        "description": "Get the current weather for a location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location"]
        }
      }
    ]
  }'
  ```

  ```bash cURL theme={null}
  # Enhanced Text Correction Mode
  curl --location 'https://api.60db.ai/v1/chat/completions' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: Bearer your-api-key' \
  --data '{
    "model": "qcall/slm-3b-int4",
    "text": "hello how r u i need help with english",
    "dictionary": [
      {"term": "r", "replacement": "are"},
      {"term": "u", "replacement": "you"}
    ],
    "style": {
      "tone": "professional",
      "autoCapitalize": true,
      "autoPunctuate": true,
      "useContractions": false,
      "expandAbbreviations": true
    },
    "appContext": "email",
    "stream": true,
    "save_chat": true
  }'
  ```

  ```javascript JavaScript theme={null}
  import { SixtyDBClient } from "60db";

  const client = new SixtyDBClient("your-api-key");

  // Direct messages mode
  const response = await client.chat.completions.create({
    model: "qcall/slm-3b-int4",
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: "How can I improve my English?" },
    ],
    stream: true,
  });

  // Handle streaming response
  for await (const chunk of response) {
    console.log(chunk.choices[0]?.delta?.content);
  }
  ```

  ```python Python theme={null}
  from sixtydb import SixtyDBClient

  client = SixtyDBClient('your-api-key')

  # Text correction mode
  response = client.chat.completion(
      text='hello how r u i need help with english',
      dictionary=[
          {'term': 'r', 'replacement': 'are'},
          {'term': 'u', 'replacement': 'you'}
      ],
      style={
          'tone': 'professional',
          'auto_capitalize': True,
          'auto_punctuate': True,
          'use_contractions': False,
          'expand_abbreviations': True
      },
      app_context='email',
      stream=True
  )

  print(response['choices'][0]['message']['content'])
  ```
</RequestExample>

<ResponseExample>
  ```json Response (Non-Streaming) theme={null}
  {
    "id": "chatcmpl-123",
    "object": "chat.completion",
    "created": 1677652288,
    "model": "qcall/slm-3b-int4",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "I'm doing well, thank you! Here are some tips to improve your English communication skills..."
        },
        "finish_reason": "stop"
      }
    ],
    "usage": {
      "prompt_tokens": 25,
      "completion_tokens": 150,
      "total_tokens": 175
    },
    "chat_id": "550e8400-e29b-41d4-a716-446655440000",
    "response_time_ms": 1250
  }
  ```

  ```json Response (Streaming - SSE) theme={null}
  data: {"id":"chatcmpl-123","choices":[{"delta":{"content":"I'm"}}]}
  data: {"id":"chatcmpl-123","choices":[{"delta":{"content":" doing"}}]}
  data: {"id":"chatcmpl-123","choices":[{"delta":{"content":" well!"}}]}
  data: {"type":"done","response_time_ms":1250}
  data: [DONE]
  ```
</ResponseExample>

## Streaming Response

<AccordionGroup>
  <Accordion title="Server-Sent Events Format">
    When `stream: true`, the response is sent as Server-Sent Events (SSE):

    1. **chat\_id event** - Sent first for new chats
    2. **content chunks** - Delta updates with incremental content
    3. **done event** - Signals completion with response time
    4. **\[DONE]** - Final termination signal

    ```javascript theme={null}
    // Handling streaming in JavaScript
    const response = await fetch('https://api.60db.ai/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer your-api-key'
      },
      body: JSON.stringify({ messages, stream: true })
    });

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

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = JSON.parse(line.slice(6));
          if (data.type === 'chat_id') {
            console.log('Chat ID:', data.chat_id);
          } else if (data.type === 'done') {
            console.log('Response time:', data.response_time_ms);
          } else if (data.choices?.[0]?.delta?.content) {
            console.log('Content:', data.choices[0].delta.content);
          }
        }
      }
    }
    ```
  </Accordion>

  <Accordion title="Function Calling with Tools">
    Define tools/functions that the model can call during conversation:

    ```json theme={null}
    {
      "tool": [
        {
          "name": "get_weather",
          "description": "Get the current weather for a location",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA"
              },
              "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"]
              }
            },
            "required": ["location"]
          }
        }
      ]
    }
    ```

    The model will respond with tool calls that you can execute and send back the results.
  </Accordion>
</AccordionGroup>

## Text Correction Features

<AccordionGroup>
  <Accordion title="Dictionary Replacements">
    Define custom term replacements that will always be applied:

    ```json theme={null}
    {
      "dictionary": [
        {"term": "pls", "replacement": "please"},
        {"term": "thx", "replacement": "thanks"},
        {"term": "ASAP", "replacement": "as soon as possible"}
      ]
    }
    ```

    Up to 100 dictionary entries are supported, each with a maximum length of 200 characters.
  </Accordion>

  <Accordion title="Style Options">
    Configure how the text should be corrected and styled:

    | Option                | Type    | Description                                          |
    | --------------------- | ------- | ---------------------------------------------------- |
    | `tone`                | string  | Target tone: "professional", "casual", "friendly"    |
    | `autoCapitalize`      | boolean | Automatically capitalize first letter of sentences   |
    | `autoPunctuate`       | boolean | Add proper punctuation marks                         |
    | `useContractions`     | boolean | Set to false to expand contractions (can't → cannot) |
    | `expandAbbreviations` | boolean | Expand common abbreviations                          |
  </Accordion>

  <Accordion title="Application Context">
    Provide context to help the model adjust its corrections:

    ```json theme={null}
    {
      "appContext": "email"
    }
    ```

    Supported contexts: "email", "chat", "document", "message", "social"
  </Accordion>
</AccordionGroup>

<Warning>
  Token costs are calculated based on usage. The current rate is approximately
  \$0.00002 per token. Costs are deducted from your workspace billing balance.
</Warning>

<Note>
  Chat history is automatically saved when `save_chat: true`. Use `chat_id` to
  continue existing conversations or create new chats by omitting this
  parameter.
</Note>
