---
title: "BCI"
canonical: https://docs.qvac.tether.io/sdk/v0.23/ai-capabilities/bci/
collection: "SDK"
package: "@qvac/sdk"
line: v0.23
current_line: false
---

# BCI (/sdk/v0.23/ai-capabilities/bci)



## Overview

Brain–computer interface (BCI) transcription uses a **GGML** engine ([`@qvac/bci-whispercpp`](https://github.com/tetherto/qvac/tree/main/packages/bci-whispercpp), built on the [`qvac-fabric-speech.cpp`](https://github.com/tetherto/qvac-fabric-speech.cpp) fork) to decode multi-channel neural signals (e.g., 512-channel microelectrode-array recordings) into text. Load a model using `modelType: "bci"`.

BCI consumes a **neural-signal buffer**. Provide the signal as `neuralData`, either as a file path (string, to a `.bin` file) or an in-memory `Uint8Array` buffer.

`bciTranscribe()` returns the complete transcript as a `string`, or — with `metadata: true` (as in the batch example below) — an array of segments, each with `text` and `startMs`/`endMs` timing. If you need partial results as they become available, use `bciTranscribeStream()` to open a duplex session that decodes a sliding window over the signal and yields transcript text as data arrives.

## Functions

Use the following sequence of function calls:

1. [`loadModel()`](/sdk/v0.23/reference/api#loadmodel)
2. [`bciTranscribe()`](/sdk/v0.23/reference/api#bcitranscribe) or [`bciTranscribeStream()`](/sdk/v0.23/reference/api#bcitranscribestream)
3. [`unloadModel()`](/sdk/v0.23/reference/api#unloadmodel)

For how to use each function, see [SDK — API reference](/sdk/v0.23/reference/api/).

<Callout type="info">
  **Neural signal format:** the `neuralData` input is a binary `.bin` file (or equivalent `Uint8Array`) with an 8-byte header — `[timesteps: uint32 LE, channels: uint32 LE]` — followed by row-major `float32` feature data (`features[t * channels + c]`). Each timestep represents a 20 ms bin of neural activity; channels correspond to individual electrodes in a microelectrode array (typically 512 channels). When streaming, this same header must lead the written bytes (`timesteps` is then ignored; `channels` must be non-zero).
</Callout>

<Callout type="info">
  **Placing streamed segments on the timeline:** with `metadata: true` and the default `emit: 'delta'`, each streamed segment also carries `windowStartTimestep`, the absolute index of the 20 ms timestep where its decode window began. A segment's own `startMs` / `endMs` are window-local, so compute the stream position as `startMs + windowStartTimestep * 20` (and the same for `endMs`). Batch segments do not carry the field: their timings are already absolute.
</Callout>

<Callout type="info">
  **Where run stats live:** `stats` and backend `diagnostics` ride the terminal frame of a batch `bciTranscribe` call, so RPC consumers (such as the Python client, which yields raw frames) can read them. The JavaScript `bciTranscribe()` resolves to text or segments only, and the streaming sessions expose neither, because the addon reports no stats for a stream.
</Callout>

<Callout type="info">
  **On the day index:** sessions recorded on different days use different day-specific projections. Set `modelConfig.bciConfig.day_idx` in `loadModel()` to match the recording session of the input signal — otherwise the decoded text will be misleading.
</Callout>

## Models

BCI transcription loads a **companion set** of two files, both required for inference:

* `ggml-bci-windowed.bin` — the GGML model: Whisper encoder/decoder (LoRA-merged), tokenizer, positional embedding, and windowed-attention header. Available constant: `BCI_WINDOWED`.
* `bci-embedder.bin` — day-projection weights: per-recording-day low-rank matrices, month projections, and session-to-day mapping. Available constant: `BCI_EMBEDDER`.

For model artifacts available as constants, see [SDK — Models](/sdk/v0.23/#models).

## Examples

### Batch

The following script transcribes a full neural signal up-front and prints the decoded text:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/bci/bci-filesystem.js title="bci-filesystem.js" lineNumbers
      /**
       * Batch BCI transcription from a neural-signal file.
       *
       * Reads a raw neural-signal `.bin` file, runs it through the BCI
       * (whisper.cpp) addon in one shot via `bciTranscribe`, and prints the
       * decoded transcript.
       *
       * Usage: npx tsx examples/bci/bci-filesystem.ts <neural-bin-file-path>
       */
      import { loadModel, unloadModel, bciTranscribe, BCI_WINDOWED } from '@qvac/sdk';
      const args = process.argv.slice(2);
      if (!args[0]) {
          console.error('Usage: npx tsx examples/bci/bci-filesystem.ts <neural-bin-file-path>');
          process.exit(1);
      }
      const neuralFilePath = args[0];
      try {
          console.log('▸ Starting BCI transcription example...');
          console.log('▸ Loading BCI model...');
          const modelId = await loadModel({
              modelSrc: BCI_WINDOWED,
              modelConfig: {
                  whisperConfig: {
                      language: 'en',
                      n_threads: 4,
                      temperature: 0.0
                  },
                  // Session day index selects the day-specific projection matrices.
                  // Set this to match the recording session your neural file came from.
                  bciConfig: {
                      day_idx: 1
                  }
              },
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log(`▸ BCI model loaded with ID: ${modelId}`);
          console.log('▸ Transcribing neural signal...');
          const segments = await bciTranscribe({
              modelId,
              neuralData: neuralFilePath,
              metadata: true
          });
          console.log('▸ Transcription result:');
          for (const segment of segments) {
              const start = (segment.startMs / 1000).toFixed(2);
              const end = (segment.endMs / 1000).toFixed(2);
              console.log(`  [${start}s → ${end}s] (id=${segment.id}, append=${segment.append}) ${segment.text}`);
          }
          console.log(segments
              .map((s) => s.text)
              .join('')
              .trim());
          console.log('▸ Unloading BCI model...');
          await unloadModel({ modelId });
          console.log('▸ BCI model unloaded successfully');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/bci/bci-filesystem.ts title="bci-filesystem.ts" lineNumbers
      /**
       * Batch BCI transcription from a neural-signal file.
       *
       * Reads a raw neural-signal `.bin` file, runs it through the BCI
       * (whisper.cpp) addon in one shot via `bciTranscribe`, and prints the
       * decoded transcript.
       *
       * Usage: npx tsx examples/bci/bci-filesystem.ts <neural-bin-file-path>
       */
      import { loadModel, unloadModel, bciTranscribe, BCI_WINDOWED } from '@qvac/sdk'

      const args = process.argv.slice(2)

      if (!args[0]) {
        console.error('Usage: npx tsx examples/bci/bci-filesystem.ts <neural-bin-file-path>')
        process.exit(1)
      }

      const neuralFilePath = args[0]

      try {
        console.log('▸ Starting BCI transcription example...')

        console.log('▸ Loading BCI model...')
        const modelId = await loadModel({
          modelSrc: BCI_WINDOWED,
          modelConfig: {
            whisperConfig: {
              language: 'en',
              n_threads: 4,
              temperature: 0.0
            },
            // Session day index selects the day-specific projection matrices.
            // Set this to match the recording session your neural file came from.
            bciConfig: {
              day_idx: 1
            }
          },
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log(`▸ BCI model loaded with ID: ${modelId}`)

        console.log('▸ Transcribing neural signal...')
        const segments = await bciTranscribe({
          modelId,
          neuralData: neuralFilePath,
          metadata: true
        })

        console.log('▸ Transcription result:')
        for (const segment of segments) {
          const start = (segment.startMs / 1000).toFixed(2)
          const end = (segment.endMs / 1000).toFixed(2)
          console.log(
            `  [${start}s → ${end}s] (id=${segment.id}, append=${segment.append}) ${segment.text}`
          )
        }
        console.log(
          segments
            .map((s) => s.text)
            .join('')
            .trim()
        )

        console.log('▸ Unloading BCI model...')
        await unloadModel({ modelId })
        console.log('▸ BCI model unloaded successfully')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/bci_filesystem.py title="bci_filesystem.py" lineNumbers
      """Python port of packages/sdk/examples/bci/bci-filesystem.ts.

      Batch BCI transcription from a neural-signal file.

      Reads a raw neural-signal `.bin` file, runs it through the BCI (whisper.cpp)
      addon in one shot via `bci_transcribe`, and prints the decoded transcript.

      JS's `bciTranscribe` takes a bare path and returns the segments; Python calls
      the generated stub, so the request carries a typed `{"type": "filePath"}`
      chunk and the segments are read off the streamed frames.

      RUN: python examples/bci_filesystem.py <neural-bin-file-path>
      """

      from __future__ import annotations

      import asyncio
      import sys

      from tetherto.qvac_sdk import (
          BciTranscribeRequest,
          Client,
          bci_transcribe,
          load_model,
          unload_model,
      )
      from tetherto.qvac_sdk.models import BCI_WINDOWED


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def main() -> int:
          if len(sys.argv) < 2:
              print(
                  "Usage: python examples/bci_filesystem.py <neural-bin-file-path>",
                  file=sys.stderr,
              )
              return 1

          neural_file_path = sys.argv[1]

          async with Client() as client:
              t = client.transport
              try:
                  print("▸ Starting BCI transcription example...")

                  print("▸ Loading BCI model...")
                  model_id = await load_model(
                      t,
                      model_src=BCI_WINDOWED,
                      model_config={
                          "whisperConfig": {
                              "language": "en",
                              "n_threads": 4,
                              "temperature": 0.0,
                          },
                          # Session day index selects the day-specific projection
                          # matrices. Set this to match the recording session your
                          # neural file came from.
                          "bciConfig": {"day_idx": 1},
                      },
                      on_progress=print_progress,
                  )
                  print(f"▸ BCI model loaded with ID: {model_id}")

                  print("▸ Transcribing neural signal...")
                  request = BciTranscribeRequest.model_validate(
                      {
                          "type": "bciTranscribe",
                          "modelId": model_id,
                          "neuralData": {"type": "filePath", "value": neural_file_path},
                          "metadata": True,
                      }
                  )

                  segments = []
                  async for response in bci_transcribe(t, request):
                      if response.error:
                          raise RuntimeError(response.error)
                      if response.segment is not None:
                          segments.append(response.segment)

                  print("▸ Transcription result:")
                  for segment in segments:
                      start = f"{segment.start_ms / 1000:.2f}"
                      end = f"{segment.end_ms / 1000:.2f}"
                      print(
                          f"  [{start}s → {end}s] (id={segment.id:g}, "
                          f"append={str(segment.append).lower()}) {segment.text}"
                      )
                  print("".join(s.text for s in segments).strip())

                  print("▸ Unloading BCI model...")
                  await unload_model(t, model_id)
                  print("▸ BCI model unloaded successfully")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/BciFilesystem.kt title="BciFilesystem.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/bci/bci-filesystem.ts.
      //
      // Batch BCI transcription from a neural-signal file.
      //
      // Reads a raw neural-signal `.bin` file, runs it through the BCI (whisper.cpp)
      // addon in one shot via `client.bci.transcribe()`, and prints the decoded
      // transcript.
      //
      // As in JS, the call takes the file as a typed input (`QvacDataInput.FilePath`,
      // one arm of a sealed interface) and returns the collected segments in
      // `QvacTranscriptionResult.segments`; an error frame is thrown as a
      // `QvacFeatureException`.
      //
      // RUN: ./gradlew -p examples run -Pexample=BciFilesystem --args="<neural-bin-file-path>"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacDataInput
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.bci
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import kotlin.system.exitProcess
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.JsonObject
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put
      import kotlinx.serialization.json.putJsonObject

      fun main(args: Array<String>): Unit = runBlocking {
          if (args.isEmpty()) {
              System.err.println("Usage: ./gradlew -p examples run -Pexample=BciFilesystem --args=\"<neural-bin-file-path>\"")
              exitProcess(1)
          }

          val neuralFilePath = args[0]

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ Starting BCI transcription example...")

              println("▸ Loading BCI model...")
              val modelId = client.loadWithProgress(
                  Models.BCI_WINDOWED,
                  modelConfig = buildJsonObject {
                      putJsonObject("whisperConfig") {
                          put("language", "en")
                          put("n_threads", 4)
                          put("temperature", 0.0)
                      }
                      // Session day index selects the day-specific projection
                      // matrices. Set this to match the recording session your
                      // neural file came from.
                      putJsonObject("bciConfig") { put("day_idx", 1) }
                  },
              )
              println("▸ BCI model loaded with ID: $modelId")

              println("▸ Transcribing neural signal...")
              val result = client.bci.transcribe(
                  modelId = modelId,
                  neuralData = QvacDataInput.FilePath(neuralFilePath),
                  metadata = true,
              )

              println("▸ Transcription result:")
              for (segment in result.segments) {
                  val start = "%.2f".format(segment.startMs / 1000)
                  val end = "%.2f".format(segment.endMs / 1000)
                  println("  [${start}s → ${end}s] (id=${segment.id.toLong()}, append=${segment.append}) ${segment.text}")
              }
              println(result.segments.joinToString("") { it.text }.trim())

              println("▸ Unloading BCI model...")
              client.models.unload(modelId)
              println("▸ BCI model unloaded successfully")
          } finally {
              client.close()
          }
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant, modelConfig: JsonObject? = null): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name, modelConfig = modelConfig).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

### Streaming

The following script feeds neural-signal chunks into a duplex session and prints transcript text as it is decoded:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/bci/bci-filesystem-streaming.js title="bci-filesystem-streaming.js" lineNumbers
      /**
       * Streaming BCI transcription from a neural-signal file.
       *
       * Reads a raw neural-signal `.bin` file and feeds it to the BCI
       * (whisper.cpp) addon chunk-by-chunk through a duplex `bciTranscribeStream`
       * session, printing transcript text as the sliding window decodes
       * successive windows.
       *
       * Usage: npx tsx examples/bci/bci-filesystem-streaming.ts <neural-bin-file-path>
       */
      import { loadModel, unloadModel, bciTranscribeStream, BCI_WINDOWED } from '@qvac/sdk';
      import { readFileSync } from 'fs';
      const args = process.argv.slice(2);
      if (!args[0]) {
          console.error('Usage: npx tsx examples/bci/bci-filesystem-streaming.ts <neural-bin-file-path>');
          process.exit(1);
      }
      const neuralFilePath = args[0];
      // Feed the neural buffer in fixed-size chunks to simulate a live stream.
      const CHUNK_SIZE = 64 * 1024;
      try {
          console.log('▸ BCI transcribeStream file test');
          console.log(`▸ File: ${neuralFilePath}`);
          console.log(`▸ Chunk size: ${CHUNK_SIZE} bytes`);
          console.log('▸ Loading model...');
          const modelId = await loadModel({
              modelSrc: BCI_WINDOWED,
              modelConfig: {
                  whisperConfig: {
                      language: 'en',
                      n_threads: 4,
                      temperature: 0.0
                  },
                  // Session day index selects the day-specific projection matrices.
                  // Set this to match the recording session your neural file came from.
                  bciConfig: {
                      day_idx: 1
                  }
              }
          });
          console.log(`▸ Model loaded: ${modelId}`);
          console.log('▸ Opening live session...');
          const session = await bciTranscribeStream({ modelId, emit: 'delta' });
          console.log('▸ Session open. Streaming neural signal...');
          // Drain the session concurrently with writing so the sliding-window
          // decode can make progress as chunks arrive instead of stalling.
          const consume = (async () => {
              let transcript = '';
              for await (const text of session) {
                  transcript += text;
                  process.stdout.write(text);
              }
              return transcript;
          })();
          const data = readFileSync(neuralFilePath);
          let totalBytes = 0;
          for (let offset = 0; offset < data.length; offset += CHUNK_SIZE) {
              const chunk = data.subarray(offset, offset + CHUNK_SIZE);
              session.write(chunk);
              totalBytes += chunk.length;
              await new Promise((resolve) => setTimeout(resolve, 10));
          }
          console.log(`\n\n▸ Neural signal streamed: ${totalBytes} bytes`);
          console.log('▸ Waiting for transcription to finish...');
          session.end();
          const transcript = await consume;
          console.log('\n▸ Results');
          console.log(transcript.trim() || '(no text received)');
          console.log('▸ Unloading model...');
          await unloadModel({ modelId });
          console.log('▸ Done.');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/bci/bci-filesystem-streaming.ts title="bci-filesystem-streaming.ts" lineNumbers
      /**
       * Streaming BCI transcription from a neural-signal file.
       *
       * Reads a raw neural-signal `.bin` file and feeds it to the BCI
       * (whisper.cpp) addon chunk-by-chunk through a duplex `bciTranscribeStream`
       * session, printing transcript text as the sliding window decodes
       * successive windows.
       *
       * Usage: npx tsx examples/bci/bci-filesystem-streaming.ts <neural-bin-file-path>
       */
      import { loadModel, unloadModel, bciTranscribeStream, BCI_WINDOWED } from '@qvac/sdk'
      import { readFileSync } from 'fs'

      const args = process.argv.slice(2)

      if (!args[0]) {
        console.error('Usage: npx tsx examples/bci/bci-filesystem-streaming.ts <neural-bin-file-path>')
        process.exit(1)
      }

      const neuralFilePath = args[0]

      // Feed the neural buffer in fixed-size chunks to simulate a live stream.
      const CHUNK_SIZE = 64 * 1024

      try {
        console.log('▸ BCI transcribeStream file test')
        console.log(`▸ File: ${neuralFilePath}`)
        console.log(`▸ Chunk size: ${CHUNK_SIZE} bytes`)

        console.log('▸ Loading model...')
        const modelId = await loadModel({
          modelSrc: BCI_WINDOWED,
          modelConfig: {
            whisperConfig: {
              language: 'en',
              n_threads: 4,
              temperature: 0.0
            },
            // Session day index selects the day-specific projection matrices.
            // Set this to match the recording session your neural file came from.
            bciConfig: {
              day_idx: 1
            }
          }
        })
        console.log(`▸ Model loaded: ${modelId}`)
        console.log('▸ Opening live session...')
        const session = await bciTranscribeStream({ modelId, emit: 'delta' })
        console.log('▸ Session open. Streaming neural signal...')

        // Drain the session concurrently with writing so the sliding-window
        // decode can make progress as chunks arrive instead of stalling.
        const consume = (async () => {
          let transcript = ''
          for await (const text of session) {
            transcript += text
            process.stdout.write(text)
          }
          return transcript
        })()

        const data = readFileSync(neuralFilePath)

        let totalBytes = 0
        for (let offset = 0; offset < data.length; offset += CHUNK_SIZE) {
          const chunk = data.subarray(offset, offset + CHUNK_SIZE)
          session.write(chunk)
          totalBytes += chunk.length
          await new Promise((resolve) => setTimeout(resolve, 10))
        }

        console.log(`\n\n▸ Neural signal streamed: ${totalBytes} bytes`)
        console.log('▸ Waiting for transcription to finish...')
        session.end()

        const transcript = await consume

        console.log('\n▸ Results')
        console.log(transcript.trim() || '(no text received)')

        console.log('▸ Unloading model...')
        await unloadModel({ modelId })
        console.log('▸ Done.')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/bci_filesystem_streaming.py title="bci_filesystem_streaming.py" lineNumbers
      """Python port of packages/sdk/examples/bci/bci-filesystem-streaming.ts.

      Streaming BCI transcription from a neural-signal file.

      Reads a raw neural-signal `.bin` file and feeds it to the BCI (whisper.cpp)
      addon chunk-by-chunk through a duplex `bci_transcribe_stream_session`,
      printing transcript text as the sliding window decodes successive windows.

      RUN: python examples/bci_filesystem_streaming.py <neural-bin-file-path>
      """

      from __future__ import annotations

      import asyncio
      import sys
      from pathlib import Path

      from tetherto.qvac_sdk import (
          Client,
          bci_transcribe_stream_session,
          load_model,
          unload_model,
      )
      from tetherto.qvac_sdk.models import BCI_WINDOWED

      # Feed the neural buffer in fixed-size chunks to simulate a live stream.
      CHUNK_SIZE = 64 * 1024


      async def main() -> int:
          if len(sys.argv) < 2:
              print(
                  "Usage: python examples/bci_filesystem_streaming.py <neural-bin-file-path>",
                  file=sys.stderr,
              )
              return 1

          neural_file_path = sys.argv[1]

          async with Client() as client:
              t = client.transport
              try:
                  print("▸ BCI transcribeStream file test")
                  print(f"▸ File: {neural_file_path}")
                  print(f"▸ Chunk size: {CHUNK_SIZE} bytes")

                  print("▸ Loading model...")
                  model_id = await load_model(
                      t,
                      model_src=BCI_WINDOWED,
                      model_config={
                          "whisperConfig": {
                              "language": "en",
                              "n_threads": 4,
                              "temperature": 0.0,
                          },
                          # Session day index selects the day-specific projection
                          # matrices. Set this to match the recording session your
                          # neural file came from.
                          "bciConfig": {"day_idx": 1},
                      },
                  )
                  print(f"▸ Model loaded: {model_id}")
                  print("▸ Opening live session...")
                  session = bci_transcribe_stream_session(t, model_id=model_id, emit="delta")
                  print("▸ Session open. Streaming neural signal...")

                  # Drain the session concurrently with writing so the sliding-window
                  # decode can make progress as chunks arrive instead of stalling.
                  async def consume() -> str:
                      transcript = ""
                      async for text in session:
                          transcript += text
                          sys.stdout.write(text)
                          sys.stdout.flush()
                      return transcript

                  consumer = asyncio.create_task(consume())

                  data = Path(neural_file_path).read_bytes()

                  total_bytes = 0
                  for offset in range(0, len(data), CHUNK_SIZE):
                      chunk = data[offset : offset + CHUNK_SIZE]
                      session.write(chunk)
                      total_bytes += len(chunk)
                      await asyncio.sleep(0.01)

                  print(f"\n\n▸ Neural signal streamed: {total_bytes} bytes")
                  print("▸ Waiting for transcription to finish...")
                  session.end()

                  transcript = await consumer

                  print("\n▸ Results")
                  print(transcript.strip() or "(no text received)")

                  print("▸ Unloading model...")
                  await unload_model(t, model_id)
                  print("▸ Done.")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/BciFilesystemStreaming.kt title="BciFilesystemStreaming.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/bci/bci-filesystem-streaming.ts.
      //
      // Streaming BCI transcription from a neural-signal file.
      //
      // Reads a raw neural-signal `.bin` file and feeds it to the BCI (whisper.cpp)
      // addon chunk-by-chunk through the duplex `client.bciTranscribeStream()`,
      // printing transcript text as the sliding window decodes successive windows.
      //
      // Kotlin note: the duplex input is a cold `Flow<ByteArray>`, not a session
      // object to `write()` and `end()`. The transport collects the input Flow while
      // you collect the replies, so there is no separate consumer task, and the
      // input Flow completing is the end-of-stream signal. The generated
      // `bciTranscribeStream` method yields every typed frame as it arrives;
      // `client.bci.transcribeStream(modelId, chunks)` takes the same Flow but
      // returns only the aggregated result once the stream ends.
      //
      // RUN: ./gradlew -p examples run -Pexample=BciFilesystemStreaming --args="<neural-bin-file-path>"

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.bciTranscribeStream
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.schema.BciTranscribeStreamRequest
      import io.tether.qvac.sdk.generated.schema.BciTranscribeStreamRequestStreamOpts
      import io.tether.qvac.sdk.generated.schema.BciTranscribeStreamRequestStreamOptsEmit
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import java.io.File
      import kotlin.system.exitProcess
      import kotlinx.coroutines.delay
      import kotlinx.coroutines.flow.flow
      import kotlinx.coroutines.runBlocking
      import kotlinx.serialization.json.buildJsonObject
      import kotlinx.serialization.json.put
      import kotlinx.serialization.json.putJsonObject

      // Feed the neural buffer in fixed-size chunks to simulate a live stream.
      private const val CHUNK_SIZE = 64 * 1024

      fun main(args: Array<String>): Unit = runBlocking {
          if (args.isEmpty()) {
              System.err.println(
                  "Usage: ./gradlew -p examples run -Pexample=BciFilesystemStreaming " +
                      "--args=\"<neural-bin-file-path>\"",
              )
              exitProcess(1)
          }

          val neuralFilePath = args[0]

          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              println("▸ BCI transcribeStream file test")
              println("▸ File: $neuralFilePath")
              println("▸ Chunk size: $CHUNK_SIZE bytes")

              println("▸ Loading model...")
              val loaded = client.models.load(
                  source = Models.BCI_WINDOWED.src,
                  modelType = Models.BCI_WINDOWED.engine,
                  modelName = Models.BCI_WINDOWED.name,
                  modelConfig = buildJsonObject {
                      putJsonObject("whisperConfig") {
                          put("language", "en")
                          put("n_threads", 4)
                          put("temperature", 0.0)
                      }
                      // Session day index selects the day-specific projection
                      // matrices. Set this to match the recording session your
                      // neural file came from.
                      putJsonObject("bciConfig") { put("day_idx", 1) }
                  },
              )
              val modelId = loaded.modelId ?: error(loaded.error ?: "loadModel failed")
              println("▸ Model loaded: $modelId")

              val data = File(neuralFilePath).readBytes()

              // The input side of the duplex call: completing this Flow ends the stream.
              val neuralChunks = flow {
                  var totalBytes = 0
                  for (offset in data.indices step CHUNK_SIZE) {
                      val chunk = data.copyOfRange(offset, minOf(offset + CHUNK_SIZE, data.size))
                      emit(chunk)
                      totalBytes += chunk.size
                      delay(10)
                  }
                  println("\n\n▸ Neural signal streamed: $totalBytes bytes")
                  println("▸ Waiting for transcription to finish...")
              }

              println("▸ Opening live session...")
              val request = BciTranscribeStreamRequest(
                  modelId = modelId,
                  streamOpts = BciTranscribeStreamRequestStreamOpts(emit = BciTranscribeStreamRequestStreamOptsEmit.DELTA),
              )
              println("▸ Session open. Streaming neural signal...")

              val transcript = StringBuilder()
              client.bciTranscribeStream(request, neuralChunks).collect { response ->
                  response.error?.let { error(it) }
                  val text = response.text
                  if (!text.isNullOrBlank()) {
                      transcript.append(text)
                      print(text)
                      System.out.flush()
                  }
              }

              println("\n▸ Results")
              println(transcript.trim().ifEmpty { "(no text received)" })

              println("▸ Unloading model...")
              client.models.unload(modelId)
              println("▸ Done.")
          } finally {
              client.close()
          }
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

<Callout type="success">
  **Tip:** all examples throughout this documentation are self-contained and runnable. For instructions on how to run them, see the [JS/TS quickstart](/sdk/v0.23/js-ts-sdk#quickstart), the [Python quickstart](/sdk/v0.23/python-sdk#quickstart), or the [Kotlin quickstart](/sdk/v0.23/kotlin-sdk#quickstart).
</Callout>
