Documentation

Everything your backend needs to run a class with the Baian Partner API.

Get started

Quickstart

Start with one teacher and one class. Your server creates the session, reads the results and stops the class. The teacher's device sends microphone audio using a short-lived token. Keep your API key on your server.

Base URL: https://api.baian.ai
  1. Step 1: Create an API key

    Create a key on the API keys page and store the secret in your server's secret manager as BAIAN_API_KEY. The secret is shown once.

  2. Step 2: Create a session for the class

    Create one session for the class. If the request times out, retry with the same Idempotency-Key and body to get the same session back. Check session.status and source. If source is present, send its livekit_url and token only to the teacher’s device.

    cURL
    curl -X POST https://api.baian.ai/v1/sessions \
      -H "Authorization: Bearer $BAIAN_API_KEY" \
      -H "Idempotency-Key: class-2026-11-02-fiqh-101" \
      -H "Content-Type: application/json" \
      -d '{
        "external_session_id": "class-2026-11-02-fiqh-101",
        "input_lang": "en",
        "additional_input_langs": ["ar"],
        "output_langs": [],
        "quran_refs": true
      }'
  3. Step 3: Connect the teacher's microphone

    On the teacher's page, call the tested helper publishTeacherMic with a function that asks your server for the source. Connect your Stop button first, so Stop also cancels a connection or microphone prompt that is still pending.

    Browser
    // Teacher page. publishTeacherMic is the helper in "Teacher device helper (browser)".
    const controller = new AbortController()
    stopButton.onclick = () => controller.abort() // connect Stop before awaiting
    
    const teacher = await publishTeacherMic(
      (signal) => fetch('/api/class/teacher-token', { method: 'POST', signal }).then(async (r) => {
        const body = await r.json()
        // A status on the error tells the helper not to reconnect after a 4xx (for example the class ended).
        if (!r.ok) throw Object.assign(new Error(body.error ?? 'token request failed'), { status: r.status })
        return body.source
      }),
      { signal: controller.signal },
    )
    // Later: teacher.stop() or controller.abort() stops the microphone.

    Copy publishTeacherMic from Teacher device helper (browser). For a server or venue box, use the Node.js audio helper.

  4. Step 4: Read the results

    Read events in order, starting from after=0. Save each event's seq and pass the last one as after next time. Keep reading until terminal is true.

    cURL
    curl "https://api.baian.ai/v1/sessions/$SESSION_ID/events?after=0&limit=100&wait=20" \
      -H "Authorization: Bearer $BAIAN_API_KEY"

    To show words while the teacher is speaking, also open the live preview stream.

  5. Step 5: Stop the class

    Stop when the class ends, then keep reading events until terminal, so the last segments are not lost.

    cURL
    curl -X POST https://api.baian.ai/v1/sessions/$SESSION_ID/stop \
      -H "Authorization: Bearer $BAIAN_API_KEY"

    For retries, reconnects and a complete server example, see the Node.js server helper.

Next: How it works

How it works

Your server creates one session per class and gives the teacher a temporary microphone token. The teacher uses it to send audio through LiveKit.

Relay /partials from your server to show the current line as it grows. Use /events to save the finished line and attach references by segment_id. Translations and hadith references are available when enabled for your organisation.

Base URL: https://api.baian.ai

Next: Authentication

Authentication

Send your key as a bearer token: Authorization: Bearer bn_live_…. Keys are created on the API keys page and the secret is shown once. Store it in your server's secret manager. Never put a key in a mobile app, web page or teacher device.

Scopes: sessions:write (create, stop, new source token, delete), sessions:read (list and read sessions and transcripts), events:read (events). A request without the needed scope returns 403 scope_forbidden. GET /v1/languages works with any valid key. Revoking a key rejects every later request made with it (401). Sessions it created keep running: stop or read them with another key of your organisation or from the dashboard. A source token already issued stays valid for joining until its expires_at (15 minutes).

Next: Hono, Workers and Expo

Hono, Workers and Expo

These two examples are for a Hono API on Cloudflare Workers with Supabase, and an Expo app for iOS and Android. They call the same endpoints as the cURL examples on this page. The API reference lists every endpoint and field.

Your API: Hono on Cloudflare Workers

Store the key as a Worker secret with wrangler secret put BAIAN_API_KEY. The Worker starts and stops authorised classes and gives the teacher's device a new source token when it reconnects. One Durable Object follows each class: its alarm makes one long-poll request at a time and saves the events to a Supabase table. It keeps reading after the request that started the class has finished. Students read that table, for example with Supabase Realtime, and never call Baian.

Connect ./teacher-access to your app’s sign-in and class records. teacherCanManage returns true only for a signed-in teacher assigned to that class. saveClassSession stores the class and Baian session IDs together so the same check applies to reconnecting and ending a class. Enable row level security on class_events so students can read only their own classes.

Events are saved with an upsert on (session_id, seq), and the cursor moves on only after the save succeeds, so a retry never skips an event or saves it twice.

Hono Worker: start, teacher token, stop, follow events into Supabase
Hono Worker: start, teacher token, stop, follow events into Supabase
// Hono on Cloudflare Workers. BAIAN_API_KEY is a Worker secret (wrangler secret put BAIAN_API_KEY)
// and never leaves this Worker. Each class is followed by a ClassFeed Durable Object, which
// long-polls Baian on an alarm and saves every event to Supabase, so it keeps running after the
// HTTP request that started the class has finished.
//
// wrangler.jsonc with a Wrangler version that supports declarative exports:
//   "durable_objects": { "bindings": [{ "name": "CLASS_FEED", "class_name": "ClassFeed" }] },
//   "exports": { "ClassFeed": { "type": "durable-object", "storage": "sqlite" } }
// For a Worker using migrations, keep its existing entries and append a new tag instead of adding exports:
//   { "tag": "add-class-feed", "new_sqlite_classes": ["ClassFeed"] }
// Supabase table: class_events (session_id uuid, seq int, type text, data jsonb, primary key (session_id, seq))
// Enable row level security. Allow enrolled students to read their class; only the Worker writes events.
import { Hono } from 'hono'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import { DurableObject } from 'cloudflare:workers'
import { createClient } from '@supabase/supabase-js'
import { teacherCanManage, saveClassSession } from './teacher-access'

type Env = {
  BAIAN_API_KEY: string
  SUPABASE_URL: string
  SUPABASE_SECRET_KEY: string // server-only key; it bypasses row level security
  CLASS_FEED: DurableObjectNamespace<ClassFeed>
}
type BaianEvent = { seq: number; type: string; data: Record<string, unknown> }
type EventPage = { events: BaianEvent[]; next_after: number; terminal: boolean }

const BASE = 'https://api.baian.ai'

// Keep existing retry keys. Use a stable ASCII digest when the ID cannot be sent in an HTTP header.
async function classKey(classId: string) {
  if (/^[\t\x20-\x7e\x80-\xff]+$/.test(classId)) return classId
  const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(classId))
  return 'class-sha256:' + Array.from(new Uint8Array(bytes), b => b.toString(16).padStart(2, '0')).join('')
}

class BaianError extends Error {
  constructor(readonly status: number, readonly code: string, message: string, readonly retryAfter = 0) { super(message) }
}

// Retry network errors, rate limits and 5xx. Return concurrency_limit so the caller can free a slot.
async function baian<T>(env: Env, path: string, init: RequestInit = {}, timeoutMs = 15_000): Promise<T> {
  for (let attempt = 1; ; attempt++) {
    try {
      const res = await fetch(BASE + path, {
        ...init,
        signal: AbortSignal.timeout(timeoutMs),
        headers: { Authorization: `Bearer ${env.BAIAN_API_KEY}`, 'Content-Type': 'application/json', ...init.headers },
      })
      const body = await res.json().catch(() => null) as { error?: { code?: string; message?: string; request_id?: string } } | null
      if (!res.ok) {
        const e = body?.error ?? {}
        throw new BaianError(res.status, e.code ?? 'http_' + res.status, `${e.code}: ${e.message} (${e.request_id})`, Number(res.headers.get('Retry-After')) || 0)
      }
      return body as T
    } catch (error) {
      const retryable = !(error instanceof BaianError) ||
        (error.status === 429 && error.code !== 'concurrency_limit') || error.status >= 500
      if (!retryable || attempt >= 5) throw error
      const backoff = Math.min(30_000, 500 * 2 ** attempt + Math.random() * 250)
      const retryAfter = error instanceof BaianError ? error.retryAfter * 1000 : 0
      if (retryAfter > 2_147_483_647) throw error // exceeds the timer limit
      await new Promise((resolve) => setTimeout(resolve, Math.max(backoff, retryAfter)))
    }
  }
}

type ClassRouteStage = 'teacher_access' | 'baian_request' | 'save_class_session' | 'follow_class_feed'
const app = new Hono<{ Bindings: Env; Variables: { failureStage: ClassRouteStage } }>()

// Your teacher-access module verifies the app sign-in and checks the teacher's class
// assignment. For { sessionId }, look up its saved class first. Only true grants access.
app.post('/classes/:classId/start', async (c) => {
  const classId = c.req.param('classId')
  c.set('failureStage', 'teacher_access')
  if (await teacherCanManage(c.req.raw, { classId }, c.env) !== true) return c.json({ error: 'teacher_access_required' }, 403)
  c.set('failureStage', 'baian_request')
  const { session, source } = await baian<{ session: { id: string; status: string }; source: { livekit_url: string; token: string; expires_at: string } | null }>(
    c.env, '/v1/sessions', {
      method: 'POST',
      headers: { 'Idempotency-Key': await classKey(classId) }, // a retry with the same key and body returns the same session
      body: JSON.stringify({ external_session_id: classId, input_lang: 'en', additional_input_langs: ['ar'], output_langs: [], quran_refs: true }),
    })
  if (!source) return c.json({ error: `Session is ${session.status}` }, 409)
  c.set('failureStage', 'save_class_session')
  await saveClassSession(classId, session.id, c.env) // persist this pair; retries can return the same session
  c.set('failureStage', 'follow_class_feed')
  await c.env.CLASS_FEED.getByName(session.id).follow(session.id)
  // Only the short-lived source token goes to the teacher's device, never the API key.
  return c.json({ session_id: session.id, source }, 200, { 'Cache-Control': 'no-store' })
})

// New source token after the teacher's device reconnects (only while the session is created or live).
app.post('/classes/:sessionId/teacher-token', async (c) => {
  const sessionId = c.req.param('sessionId')
  c.set('failureStage', 'teacher_access')
  if (await teacherCanManage(c.req.raw, { sessionId }, c.env) !== true) return c.json({ error: 'teacher_access_required' }, 403)
  c.set('failureStage', 'baian_request')
  const { source } = await baian<{ source: unknown }>(c.env, `/v1/sessions/${sessionId}/source-token`, { method: 'POST' })
  return c.json({ source }, 200, { 'Cache-Control': 'no-store' })
})

// Stop the class. Safe to repeat; the Durable Object keeps reading until the last event.
app.post('/classes/:sessionId/stop', async (c) => {
  const sessionId = c.req.param('sessionId')
  c.set('failureStage', 'teacher_access')
  if (await teacherCanManage(c.req.raw, { sessionId }, c.env) !== true) return c.json({ error: 'teacher_access_required' }, 403)
  c.set('failureStage', 'baian_request')
  const { session } = await baian<{ session: { status: string } }>(c.env, `/v1/sessions/${sessionId}/stop`, { method: 'POST' })
  return c.json({ status: session.status })
})

// Pass Baian's 4xx codes through (for example session_not_active once the class has ended), so the
// teacher app stops reconnecting. Log request_id from error.message when you contact Baian.
app.onError((error, c) => {
  if (error instanceof BaianError) {
    console.error(error.message)
    if (error.status < 500) return c.json({ error: error.code }, error.status as ContentfulStatusCode)
  } else {
    // Log only the fixed stage. Partner errors may include credentials or personal data.
    console.error('Class route failed', { stage: c.get('failureStage') ?? 'route' })
  }
  return c.json({ error: 'upstream_error' }, 502)
})

export default app

// Reads one class's events in order and saves them. Students read class_events from Supabase
// (for example with Supabase Realtime) and never call Baian themselves.
export class ClassFeed extends DurableObject<Env> {
  async follow(sessionId: string): Promise<void> {
    await this.ctx.storage.put('sessionId', sessionId)
    if ((await this.ctx.storage.get('after')) === undefined) await this.ctx.storage.put('after', 0)
    const nextAlarm = await this.ctx.storage.getAlarm()
    if (nextAlarm === null || nextAlarm <= Date.now()) await this.ctx.storage.setAlarm(Date.now())
  }

  async alarm(): Promise<void> {
    const sessionId = await this.ctx.storage.get<string>('sessionId')
    if (!sessionId) return
    let after = (await this.ctx.storage.get<number>('after')) ?? 0
    const supabase = createClient(this.env.SUPABASE_URL, this.env.SUPABASE_SECRET_KEY, { auth: { persistSession: false } })
    try {
      // One long-poll per alarm: Baian holds the request for up to 20 s while it waits for new events.
      const page = await baian<EventPage>(this.env, `/v1/sessions/${sessionId}/events?after=${after}&limit=200&wait=20`, {}, 30_000)
      if (page.events.length > 0) {
        const rows = page.events.map((event) => ({ session_id: sessionId, seq: event.seq, type: event.type, data: event.data }))
        // Upsert on (session_id, seq): an event saved twice after a retry stays one row.
        const { error } = await supabase.from('class_events').upsert(rows, { onConflict: 'session_id,seq' })
        if (error) throw error
      }
      // Save the cursor only after the events are stored, so nothing is skipped after a failure.
      after = Math.max(after, page.next_after)
      await this.ctx.storage.put('after', after)
      if (page.terminal) {
        await this.ctx.storage.deleteAll() // every event is saved; this class is finished
        return
      }
      await this.ctx.storage.setAlarm(Date.now())
    } catch (error) {
      // 401, 403 or 404 will not fix themselves: stop following and alert someone.
      if (error instanceof BaianError && error.status >= 400 && error.status < 500 && (error.status !== 429 || error.code === 'concurrency_limit')) {
        console.error('Stopped following class', sessionId, error.message)
        return
      }
      await this.ctx.storage.setAlarm(Date.now() + 5_000)
    }
  }
}

Teacher app: Expo

Show “Connecting” at first. Use onReadyChange to show “Speak now” or “Wait before speaking”. While waiting after a drop, offer a Reconnect button that restarts the microphone in the same class.

The teacher's phone or tablet publishes its microphone with LiveKit's React Native SDK. The SDK contains native code. Expo Go cannot run it, so you need a development build (npx expo run:ios, npx expo run:android or an EAS development build). Install the packages with npx expo install, add the two config plugins to app.json and call registerGlobals() once when the app starts.

The first time the microphone starts, the phone asks the teacher for permission. On iOS the config plugin adds the permission text. To keep sending audio while the screen is locked, add audio to UIBackgroundModes. Test on a real device, because simulators do not capture a real microphone.

Expo teacher device (@livekit/react-native)
Expo teacher device (@livekit/react-native)
// Expo (iOS and Android) teacher screen. It publishes the microphone with LiveKit's React Native SDK.
// The LiveKit SDK uses native code, so it does not run in Expo Go: use a development build
// (npx expo run:ios / npx expo run:android, or an EAS development build).
//
//   npx expo install @livekit/react-native @livekit/react-native-webrtc @livekit/react-native-expo-plugin @config-plugins/react-native-webrtc livekit-client
//
// app.json: "plugins": ["@livekit/react-native-expo-plugin",
//   ["@config-plugins/react-native-webrtc", { "microphonePermission": "Allow $(PRODUCT_NAME) to send your class audio to Baian." }]]
// To keep sending audio while the screen is locked, also add "ios": { "infoPlist": { "UIBackgroundModes": ["audio"] } }.
import { registerGlobals, AudioSession } from '@livekit/react-native'
import { Room, RoomEvent, type LocalTrack, type LocalTrackPublication, type RemoteParticipant } from 'livekit-client'

registerGlobals() // once, at app start (for example in your root _layout.tsx), before any Room is created

type Source = { livekit_url: string; token: string }

// Native audio belongs to the whole app. Class screens can overlap while a room disconnects.
let audioPublishers = 0
let audioTransition = Promise.resolve()
function updateAudioSession(action: 'acquire' | 'release') {
  const next = audioTransition.then(async () => {
    if (action === 'acquire') {
      if (audioPublishers === 0) await AudioSession.startAudioSession()
      audioPublishers++
    } else {
      audioPublishers--
      if (audioPublishers === 0) await AudioSession.stopAudioSession()
    }
  })
  audioTransition = next.catch(() => {}) // a failed native call must not block the next class
  return next
}

// getSource calls YOUR server (the Hono routes above), never Baian, so the API key stays on the server.
// Wire Stop to the AbortSignal before awaiting: stopping also cancels a pending connection.
export async function publishTeacherMic(
  getSource: (signal: AbortSignal) => Promise<Source>,
  signal: AbortSignal,
  onReadyChange?: (ready: boolean) => void,
) {
  const checkCancelled = () => {
    if (signal.aborted) throw new Error('Microphone start cancelled.')
  }
  checkCancelled()
  await updateAudioSession('acquire')
  const room = new Room({ audioCaptureDefaults: { echoCancellation: true, noiseSuppression: true } })
  let finishWait!: (ready: boolean) => void
  const receiver = new Promise<boolean>(resolve => { finishWait = resolve })
  let capture: LocalTrack | undefined
  let published = false
  let subscribed = false
  let ready = false
  const updateCue = () => {
    const next = published && subscribed && room.state === 'connected' && !signal.aborted
    if (ready === next) return
    ready = next
    if (ready) finishWait(true)
    onReadyChange?.(ready)
  }
  const onSubscribed = (publication: LocalTrackPublication) => {
    if (publication.source !== 'microphone') return
    subscribed = true
    updateCue()
  }
  const receiverLost = () => {
    subscribed = false
    updateCue()
  }
  const onUnpublished = (publication: LocalTrackPublication) => {
    if (publication.source === 'microphone') receiverLost()
  }
  const onParticipantLeft = (participant: RemoteParticipant) => {
    if (participant.isAgent || room.remoteParticipants.size === 0) receiverLost()
  }
  let timer: ReturnType<typeof setTimeout> | undefined
  // The audio session belongs to the whole app: stop it exactly once, and only for this publisher,
  // so a late abort from an old screen can never stop a newer class.
  let stopping: Promise<void> | null = null
  const onAbort = () => { void stop().catch(() => {}) }
  const stop = () => {
    stopping ??= (async () => {
      finishWait(false)
      signal.removeEventListener('abort', onAbort)
      room.off(RoomEvent.Disconnected, onDisconnected)
      room.off(RoomEvent.LocalTrackSubscribed, onSubscribed)
      room.off(RoomEvent.LocalTrackUnpublished, onUnpublished)
      room.off(RoomEvent.ParticipantDisconnected, onParticipantLeft)
      room.off(RoomEvent.ConnectionStateChanged, updateCue)
      receiverLost()
      capture?.stop()
      try { await room.disconnect() } finally { await updateAudioSession('release') }
    })()
    return stopping
  }
  // LiveKit handles short network drops. After a permanent disconnect, release the device.
  // The screen can then call reconnect() for a new token on the same session.
  const onDisconnected = () => { void stop().catch(() => {}) }
  signal.addEventListener('abort', onAbort, { once: true })
  try {
    checkCancelled()
    const source = await getSource(signal)
    checkCancelled()
    await room.connect(source.livekit_url, source.token)
    checkCancelled()
    room.on(RoomEvent.Disconnected, onDisconnected)
    room.on(RoomEvent.LocalTrackSubscribed, onSubscribed)
    room.on(RoomEvent.LocalTrackUnpublished, onUnpublished)
    room.on(RoomEvent.ParticipantDisconnected, onParticipantLeft)
    room.on(RoomEvent.ConnectionStateChanged, updateCue)
    // iOS and Android ask for microphone permission here the first time.
    const [track] = await room.localParticipant.createTracks({ audio: true, video: false })
    if (stopping || signal.aborted) {
      track.stop()
      throw new Error('Microphone start cancelled.')
    }
    capture = track
    await room.localParticipant.publishTrack(track)
    checkCancelled()
    published = true
    updateCue()
    timer = setTimeout(() => finishWait(false), 15_000)
    const connected = await receiver
    checkCancelled()
    if (stopping || !connected || !ready) throw new Error('Class receiver unavailable. Reconnect before speaking.')
  } catch (error) {
    await stop()
    throw error
  } finally {
    clearTimeout(timer)
  }
  return { stop, room }
}

// Construct once per class screen. Wire Stop before awaiting start().
export function createTeacherControls(
  workerUrl: string,
  classId: string,
  getAppToken: () => string,
  onReadyChange: (ready: boolean) => void,
) {
  let sessionId: string | undefined
  let ending = false
  let current: { controller: AbortController; publication: ReturnType<typeof publishTeacherMic> } | undefined

  async function disconnect(publisher: typeof current) {
    publisher?.controller.abort()
    if (publisher) {
      const handle = await publisher.publication.catch(() => undefined)
      await handle?.stop()
    }
  }

  function connect() {
    if (ending) return Promise.reject(new Error('End class was requested. Retry End if needed.'))
    const previous = current
    const controller = new AbortController()
    const publication = (async () => {
      await disconnect(previous)
      if (controller.signal.aborted) throw new Error('Microphone start cancelled.')
      return publishTeacherMic(async (signal) => {
        const route = sessionId
          ? '/classes/' + encodeURIComponent(sessionId) + '/teacher-token'
          : '/classes/' + encodeURIComponent(classId) + '/start'
        const res = await fetch(workerUrl + route, {
          method: 'POST', signal, headers: { Authorization: 'Bearer ' + getAppToken() },
        })
        if (!res.ok) throw new Error('Could not connect to the class (' + res.status + ').')
        const result = await res.json()
        sessionId ??= result.session_id
        return result.source
      }, controller.signal, ready => {
        if (current?.controller === controller) onReadyChange(ready)
      })
    })()
    current = { controller, publication }
    onReadyChange(false)
    return publication
  }

  async function stopMicrophone() {
    const publisher = current
    try {
      await disconnect(publisher)
    } finally {
      if (current === publisher) {
        current = undefined
        onReadyChange(false)
      }
    }
  }

  return {
    start: connect,
    async reconnect() {
      if (!sessionId) throw new Error('Start the class before reconnecting.')
      return connect()
    },
    stopMicrophone,
    async endClass() {
      if (!sessionId) throw new Error('Start the class before ending it.')
      ending = true
      // Abort capture now. A pending OS permission prompt can outlast the server request.
      void stopMicrophone().catch(() => console.warn('Could not finish microphone cleanup.'))
      const res = await fetch(workerUrl + '/classes/' + encodeURIComponent(sessionId) + '/stop', {
        method: 'POST', headers: { Authorization: 'Bearer ' + getAppToken() },
      })
      if (!res.ok) throw new Error('Could not end the class (' + res.status + '). Retry End.')
    },
  }
}

// In your screen, wire controls.start(), controls.reconnect() and controls.stopMicrophone().
// Show “Speak now” only when onReadyChange(true) fires. Show connection errors and let the teacher retry.
// Stop microphone releases this device. After Start succeeds, wire End class to controls.endClass().
// If End fails, let the teacher retry it. The Worker saves the last events after End.

Next: Create a session

Guides

Create a session

Send an Idempotency-Key header (1 to 200 characters). Retrying with the same key and body returns the same session; the same key with a different body returns 409 idempotency_conflict.

  • external_session_id (required): your class ID, up to 200 characters after trimming surrounding whitespace. Only one running session per ID.
  • input_lang (required): main spoken language code.
  • additional_input_langs (optional): other languages the teacher mixes in. Send up to three distinct codes after normalisation, excluding the primary language. Omission or null means none. For an English class with Arabic Quran quotations send ["ar"], otherwise the Arabic is not transcribed as Arabic and quotations cannot be detected.
  • output_langs (optional): up to five distinct translation codes after normalisation. An empty array, omission or null means transcript only.
  • quran_refs (optional, default true).
  • hadith_refs (optional, default false): Arabic hadith quotations. Request it only when GET /v1/languages reports features.hadith_refs enabled. It works independently of Quran and translation.
  • metadata (optional): a JSON object, up to 4,096 serialized UTF-8 bytes. Omission or null becomes an empty object.

Your organisation can have a limited number of sessions open at once (created, live or ending); the default is 2. A create beyond that returns 429 concurrency_limit. The current limit is shown on the portal overview.

201 Created means a session record exists. Check session.status and source before trying to connect. If provisioning fails, the response has status: "failed", failure_code: "provisioning_failed" and source: null. Retrying the create of a finished session also returns source: null.

cURL
curl -X POST https://api.baian.ai/v1/sessions \
  -H "Authorization: Bearer $BAIAN_API_KEY" \
  -H "Idempotency-Key: class-2026-11-02-fiqh-101" \
  -H "Content-Type: application/json" \
  -d '{
    "external_session_id": "class-2026-11-02-fiqh-101",
    "input_lang": "en",
    "additional_input_langs": ["ar"],
    "output_langs": [],
    "quran_refs": true
  }'
201 response (excerpt)
{
  "session": {
    "id": "6f1c…",
    "external_session_id": "class-2026-11-02-fiqh-101",
    "status": "created",
    "input_lang": "en",
    "output_langs": [],
    "quran_refs": true,
    "last_event_seq": 0
  },
  "source": {
    "livekit_url": "wss://…",
    "token": "eyJ…",
    "identity": "source-6f1c2a9b",
    "expires_at": "2026-11-02T18:15:00Z"
  }
}

Next: Send teacher audio

Send teacher audio

The source token lets one device join the session's LiveKit room and publish a microphone track. It cannot subscribe, send data or join any other room. It must be used to join within 15 minutes; request a fresh one with POST /v1/sessions/{id}/source-token if it expires or the device reconnects.

Baian accepts teacher audio only as a LiveKit microphone track. There is no WebSocket, RTMP or file upload input in this API.

getToken must call your server, which calls startClass or teacherToken. Pass an AbortSignal as signal, and connect your Stop button to it before you await. Aborting also cancels the first connection, including a pending token request or an open microphone prompt. If the teacher allows the microphone after that, nothing is published. Once the microphone is live, stop() on the returned handle does the same.

If the first connection fails, the call rejects and nothing is published. If a later reconnect gets a 4xx from your token endpoint, for example because the class has ended, give the error a status property. The helper then stops reconnecting and reports the error through onError. Network failures are retried with backoff, at most maxReconnects times.

The quickstart calls publishTeacherMic. Copy the full helper below; it is the same code Baian tests.

Teacher device helper (browser, livekit-client)
Teacher device helper (browser, livekit-client)
// Teacher device (browser, livekit-client). It never sees your API key:
// getToken(signal) calls YOUR server, which calls startClass() or teacherToken() and returns
// { livekit_url, token }. Each attempt uses its own Room.
// Aborting signal cancels everything, including the FIRST connection and an open microphone
// prompt, so wire your Stop button to it before awaiting. stop() on the returned handle does the same.
import { Room, RoomEvent } from 'livekit-client'

export async function publishTeacherMic(getToken, { signal, onError = console.error, maxReconnects = 5 } = {}) {
  let stopped = signal?.aborted ?? false
  let attempt = 0 // generation: callbacks from an older attempt are ignored
  let current = null // The active room and any microphone capture, including during startup.
  let timer = null
  let reconnects = 0

  async function leave(room) {
    try {
      for (const pub of room.localParticipant.trackPublications.values()) pub.track?.mediaStreamTrack?.stop()
      await room.localParticipant.setMicrophoneEnabled(false)
    } catch {
      // already disconnected
    } finally {
      await room.disconnect()
    }
  }

  async function stop() {
    stopped = true
    attempt += 1 // any connect still waiting on the token, room or microphone will leave
    clearTimeout(timer)
    timer = null
    const active = current
    current = null
    active?.track?.stop()
    if (active) await leave(active.room)
  }
  signal?.addEventListener('abort', () => { void stop() }, { once: true })

  // Resolves true once the microphone is published, false if it was cancelled first.
  async function connect() {
    const mine = ++attempt
    const source = await getToken(signal)
    if (stopped || mine !== attempt) return false
    const room = new Room({ audioCaptureDefaults: { echoCancellation: true, noiseSuppression: true } })
    const active = { room, track: null }
    current = active
    try {
      await room.connect(source.livekit_url, source.token)
      if (stopped || mine !== attempt) { await leave(room); return false }
      // The browser may show a microphone prompt here; Stop can happen while it is open.
      const [track] = await room.localParticipant.createTracks({ audio: true, video: false })
      active.track = track
      if (stopped || mine !== attempt) { track.stop(); await leave(room); return false }
      await room.localParticipant.publishTrack(track)
      if (stopped || mine !== attempt) { await leave(room); return false }
    } catch (error) {
      active.track?.stop()
      if (current === active) current = null
      await leave(room)
      if (stopped || mine !== attempt) return false
      throw error
    }
    reconnects = 0
    room.on(RoomEvent.Disconnected, () => {
      // LiveKit already retries short network drops. This runs when the room is lost for good.
      if (stopped || current?.room !== room) return
      current = null
      scheduleReconnect()
    })
    return true
  }

  function scheduleReconnect() {
    if (stopped || timer || reconnects >= maxReconnects) {
      if (!stopped && reconnects >= maxReconnects) onError(new Error('Teacher audio could not reconnect.'))
      return
    }
    reconnects += 1
    timer = setTimeout(async () => {
      timer = null
      if (stopped) return
      try {
        await connect()
      } catch (error) {
        if (stopped) return
        // A 4xx from your token endpoint (for example the class already ended) is final.
        if (error?.status >= 400 && error?.status < 500) return onError(error)
        scheduleReconnect()
      }
    }, Math.min(30_000, 1000 * 2 ** reconnects))
  }

  // The first attempt is not retried: if it fails, this rejects and nothing is published.
  if (stopped || !(await connect())) throw new DOMException('Teacher audio was cancelled.', 'AbortError')
  return { stop }
}

// Usage: Stop works even while the first connection or microphone prompt is pending.
// const controller = new AbortController()
// stopButton.onclick = () => controller.abort()
// const teacher = await publishTeacherMic(
//   (signal) => fetch('/api/class/teacher-token', { method: 'POST', signal }).then(async (r) => {
//     const body = await r.json()
//     if (!r.ok) throw Object.assign(new Error(body.error ?? 'token request failed'), { status: r.status })
//     return body.source
//   }),
//   { signal: controller.signal, onError: showTeacherError },
// )
Server or venue box helper (@livekit/rtc-node)
Server or venue box helper (@livekit/rtc-node)
// Teacher audio from a server or venue box: 16 kHz mono PCM16 frames.
import { AudioFrame, AudioSource, LocalAudioTrack, Room, TrackPublishOptions, TrackSource } from '@livekit/rtc-node'

export async function publishPcm(source, pcmChunks /* AsyncIterable<Int16Array> */) {
  const room = new Room()
  const audio = new AudioSource(16000, 1)
  const track = LocalAudioTrack.createAudioTrack('teacher', audio)
  let subscriptionTimeout
  try {
    await room.connect(source.livekit_url, source.token)
    const options = new TrackPublishOptions()
    options.source = TrackSource.SOURCE_MICROPHONE
    const publication = await room.localParticipant.publishTrack(track, options)
    // Keep the first words in the input until the classroom receiver connects.
    await Promise.race([
      publication.waitForSubscription(),
      new Promise((_, reject) => {
        subscriptionTimeout = setTimeout(() => reject(new Error('No receiver joined the class within 15 seconds.')), 15_000)
      }),
    ])
    clearTimeout(subscriptionTimeout)
    for await (const pcm of pcmChunks) {
      // rtc-node reads from the start of the buffer. A subarray can start partway through it.
      const samples = pcm.byteOffset === 0 ? pcm : new Int16Array(pcm)
      await audio.captureFrame(new AudioFrame(samples, 16000, 1, samples.length))
    }
    // 200 ms of silence so the end of the last real frame is sent before the track closes
    // (adds 0.2 processed seconds to source_seconds when the audio ends normally).
    await audio.captureFrame(new AudioFrame(new Int16Array(3200), 16000, 1, 3200))
    await audio.waitForPlayout()
  } finally {
    clearTimeout(subscriptionTimeout)
    // Runs on failure too, so a broken stream never leaves the teacher in the room.
    try { await track.close() } finally { await room.disconnect() }
  }
}

Next: Read events

Read events

Each session has an event log numbered from 1, with no gaps. Read it as JSON over HTTP. Baian does not send saved events through webhooks or WebSockets. Store the last seq you read and pass it as after on the next request. Use after: 0 to read from the beginning. The cursor must be a safe non-negative integer. Events remain available until the session is deleted or its retention period ends.

Request 1 to 500 events with limit. Set wait to 0 to 25 seconds. If there are no new events, the server can hold the request for up to that long. Existing events can return immediately. Keep reading until terminal is true, which means the session has finished and you have read every event.

Show each transcript.final as soon as you receive it. The first line can arrive before session.live.

Reference results can arrive after the transcript and may be updated when later speech identifies a quotation. For each segment_id, replace that kind's reference list with the latest event in seq order. Keep the transcript text unchanged.

Apply reference updates
Apply reference updates
// One map per class. Call this for each saved event.
const referencesBySegment = new Map()

function applyReferenceEvent(event) {
  const kind = event.type === 'quran.references' ? 'quran'
    : event.type === 'hadith.references' ? 'hadith' : null
  if (!kind) return
  const key = event.data.segment_id + ':' + kind
  const previous = referencesBySegment.get(key)
  if (previous && previous.seq >= event.seq) return
  referencesBySegment.set(key, { ...event.data, seq: event.seq })
}

Show words during speech

Open GET /sessions/{id}/partials once per active class on your server and relay transcript.partial messages to students who can access that class. Keep your API key on your server. Keep reading /events for finished lines and references.

cURL
curl -N "https://api.baian.ai/v1/sessions/$SESSION_ID/partials" \
  -H "Authorization: Bearer $BAIAN_API_KEY"

Show the latest preview in one line. Replace it with transcript.final for the same segment_id. Empty preview text clears that preview. Only save final lines.

Reconnect the preview stream when it closes after up to 25 seconds. A new connection gets the current preview when there is one. On 204, stop reconnecting and keep reading /events until the class is finished.

Apply live transcript updates
Apply live transcript updates
// Use one instance per class. Supply your app's three rendering functions.
function transcriptReader(showPreview, clearPreview, saveFinal) {
  const finished = new Set()
  let previewId = null
  let revision = 0

  return {
    // Parse the data of each transcript.partial message from your live feed.
    onPartial(partial) {
      if (finished.has(partial.segment_id) || partial.revision < revision) return
      revision = partial.revision
      if (partial.text) {
        previewId = partial.segment_id
        showPreview(partial)
      } else if (previewId === partial.segment_id) {
        previewId = null
        clearPreview()
      }
    },
    // Pass committed events here in seq order, including catch-up after a reconnect.
    async onEvent(event) {
      if (event.type !== 'transcript.final' || finished.has(event.data.segment_id)) return
      await saveFinal(event.data)
      finished.add(event.data.segment_id)
      if (previewId === event.data.segment_id) {
        previewId = null
        clearPreview()
      }
    },
  }
}

Student bookmarks

When a student bookmarks a line, save its session_id and segment_id with their bookmark in your app. To reopen it from Supabase, filter class_events by session_id and data->>segment_id, then read the matching events in seq order. This includes citations that arrived much later in the class. To keep bookmarks beyond Baian’s retention period, store the transcript and reference updates in your own database.

What final means

A transcript.final segment is committed once and its text stays the same. Its words come from the speech recogniser and may include words the recogniser had not yet confirmed when Baian committed the segment.

A transcript segment's language records the session's configured input_lang. It stays the same when the teacher switches languages: an English class can contain an Arabic quotation with language: "en". This field does not identify the language of each passage.

Timestamps and missing fields

start_ms, end_ms and gap from_ms/to_ms are whole milliseconds since session.created. They include microphone setup and gaps, so the first segment usually starts after 0. For usage, read source_seconds: it counts processed teacher audio and excludes setup and gaps.

Some fields can be null: in the transcript, a segment's text and language are null if only translation or reference events arrived for it, and start_ms/end_ms may be null. Ignore unknown event types and unknown fields so new ones do not break your integration.

cURL
curl "https://api.baian.ai/v1/sessions/$SESSION_ID/events?after=0&limit=100&wait=20" \
  -H "Authorization: Bearer $BAIAN_API_KEY"
200 response (excerpt)
{
  "events": [
    {
      "id": "evt_6f1c…_3",
      "seq": 3,
      "type": "transcript.final",
      "session_id": "6f1c…",
      "external_session_id": "class-2026-11-02-fiqh-101",
      "created_at": "2026-11-02T18:02:11Z",
      "data": { "segment_id": "k9x2:14", "text": "…", "language": "en", "start_ms": 52100, "end_ms": 57900 }
    },
    {
      "id": "evt_6f1c…_4",
      "seq": 4,
      "type": "quran.references",
      "data": {
        "segment_id": "k9x2:14",
        "status": "accepted",
        "references": [{ "ref": "2:255", "surah": 2, "ayah_start": 255, "ayah_end": 255, "matched_text": "…" }]
      }
    }
  ],
  "next_after": 4,
  "session_status": "live",
  "terminal": false
}
Server helper (Node.js): create, read events with retries, stop
Server helper (Node.js): create, read events with retries, stop
// Node 18+ on YOUR server. Never send BAIAN_API_KEY to an app, page or teacher device.
const BASE = 'https://api.baian.ai'
const KEY = process.env.BAIAN_API_KEY

class BaianError extends Error {
  constructor(status, body) {
    const e = body?.error ?? {}
    super(`${e.code ?? 'http_' + status}: ${e.message ?? 'request failed'} (${e.request_id ?? 'no request id'})`)
    this.status = status
    this.code = e.code
    this.requestId = e.request_id
  }
}

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const retryable = (error) => !(error instanceof BaianError) ||
  (error.status === 429 && error.code !== 'concurrency_limit') || error.status >= 500

// Retries network errors, rate limits and 5xx with exponential backoff and jitter.
// Free a class slot before retrying concurrency_limit. Other 4xx need a changed request.
// timeoutMs: per attempt. Long-poll reads use wait=20, so allow 30 s; other calls 15 s.
async function baian(path, init = {}, attempts = 5, timeoutMs = 15_000) {
  for (let attempt = 1; ; attempt++) {
    try {
      const res = await fetch(BASE + path, {
        signal: AbortSignal.timeout(timeoutMs),
        ...init,
        headers: { Authorization: `Bearer ${KEY}`, 'Content-Type': 'application/json', ...init.headers },
      })
      const body = await res.json().catch(() => null)
      if (!res.ok) throw Object.assign(new BaianError(res.status, body), { retryAfter: Number(res.headers.get('Retry-After')) || 0 })
      return body
    } catch (error) {
      if (attempt >= attempts || !retryable(error)) throw error
      const backoff = Math.min(30_000, 500 * 2 ** attempt) + Math.random() * 250
      const retryAfter = (error.retryAfter ?? 0) * 1000
      if (retryAfter > 2_147_483_647) throw error // exceeds the timer limit
      await sleep(Math.max(backoff, retryAfter))
    }
  }
}

// Keep existing retry keys. Use a stable ASCII digest when the ID cannot be sent in an HTTP header.
async function classKey(classId) {
  if (/^[\t\x20-\x7e\x80-\xff]+$/.test(classId)) return classId
  const bytes = await (globalThis.crypto?.subtle ?? (await import('node:crypto')).webcrypto.subtle).digest('SHA-256', new TextEncoder().encode(classId))
  return 'class-sha256:' + Array.from(new Uint8Array(bytes), b => b.toString(16).padStart(2, '0')).join('')
}

// 1. One session per class. The Idempotency-Key makes retries safe: the same key and
//    body always return the same session, even if the first response was lost.
export async function startClass(classId, { inputLang = 'en', alsoSpoken = ['ar'], translateTo = [] } = {}) {
  const { session, source } = await baian('/v1/sessions', {
    method: 'POST',
    headers: { 'Idempotency-Key': await classKey(classId) },
    body: JSON.stringify({
      external_session_id: classId,
      input_lang: inputLang,
      additional_input_langs: alsoSpoken, // add "ar" so Arabic Quran quotations are detected in English classes
      output_langs: translateTo,
      quran_refs: true,
    }),
  })
  if (!source) throw new Error(`Session ${session.id} is ${session.status}; it cannot receive audio.`)
  // Send source.livekit_url and source.token to the teacher device only.
  return { sessionId: session.id, source }
}

// 2. New teacher token after a disconnect (only while the session is created or live).
export async function teacherToken(sessionId) {
  const { source } = await baian(`/v1/sessions/${sessionId}/source-token`, { method: 'POST' })
  return source
}

// 3. Read events in seq order. Store event.seq with what you save and resume with the
//    last stored seq as `after`. If your process stops between saving an event and
//    recording its seq, that event is delivered again on restart: de-duplicate by seq.
export async function followClass(sessionId, onEvent, after = 0) {
  for (;;) {
    const page = await baian(`/v1/sessions/${sessionId}/events?after=${after}&limit=200&wait=20`, {}, 5, 30_000)
    for (const event of page.events) {
      await onEvent(event)
      after = event.seq
    }
    after = Math.max(after, page.next_after)
    if (page.terminal) return after
  }
}

// 4. Stop when the class ends. Safe to repeat; keep reading events until terminal.
export async function stopClass(sessionId) {
  const { session } = await baian(`/v1/sessions/${sessionId}/stop`, { method: 'POST' })
  return session
}

// 5. Optional: delete a finished session's transcript and events before retention ends.
export async function deleteClass(sessionId) {
  return baian(`/v1/sessions/${sessionId}`, { method: 'DELETE' })
}

Read one session (wrapped in session):

cURL
curl https://api.baian.ai/v1/sessions/$SESSION_ID \
  -H "Authorization: Bearer $BAIAN_API_KEY"
200 response
{
  "session": {
    "id": "6f1c…",
    "external_session_id": "class-2026-11-02-fiqh-101",
    "status": "live",
    "source_seconds": 312.4,
    "last_event_seq": 41
  }
}

List your sessions, newest first. Filter with status or external_session_id; limit is 1 to 100 (default 25). When next_cursor is not null, pass it as cursor to get the next page.

cURL
curl "https://api.baian.ai/v1/sessions?status=live&limit=25" \
  -H "Authorization: Bearer $BAIAN_API_KEY"
200 response (excerpt)
{
  "sessions": [
    { "id": "6f1c…", "external_session_id": "class-2026-11-02-fiqh-101", "status": "live", "created_at": "2026-11-02T18:00:00Z" }
  ],
  "next_cursor": "MjAyNi0xMS0wMlQxODowMDowMC4wMDAwMDBafDZmMWM…"
}

The assembled transcript is also available at any time:

cURL
curl https://api.baian.ai/v1/sessions/$SESSION_ID/transcript \
  -H "Authorization: Bearer $BAIAN_API_KEY"

Next: Quran references

Quran references

Baian looks for Arabic-script Quran quotations in the teacher's speech, whatever the main language is. A verse given only in translation is not detected. Each enabled segment gets a quran.references result with a status:

  • accepted: references lists the verses, each with ref (for example 2:255 or a range), surah, ayah_start, ayah_end and matched_text: the part of Baian's raw transcript that matched. Speech recognition can mishear words or omit Arabic vowel marks (tashkeel). To display a fully vowelled verse, look it up by ref in your Quran edition.
  • abstained: a possible quotation was found but Baian was not confident enough to name it.
  • failed: the check could not run for this segment.
  • no_candidates: nothing matched.

Show only accepted references as verses. An abstained or failed result does not mean that no verse was quoted.

Next: Hadith references

Hadith references

Hadith references are switched on per organisation. To see whether yours has them, call GET /v1/languages with your API key and read features.hadith_refs. Request hadith_refs only when it is true.

Send "hadith_refs": true when you create a session, and results arrive as hadith.references events. record_id and record_number identify the record in the named source edition. They are dataset identifiers, not hadith citation numbers. Take a number to show only from citation, as described below. Older sessions can send one marked verification: "unverified". A match is not a judgment on authenticity or grading. The OpenAPI specification describes every field.

Join each hadith.references event to transcript.final using segment_id. Show references only for accepted; abstained, no_candidates and failed carry no references. A failed or missing requested result makes the session incomplete. Keep matched_text (the unchanged transcript excerpt) separate from canonical_quote (the corpus excerpt). Retain corpus_version with the record identifiers so the source can be traced later.

Showing a hadith number

Use citation to decide what to show. Never show record_number as a hadith number.

  • citation.scheme is print_edition: show the collection and citation.number. Name citation.edition where readers can find it, such as a tooltip, footnote or detail view.
  • If citation is missing or null, show the collection and canonical_quote. A later hadith.references event can add the number. Update the bookmark for that segment_id.
  • citation.scheme is upstream_arabicnumber: sent by older sessions with verification: "unverified". Treat the number as unverified or leave it out.

edition_text_match means Baian matched the record to a numbered entry in a digital transcription of the named print edition. The edition’s wording can differ from canonical_quote. Hadith grading is separate.

Hadith reference with a print edition number
{
  "record_id": "ara-muslim:4927",
  "collection": "muslim",
  "edition": "ara-muslim",
  "record_number": "4927",
  "citation": {
    "number": "1907",
    "scheme": "print_edition",
    "edition": "ed. Muhammad Fuad Abd al-Baqi",
    "verification": "edition_text_match"
  },
  "matched_text": "انما الاعمال بالنية",
  "canonical_quote": "إِنَّمَا الأَعْمَالُ بِالنِّيَّةِ",
  "match_type": "near_verbatim"
}
Choose what to show for a hadith reference
Choose what to show for a hadith reference
// What to show for one reference from an accepted hadith.references event.
// collectionName is your label for reference.collection, for example 'Sahih Muslim'.
function describeHadithReference(reference, collectionName) {
  const citation = reference.citation
  if (citation && citation.scheme === 'print_edition') {
    return {
      title: collectionName + ' ' + citation.number,
      note: 'Number in ' + citation.edition, // tooltip, footnote or detail view
      quote: reference.canonical_quote,
    }
  }
  if (citation && citation.scheme === 'upstream_arabicnumber') {
    // Older sessions only. This number was never checked.
    return { title: collectionName, note: 'Unverified source number ' + citation.number, quote: reference.canonical_quote }
  }
  // No checked number: show the collection and the source text. Never show record_number.
  return { title: collectionName, note: null, quote: reference.canonical_quote }
}

Next: Stop and reconnect

Stop and reconnect

A session moves from created to live, then ending, then ended. It can also end as failed or expired.

  • No teacher audio within 10 minutes of creation: the session becomes expired and frees its slot.
  • A source token must be used to join within 15 minutes (source.expires_at). An already connected teacher is not disconnected when it passes.
  • Teacher disconnects: request a new source token with POST /v1/sessions/{id}/source-token (only while created or live) and reconnect. If no audio arrives for 5 minutes, Baian stops the session with reason source_lost. A session.gap is sent only when audio resumes after a disconnect or restart. There is no gap event for a source that never comes back, or for a connected microphone that is simply silent.
  • Source audio per class: session.max_session_seconds (default 4 hours). The separate elapsed ceiling, max_elapsed_seconds, is at most 8 hours from creation, including setup and pauses. Either limit stops the class with reason max_duration.
  • Pilot allowance: 2,000 audio minutes and 2,500 total running minutes for an explicitly activated month. Every API key and test-console class shares the same allowance. GET /v1/usage shows the dates and remaining seconds; the portal Usage page shows minutes. Running time includes setup, pauses and finishing. Baian stops classes at the audio limit (usage_limit), running-time limit (runtime_limit) or period boundary (usage_period_ended). Contact Baian for renewal or extra usage. Baian does not charge for overage automatically.
  • Translation is off unless enabled for your organisation. Use an empty output_langs array for transcription and references. Requesting translations without access returns 403 translation_not_enabled.
  • Usage reports normally arrive every 10 seconds; the fallback sweep runs every minute. Some audio can arrive before a stop takes effect, especially with simultaneous classes. Final words still finish saving, and actual usage is retained.
  • Stop is safe to repeat. A newly created session ends immediately if Baian has not attempted to dispatch the interpreter. Once dispatch starts, the session moves through ending and finishes saving results before ended, even if the first audio has yet to arrive. If processing does not finish within 2 minutes the session ends incomplete. Allowance, duration and access stop reasons are kept; other cases use agent_lost.
  • Access removed: if your organisation is suspended, or the dashboard user who started a console session loses owner or admin access, running sessions are stopped within about 10 seconds and end with reason access_revoked. If processing is not running, this takes about 3 minutes and the session ends incomplete. While suspended, every API-key request returns 403 org_suspended. Re-activation does not resume a stopped session.
  • On 429 rate_limited, wait at least the number of seconds in Retry-After. On 429 concurrency_limit, free a class slot before retrying.

The last event is session.ended or session.failed with completeness. incomplete means some results may be missing; missing_segment_ids lists known gaps and detail explains why.

detail is a diagnostic string, not a fixed list: log it and show it to support, but do not branch on exact values. Common examples: control_unavailable or heartbeat_… (Baian lost contact with its control service), source_… (some captured audio could not be transcribed), quran_… (Quran reference lookup failed for some segments), translation_failed (some translations failed; see translation.failed events), retries_exhausted or queue_capacity_reached (some results could not be saved) and close_timeout (processing did not finish in time). A session the interpreter ends on its own, without a stop request, has reason source_lost and is incomplete.

Stop
curl -X POST https://api.baian.ai/v1/sessions/$SESSION_ID/stop \
  -H "Authorization: Bearer $BAIAN_API_KEY"
New source token
curl -X POST https://api.baian.ai/v1/sessions/$SESSION_ID/source-token \
  -H "Authorization: Bearer $BAIAN_API_KEY"

Data retention and deletion

Baian deletes transcripts, references, events, metadata and your external session ID when your retention period ends. The default is 30 days after the session ends. See your organisation’s period in the portal. To delete sooner, call DELETE /v1/sessions/{id} on a finished session with sessions:write. If Baian returns 409 cleanup_pending, wait briefly and retry. Deleted sessions disappear from lists. Detail, events and transcript requests return 404.

Baian keeps a private record of the session, organisation and API key IDs, status, timestamps, end reason, completeness and source seconds for usage. It also keeps the original Idempotency-Key and a request hash so a retry cannot rebuild deleted content. Reusing that key returns 410 session_deleted. Keep personal or sensitive information out of idempotency keys. Baian does not record teacher audio for partner sessions.

Delete
curl -X DELETE https://api.baian.ai/v1/sessions/$SESSION_ID \
  -H "Authorization: Bearer $BAIAN_API_KEY"

Next: Event types

Reference

Event types

typeMeaning
session.createdSession exists; waiting for teacher audio. data.status.
session.liveTeacher audio arrived and processing started. data.media_ready_at.
transcript.finalA segment Baian has committed: segment_id (string), text, language, start_ms, end_ms. Sent once per segment; never updated afterwards.
translation.finalTranslation of a committed segment: segment_id, language, text. Only for languages in output_langs.
translation.failedA segment could not be translated into one language: segment_id, language, reason. The original transcript is unaffected.
quran.referencesReference decision for a segment: segment_id, status, references[], reason, selector_version.
hadith.referencesWhen hadith_refs is enabled and requested: segment_id, status, references[], reason, selector_version, corpus_version. Join it to transcript.final by segment_id.
session.gapSent when audio resumes after a disconnect or a processing restart: no teacher audio was processed between from_ms and to_ms. Fields: from_ms, to_ms, reason (for example source_reconnect or agent_restart).
session.endedLast event: status, reason, completeness, missing_segment_ids[], unacked_event_count, detail, source_seconds.
session.failedLast event when the session could not run: status, reason, detail, optional code, completeness, source_seconds.

segment_id is a string. Treat it as opaque and use it to join transcript, translation and reference events for the same segment.

Next: Errors and retries

Errors and retries

Every error contains error.code, error.message and error.request_id. Some include extra fields, such as session_id. Every response also includes an X-Request-Id header; keep it when asking for help.

Retry network errors, 429 rate_limited and 5xx with increasing delays. For example, wait 1, 2, 4 and 8 seconds plus jitter, with at most five attempts. When Retry-After is present, wait at least that long. For 429 concurrency_limit, wait for a class slot to free up. Other 4xx errors need a changed request.

Keep the same Idempotency-Key when retrying session creation. Keep your events cursor too, so a retry never skips or repeats events. The Node.js server helper includes this retry behaviour.

HTTPcodeMeaningWhat to do
400validation_failedA field is missing or invalid, including an invalid cursor or limit. The message names the field.Fix the request
400idempotency_key_requiredPOST /v1/sessions without an Idempotency-Key header (1 to 200 characters).Fix the request
401unauthorizedMissing, malformed, unknown or revoked key.Do not retry; check the key
403scope_forbiddenThe key does not have the scope this endpoint needs.Use a key with the scope
403org_suspendedYour organisation is suspended. Every API-key request is rejected, including reads and stop, and running sessions are stopped.Contact Baian
403usage_period_requiredNo active monthly pilot allowance.Ask Baian to activate the agreed month
403usage_limit_reachedThe shared source-audio allowance is used up.Contact Baian before starting another class
403runtime_limit_reachedThe shared running-time allowance is used up, including setup and pauses.Contact Baian before starting another class
403translation_not_enabledTranslation has not been enabled for this organisation.Use output_langs: [] or contact Baian
403hadith_not_enabledHadith references have not been enabled for this organisation.Omit hadith_refs or contact Baian
404not_foundThe session does not exist, was deleted, or belongs to another organisation.Do not retry
409idempotency_conflictThe same Idempotency-Key was used with a different body.Use a new key for a new request
409session_already_activeexternal_session_id already has a session that is created, live or ending. error.session_id names it.Reuse or stop that session
409session_not_activeA source token was requested for a session that is no longer created or live.Start a new session
409session_not_endedDELETE on a session that has not finished.Stop it and wait for terminal
409cleanup_pendingDELETE while Baian is still closing the session.Retry after a minute
410session_deletedThe Idempotency-Key belongs to a session that was deleted or purged. The same external_session_id can be used with a new key.Use a new Idempotency-Key
413payload_too_largeRequest body too large (for example metadata over 4 KB).Fix the request
429concurrency_limitYour organisation already has its maximum number of open sessions.Stop a session, then retry
429rate_limitedToo many requests for this key.Retry with backoff
500internal_errorUnexpected error.Retry with backoff; quote request_id
503partner_api_disabledThe Partner API is switched off on this environment.Retry later
503feature_unavailableHadith detection was requested but is not enabled in this environment.Check GET /v1/languages; omit hadith_refs until enabled
503rate_limiter_unavailableBaian could not check the request rate limit, so the request was not processed.Retry with backoff

Next: Limits

Limits

  • Budget 600 requests per minute per API key. Cloudflare applies the limit approximately at each location. On 429 rate_limited, wait for the duration in Retry-After.
  • Open sessions (created, live or ending): your organisation's limit, 2 by default. A create beyond it returns 429 concurrency_limit. The current limit is on the portal overview.
  • Session length: max_session_seconds of processed teacher audio, 4 hours by default, and max_elapsed_seconds of elapsed time, at most 8 hours.
  • Monthly pilot allowance: 2,000 source-audio minutes and 2,500 running minutes, shared by every key and console class. Check GET /v1/usage (scope sessions:read) for the active dates and remaining seconds. Translation needs to be enabled separately. See Stop and reconnect for what happens at a limit and how renewal works.
  • A new session with no teacher audio expires after 10 minutes. A live session with no audio for 5 minutes stops with source_lost.
  • Source token: join within 15 minutes of issue.
  • Per session: up to 5 output_langs, 3 additional_input_langs and 4 KB of metadata.
  • Pages: events limit 1 to 500 with wait 0 to 25 seconds; session lists limit 1 to 100.
  • API keys: up to 25 active keys per organisation.

Next: Languages

Languages

cURL
curl https://api.baian.ai/v1/languages \
  -H "Authorization: Bearer $BAIAN_API_KEY"

The response lists input (spoken) and output (translation) codes, limits, features and notes. Outputs marked text_only are supported for text; Baian does not provide speech output in this API.

Loading…

OpenAPI 3.1 specification: https://api.baian.ai/v1/openapi.json