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

# Sending browser video to Interhuman

> How The Pitch Practice, an open-source founder-coaching demo, streams browser video to Interhuman and scores delivery in real time — the integration rebuilt on the current API and the Interhuman SDKs, with code, container details, and the size limits worth knowing.

*TL;DR: [The Pitch Practice](https://github.com/InterhumanAI/interhuman-example-pitch) is an open-source demo where founders record a pitch and get scored on both delivery and content. The behavioral half runs on Interhuman's [stream analysis](https://docs.interhuman.ai/how-to/build-with-the-stream-endpoint.md), and the whole integration is small enough to read in one sitting: a token route on your server, a streaming client in the browser, and a bit of scoring on top. This post rebuilds that integration end to end on the current API (Inter-2) and the Interhuman SDKs, plus the WebM container details and size limits worth knowing before you ship.*

The Pitch Practice scores something a transcript can't reach. A pitch that reads well on paper still falls apart in the room when the energy drops or the ask trails off, and that half of the story lives in delivery rather than words. A founder records a one-to-three-minute pitch to their webcam, and the app scores both the substance of what they said and the way they said it, with per-moment signals like confidence, hesitation, and stress pinned to the exact second they happened.

The interesting part for a builder is how little it takes to wire that up. In this demo the browser streams straight to Interhuman, so no media passes through the app's own servers and there's no socket to host. That's a deliberate choice to keep a demo lightweight, not the only way to build it. You can just as easily route the stream through your own backend, and a serious product often will, to keep the connection under your control and add auth, logging, rate limiting, or your own retention rules. Interhuman supports both; the difference is operational surface area, not capability. The rest of this post walks the direct-from-browser path the demo uses, with enough detail about the format underneath that nothing surprises you in production.

> [!NOTE]
>
> The code in this post uses the current Interhuman API (`WS /v2/stream/analyze` and `POST /v2/upload/analyze`) through the first-party SDKs: [`@interhumanai/sdk`](https://docs.interhuman.ai/sdk-reference/typescript-sdk) for TypeScript and [`interhumanai`](https://docs.interhuman.ai/sdk-reference/python-sdk) for Python. The open-source repository predates the SDKs, so its transport code differs from the samples here; its scoring code is the same.

## The shape of it

Three pieces, one job each.

```mermaid theme={null}
flowchart LR
    A["Browser<br/>MediaRecorder, 3s chunks"] -- "1 - request session" --> B["/api/stream/session<br/>(holds the API key)"]
    B -- "mint client token" --> C["Interhuman"]
    C -- "capped client token" --> B
    B -- "client token" --> A
    A -- "2 - wss /v2/stream/analyze<br/>+ client token" --> C
    A -- "3 - each chunk, as produced" --> C
    C -- "signal.*, engagement.*,<br/>conversation_quality.*" --> A
```

Your server mints a short-lived **client token** with your API key. The browser connects directly to Interhuman with it, streams recorded chunks up as it captures them, and receives analysis events back. The caps on the token (lifetime, session duration, bytes, media seconds, allowed origins) are enforced by Interhuman itself.

> [!NOTE]
>
> This is the demo's architecture, chosen because it's the lightest to run. It is not the only one. If you'd rather keep every byte under your control, proxy the WebSocket through your own backend and forward frames upstream to Interhuman instead of connecting the browser directly. That's the more common shape for a production app that wants server-side auth, logging, rate limiting, or retention. Interhuman works the same either way.

## 1. Mint a client token, server-side

Your API key never leaves the server. The one server responsibility is handing the browser a short-lived, capped [client token](https://docs.interhuman.ai/api-reference/client-tokens.md) it can open a session with. The SDK's `AuthClient` mints one:

```typescript TypeScript icon="square-js" theme={null}
// app/api/stream/session/route.ts — runs on your server only
import { AuthClient, Scope } from "@interhumanai/sdk";

const auth = new AuthClient();

export async function POST() {
  const token = await auth.createClientToken({
    apiKey: process.env.INTERHUMAN_API_KEY!, // never sent to the browser
    scopes: [Scope.Stream],
    expiresIn: 300, // seconds to open the session; clamped to 60–3600
    maxDurationSeconds: 240, // a pitch is at most three minutes
    maxVideoSeconds: 240,
    allowedOrigins: [process.env.APP_ORIGIN!], // e.g. "https://pitch.example.com"
  });
  return Response.json({ token: token.access_token });
}
```

```python Python icon="python" theme={null}
# A server-side token route, for a Python backend
import os

from interhumanai import AuthClient, Scope

auth = AuthClient()


async def mint_stream_token() -> str:
    token = await auth.create_client_token(
        api_key=os.environ["INTERHUMAN_API_KEY"],  # never sent to the browser
        scopes=[Scope.STREAM],
        expires_in=300,  # seconds to open the session; clamped to 60-3600
        max_duration_seconds=240,  # a pitch is at most three minutes
        max_video_seconds=240,
        allowed_origins=[os.environ["APP_ORIGIN"]],  # e.g. "https://pitch.example.com"
    )
    return token.access_token
```

Expose that behind a single route (`POST /api/stream/session`) that returns the token. That's the entire backend. Size the caps to the session you expect: they are your blast radius if a token leaks, and [Build with the stream endpoint](https://docs.interhuman.ai/how-to/build-with-the-stream-endpoint.md#mint-a-client-token) lists every one.

## 2. Stream from the browser

Record with `MediaRecorder` on a timeslice, and send each chunk the moment it's produced. The SDK's `StreamClient` opens the WebSocket, authenticates with the client token (browsers can't set an `Authorization` header on a WebSocket, so it sends the token in the `access_token` subprotocol pair), and gives you typed events.

```typescript theme={null}
import { StaticTokenProvider, StreamClient } from "@interhumanai/sdk";

// open the session with the client token from your route
const res = await fetch("/api/stream/session", { method: "POST" });
if (!res.ok) throw new Error(`Could not start an analysis session (${res.status})`);
const { token } = await res.json();

const stream = new StreamClient({
  tokenProvider: new StaticTokenProvider(token),
  apiVersion: "v2", // WS /v2/stream/analyze
  model: "inter-2", // reads picture and sound together
});

await stream.connect();
await stream.waitForSessionReady();
stream.updateConfig({ include: ["conversation_quality_overall"] });
```

```typescript theme={null}
// send each MediaRecorder chunk live, in order, exactly as produced.
// Keep the handler synchronous so chunks can't reorder and the close can't
// overtake the last one.
recorder.ondataavailable = (e) => {
  if (e.data.size > 0) {
    chunksRef.current.push(e.data); // kept only for local playback
    stream.sendVideo(e.data); // sent live for analysis
  }
  if (recorder.state === "inactive") stream.requestClose(); // after the last chunk
};

recorder.start(3000); // the next 3s piece of one continuous recording, every 3 seconds
```

One rule makes this reliable, and it's a rule about doing *less*: send each segment exactly as `MediaRecorder` produces it. No buffering, no re-slicing, no reassembly. The next section is why that rule exists, and it's worth understanding once so you never fight it.

## Under the hood: what MediaRecorder hands you

A WebM file isn't a flat blob of video. It's a nested binary structure (EBML, from the same family as Matroska and MKV), with a header describing the codecs and tracks, followed by one or more **Clusters** that each hold a chunk of frames. A player reads the header once, up front, to know what it's looking at.

The detail that matters for streaming is what a timeslice does to that layout.

> [!WARNING]
>
> With a `MediaRecorder` timeslice, only the **first** chunk carries the header (EBML, Segment, Info, and Tracks). Every chunk after it is a bare Cluster — playable in context, and not decodable on its own.

This is exactly why the live-streaming path is the clean one. When you forward each chunk the instant it's produced, in order, on one session, the sequence reconstructs perfectly on Interhuman's side: the first frame establishes the header, and each later frame continues from it. The browser is already producing valid segments, so you just relay them.

It's also why you don't want to parse or rebuild the container yourself. Browser recordings are *live-muxed*: Chrome has no idea how long you'll talk, so it writes the Segment and each Cluster with an **unknown size** (a special all-ones bit pattern in the EBML length field) rather than a known byte count. A parser that only handles known-size elements — which is what a unit test against `ffmpeg`-generated fixtures quietly validates — will mis-cut real Chrome output and produce a segment the API rejects with [`ih5004`](https://docs.interhuman.ai/api-reference/error-handling) ("malformed segment"). The live path sidesteps all of it, which is the whole point of streaming segments verbatim.

> [!NOTE]
>
> The full guidance is in [Build with the stream endpoint](https://docs.interhuman.ai/how-to/build-with-the-stream-endpoint.md): mint a capped client token server-side, stream directly from the browser, and never re-slice or reinterpret the media container in between.

## Size limits worth knowing

Two numbers shape the design.

The stream endpoint caps a single WebSocket message at **32 MB**, and large single messages fail unreliably even under the cap. So the stream wants many small frames — one per recorder chunk — rather than one big one. The Pitch Practice records at a **1 Mbps** video bitrate, which is ample for face-and-voice delivery analysis: each 3-second chunk is roughly 400 KB, and a whole three-minute pitch comes to around 25 MB.

```typescript theme={null}
const recorder = new MediaRecorder(mediaStream, {
  mimeType, // video/webm;codecs=vp9,opus (or vp8 fallback)
  videoBitsPerSecond: 1_000_000, // 1 Mbps — plenty for delivery analysis
  audioBitsPerSecond: 128_000,
});
```

The second number is the upload limit, for the saved-video path below: `POST /v2/upload/analyze` takes a file of up to **100 MB** and 30 minutes, so a saved pitch fits with room to spare. A larger file is refused with `ih4003`.

## The saved-video path

Live streaming covers the common case. The Pitch Practice also lets founders re-analyze a pitch they saved locally earlier, where there's no live recorder to stream from — just a finished blob. The demo replays the saved chunks into a new stream, rebuilding the header for each one. On the current API, don't: a finished file is what the [upload endpoint](https://docs.interhuman.ai/api-reference/upload-analyze.md) is for. Submit the whole blob as an analysis job, and read the job when it finishes. Nothing parses or re-slices the container.

The browser can submit it directly, like the stream. Have your token route mint a second client token with the upload scope (`scopes: [Scope.Upload]`). Every poll of the job sends that token too, so give it a lifetime that covers the upload, any retry waits, and the analysis — `expiresIn: 1800` is comfortable for a three-minute pitch. Then:

```typescript theme={null}
import { InterhumanApiError, InterhumanClient, newIdempotencyKey } from "@interhumanai/sdk";

const client = new InterhumanClient({ accessToken: token }); // a client token with Scope.Upload

async function submitWithRetry(file: Blob, attempts = 5) {
  // One key per file, reused only for that file's retries: a retry with the
  // same key returns the first job instead of starting a duplicate.
  const idempotencyKey = newIdempotencyKey();
  for (let attempt = 1; ; attempt++) {
    try {
      return await client.upload.submit({
        file,
        filename: "pitch.webm",
        model: "inter-2",
        include: ["conversation_quality_overall", "signals"],
        idempotencyKey,
      });
    } catch (err) {
      // 503 and ih4024 ask for a retry. A network failure (fetch's TypeError) may
      // have reached the server, which is the case the key makes safe to retry.
      const retryable =
        (err instanceof InterhumanApiError && (err.status === 503 || err.errorId === "ih4024")) ||
        err instanceof TypeError;
      if (!retryable || attempt === attempts) throw err;
      // Wait as long as Retry-After asks, plus a little jitter.
      const retryAfter = err instanceof InterhumanApiError ? err.retryAfterSeconds : undefined;
      const waitSeconds = (retryAfter ?? 2) + Math.random() * 2;
      await new Promise((resolve) => setTimeout(resolve, waitSeconds * 1000));
    }
  }
}

const job = await client.upload.waitForJob(await submitWithRetry(savedBlob));
if (job.status === "failed") throw new Error(job.error?.message ?? "Analysis failed");
// job.result.signals and job.result.conversation_quality feed the same scoring code
```

`idempotencyKey` and `newIdempotencyKey()` need `@interhumanai/sdk` 4.0.0 or later. A job stays readable until its `expires_at`, 24 hours after submission. Read the result and keep what you need before `expires_at`. [Upload jobs](https://docs.interhuman.ai/api-reference/upload-jobs.md) has the job envelope, and [Error handling](https://docs.interhuman.ai/api-reference/error-handling.md) has the full retry guidance.

> [!NOTE]
>
> For a deeper read of a saved recording, `inter-2-deep` reads the same video files and adds reasoning to every window of its result. It uses the same `interhumanai.upload` scope, and by default it accepts files up to two minutes long, so a three-minute pitch needs `inter-2`.

## A note on serverless hosts

One deployment detail is worth knowing on serverless hosts: on Vercel, function request bodies cap around 4.5MB while Vercel Blob multipart parts must be at least 5MB, so a real recording can't be proxied through a function part-by-part. The client-token pattern above already avoids the problem — the browser sends the bytes to Interhuman directly, and the token route is one small JSON request. If you also keep your own copy of the recording, upload it client-direct to Blob with a signed token, keeping the bytes out of your function entirely:

```typescript theme={null}
// upload straight to Blob storage; the serverless function is never
// in the data path
import { upload } from "@vercel/blob/client";

const blob = await upload(`pitches/${videoId}.webm`, recordedBlob, {
  access: "public",
  handleUploadUrl: "/api/upload/blob",
});
```

For the live coaching experience, though, streaming wins outright: signals arrive while the user is still talking, so the read is essentially done by the time they stop.

## Fold events into your UI

Analysis events stream back as JSON throughout the recording, and the SDK hands each one to a typed handler. Each event type maps straight onto whatever your results view needs. Register the handlers before you start the recorder, so no event arrives unheard.

```typescript theme={null}
import type { Probability, SignalType } from "@interhumanai/sdk";

type OpenSignal = { start: number; probability: Probability | null; rationale: string | null };
const signals: (OpenSignal & { type: SignalType; end: number })[] = [];
const open = new Map<SignalType, OpenSignal>();

stream.on("signal.detected", ({ data }) => {
  // start of confidence/hesitation/…
  const { start, probability, rationale } = data;
  open.set(data.signal_type, { start, probability, rationale });
});
stream.on("signal.updated", ({ data }) => {
  // the same signal, with a new probability or rationale
  const current = open.get(data.signal_type);
  if (current) Object.assign(current, { probability: data.probability, rationale: data.rationale });
});
stream.on("signal.ended", ({ data }) => {
  // its matching end
  const started = open.get(data.signal_type);
  if (started) signals.push({ type: data.signal_type, ...started, end: data.end });
  open.delete(data.signal_type);
});
stream.on("engagement.updated", ({ data }) => engagementStates.push(data)); // { state, start }
stream.on("conversation_quality.updated", ({ data }) => {
  if (data.overall) applyQuality(data.overall); // clarity / authority / energy
});
stream.on("error", ({ data }) => console.warn(data.code, data.message));
stream.on("close", () => showResults(signals)); // after session.ended, or on any other close
```

Signals arrive as a `signal.detected` / `signal.ended` pair: the detection carries a probability and a plain-language rationale, a `signal.updated` revises them while the signal is active, and the end closes it. On a real pitch, a hesitation signal landed right on the traction number, flagged as *"a noticeable pause and a rising, uncertain tone right before the revenue numbers — the traction is strong but the delivery hedges it."* That's the raw material a coaching UI turns into "say the traction number like you believe it."

When the user stops, the recorder hands over its last chunk and the handler calls `stream.requestClose()`. The server finishes analyzing what it has, sends `signal.ended` for anything still active, then `session.ended`, and closes the socket — so wait for that close rather than closing the socket yourself, or you lose the trailing analysis. Showing results on `close` also covers a session that ends any other way, with whatever arrived.

## Turning signals into a score

With the events accumulated, the score is straightforward. Delivery is a weighted blend of five fields, with a signal-only fallback when conversation quality isn't requested.

```typescript theme={null}
// src/lib/scoring.ts
if (hasConversationQuality) {
  deliveryComposite = Math.round(
    breakdown.authority * 0.3 +
    breakdown.clarity * 0.25 +
    breakdown.energy * 0.2 +
    breakdown.confidence * 0.15 +
    breakdown.lowHesitation * 0.1
  );
} else {
  deliveryComposite = Math.round((confidenceScore + lowHesitationScore) / 2);
}
```

Worth being precise about where each of those five numbers comes from, because some are Interhuman's and some are The Pitch Practice's own:

| Field | Comes from | What it is |
| - | - | - |
| `authority` | **Interhuman** | Read straight off `conversation_quality.overall`. Interhuman returns this as a 0–100 dimension. |
| `clarity` | **Interhuman** | Same — a `conversation_quality.overall` dimension. |
| `energy` | **Interhuman** | Same — a `conversation_quality.overall` dimension. |
| `confidence` | **The Pitch Practice** | Derived from the raw signal stream, not returned by Interhuman. The app counts medium/high-probability `confidence` signals net of `hesitation` and `uncertainty` over the recording's duration. |
| `lowHesitation` | **The Pitch Practice** | Also derived — a penalty built from `hesitation`, `stress`, and `uncertainty` signal counts. |

So Interhuman gives you two kinds of output: a set of `conversation_quality` dimensions (the demo uses `authority`, `clarity`, and `energy`, and the endpoint also returns `quality_index`, `rapport`, and `learning`), and a stream of discrete social **signals** — `confidence`, `hesitation`, `stress`, `uncertainty`, `interest` — each with a probability, timestamps, and a rationale. The `confidence` and `lowHesitation` breakdown fields are the app's own summaries of those raw signals; there is no "confidence score" in the API response. The weights themselves (0.3 / 0.25 / 0.2 / 0.15 / 0.1) are entirely The Pitch Practice's editorial call about what makes a good pitch — Interhuman supplies the dimensions and signals, and how you roll them into one headline number is yours. The fallback branch runs when you don't request conversation quality at all, scoring purely from those two signal-derived numbers.

Content is scored separately from the transcript: an LLM rubric (message clarity, problem framing, solution value, evidence specificity, narrative, and the ask) blended with speech metrics computed from the words themselves — pace, which reads best around 150 words a minute, and filler density, which counts every "um" and "you know."

```typescript theme={null}
// src/lib/transcript-scoring.ts — pace peaks at ~150 wpm; heavy filler
// use floors the score rather than zeroing it out
const paceScore = clamp(Math.round(100 - Math.abs(wordsPerMinute - 150) * 0.5));
const fillerScore = clamp(Math.round(100 - Math.min(70, fillerDensity * 6)));
```

Delivery from Interhuman's audio and video signals, content from the transcript, blended 50/50 into one number a founder can act on. The whole scoring layer is a handful of small, pure functions on top of the event stream.

The content rubric has real research behind it. One mode, Q\&A Practice, is built on a finding from Kanze et al. on investor pitch questions: investors unconsciously ask founders *prevention*-framed questions (what could go wrong, how you'll defend your position) far more often than *promotion*-framed ones (what the upside is, how you'll grow), and founders who catch a prevention question and reframe their answer toward promotion raise measurably more money. The practice mode turns that reframe into a trained reflex instead of something you improvise for the first time in front of a term sheet.

## Lift it into your own app

That's the complete integration: a token route, a streaming client, a scoring pass, and a clear picture of the container it all rides on. No media on your servers, no infrastructure to run, and real-time behavioral signals arriving while the user is still speaking. The same three pieces drop into interview practice, sales coaching, or anywhere else a human is talking to a camera. For a microphone-only product, open the session with `model: "inter-2-audio"` and record audio alone; [Choose a model](https://docs.interhuman.ai/how-to/build-with-the-stream-endpoint.md#choose-a-model) has the lines that change. That model reports the six signals it can hear (agreement, confidence, frustration, hesitation, interest, and uncertainty) and no `stress`, so a score built from `stress` needs adjusting.

The Pitch Practice is open source and [MIT-licensed on GitHub](https://github.com/InterhumanAI/interhuman-example-pitch). You can stand up your own copy on Vercel in one click — the clone flow forks the repo into your own GitHub account, provisions a Vercel project, and prompts for the single required environment variable, `INTERHUMAN_API_KEY` (the optional Supabase variables add the leaderboard; the app runs fine without them):

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FInterhumanAI%2Finterhuman-example-pitch\&project-name=the-pitch-practice\&repository-name=the-pitch-practice\&env=INTERHUMAN_API_KEY\&env=NEXT_PUBLIC_SUPABASE_URL\&env=NEXT_PUBLIC_SUPABASE_ANON_KEY\&env=SUPABASE_SERVICE_ROLE_KEY\&envDescription=INTERHUMAN_API_KEY%20is%20required.%20For%20the%20leaderboard%2C%20set%20all%20three%20Supabase%20variables%20and%20apply%20supabase%2Fschema.sql%20in%20the%20Supabase%20SQL%20Editor%2C%20then%20redeploy%20Production.\&envLink=https%3A%2F%2Fdocs.interhuman.ai%2Fhow-to%2Fget-api-key)

Prefer to work locally? Clone the repo, read the scoring code, and lift the behavioral layer into whatever you're building with the SDK samples above.

## Next steps

* [Build with the stream endpoint](https://docs.interhuman.ai/how-to/build-with-the-stream-endpoint.md) — the architecture above, in full.
* [Stream analysis reference](https://docs.interhuman.ai/api-reference/stream-analyze.md) — the message schema for `wss://api.interhuman.ai/v2/stream/analyze`.
* [Client tokens](https://docs.interhuman.ai/api-reference/client-tokens.md) — the caps and scopes a browser token can carry.
* [TypeScript SDK](https://docs.interhuman.ai/sdk-reference/typescript-sdk.md) and [Python SDK](https://docs.interhuman.ai/sdk-reference/python-sdk.md) — `AuthClient`, `StreamClient`, typed events, and upload jobs.
* [Upload analysis reference](https://docs.interhuman.ai/api-reference/upload-analyze.md) — the saved-video path, with limits and retries.
* [Error handling](https://docs.interhuman.ai/api-reference/error-handling.md) — the full catalog, including `ih5004` and `ih6002`.
* [The Pitch Practice on GitHub](https://github.com/InterhumanAI/interhuman-example-pitch) — the repo this post is drawn from.
* [Social signals](https://docs.interhuman.ai/explanations/social-signals.md) and [Conversation quality](https://docs.interhuman.ai/explanations/conversation-quality.md) — what the delivery score is built from.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.