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

# Stream Chat

> Start a streaming chat session with the Greenflash AI agent.

**Requires a Growth or Enterprise plan.**

The response is a Server-Sent Events (SSE) stream (`Content-Type: text/event-stream`).
Each event follows the format:

```
event: <type>
data: <json>
```

**Event types:**
- `tool_call` — The agent is invoking a tool. Data: `{"step": 1, "toolName": "...", "displayName": "..."}`
- `tool_result` — A tool returned its result. Data: `{"step": 1, "toolName": "...", "displayName": "..."}`. For `draftTicket` and `createTicket`, the event also includes an `output` field with the tool's payload (see *Ticket creation* below).
- `text_delta` — A chunk of the agent's text response. Concatenate all deltas to build the full message. Data: `{"text": "..."}`
- `done` — The stream completed successfully. Data: `{"conversationId": "...", "status": "complete", "usage": {"toolCalls": N, "tools": ["..."]}}`
- `error` — An error occurred during processing. Data: `{"error": "...", "code": "..."}`

**Multi-turn conversations:** Pass previous messages in the `messages` array and reuse the `conversationId` returned in the `done` event.

**Rate limits:** This endpoint is rate-limited per tenant (requests/hour) and subject to token usage limits.

### Ticket creation (two-step draft → confirm)

When the tenant has an active ticket-provider connection (e.g. Linear), the agent may emit a `draftTicket` tool call. The `tool_result` event includes an `output` field shaped like:

```json
{
  "step": 2,
  "toolName": "draftTicket",
  "displayName": "Drafting ticket",
  "output": {
    "draft": {
      "provider": "linear",
      "title": "Billing page 500 for enterprise users",
      "description": "...",
      "target": { "teamId": "t_123", "teamName": "Core", "teamKey": "CORE" },
      "labelIds": ["lbl_bug"],
      "source": { "type": "conversation", "conversationId": "conv-abc-123" }
    },
    "availableLabels": [
      { "id": "lbl_bug", "name": "bug", "color": "#f00" }
    ],
    "dedupWarning": null
  }
}
```

API consumers should render this draft to the end user. To confirm (optionally with edits), send a follow-up user message asking the agent to call `createTicket` with the final payload. The `createTicket` `tool_result` event contains:

```json
{
  "step": 3,
  "toolName": "createTicket",
  "displayName": "Creating ticket",
  "output": {
    "status": "created",
    "providerIdentifier": "LIN-99",
    "providerTicketUrl": "https://linear.app/acme/issue/LIN-99"
  }
}
```

`status` is `"created"` on success, `"already_exists"` when deduplication matched an existing ticket (the existing `providerIdentifier` / `providerTicketUrl` are returned), or the event may carry an `error` field (e.g. `"provider_needs_setup"`).



## OpenAPI

````yaml https://www.greenflash.ai/api/openapi post /chat
openapi: 3.1.0
info:
  title: Greenflash API Reference
  version: 1.0.0
  description: >-
    Greenflash endpoints for capturing interactions, managing prompts, and
    identifying users.
servers:
  - url: https://www.greenflash.ai/api/v1
    description: Greenflash API v1
security: []
tags:
  - name: Interactions
    description: Capture interactions between users and AI
  - name: Business Events
    description: Capture business events
  - name: Analytics
    description: Understand chat and agentic interactions analyses
  - name: Inbox
    description: Review flagged conversations
  - name: Segments
    description: Manage user segments
  - name: Prompts
    description: Manage prompts
  - name: Chat
    description: Stream chat and agentic conversations
  - name: Models
    description: Manage AI models
  - name: Products
    description: Manage products
  - name: Users
    description: Manage users
  - name: Organizations
    description: Manage organizations
paths:
  /chat:
    post:
      tags:
        - Chat
      summary: Stream Chat
      description: >-
        Start a streaming chat session with the Greenflash AI agent.


        **Requires a Growth or Enterprise plan.**


        The response is a Server-Sent Events (SSE) stream (`Content-Type:
        text/event-stream`).

        Each event follows the format:


        ```

        event: <type>

        data: <json>

        ```


        **Event types:**

        - `tool_call` — The agent is invoking a tool. Data: `{"step": 1,
        "toolName": "...", "displayName": "..."}`

        - `tool_result` — A tool returned its result. Data: `{"step": 1,
        "toolName": "...", "displayName": "..."}`. For `draftTicket` and
        `createTicket`, the event also includes an `output` field with the
        tool's payload (see *Ticket creation* below).

        - `text_delta` — A chunk of the agent's text response. Concatenate all
        deltas to build the full message. Data: `{"text": "..."}`

        - `done` — The stream completed successfully. Data: `{"conversationId":
        "...", "status": "complete", "usage": {"toolCalls": N, "tools":
        ["..."]}}`

        - `error` — An error occurred during processing. Data: `{"error": "...",
        "code": "..."}`


        **Multi-turn conversations:** Pass previous messages in the `messages`
        array and reuse the `conversationId` returned in the `done` event.


        **Rate limits:** This endpoint is rate-limited per tenant
        (requests/hour) and subject to token usage limits.


        ### Ticket creation (two-step draft → confirm)


        When the tenant has an active ticket-provider connection (e.g. Linear),
        the agent may emit a `draftTicket` tool call. The `tool_result` event
        includes an `output` field shaped like:


        ```json

        {
          "step": 2,
          "toolName": "draftTicket",
          "displayName": "Drafting ticket",
          "output": {
            "draft": {
              "provider": "linear",
              "title": "Billing page 500 for enterprise users",
              "description": "...",
              "target": { "teamId": "t_123", "teamName": "Core", "teamKey": "CORE" },
              "labelIds": ["lbl_bug"],
              "source": { "type": "conversation", "conversationId": "conv-abc-123" }
            },
            "availableLabels": [
              { "id": "lbl_bug", "name": "bug", "color": "#f00" }
            ],
            "dedupWarning": null
          }
        }

        ```


        API consumers should render this draft to the end user. To confirm
        (optionally with edits), send a follow-up user message asking the agent
        to call `createTicket` with the final payload. The `createTicket`
        `tool_result` event contains:


        ```json

        {
          "step": 3,
          "toolName": "createTicket",
          "displayName": "Creating ticket",
          "output": {
            "status": "created",
            "providerIdentifier": "LIN-99",
            "providerTicketUrl": "https://linear.app/acme/issue/LIN-99"
          }
        }

        ```


        `status` is `"created"` on success, `"already_exists"` when
        deduplication matched an existing ticket (the existing
        `providerIdentifier` / `providerTicketUrl` are returned), or the event
        may carry an `error` field (e.g. `"provider_needs_setup"`).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/StreamChatRequest'
            example:
              question: What are the top complaints from enterprise customers this week?
              messages:
                - role: user
                  content: Show me sentiment trends for the support bot.
                - role: assistant
                  content: >-
                    Based on the last 30 days, sentiment is trending slightly
                    negative (-0.08). The main driver is billing-related
                    frustration, which accounts for 34% of negative
                    conversations.
              conversationId: conv-abc-123
              context: Focus on the Customer Support Bot product.
              productId: 123e4567-e89b-12d3-a456-426614174000
      responses:
        '200':
          description: >-
            SSE stream of chat events (text/event-stream). See endpoint
            description for event format.


            **Example SSE stream:**

            ```

            event: tool_call

            data:
            {"step":1,"toolName":"getConversations","displayName":"Searching
            conversations"}


            event: tool_call

            data: {"step":2,"toolName":"getUserRanking","displayName":"Ranking
            users by metrics"}


            event: tool_result

            data:
            {"step":1,"toolName":"getConversations","displayName":"Searching
            conversations"}


            event: tool_result

            data: {"step":2,"toolName":"getUserRanking","displayName":"Ranking
            users by metrics"}


            event: text_delta

            data: {"text":"Based on your"}


            event: text_delta

            data: {"text":" conversation data, the top complaints"}


            event: text_delta

            data: {"text":" from enterprise customers this week are..."}


            event: done

            data:
            {"conversationId":"conv-abc-123","status":"complete","usage":{"toolCalls":2,"tools":["getConversations","getUserRanking"]}}

            ```
        '400':
          description: Bad request — invalid or missing parameters
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    description: Whether the API call was successful (false for errors).
                  error:
                    type: string
                    description: Error message describing what went wrong.
                description: Error response for stream chat operations.
              example:
                success: false
                error: >-
                  Validation error: question must be between 1 and 4000
                  characters
        '403':
          description: Forbidden — requires a Growth or Enterprise plan
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    description: Whether the API call was successful (false for errors).
                  error:
                    type: string
                    description: Error message describing what went wrong.
                description: Error response for stream chat operations.
              example:
                success: false
                error: This endpoint requires a Growth plan or higher
        '429':
          description: Rate limit or token usage limit exceeded
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    description: Whether the API call was successful (false for errors).
                  error:
                    type: string
                    description: Error message describing what went wrong.
                description: Error response for stream chat operations.
              example:
                success: false
                error: Rate limit exceeded for chat requests. Please try again later.
        '500':
          description: Server error
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    description: Whether the API call was successful (false for errors).
                  error:
                    type: string
                    description: Error message describing what went wrong.
                description: Error response for stream chat operations.
      security:
        - bearerAuth: []
      x-codeSamples:
        - lang: JavaScript
          source: |-
            import Greenflash from 'greenflash';

            const client = new Greenflash({
              apiKey: process.env['GREENFLASH_API_KEY'], // This is the default and can be omitted
            });

            await client.chat.create({
              question: 'What are the top complaints from enterprise customers this week?',
              context: 'Focus on the Customer Support Bot product.',
              conversationId: 'conv-abc-123',
              messages: [
                { role: 'user', content: 'Show me sentiment trends for the support bot.' },
                {
                  role: 'assistant',
                  content:
                    'Based on the last 30 days, sentiment is trending slightly negative (-0.08). The main driver is billing-related frustration, which accounts for 34% of negative conversations.',
                },
              ],
              productId: '123e4567-e89b-12d3-a456-426614174000',
            });
        - lang: Python
          source: |-
            import os
            from greenflash import Greenflash

            client = Greenflash(
                api_key=os.environ.get("GREENFLASH_API_KEY"),  # This is the default and can be omitted
            )
            client.chat.create(
                question="What are the top complaints from enterprise customers this week?",
                context="Focus on the Customer Support Bot product.",
                conversation_id="conv-abc-123",
                messages=[{
                    "role": "user",
                    "content": "Show me sentiment trends for the support bot.",
                }, {
                    "role": "assistant",
                    "content": "Based on the last 30 days, sentiment is trending slightly negative (-0.08). The main driver is billing-related frustration, which accounts for 34% of negative conversations.",
                }],
                product_id="123e4567-e89b-12d3-a456-426614174000",
            )
components:
  schemas:
    StreamChatRequest:
      type: object
      properties:
        question:
          type: string
          minLength: 1
          maxLength: 4000
          description: The current user question to send to the AI agent.
        messages:
          type: array
          items:
            type: object
            properties:
              role:
                type: string
                enum:
                  - user
                  - assistant
                description: The role of the message sender.
              content:
                type: string
                description: The text content of the message.
            required:
              - role
              - content
          maxItems: 50
          description: >-
            Prior conversation history (NOT including the current question).
            Used for multi-turn context.
        conversationId:
          type: string
          maxLength: 128
          description: >-
            Stable identifier for multi-turn conversations. If omitted, a new ID
            is generated.
        context:
          type: string
          maxLength: 2000
          description: Free-form hint injected into the system prompt for this turn only.
        productId:
          type: string
          format: uuid
          description: >-
            Scope the chat to a specific product. If omitted, the agent can
            access all products.
      required:
        - question
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer

````