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

# Streaming Search

> 
> **⚠️ Important Note**: The auto-generated code samples in the playground will not work for this WebSocket endpoint, with the exception of the Python and JS(WebSocket) examples shown. Please use these provided examples only, and not the auto-generated ones.

This endpoint provides a WebSocket connection for streaming search results in real-time.

#### Connection
Connect to: `wss://api.critique-labs.ai/v1/ws/search`

#### Headers
- **X-API-Key**: (Required) Your unique API key for authentication.

#### Message Format
After connecting, send a JSON message with the following structure:
```json
{
    "prompt": "your search query",
    "image": "optional base64 image or URL",
    "source_blacklist": ["optional list of domains to exclude"],
    "output_format": {
        // Optional structured output format
    }
}
```

#### Streaming Responses
The server will stream responses as JSON messages with the following structure:
```json
{
    "type": "response" | "context" | "error",
    "content": "the actual content"
}
```

- `type: "response"` - Contains generated response content
- `type: "context"` - Contains source context information
- `type: "error"` - Contains error messages if any occur




## OpenAPI

````yaml https://api.critique-labs.ai/openapi.json get /v1/ws/search
openapi: 3.1.0
info:
  title: Critique Flow API
  summary: >-
    Gives you researched in-line cited search responses from Critique's in-built
    LLM powered agentic search engine
  description: >

    **URL**: `https://api.critique-labs.ai/v1/search`  

    **Method**: `POST`  

    **Content-Type**: `application/json`  


    #### Headers

    - **X-API-Key**: (Required) Your unique API key for authentication.

    - **Content-Type**: (Required) Should be set to `application/json`.


    #### Request Body Parameters

    | Parameter        | Type              |
    Description                                                                                                                                                                                                                        
    |

    |------------------|-------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

    | **image**        | `string` (optional) | A base64-encoded string of the
    image or a URL to the image. Providing this parameter allows the API to
    incorporate visual data into the search. If both `image` and `prompt` are
    included, they are combined to refine the search. |

    | **prompt**       | `string`          | A natural language question or
    statement that specifies the information you are seeking. The prompt can
    include specific instructions about the expected answer type, timeframe, or
    content source.                                  |

    | **source_blacklist** | `array` of `string` (optional) | A list of URLs or
    domains (e.g., `"expedia.com"`) that should be excluded from the search
    results. Cannot be used together with
    source_whitelist.                              |

    | **source_whitelist** | `array` of `string` (optional) | A list of URLs or
    domains that should be exclusively used in the search results. Cannot be
    used together with source_blacklist.                              |

    | **output_format**   | `object` (optional) | A JSON object that specifies
    the expected structure of the response. This allows for control over the
    format and detail level of the results, making integration into structured
    applications seamless. See details below.      |


    #### `output_format` Parameter

    The `output_format` parameter is a JSON object that defines the desired
    structure of the API response. Each key in this object represents a field in
    the response, and the value defines its data type or structure.


    ##### Supported Data Types

    - **Primitive Types**: `"string"`, `"number"`, `"boolean"`

    - **Nested Objects**: An object can have other fields, each with types or
    nested structures.

    - **Arrays of Objects**: Arrays can contain objects with defined structures.


    ##### Example of `output_format`

    ```json

    {
      "flights": [
        {
          "destination": "string",
          "price": "number",
          "date": "string"
        }
      ],
      "summary": "string",
      "isAvailable": "boolean"
    }

    ```


    In this example:

    - `flights` is an array where each object has `destination` (a string),
    `price` (a number), and `date` (a string).

    - `summary` is a single string.

    - `isAvailable` is a boolean value.


    ##### Request Example

    Here's an example request using the parameters defined:


    ```json

    {
      "image": "https://cdn.britannica.com/95/94195-050-FCBF777E/Golden-Gate-Bridge-San-Francisco.jpg",
      "prompt": "What are the current flight prices to this location from Hong Kong?",
      "source_blacklist": ["expedia.com"],
      "output_format": {
        "flights": [
          {
            "destination": "string",
            "price": "number",
            "date": "string"
          }
        ],
        "response": "string"
      }
    }

    ```


    In this request:

    - `image` provides an image URL.

    - `prompt` specifies the information sought.

    - `source_blacklist` excludes results from `"expedia.com"`.

    - `output_format` requests a structured response with `flights` (each with
    `destination`, `price`, and `date`) and an additional `response` as a
    summary string.


    #### Response

    The API returns a JSON object formatted according to the `output_format`,
    providing flexibility in structuring the data based on application needs.
  termsOfService: https://api.critique-labs.ai/en/docs/terms-of-service
  contact:
    email: support@critique-labs.ai
  version: 1.5.0
  x-logo:
    url: >-
      https://critique-labs.ai/_next/image?url=%2Fimages%2Ficon_only.png&w=96&q=75
servers:
  - url: https://api.critique-labs.ai
  - url: http://localhost
security: []
paths:
  /v1/ws/search:
    get:
      summary: Streaming Search
      description: >

        > **⚠️ Important Note**: The auto-generated code samples in the
        playground will not work for this WebSocket endpoint, with the exception
        of the Python and JS(WebSocket) examples shown. Please use these
        provided examples only, and not the auto-generated ones.


        This endpoint provides a WebSocket connection for streaming search
        results in real-time.


        #### Connection

        Connect to: `wss://api.critique-labs.ai/v1/ws/search`


        #### Headers

        - **X-API-Key**: (Required) Your unique API key for authentication.


        #### Message Format

        After connecting, send a JSON message with the following structure:

        ```json

        {
            "prompt": "your search query",
            "image": "optional base64 image or URL",
            "source_blacklist": ["optional list of domains to exclude"],
            "output_format": {
                // Optional structured output format
            }
        }

        ```


        #### Streaming Responses

        The server will stream responses as JSON messages with the following
        structure:

        ```json

        {
            "type": "response" | "context" | "error",
            "content": "the actual content"
        }

        ```


        - `type: "response"` - Contains generated response content

        - `type: "context"` - Contains source context information

        - `type: "error"` - Contains error messages if any occur
      parameters:
        - name: X-API-Key
          in: header
          required: true
          schema:
            type: string
          description: Your API key for authentication
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - prompt
              properties:
                prompt:
                  type: string
                  description: The search query, can be as extended or succinct as you like
                image:
                  type: string
                  description: >-
                    Optional, This string can be the url of the image you want
                    to send. Alternatively, (and the preferred method) is
                    providing a base64 encoded string of the image. If providing
                    a url, the link must start with https:// and ends with a
                    common image file extension like .jpg, .jpeg, .png, .gif,
                    etc.
                source_blacklist:
                  type: array
                  items:
                    type: string
                  description: >-
                    Optional, a list of strings representing domains you want to
                    exclude from the agentic search. ['cnn.com','foxnews.com'].
                output_format:
                  type: object
                  description: >-
                    Optional, a json schema for the response. This will be used
                    to format the response of the agentic search. The types
                    allowed can be any of: string, number, boolean, integer,
                    array
      responses:
        '101':
          description: WebSocket connection established
      x-codeSamples:
        - lang: Python
          source: |

            import websockets
            import asyncio
            import json

            async def search_streaming():
                uri = "wss://api.critique-labs.ai/v1/ws/search"
                headers = {
                    'X-API-Key': '<YOUR API KEY HERE>'
                }
                
                async with websockets.connect(uri, extra_headers=headers) as websocket:
                    # Send the search request
                    await websocket.send(json.dumps({
                        'prompt': 'how much are flights to this place from Hong Kong right now',
                        'source_blacklist': ['expedia.com'],  # optional - specify either source_blacklist or source_whitelist, not both
                        # 'source_whitelist': ['kayak.com'],  # optional - specify either source_blacklist or source_whitelist, not both
                        'output_format': {
                            'flights': [{"origin": "string", "airline": "string", "destination": "string", "price": "number"}],
                            "response": "string"
                        }
                    }))
                    
                    # Receive and process streaming responses
                    while True:
                        try:
                            response = await websocket.recv()
                            data = json.loads(response)
                            
                            # Handle different types of responses
                            if data['type'] == 'response':
                                print('Response:', data['content'])
                            elif data['type'] == 'context':
                                print('Context:', data['content'])
                            elif data['type'] == 'error':
                                print('Error:', data['content'])
                                break
                        except websockets.exceptions.ConnectionClosed:
                            print("Connection closed")
                            break

            # Run the async function
            asyncio.run(search_streaming())
          label: Python
        - lang: JavaScript
          source: >

            const WebSocket = require("ws");

            const ws = new WebSocket('wss://api.critique-labs.ai/v1/ws/search',
            {
                headers: {
                    'X-API-Key': '<YOUR API KEY HERE>'
                }
            });


            ws.onopen = () => {
                // Send the search request
                ws.send(JSON.stringify({
                    prompt: 'how much are flights to this place from Hong Kong right now',
                    source_blacklist: ['expedia.com'],  # optional - specify either source_blacklist or source_whitelist, not both
                    // source_whitelist: ['kayak.com'],  # optional - specify either source_blacklist or source_whitelist, not both
                    output_format: {
                        flights: [{"origin": "string", "airline": "string", "destination": "string", "price": "number"}],
                        response: "string"
                    }
                }));
            };


            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                
                // Handle different types of responses
                switch(data.type) {
                    case 'response':
                        console.log('Response:', data.content);
                        break;
                    case 'context':
                        console.log('Context:', data.content);
                        break;
                    case 'error':
                        console.log('Error:', data.content);
                        ws.close();
                        break;
                }
            };


            ws.onerror = (error) => {
                console.error('WebSocket error:', error);
            };


            ws.onclose = () => {
                console.log('Connection closed');
            };
          label: JS (WebSocket)

````