DocumentationAPI ReferenceReact SDKRelease Notes
ScaleAI

Getting Started

OverviewInstallationQuick Start

Core

Provider & Setup

Hooks

AgentsOutbound CallsCall HistoryPhone NumbersIntegration CredentialsWebhooksKnowledge BasesFunction ToolsFunction Logs

Realtime

Realtime

UI

Components

Reference

TypesUtilities
Go to platform

Realtime

Stream live call transcripts over WebSocket and track post-call processing stages over SSE.

ScaleAI provides two realtime hooks that cover the full lifecycle of a call:

HookTransportWhen to open
useCallTranscriptWebSocketImmediately after initiating a call — live audio.
usePostCallSseSSEAfter the call ends — summary, recording, billing.

Both hooks require the call session ID returned by useInitiateTelephonyCall or useOriginateSipCall.


Live call transcript

useCallTranscript

Opens a WebSocket connection to the transcript endpoint and accumulates TranscriptMessage frames as they arrive. You control the connection lifecycle with startTranscriptSession and stopTranscriptSession. The hook also closes the socket automatically on unmount.

import { useCallTranscript } from "@scalereal/sr-voice-engine-react-sdk/hooks";

export function LiveTranscript({ callSessionId }: { callSessionId: string }) {
  const {
    status,
    transcripts,
    isTyping,
    thinkingSide,
    startTranscriptSession,
    stopTranscriptSession,
  } = useCallTranscript({
    onCallEnded: () => console.info("Call ended"),
    onError: (message) => console.error("Transcript error:", message),
  });

  return (
    <section>
      <div>
        <button
          type="button"
          onClick={() => startTranscriptSession(callSessionId)}
          disabled={status === "connecting" || status === "connected"}
        >
          Connect
        </button>
        <button type="button" onClick={stopTranscriptSession}>
          Disconnect
        </button>
        <span>Status: {status}</span>
      </div>

      {isTyping && (
        <p className="animate-pulse">{thinkingSide} is thinking…</p>
      )}

      <ul>
        {transcripts.map((message, index) => (
          <li key={`${message.timestamp}-${index}`}>
            <strong>{message.role}:</strong>{" "}
            {message.type === "transcript" || message.type === "transcription"
              ? typeof message.content === "string"
                ? message.content
                : message.content.message
              : "[function call]"}
          </li>
        ))}
      </ul>
    </section>
  );
}

Connection status

ValueMeaning
"idle"No connection has been opened.
"connecting"Socket is being established.
"connected"Receiving transcript frames.
"error"Connection failed. Call startTranscriptSession to retry.

Calling startTranscriptSession on a hook that already has transcripts will clear the previous transcript array before connecting. This is intentional — each call session starts fresh.

Return values

PropertyTypeDescription
status"idle" | "connecting" | "connected" | "error"Current WebSocket connection state.
transcriptsTranscriptMessage[]Accumulated frames for the current session.
thinkingSideThinkingSide | nullWhich side the system is waiting on ("agent", "user", etc.), or null when idle.
isTypingbooleanShorthand for thinkingSide !== null. Drive a typing indicator with this.
startTranscriptSession(callSessionId: string) => voidOpens (or reopens) the WebSocket for the given session.
stopTranscriptSession() => voidCloses the socket and resets status to "idle".

Options

OptionTypeDescription
onCallEnded() => voidCalled when the server signals the call has ended.
onError(message: string) => voidCalled on socket or server-side errors.
buildUrl(callSessionId: string, ctx: { projectId: string; secretKey: string }) => stringOverride the WebSocket URL. Useful for proxying.
createSocket(url: string) => WebSocketOverride the WebSocket constructor. Useful for testing.

The WebSocket URL includes the secretKey as a query parameter (?token=…). This is a browser limitation — WebSocket connections cannot carry custom Authorization headers. Use the buildUrl option to route through a server-side proxy if you need to hide credentials from the browser.

Opening the transcript right after a call

Use mutateAsync on the call initiation hook to get the session ID synchronously, then start the transcript in the same handler:

import {
  useInitiateTelephonyCall,
  useCallTranscript,
} from "@scalereal/sr-voice-engine-react-sdk/hooks";

export function CallWithLiveTranscript({ agentId }: { agentId: string }) {
  const initiateCall = useInitiateTelephonyCall();
  const transcript = useCallTranscript({
    onCallEnded: () => setCallActive(false),
  });
  const [callActive, setCallActive] = React.useState(false);

  const handleStart = async () => {
    const session = await initiateCall.mutateAsync({
      agent_id: agentId,
      destination_number: "+14155552671",
      telephony_provider: "twilio",
    });

    setCallActive(true);
    transcript.startTranscriptSession(session.id);
  };

  return (
    <div>
      <button type="button" onClick={handleStart} disabled={initiateCall.isPending || callActive}>
        Start call
      </button>
      {callActive && <p>Status: {transcript.status}</p>}
    </div>
  );
}

Post-call processing

usePostCallSse

Opens a Server-Sent Events (SSE) stream after the call ends. The platform processes recordings, generates a summary, calculates billing, and fires webhooks asynchronously. usePostCallSse lets your UI track each stage as it completes.

The hook auto-retries with exponential backoff when the connection drops, up to a maximum retry count. If all retries are exhausted, onFailed is called.

import { usePostCallSse } from "@scalereal/sr-voice-engine-react-sdk/hooks";

export function PostCallDashboard({ callSessionId }: { callSessionId: string | null }) {
  const {
    stages,
    summary,
    sentiment,
    audioUrl,
    finalCharge,
    transcript,
    isConnected,
  } = usePostCallSse({
    callSessionId,
    onCompleted: () => console.info("All post-call stages done"),
    onFailed: (error) => console.error("Post-call SSE failed:", error),
  });

  return (
    <section>
      <p>{isConnected ? "Processing…" : "Awaiting connection"}</p>

      <ul>
        <li>Summary: {stages.summary_done ? summary ?? "—" : "Pending"}</li>
        <li>Recording: {stages.recording_done ? <a href={audioUrl ?? "#"}>Listen</a> : "Pending"}</li>
        <li>Billing: {stages.billing_done ? `${finalCharge} credits` : "Pending"}</li>
        <li>Structured output: {stages.structured_output_done ? "Done" : "Pending"}</li>
        <li>Webhooks: {stages.webhook_done ? "Fired" : "Pending"}</li>
      </ul>

      {sentiment && <p>Sentiment: {sentiment}</p>}
    </section>
  );
}

Options

OptionTypeDescription
callSessionIdstring | nullRequired. The call session to monitor. Pass null to keep the hook idle.
enabledbooleanSet to false to prevent or close the stream without unmounting. Optional.
onCompleted() => voidCalled when the post_call.completed event arrives — all stages are done.
onFailed(error: string) => voidCalled after max retries or when a post_call.failed event arrives.
buildUrl(callSessionId: string) => stringOverride the SSE endpoint URL. Optional.

Return values

PropertyTypeDescription
stagesPostCallStagesMap of pipeline stage names to completion booleans (see below).
summarystring | nullAI-generated call summary. Available when stages.summary_done is true.
sentiment"positive" | "negative" | "neutral" | nullSentiment classification of the call.
audioUrlstring | nullRecording download URL. Available when stages.recording_done is true.
finalChargestring | nullDecimal-string credit amount billed for the call. Available when stages.billing_done.
transcriptTranscriptMessage[] | nullFull transcript snapshot when the recording is done.
transferLegBilling{ status: TransferLegBillingStatus | null; fullyBilled: boolean | null }Billing state for transferred call legs.
isConnectedbooleanWhether the SSE stream is currently open.

Processing stages — PostCallStages

Stage keyDescription
summary_doneAI summary has been generated.
structured_output_doneStructured output extraction is complete.
usage_doneUsage/token metrics have been recorded.
recording_doneCall recording is ready. audioUrl is now set.
webhook_doneConfigured outbound webhooks have fired.
call_session_doneThe call session record has been finalized.
billing_doneCredits have been deducted. finalCharge is now set.

End-to-end flow

The following pattern covers the full lifecycle from initiating a call to tracking post-call processing:

import React from "react";
import {
  useInitiateTelephonyCall,
  useCallTranscript,
  usePostCallSse,
} from "@scalereal/sr-voice-engine-react-sdk/hooks";

type CallPhase = "idle" | "live" | "post-call" | "done";

export function FullCallFlow({ agentId }: { agentId: string }) {
  const [phase, setPhase] = React.useState<CallPhase>("idle");
  const [sessionId, setSessionId] = React.useState<string | null>(null);

  const initiateCall = useInitiateTelephonyCall();

  // 1. Live transcript — open immediately after call starts
  const transcript = useCallTranscript({
    onCallEnded: () => {
      transcript.stopTranscriptSession();
      setPhase("post-call");
    },
  });

  // 2. Post-call SSE — enabled only when the call has ended
  const postCall = usePostCallSse({
    callSessionId: phase === "post-call" ? sessionId : null,
    onCompleted: () => setPhase("done"),
  });

  const handleStart = async () => {
    const session = await initiateCall.mutateAsync({
      agent_id: agentId,
      destination_number: "+14155552671",
      telephony_provider: "twilio",
    });
    setSessionId(session.id);
    setPhase("live");
    transcript.startTranscriptSession(session.id);
  };

  return (
    <div>
      {phase === "idle" && (
        <button type="button" onClick={handleStart} disabled={initiateCall.isPending}>
          Start call
        </button>
      )}
      {phase === "live" && <p>Live — {transcript.status}</p>}
      {phase === "post-call" && <p>Processing: {JSON.stringify(postCall.stages)}</p>}
      {phase === "done" && <p>Summary: {postCall.summary}</p>}
    </div>
  );
}

Related pages

  • Calls — Initiate telephony and SIP calls to get a session ID.
  • Call History — Query past sessions and their metadata.
  • Components — Pre-built TranscriptView and related UI components.
  • Types — TranscriptMessage, PostCallStages, ThinkingSide, and other type definitions.

Function Logs

Query tool invocation logs to debug, monitor, and audit function calls made by agents during calls.

Components

Add managed call-history views or compose the SDK's presentation components.

On this page

Live call transcriptuseCallTranscriptConnection statusReturn valuesOptionsOpening the transcript right after a callPost-call processingusePostCallSseOptionsReturn valuesProcessing stages — PostCallStagesEnd-to-end flowRelated pages