> For clean Markdown of any page, append .md to the page URL. For a complete documentation index, see https://docs.sonicalpha.ai/llms.txt. For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.sonicalpha.ai/_mcp/server. For SDK generation or contract validation, use the authoritative OpenAPI spec at https://api.sonicalpha.ai/openapi.json — this docs domain's /openapi.json is a regenerated copy that can differ in auth modeling and strictness annotations.

# Ask (streaming)

POST https://api.sonicalpha.ai/v1/insights/ask/stream
Content-Type: application/json

Streaming variant of Ask: the same request and behavior, delivered
as Server-Sent Events while the research runs.

Each SSE `data:` line is one JSON object with a `type` field. There
are no named SSE `event:` frames — parse the JSON rather than using
`addEventListener`.

Events arrive in order:

* `stage` — a phase begins: `retrieval`, then `synthesis` (when
  `answer` is true).
* `sub_query` — the agent issued one search against the corpus;
  `sub_query_result` follows with its hit count, matched by `seq`.
* `retrieval_done` — evidence gathering finished.
* `sources` — the full ranked evidence set, the same objects the
  blocking endpoint returns. Sent before synthesis, so you can
  render evidence immediately.
* `answer_delta` — incremental answer text; only when `answer` is
  true.
* `done` — terminal: the final `answer` (treat it as the canonical
  text; `answer_delta` events are for display), plus `note_type`,
  `note`, and `took_ms`. Sources are NOT repeated here — keep the
  earlier `sources` event.
* `ping` — keep-alive during quiet stretches; ignore.
* `error` — terminal; replaces `done` on failure.

Consuming the stream (Python):

```python
import json, requests

sources = []
with requests.post(
    "https://api.sonicalpha.ai/v1/insights/ask/stream",
    headers={"Authorization": f"Bearer {KEY}"},
    json={"query": "How have investor views on NVDA changed since June?",
          "answer": True},
    stream=True,
) as r:
    r.raise_for_status()
    for line in r.iter_lines():
        if not line.startswith(b"data: "):
            continue
        event = json.loads(line[len(b"data: "):])
        if event["type"] == "ping":
            continue
        if event["type"] == "error":
            raise RuntimeError(event.get("message"))
        if event["type"] == "sources":
            sources = event["sources"]  # the ranked evidence set
        if event["type"] == "answer_delta":
            print(event["text"], end="", flush=True)
        if event["type"] == "done":
            # canonical answer + note + took_ms; sources arrived above
            final = {**event, "sources": sources}
```

Reference: https://docs.sonicalpha.ai/api-reference/insights/ask-stream

## Authentication

- `Authorization` header (bearer token, required) — Bearer authentication of the form `Bearer <token>`, where token is your auth token.

## Request

### Body (application/json)

This endpoint expects an InsightAskRequest.

- `query` (string, required) — The research question, in natural language (8–1000 characters) — phrase it as a question or claim, not keywords. Scope by naming shows, audiences, or time windows directly in the wording.
- `answer` (boolean, optional, default: false) — Default (false) returns the agent-curated evidence (`sources`) with `answer: null` in ~10-30s. Set true for a written, cited answer — every `[n]` maps to a source object; adds ~15-25s.
- `include_quotes` (boolean, optional, default: false) — Attach the verbatim transcript passage to each source as `quote`.

## Response

### 200

Server-Sent Events: stage, sub_query, sub_query_result, retrieval_done, sources, answer_delta, done, ping, error.

- Streaming response of `string`.

## Errors

### 400 Bad Request Error

Malformed request: unknown field, bad cursor, or out-of-range parameter

- `error` (ErrorResponseError, required) — The error envelope. Every non-2xx response on every endpoint uses this shape.

### 401 Unauthorized Error

Missing or invalid API key

- `error` (ErrorResponseError, required) — The error envelope. Every non-2xx response on every endpoint uses this shape.

### 422 Unprocessable Entity Error

Invalid request (validation)

- `error` (ErrorResponseError, required) — The error envelope. Every non-2xx response on every endpoint uses this shape.

### 429 Too Many Requests Error

Rate limit or daily quota exceeded; includes Retry-After

- `error` (ErrorResponseError, required) — The error envelope. Every non-2xx response on every endpoint uses this shape.

### 500 Internal Server Error

Internal error

- `error` (ErrorResponseError, required) — The error envelope. Every non-2xx response on every endpoint uses this shape.

## Types

### ErrorResponseError

The error envelope. Every non-2xx response on every endpoint uses this shape.

- `type` (enum, required)
  - Allowed values: `invalid_request_error`, `authentication_error`, `permission_error`, `not_found_error`, `rate_limit_error`, `api_error`
- `message` (string, required)

## Examples

**Request**

```json
{
  "query": "What are investors expecting from NVDA's datacenter revenue over the next two quarters?"
}
```

**SDK Code**

```python insights_ask-stream_example
import requests

url = "https://api.sonicalpha.ai/v1/insights/ask/stream"

payload = { "query": "What are investors expecting from NVDA's datacenter revenue over the next two quarters?" }
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript insights_ask-stream_example
const url = 'https://api.sonicalpha.ai/v1/insights/ask/stream';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"query":"What are investors expecting from NVDA\'s datacenter revenue over the next two quarters?"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go insights_ask-stream_example
package main

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

func main() {

	url := "https://api.sonicalpha.ai/v1/insights/ask/stream"

	payload := strings.NewReader("{\n  \"query\": \"What are investors expecting from NVDA's datacenter revenue over the next two quarters?\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby insights_ask-stream_example
require 'uri'
require 'net/http'

url = URI("https://api.sonicalpha.ai/v1/insights/ask/stream")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"query\": \"What are investors expecting from NVDA's datacenter revenue over the next two quarters?\"\n}"

response = http.request(request)
puts response.read_body
```

```java insights_ask-stream_example
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.sonicalpha.ai/v1/insights/ask/stream")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"query\": \"What are investors expecting from NVDA's datacenter revenue over the next two quarters?\"\n}")
  .asString();
```

```php insights_ask-stream_example
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.sonicalpha.ai/v1/insights/ask/stream', [
  'body' => '{
  "query": "What are investors expecting from NVDA\'s datacenter revenue over the next two quarters?"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp insights_ask-stream_example
using RestSharp;

var client = new RestClient("https://api.sonicalpha.ai/v1/insights/ask/stream");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"query\": \"What are investors expecting from NVDA's datacenter revenue over the next two quarters?\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift insights_ask-stream_example
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = ["query": "What are investors expecting from NVDA's datacenter revenue over the next two quarters?"] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.sonicalpha.ai/v1/insights/ask/stream")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```