> ## Documentation Index
> Fetch the complete documentation index at: https://docs.thinnest.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Stream Message

> Send a message and receive a streaming response via Server-Sent Events (SSE).

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST https://api.thinnest.ai/chat/stream \
    -H "Authorization: Bearer $THINNESTAI_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
    "agent_id": "ag_c47e7c97_b2f2",
    "message": "Explain how machine learning works",
    "session_id": "sess_customer_001"
  }'
  ```

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

  url = "https://api.thinnest.ai/chat/stream"
  headers = {
      "Authorization": "Bearer " + "YOUR_THINNESTAI_API_KEY",
      "Content-Type": "application/json",
  }

  payload = {
    "agent_id": "ag_c47e7c97_b2f2",
    "message": "Explain how machine learning works",
    "session_id": "sess_customer_001"
  }

  response = requests.post(url, headers=headers, json=payload)
  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://api.thinnest.ai/chat/stream", {
    method: "POST",
    headers: {
      "Authorization": "Bearer " + "YOUR_THINNESTAI_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
    "agent_id": "ag_c47e7c97_b2f2",
    "message": "Explain how machine learning works",
    "session_id": "sess_customer_001"
  }),
  });

  const data = await response.json();
  console.log(data);
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "fmt"
      "io"
      "net/http"
  )

  func main() {
      payload := []byte(`{
    "agent_id": "ag_c47e7c97_b2f2",
    "message": "Explain how machine learning works",
    "session_id": "sess_customer_001"
  }`)
      req, _ := http.NewRequest("POST", "https://api.thinnest.ai/chat/stream", bytes.NewBuffer(payload))
      req.Header.Set("Authorization", "Bearer YOUR_THINNESTAI_API_KEY")
      req.Header.Set("Content-Type", "application/json")

      resp, err := http.DefaultClient.Do(req)
      if err != nil { panic(err) }
      defer resp.Body.Close()
      body, _ := io.ReadAll(resp.Body)
      fmt.Println(string(body))
  }
  ```
</RequestExample>

***

## Request Body

Same as [Send Message](/api-reference/chat/send) — all fields are identical.

<ParamField body="agent_id" type="string" required>
  Target agent ID (ag\_\*)
</ParamField>

<ParamField body="message" type="string" required>
  User message text
</ParamField>

<ParamField body="session_id" type="string">
  Session ID for conversation memory
</ParamField>

***

## Response — Server-Sent Events (SSE)

The response is a stream of `text/event-stream` events. Each event is a JSON object on a `data:` line:

```
data: {"type": "text", "content": "Machine learning is"}
data: {"type": "text", "content": " a subset of artificial intelligence"}
data: {"type": "text", "content": " that enables systems to learn"}
data: {"type": "tool_call", "name": "web_search", "args": {"query": "ML applications 2026"}}
data: {"type": "tool_result", "name": "web_search", "result": "..."}
data: {"type": "text", "content": " from data without being explicitly programmed."}
data: {"type": "done", "usage": {"input_tokens": 50, "output_tokens": 120, "total_tokens": 170}}
```

### Event Types

| Type          | Fields           | Description                                                       |
| ------------- | ---------------- | ----------------------------------------------------------------- |
| `text`        | `content`        | Partial text chunk — concatenate all chunks for the full response |
| `tool_call`   | `name`, `args`   | Agent is invoking a tool                                          |
| `tool_result` | `name`, `result` | Tool execution result                                             |
| `done`        | `usage`          | Stream complete — includes final token usage                      |
| `error`       | `message`        | Error during generation                                           |

***

## Client Example — JavaScript

```javascript theme={null}
const response = await fetch('https://api.thinnest.ai/chat/stream', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    agent_id: 'ag_c47e7c97_b2f2',
    message: 'Hello',
  }),
});

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

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

  const text = decoder.decode(value);
  for (const line of text.split('\n')) {
    if (line.startsWith('data: ')) {
      const event = JSON.parse(line.slice(6));
      if (event.type === 'text') {
        process.stdout.write(event.content);
      }
    }
  }
}
```

***

## Client Example — Python

```python theme={null}
import httpx
import json

with httpx.stream("POST", "https://api.thinnest.ai/chat/stream",
    headers={"Authorization": "Bearer YOUR_TOKEN"},
    json={"agent_id": "ag_c47e7c97_b2f2", "message": "Hello"}
) as response:
    for line in response.iter_lines():
        if line.startswith("data: "):
            event = json.loads(line[6:])
            if event["type"] == "text":
                print(event["content"], end="", flush=True)
```

***

## Errors

| Code  | Description                       |
| ----- | --------------------------------- |
| `401` | Missing or invalid authentication |
| `402` | Insufficient balance              |
| `404` | Agent not found                   |
| `429` | Rate limit exceeded               |


## OpenAPI

````yaml POST /chat/stream
openapi: 3.1.0
info:
  title: ThinnestAI API
  description: REST API for ThinnestAI — build, deploy, and manage AI agents.
  version: 1.0.0
servers: []
security: []
tags:
  - name: Agents
    description: Create, configure, and manage AI agents
  - name: Chat
    description: Send messages and get AI responses from agents
  - name: Knowledge
    description: Upload files, URLs, and text to agent knowledge bases
  - name: Sessions
    description: View and manage chat sessions and message history
  - name: Voice
    description: Start and manage voice call sessions
  - name: Recordings
    description: Manage voice call recordings
  - name: Campaigns
    description: Create and run automated outreach campaigns
  - name: Webhooks
    description: Register webhook endpoints for real-time event notifications
  - name: Evaluations
    description: Run and track agent evaluation benchmarks
  - name: Analytics
    description: Query agent performance metrics and usage data
  - name: Agent Tools
    description: View and manage tools attached to agents
  - name: BYOK
    description: >-
      Bring Your Own Key — manage credentials for LLM/STT/TTS providers,
      telephony BYOK (Vobiz/Twilio/Plivo/Exotel/Telnyx), and tool-specific BYOK
      (Razorpay UPI Payment, Surepass Aadhaar eKYC)
paths:
  /chat/stream:
    post:
      tags:
        - Chat
      summary: Chat Stream Endpoint
      description: |-
        Streaming chat endpoint with async billing.

        Uses Server-Sent Events (SSE) to stream response chunks.
        Billing is pushed to async queue for ultra-low latency.

        Event types:
        - content: Response text chunk
        - done: Final message with session_id and metrics
        - error: Error message
      operationId: chat_stream_endpoint_chat_stream_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChatRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - HTTPBearer: []
components:
  schemas:
    ChatRequest:
      properties:
        user_id:
          anyOf:
            - type: string
            - type: 'null'
          title: User Id
        agent_id:
          type: string
          title: Agent Id
        query:
          type: string
          title: Query
        session_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Session Id
      type: object
      required:
        - agent_id
        - query
      title: ChatRequest
      examples:
        - agent_id: ag_abc123
          query: Hello, help me with...
          user_id: auth0|123456
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````