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

Call History

Query, filter, inspect, and export call history with the React SDK.

The call-history hooks load paginated calls, fetch an individual call, and resolve short-lived recording URLs. For the prebuilt searchable list and detail UI, see Components.

List calls

Import

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

Usage

useCallHistory returns a TanStack Query result whose data is a paginated response. It refetches when the project or filter parameters change.

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

export function RecentCalls() {
  const { data, isPending, isError } = useCallHistory({
    page: 1,
    size: 20,
    sort_by: "-connected_at",
  });

  if (isPending) return <p>Loading calls…</p>;
  if (isError) return <p>Could not load calls.</p>;

  return (
    <section>
      <p>{data.total} calls</p>
      <ul>
        {data.items.map((call) => (
          <li key={call.id}>
            {call.from_number ?? "Unknown caller"} — {call.current_status}
          </li>
        ))}
      </ul>
      <p>
        Page {data.page} of {data.pages}
      </p>
    </section>
  );
}

The response includes items, total, page, size, and pages. Each item is a CallHistory object.

Parameters

useCallHistory(params?: ListCallHistoryParams) accepts these optional filters:

ParameterDescription
page1-based page number.
sizeNumber of calls per page.
searchText search across call numbers and summary.
current_statusFilter by initiated, ringing, in_progress, completed, failed, missed, or ongoing.
directioninbound or outbound.
providerTelephony provider name.
call_typeCall type, such as a campaign call or manual call.
start_dateInclude calls connected on or after yyyy-MM-dd.
end_dateInclude calls connected on or before yyyy-MM-dd.
agent_idRestrict results to an agent.
agent_familyInclude every version of the selected agent's family.
batch_idRestrict results to a batch.
campaign_idRestrict results to a campaign.
sort_bySort by created_at, connected_at, ended_at, or call_durations; prefix the field with - for descending order.
custom_attributesArray of CustomAttributeFilter conditions on the call's custom_attributes JSON column, combined with AND.

Empty values are removed before the request. The default page, size, and sort behavior is determined by the service unless you provide values.

Filter by custom attributes

Calls can store arbitrary JSON metadata in their custom_attributes column (for example, customer tier, CRM record IDs, or cart contents). The call-sessions endpoint supports deep filtering on this column.

When sent to the API, each filter becomes a flat query parameter:

  • Dotted paths become custom_attributes.<path>__<op>=<value> (e.g. custom_attributes.plan__eq=pro).
  • Root column filters become custom_attributes__<op>=<value> (e.g. custom_attributes__isnull=false).

Path segments support nested keys (user.address.city), numeric array indexes (orders.0.sku), and * wildcards matching any array element (tags.*).

The SDK provides two ways to build these filters: the attr helper object and the chainable customAttributeQuery() builder.

Using the attr helper

The attr object provides typed helper functions for every supported operator:

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

export function HighValueCalls() {
  const { data, isPending, isError } = useCallHistory({
    page: 1,
    size: 20,
    custom_attributes: [
      attr.eq("plan", "enterprise"),
      attr.gte("customer.lifetime_value", 5000),
      attr.contains("tags", ["vip", "priority"]),
      attr.rootIsNull(false),
    ],
  });

  if (isPending) return <p>Loading enterprise calls…</p>;
  if (isError) return <p>Failed to load calls.</p>;

  return (
    <ul>
      {data.items.map((call) => (
        <li key={call.id}>
          {call.from_number} — Plan: {String(call.custom_attributes?.plan ?? "none")}
        </li>
      ))}
    </ul>
  );
}

Using customAttributeQuery() builder

When constructing filters dynamically or passing them across functions, use customAttributeQuery():

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

export function FilteredCallsView({ minScore }: { minScore: number }) {
  const query = customAttributeQuery()
    .eq("verified", true)
    .gte("qualification_score", minScore)
    .like("account.region", "US")
    .rootExists(true);

  const { data } = useCallHistory({
    page: 1,
    size: 20,
    custom_attributes: query.toFilters(),
  });

  return <p>{data?.total ?? 0} qualified calls</p>;
}

Supported operators

All operators are type-checked against their operand value:

OperatorHelperMatchesOperand type
eqattr.eq(path, value)Exact match; arrays match when containing the valuestring | number | boolean
neqattr.neq(path, value)Value differs; never matches missing keys or nullstring | number | boolean
gtattr.gt(path, value)Greater than (numeric or ISO date comparison)number | string | Date
ltattr.lt(path, value)Less than (numeric or ISO date comparison)number | string | Date
gteattr.gte(path, value)Greater than or equal tonumber | string | Date
lteattr.lte(path, value)Less than or equal tonumber | string | Date
btwattr.btw(path, min, max)Inclusive range [min, max][Comparable, Comparable]
nbtwattr.nbtw(path, min, max)Outside inclusive range[Comparable, Comparable]
likeattr.like(path, text)Substring, case-sensitivestring
ilikeattr.ilike(path, text)Substring, case-insensitivestring
nlikeattr.nlike(path, text)Does not contain substring, case-sensitivestring
nilikeattr.nilike(path, text)Does not contain substring, case-insensitivestring
startswithattr.startswith(path, prefix)Prefix matchstring
endswithattr.endswith(path, suffix)Suffix matchstring
inattr.in(path, values)Value (or any array element) is in the list(string | number)[]
ninattr.nin(path, values)Value is not in the list(string | number)[]
containsattr.contains(path, values)Array contains every listed value(string | number)[]
existsattr.exists(path, bool?)Key is present (true, default) or absent (false)boolean
isnullattr.isnull(path, bool?)Value is JSON null (true, default) or not null (false)boolean
lenattr.len(path, length)Array length equals valuenumber
len_gtattr.len_gt(path, length)Array length greater than valuenumber
len_gteattr.len_gte(path, length)Array length greater than or equal tonumber
len_ltattr.len_lt(path, length)Array length less than valuenumber
len_lteattr.len_lte(path, length)Array length less than or equal tonumber
Root isnullattr.rootIsNull(bool?)Whole custom_attributes column is NULLboolean
Root existsattr.rootExists(bool?)Whole custom_attributes column has attributesboolean

Fetch call details

Import

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

Usage

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

export function CallSummary({ callSessionId }: { callSessionId: string }) {
  const { data, isPending, isError } = useCallDetails(callSessionId);

  if (isPending) return <p>Loading call…</p>;
  if (isError) return <p>Could not load this call.</p>;
  if (!data) return null;

  return (
    <article>
      <h2>{data.agent_name}</h2>
      <p>{data.summary ?? "No summary available."}</p>
      <p>Status: {data.current_status}</p>
    </article>
  );
}

Parameters

callSessionId

callSessionId: string

Call session identifier. An empty or whitespace-only ID keeps the query disabled.

enabled

enabled: boolean | undefined

Set to false to pause fetching while retaining cached data. It defaults to true; fetching also requires a non-empty callSessionId.

The result data is a CallDetailsResponse, including call metadata, transcript, recording fields, summary, structured output, custom_attributes (arbitrary JSON set during the call or by the agent), and post-call processing state when available.

Read custom attributes on a call

Use getCustomAttribute to safely traverse nested properties in custom_attributes using dotted paths without manual null checks:

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

export function CallMetadata({ callSessionId }: { callSessionId: string }) {
  const { data } = useCallDetails(callSessionId);
  if (!data) return null;

  const userCity = getCustomAttribute(data.custom_attributes, "user.address.city");
  const accountTier = getCustomAttribute(data.custom_attributes, "account.tier");

  return (
    <div>
      <p>City: {String(userCity ?? "Unknown")}</p>
      <p>Tier: {String(accountTier ?? "Standard")}</p>
    </div>
  );
}

Resolve a recording URL

Import

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

Usage

Call mutate or mutateAsync with a session ID and an action. The response contains a short-lived audio_url.

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

export function RecordingLink({ callSessionId }: { callSessionId: string }) {
  const recording = useCallRecordingUrl();
  const [audioUrl, setAudioUrl] = useState<string | null>(null);

  async function openRecording() {
    const result = await recording.mutateAsync({
      callSessionId,
      action: "play",
    });
    setAudioUrl(result.audio_url);
  }

  return (
    <div>
      <button type="button" onClick={openRecording} disabled={recording.isPending}>
        {recording.isPending ? "Preparing recording…" : "Prepare recording"}
      </button>
      {audioUrl && <audio controls src={audioUrl} />}
    </div>
  );
}

action is either play or download. Request a fresh URL when needed; do not persist it as a permanent recording link.

Parameters

callSessionId

callSessionId: string

Call session whose recording URL to resolve.

action

action: "play" | "download"

Choose a playback or download URL. The mutation resolves to CallRecordingUrlResponse (call_session_id and audio_url).

Manage list filters

useCallHistoryFilters holds common search, status, direction, date, paging, and sorting state and projects it into ListCallHistoryParams. Pair its params with useCallHistory:

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

export function FilteredCalls() {
  const filters = useCallHistoryFilters({ debounceMs: 300 });
  const calls = useCallHistory(filters.params);

  return (
    <section>
      <label>
        Search calls
        <input
          value={filters.searchInput}
          onChange={(event) => filters.setSearchInput(event.target.value)}
        />
      </label>
      {calls.isPending ? <p>Loading calls…</p> : <p>{calls.data?.total ?? 0} calls</p>}
    </section>
  );
}

Search is trimmed and debounced (300 ms by default). Changing status, direction, dates, page size, or sort resets the page to 1. initialParams can seed the search, status, dates, page, size, custom-attribute conditions (custom_attributes), and agent, batch, or campaign scope.

useCallHistoryFilters return values

ValuePurpose
searchInput, setSearchInputRaw search field value and setter.
searchTrimmed, debounced search term.
status, setStatusStatus filter; "" means all statuses.
direction, setDirectionDirection filter; "" means both directions.
startDate, setStartDateInclusive start date in yyyy-MM-dd format.
endDate, setEndDateInclusive end date in yyyy-MM-dd format.
page, setPageCurrent 1-based page and setter.
size, setSizePage size and setter.
sortField, sortDirectionCurrent sort field and asc/desc direction.
handleSort(field)Toggle direction for the selected field; a new field starts descending.
paramsCurrent filters projected to ListCallHistoryParams.

The hook accepts initialParams and debounceMs (default 300 ms).

Export calls

useCallExport provides browser-side CSV and PDF export handlers. By default, CSV exports the rows passed in calls, and PDF exports the call passed in. You can provide onExportCSV or onExportPDF to replace either exporter.

import { useCallExport } from "@scalereal/sr-voice-engine-react-sdk/hooks";
import type { CallHistory } from "@scalereal/sr-voice-engine-react-sdk/types";

export function ExportCurrentPage({ calls }: { calls: CallHistory[] }) {
  const { exportCsv, exportingCsv } = useCallExport({ calls });

  return (
    <button type="button" onClick={exportCsv} disabled={exportingCsv || calls.length === 0}>
      {exportingCsv ? "Exporting…" : "Export CSV"}
    </button>
  );
}

Parameters

calls

calls: CallHistory[] | undefined

Rows to include in the default CSV export. The SDK exports the rows passed here, which are typically the current filtered page. An empty array makes exportCsv a no-op.

call

call: CallHistory | CallDetailsResponse | null | undefined

Call to include in the default PDF report. When omitted or null, exportPdf is a no-op.

onExportCSV

onExportCSV: ((calls: CallHistory[]) => void | Promise<void>) | undefined

Replace the default CSV generation and browser download with a custom exporter.

onExportPDF

onExportPDF: ((call: CallHistory | CallDetailsResponse) => void | Promise<void>) | undefined

Replace the default PDF generation and browser download with a custom exporter.

onError

onError: ((message: string) => void) | undefined

Receive a human-readable message if CSV or PDF export fails. The default error messages are Failed to export CSV. and Failed to generate PDF.

useCallExport returns exportCsv, exportPdf, exportingCsv, and exportingPdf. Both default exporters run in the browser.

Cache keys

callSessionKeys is the query-key factory for call-history and detail queries. Use its all key to target all SDK call-session data when invalidating your shared QueryClient:

import { useQueryClient } from "@tanstack/react-query";
import { callSessionKeys } from "@scalereal/sr-voice-engine-react-sdk/hooks";

function useRefreshCallHistory() {
  const queryClient = useQueryClient();
  return () => queryClient.invalidateQueries({ queryKey: callSessionKeys.all });
}

Related pages

  • Provider & Setup Configure the required provider and query client.
  • Components Use the managed call list, details panel, and audio player.
  • Realtime Subscribe to transcript and post-call updates.
  • Types Browse the call-history models and shared types.

Outbound Calls

Initiate telephony and SIP calls, handle dynamic variables, and recall existing sessions.

Phone Numbers

Manage SIP and telephony phone numbers — list, create, update, delete, and sync from providers.

On this page

List callsImportUsageParametersFilter by custom attributesUsing the attr helperUsing customAttributeQuery() builderSupported operatorsFetch call detailsImportUsageParameterscallSessionIdenabledRead custom attributes on a callResolve a recording URLImportUsageParameterscallSessionIdactionManage list filtersuseCallHistoryFilters return valuesExport callsParameterscallscallonExportCSVonExportPDFonErrorCache keysRelated pages