# Quickstart

> Send two turns of a conversation and receive the moments in them, in five minutes.

You'll create a conversation, send it two things people said on a renewal call, and receive a
`decision` and a `request.do`: first on an event stream, then as a signed webhook.

**@sparkle/sdk is in private beta**
The TypeScript tabs use `@sparkle/sdk`, which isn't on npm yet. To try it, [ask us for
access](https://sparkle.ai/contact). Python and Go have no SDK yet: the cURL, Python and Go tabs
call the HTTP API directly.

### Get a test key

In the dashboard, open **Settings → API keys** and create a key in the test environment. Test keys
start with `spk_test_` and are never billed. Their conversations' events, marked `livemode: false`,
go only to test webhook subscriptions, never to your live endpoints ([test and
live](/docs/webhooks#test-and-live)). Export it for the commands below:

```bash
export SPARKLE_API_KEY=spk_test_...
```

### Create a conversation

A conversation is one call or meeting. Create it with a `webhook_url`, and every event of this
conversation is delivered there. Use any public HTTPS URL that reaches port 3000 on your machine,
such as one from `ngrok http 3000`; you'll start the server behind it in step 5.

**cURL**
```bash
curl https://api.sparkle.ai/public/v1/conversations \
  -H "X-API-Key: $SPARKLE_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Acme renewal call",
    "webhook_url": "https://example.ngrok.app/sparkle"
  }'
```

**TypeScript**
```ts
import { Sparkle } from "@sparkle/sdk";

const sparkle = new Sparkle(); // reads SPARKLE_API_KEY

const { conversation, webhook } = await sparkle.conversations.create({
  title: "Acme renewal call",
  webhook_url: "https://example.ngrok.app/sparkle",
});
```

**Python**
```python
import os
import uuid

import requests

API = "https://api.sparkle.ai/public/v1"
headers = {"X-API-Key": os.environ["SPARKLE_API_KEY"]}

created = requests.post(
    f"{API}/conversations",
    headers={**headers, "Idempotency-Key": str(uuid.uuid4())},
    json={
        "title": "Acme renewal call",
        "webhook_url": "https://example.ngrok.app/sparkle",
    },
).json()
conversation_id = created["conversation"]["id"]
```

**Go**
```go
body := strings.NewReader(`{
  "title": "Acme renewal call",
  "webhook_url": "https://example.ngrok.app/sparkle"
}`)
req, _ := http.NewRequest("POST", "https://api.sparkle.ai/public/v1/conversations", body)
req.Header.Set("X-API-Key", os.Getenv("SPARKLE_API_KEY"))
req.Header.Set("Idempotency-Key", rand.Text()) // crypto/rand
req.Header.Set("Content-Type", "application/json")

resp, err := http.DefaultClient.Do(req)
if err != nil {
	log.Fatal(err)
}
defer resp.Body.Close()

var created struct {
	Conversation struct{ ID string } `json:"conversation"`
	Webhook      struct{ Secret string } `json:"webhook"`
}
json.NewDecoder(resp.Body).Decode(&created)
```

Every `POST` and `PUT` takes an `Idempotency-Key`: sending the same key again returns the first
response instead of acting twice. The response holds the conversation and its webhook:

```json
{
  "conversation": {
    "id": "cnv_2kd7q1v9x4m8r2t6b3ny",
    "tenant_id": "ten_2kd5m0c8w3e7h1p4s9fa",
    "organization_id": "org_2kd5m0d2y6b0k4n8r1gc",
    "environment": "test",
    "status": "live",
    "title": "Acme renewal call",
    "metadata": {},
    "moment_types": [],
    "moments_count": 0,
    "started_at": "2026-12-03T15:00:00Z",
    "webhook": {
      "id": "whs_2kd7q1w3z7c1f5j9m2pd",
      "url": "https://example.ngrok.app/sparkle"
    },
    "created_at": "2026-12-03T15:00:00Z",
    "updated_at": "2026-12-03T15:00:00Z"
  },
  "receivers": [],
  "webhook": {
    "id": "whs_2kd7q1w3z7c1f5j9m2pd",
    "url": "https://example.ngrok.app/sparkle",
    "secret": "whsec_8c1f4e0b9a6d2f7e5c3b1a0d9e8f7c6b5a4d3e2f"
  }
}
```

`webhook.secret` signs every delivery to that URL, and this is the only time you see it. The URL
receives this conversation's `conversation.created`, `moment.detected` and `conversation.ended`. For
one URL that receives every conversation's events, `conversation.deleted` included, create a
[webhook subscription](/docs/webhooks) instead, once, and leave `webhook_url` out.

Keep the secret, along with the conversation's `id`:

```bash
export CONVERSATION_ID=cnv_2kd7q1v9x4m8r2t6b3ny
export SPARKLE_WEBHOOK_SECRET=whsec_8c1f4e0b9a6d2f7e5c3b1a0d9e8f7c6b5a4d3e2f
```

`started_at` is time zero of the conversation's clock. Turn times count from it, in seconds.

### Send two turns

A turn is one stretch of one person speaking. Send two: Sam agrees to the renewal terms four seconds
in, and Dana commits to a fix twenty seconds later.

**cURL**
```bash
curl https://api.sparkle.ai/public/v1/conversations/$CONVERSATION_ID/turns \
  -H "X-API-Key: $SPARKLE_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{
    "turns": [
      {
        "id": "t1",
        "final": true,
        "speaker": "sam",
        "name": "Sam",
        "channel": "mic",
        "start": 0.8,
        "end": 4.1,
        "text": "Okay, let'\''s go with the two-year term at the current tier."
      },
      {
        "id": "t2",
        "final": true,
        "speaker": "dana",
        "name": "Dana",
        "channel": "remote",
        "start": 21.0,
        "end": 23.4,
        "text": "I'\''ll get the SSO fix out by Friday."
      }
    ]
  }'
```

**TypeScript**
```ts
await sparkle.conversations.turns.send(conversation.id, [
  {
    id: "t1",
    final: true,
    speaker: "sam",
    name: "Sam",
    channel: "mic",
    start: 0.8,
    end: 4.1,
    text: "Okay, let's go with the two-year term at the current tier.",
  },
  {
    id: "t2",
    final: true,
    speaker: "dana",
    name: "Dana",
    channel: "remote",
    start: 21.0,
    end: 23.4,
    text: "I'll get the SSO fix out by Friday.",
  },
]);
```

**Python**
```python
requests.post(
    f"{API}/conversations/{conversation_id}/turns",
    headers={**headers, "Idempotency-Key": str(uuid.uuid4())},
    json={
        "turns": [
            {
                "id": "t1",
                "final": True,
                "speaker": "sam",
                "name": "Sam",
                "channel": "mic",
                "start": 0.8,
                "end": 4.1,
                "text": "Okay, let's go with the two-year term at the current tier.",
            },
            {
                "id": "t2",
                "final": True,
                "speaker": "dana",
                "name": "Dana",
                "channel": "remote",
                "start": 21.0,
                "end": 23.4,
                "text": "I'll get the SSO fix out by Friday.",
            },
        ]
    },
).raise_for_status()
```

**Go**
```go
type Turn struct {
	ID      string  `json:"id"`
	Final   bool    `json:"final"`
	Speaker string  `json:"speaker"`
	Name    string  `json:"name,omitempty"`
	Channel string  `json:"channel"`
	Start   float64 `json:"start"`
	End     float64 `json:"end"`
	Text    string  `json:"text"`
}

payload, _ := json.Marshal(map[string][]Turn{"turns": {
	{"t1", true, "sam", "Sam", "mic", 0.8, 4.1,
		"Okay, let's go with the two-year term at the current tier."},
	{"t2", true, "dana", "Dana", "remote", 21.0, 23.4,
		"I'll get the SSO fix out by Friday."},
}})
url := "https://api.sparkle.ai/public/v1/conversations/" + created.Conversation.ID + "/turns"
req, _ := http.NewRequest("POST", url, bytes.NewReader(payload))
req.Header.Set("X-API-Key", os.Getenv("SPARKLE_API_KEY"))
req.Header.Set("Idempotency-Key", rand.Text())
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
```

Sparkle answers `202 Accepted` with no body: it has stored the turns and reads them in the
background. [The turn contract](/docs/concepts/turns) explains each field, and why sending a turn
twice is safe.

### Stream the moments

The conversation's event stream sends each moment as a server-sent event, the ones already detected
first. `-N` turns off curl's buffering, so each event prints as it arrives:

**cURL**
```bash
curl -N https://api.sparkle.ai/public/v1/conversations/$CONVERSATION_ID/stream \
  -H "X-API-Key: $SPARKLE_API_KEY"
```

**TypeScript**
```ts
for await (const event of sparkle.conversations.stream(conversation.id)) {
  if (event.type === "moment.detected") {
    console.log(event.data.kind, event.data.speaker.name, event.data.text);
  }
}
```

**Python**
```python
import json

with requests.get(
    f"{API}/conversations/{conversation_id}/stream", headers=headers, stream=True
) as stream:
    for line in stream.iter_lines(decode_unicode=True):
        if line.startswith("data: "):
            moment = json.loads(line[len("data: "):])["data"]
            print(moment["kind"], moment["speaker"]["name"], moment["text"])
```

**Go**
```go
url := "https://api.sparkle.ai/public/v1/conversations/" + created.Conversation.ID + "/stream"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("X-API-Key", os.Getenv("SPARKLE_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
	log.Fatal(err)
}
defer resp.Body.Close()

scanner := bufio.NewScanner(resp.Body)
scanner.Buffer(make([]byte, 0, 64*1024), 1<<20)
for scanner.Scan() {
	if data, ok := strings.CutPrefix(scanner.Text(), "data: "); ok {
		var event struct {
			Data struct {
				Kind string `json:"kind"`
				Text string `json:"text"`
			} `json:"data"`
		}
		json.Unmarshal([]byte(data), &event)
		fmt.Println(event.Data.Kind, event.Data.Text)
	}
}
```

Two events arrive. Lines that start with `:` are comments that keep the connection open:

```text
: connected

id: 1796310031204-0
event: moment.detected
data: {"id":"evt_2kd7qc4h8n1s5w9z3b6e","object":"event","type":"moment.detected","livemode":false,"data":{"kind":"decision","text":"Okay, let's go with the two-year term at the current tier.",…}}

id: 1796310031377-0
event: moment.detected
data: {"id":"evt_2kd7qd8k2p6t0x4a7c1f","object":"event","type":"moment.detected","livemode":false,"data":{"kind":"request.do","text":"I'll get the SSO fix out by Friday.",…}}
```

Each `data` line is one event. The second one, formatted:

```json
{
  "id": "evt_2kd7qd8k2p6t0x4a7c1f",
  "object": "event",
  "type": "moment.detected",
  "livemode": false,
  "created_at": "2026-12-03T15:00:31Z",
  "data": {
    "id": "mom_2kd7qb3f7j1n5r9v2y6d",
    "object": "moment",
    "conversation_id": "cnv_2kd7q1v9x4m8r2t6b3ny",
    "kind": "request.do",
    "title": "Dana · Ship the SSO fix by Friday",
    "text": "I'll get the SSO fix out by Friday.",
    "speaker": { "key": "dana", "name": "Dana" },
    "at": 23.4,
    "confidence": 0.91,
    "turn_ids": ["t2"],
    "settled_ms": 0,
    "classifier": "typesafe:…",
    "definition": null,
    "created_at": "2026-12-03T15:00:31.377214Z"
  }
}
```

Look at `settled_ms`. The `decision` went out 5,000 ms after Sam stopped talking: Sparkle waited
for the exchange to settle, in case someone objected. The `request.do` has `0`: a commitment is
complete when it's said. [Timing profiles](/docs/concepts/timing) explains the difference.

### Receive the webhook

The same two events were sent to your `webhook_url`, signed with the conversation's secret. Run a
server on port 3000 behind that URL. It checks the signature on the raw body, drops events it has
already handled, and answers `2xx` quickly:

**TypeScript**
```ts title="server.ts"
import { createServer } from "node:http";
import { Sparkle, SparkleSignatureError } from "@sparkle/sdk";

const seen = new Set<string>();

createServer(async (req, res) => {
  const chunks: Buffer[] = [];
  for await (const chunk of req) chunks.push(chunk);
  try {
    // Checks Sparkle-Signature against the raw body, and its timestamp against your clock.
    const event = await Sparkle.webhooks.verify(
      Buffer.concat(chunks),
      req.headers,
      process.env.SPARKLE_WEBHOOK_SECRET!
    );
    if (!seen.has(event.id)) {
      seen.add(event.id);
      if (event.type === "moment.detected") {
        console.log(event.type, event.data.kind, event.data.text);
      } else {
        console.log(event.type);
      }
    }
    res.writeHead(204).end();
  } catch (error) {
    if (!(error instanceof SparkleSignatureError)) throw error;
    res.writeHead(400).end("invalid signature");
  }
}).listen(3000);
```

**Python**
```python title="server.py"
import hashlib
import hmac
import json
import os
import time

from flask import Flask, request

app = Flask(__name__)
SECRET = os.environ["SPARKLE_WEBHOOK_SECRET"].encode()
seen: set[str] = set()

def verify(header: str, body: bytes) -> bool:
    parts = [part.strip().partition("=") for part in header.split(",")]
    t = next((value for key, _, value in parts if key == "t"), "")
    signatures = [value for key, _, value in parts if key == "v1"]
    if not t.isdigit() or not signatures or abs(time.time() - int(t)) > 300:
        return False
    expected = hmac.new(SECRET, f"{t}.".encode() + body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, sig) for sig in signatures)

@app.post("/sparkle")
def sparkle():
    body = request.get_data()
    if not verify(request.headers.get("Sparkle-Signature", ""), body):
        return "invalid signature", 400
    event = json.loads(body)
    if event["id"] not in seen:
        seen.add(event["id"])
        if event["type"] == "moment.detected":
            print(event["type"], event["data"]["kind"], event["data"]["text"])
        else:
            print(event["type"])
    return "", 204

app.run(port=3000)
```

**Go**
```go title="main.go"
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

func verify(secret, header string, body []byte) bool {
	var t string
	var signatures []string
	for _, part := range strings.Split(header, ",") {
		key, value, _ := strings.Cut(strings.TrimSpace(part), "=")
		switch key {
		case "t":
			t = value
		case "v1":
			signatures = append(signatures, value)
		}
	}
	signedAt, err := strconv.ParseInt(t, 10, 64)
	if err != nil || len(signatures) == 0 {
		return false
	}
	if age := time.Now().Unix() - signedAt; age > 300 || age < -300 {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(t + "."))
	mac.Write(body)
	expected := mac.Sum(nil)
	for _, signature := range signatures {
		got, err := hex.DecodeString(signature)
		if err == nil && hmac.Equal(got, expected) {
			return true
		}
	}
	return false
}

func main() {
	secret := os.Getenv("SPARKLE_WEBHOOK_SECRET")
	seen := map[string]bool{}
	http.HandleFunc("POST /sparkle", func(w http.ResponseWriter, r *http.Request) {
		body, _ := io.ReadAll(r.Body)
		if !verify(secret, r.Header.Get("Sparkle-Signature"), body) {
			http.Error(w, "invalid signature", http.StatusBadRequest)
			return
		}
		var event struct {
			ID   string         `json:"id"`
			Type string         `json:"type"`
			Data map[string]any `json:"data"`
		}
		json.Unmarshal(body, &event)
		if !seen[event.ID] {
			seen[event.ID] = true
			if kind, ok := event.Data["kind"]; ok {
				fmt.Println(event.Type, kind, event.Data["text"])
			} else {
				fmt.Println(event.Type)
			}
		}
		w.WriteHeader(http.StatusNoContent)
	})
	http.ListenAndServe(":3000", nil)
}
```

A delivery that fails, because the server wasn't up yet for example, is retried after 1, 2, 4 and
8 minutes, so the two moments arrive within a few minutes of starting it. They print as:

```text
conversation.created
moment.detected decision Okay, let's go with the two-year term at the current tier.
moment.detected request.do I'll get the SSO fix out by Friday.
```

### End the conversation

When the call is over, end the conversation. Sparkle lets any moment still settling go, then sends
`conversation.ended` with a summary:

**cURL**
```bash
curl -X POST https://api.sparkle.ai/public/v1/conversations/$CONVERSATION_ID/end \
  -H "X-API-Key: $SPARKLE_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)"
```

**TypeScript**
```ts
await sparkle.conversations.end(conversation.id);
```

**Python**
```python
requests.post(
    f"{API}/conversations/{conversation_id}/end",
    headers={**headers, "Idempotency-Key": str(uuid.uuid4())},
).raise_for_status()
```

**Go**
```go
url := "https://api.sparkle.ai/public/v1/conversations/" + created.Conversation.ID + "/end"
req, _ := http.NewRequest("POST", url, nil)
req.Header.Set("X-API-Key", os.Getenv("SPARKLE_API_KEY"))
req.Header.Set("Idempotency-Key", rand.Text())
resp, err := http.DefaultClient.Do(req)
```

```json
{
  "id": "evt_2kd7qf1m5q9u3y7b0d4h",
  "object": "event",
  "type": "conversation.ended",
  "livemode": false,
  "created_at": "2026-12-03T15:02:10Z",
  "data": {
    "conversation": { "id": "cnv_2kd7q1v9x4m8r2t6b3ny", "status": "ended", "…": "…" },
    "summary": {
      "moments_count": 2,
      "moments_by_kind": { "decision": 1, "request.do": 1 },
      "duration_s": 130,
      "turns_count": 2
    }
  }
}
```

## Next steps

- [Send a live transcript](https://docs.sparkle.ai/docs/concepts/turns): The turn contract: partial turns, corrections and speakers.

- [Connect Recall.ai or Deepgram](https://docs.sparkle.ai/docs/receivers/recall): Let a meeting bot or a speech-to-text stream post the turns for you.

- [Define your own moment](https://docs.sparkle.ai/docs/guides/custom-moments): Describe it in plain English, test it on a transcript, then make it live.

- [Import a finished call](https://docs.sparkle.ai/docs/guides/import): Run a recorded transcript through the same detection after the call.