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

# Chat endpoint

> Interactive chat interface with streaming responses and research capabilities

The chat endpoint provides an interactive conversational interface with AI-powered search and research capabilities. It returns streaming responses with structured blocks for a rich chat experience.

## Endpoint

<CodeGroup>
  ```bash POST /api/chat theme={null}
  http://localhost:3000/api/chat
  ```
</CodeGroup>

<Note>Replace `localhost:3000` with your Perplexica instance URL if running on a different host or port.</Note>

## Request body

<ParamField body="message" type="object" required>
  The message object containing the user's input and metadata.

  <Expandable title="properties">
    <ParamField body="messageId" type="string" required>
      A unique identifier for this message.
    </ParamField>

    <ParamField body="chatId" type="string" required>
      The ID of the chat conversation.
    </ParamField>

    <ParamField body="content" type="string" required>
      The message content from the user.
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="chatModel" type="object" required>
  Defines the chat model to be used. Get available providers and models from the `/api/providers` endpoint.

  <Expandable title="properties">
    <ParamField body="providerId" type="string" required>
      The UUID of the provider.
    </ParamField>

    <ParamField body="key" type="string" required>
      The model key/identifier (e.g., `gpt-4o-mini`).
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="embeddingModel" type="object" required>
  Defines the embedding model for similarity-based searching.

  <Expandable title="properties">
    <ParamField body="providerId" type="string" required>
      The UUID of the embedding provider.
    </ParamField>

    <ParamField body="key" type="string" required>
      The embedding model key (e.g., `text-embedding-3-large`).
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="optimizationMode" type="string" required>
  Optimization mode to control performance and quality balance. Available values: `speed`, `balanced`, `quality`.
</ParamField>

<ParamField body="sources" type="array" default={[]}>
  Which search sources to enable. Available values: `web`, `academic`, `discussions`.
</ParamField>

<ParamField body="history" type="array" default={[]}>
  An array of message pairs representing the conversation history. Each pair consists of a role (either `human` or `assistant`) and the message content.
</ParamField>

<ParamField body="files" type="array" default={[]}>
  An array of file IDs to include in the context for this message.
</ParamField>

<ParamField body="systemInstructions" type="string" default="">
  Custom instructions to guide the AI's response. Set to `null` or empty string for default behavior.
</ParamField>

## Response

The chat endpoint returns a streaming response with `Content-Type: text/event-stream`. Each line contains a newline-delimited JSON object representing different types of events.

### Stream event types

<ResponseField name="block" type="object">
  A new content block has been created. Contains the block object with its initial state.
</ResponseField>

<ResponseField name="updateBlock" type="object">
  An existing block has been updated.

  <Expandable title="properties">
    <ResponseField name="blockId" type="string">
      The ID of the block being updated.
    </ResponseField>

    <ResponseField name="patch" type="object">
      A JSON patch object describing the changes to apply to the block.
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="researchComplete" type="object">
  Indicates that the research phase is complete and the AI is ready to generate the final response.
</ResponseField>

<ResponseField name="messageEnd" type="object">
  Indicates the message stream has completed successfully.
</ResponseField>

<ResponseField name="error" type="object">
  An error occurred during processing.

  <Expandable title="properties">
    <ResponseField name="data" type="any">
      Error details.
    </ResponseField>
  </Expandable>
</ResponseField>

## Request example

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://localhost:3000/api/chat \
    -H "Content-Type: application/json" \
    -d '{
      "message": {
        "messageId": "msg-123",
        "chatId": "chat-456",
        "content": "What is the latest news about AI?"
      },
      "chatModel": {
        "providerId": "550e8400-e29b-41d4-a716-446655440000",
        "key": "gpt-4o-mini"
      },
      "embeddingModel": {
        "providerId": "550e8400-e29b-41d4-a716-446655440000",
        "key": "text-embedding-3-large"
      },
      "optimizationMode": "balanced",
      "sources": ["web"],
      "history": [],
      "files": [],
      "systemInstructions": ""
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:3000/api/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      message: {
        messageId: 'msg-123',
        chatId: 'chat-456',
        content: 'What is the latest news about AI?'
      },
      chatModel: {
        providerId: '550e8400-e29b-41d4-a716-446655440000',
        key: 'gpt-4o-mini'
      },
      embeddingModel: {
        providerId: '550e8400-e29b-41d4-a716-446655440000',
        key: 'text-embedding-3-large'
      },
      optimizationMode: 'balanced',
      sources: ['web'],
      history: [],
      files: [],
      systemInstructions: ''
    })
  });

  // Handle streaming response
  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    
    const chunk = decoder.decode(value);
    const lines = chunk.split('\n').filter(line => line.trim());
    
    for (const line of lines) {
      const event = JSON.parse(line);
      console.log(event);
    }
  }
  ```

  ```python Python theme={null}
  import requests
  import json

  response = requests.post(
      'http://localhost:3000/api/chat',
      json={
          'message': {
              'messageId': 'msg-123',
              'chatId': 'chat-456',
              'content': 'What is the latest news about AI?'
          },
          'chatModel': {
              'providerId': '550e8400-e29b-41d4-a716-446655440000',
              'key': 'gpt-4o-mini'
          },
          'embeddingModel': {
              'providerId': '550e8400-e29b-41d4-a716-446655440000',
              'key': 'text-embedding-3-large'
          },
          'optimizationMode': 'balanced',
          'sources': ['web'],
          'history': [],
          'files': [],
          'systemInstructions': ''
      },
      stream=True
  )

  for line in response.iter_lines():
      if line:
          event = json.loads(line)
          print(event)
  ```
</CodeGroup>

## Response example

```json theme={null}
{"type":"block","block":{"id":"block-1","type":"text","content":""}}
{"type":"updateBlock","blockId":"block-1","patch":{"content":"Here are the latest "}}
{"type":"updateBlock","blockId":"block-1","patch":{"content":"Here are the latest developments in AI..."}}
{"type":"researchComplete"}
{"type":"messageEnd"}
```

<Warning>
  All request body fields must pass validation. The endpoint uses Zod schemas to validate input and will return detailed error messages for invalid requests.
</Warning>

## Error responses

<ResponseField name="400" type="Bad Request">
  Returned if the request body is invalid or missing required fields. The response will include detailed error information with field paths and validation messages.
</ResponseField>

<ResponseField name="500" type="Internal Server Error">
  Returned if an error occurs while processing the chat request.
</ResponseField>
