LIVE-CALL GROUNDED AI COPILOT DUAL-STREAM CORE AUDIO & FASTER-WHISPER ZERO-HALLUCINATION CHROMADB RAG

Live Call AI Assistant: Grounded ChatGPT Call Copilot for macOS

A Python desktop copilot for macOS that listens to both sides of a live business call (your microphone and the remote participant via Core Audio Multi-Output / BlackHole loopback), transcribes phrases locally on the CPU with faster-whisper, retrieves strictly isolated client facts from local ChromaDB collections, and writes a 1–2 sentence response you can speak aloud—refusing to invent budgets, dates, or commitments when the history lacks the answer.

16 kHz
Kaiser Anti-Aliased Audio
Temp 0.0
Zero-Hallucination Contract
prof_*
Isolated ChromaDB Profiles
2 Editions
Aurora (Rust/Skia) & Tkinter

Only Repeating What the Work History Already Knows

During a live client call, generic AI assistants are dangerous: if asked about an unrecorded delivery date, SLA target, or budget cap, they eagerly improvise plausible-sounding numbers. In real engineering consulting, a hallucinated commitment creates immediate contractual liability.

  • Local Export & Ownership: ChatGPT does not hand third-party apps your chat threads. Instead, you export the conversations you care about (conversations.json or account .zip), and the copilot indexes them locally on disk under `~/.context_assistant/vector_db`.
  • Strict Profile Segregation: Every client workspace lives in its own sanitized ChromaDB collection (prof_<slug>). Default_Client and Other_Client never share embeddings.
  • Deterministic Refusal Guardrail: If the retrieved chunks do not contain the answer, the copilot outputs a single deterministic refusal line and stops.
  • Post-Call Memory Sync: Stopping a call writes a Markdown review packet containing an UPDATE_WORKSPACE_MEMORY_PROTOCOL_INIT block ready to paste back into your ChatGPT thread.
Immutable Zero-Hallucination Refusal Contract:
// Triggered when retrieved ChromaDB chunks lack the requested fact
"I don't have that documented in our prior work history,
but let me check and follow up."

Solving macOS Headphone & Whisper Traps

Capturing both sides of a call on macOS while wearing AirPods or headphones requires bridging low-level audio driver gaps and speech model quirks:

Core Audio Multi-Output Discovery: PortAudio hides macOS Multi-Output Devices because they are output-only. Our audio_devices.py queries Core Audio directly via ctypes (dev# and agrp selectors) to locate the underlying BlackHole loopback input member.
Silence & Hallucination Suppression: Whisper invents "Bye." and "Thanks for watching" when handed amplified room hiss. prepare_speech_audio scores 20 ms frames by RMS, drops clips below 0.005, trims quiet tails, and normalizes robust 99.9th-percentile peaks to 0.95.
Cross-Talk Echo Deduplication: When acoustic bleed causes both streams to hear the same sentence, SequenceMatcher (ratio ≥ 0.72 across opposite speakers) drops the duplicate while preserving legitimate self-repetition.

Dual-Stream Audio & Grounded RAG Pipeline

Every spoken phrase follows a deterministic, non-blocking path from hardware audio capture through signal conditioning, local CPU speech-to-text, cross-talk filtering, and isolated vector retrieval before reaching the language model.

+----------------------------------------------------------------------------------------------------+
|                         MACOS CORE AUDIO & PORTAUDIO CAPTURE LAYER                                 |
|  [Physical Microphone / AirPods]               [Meeting Audio: Multi-Output -> BlackHole 2ch]      |
|  (sd.InputStream @ native Hz, 250ms blocks)    (CoreAudio ctypes 'agrp' lookup -> high-energy ch)  |
+----------------------+-------------------------------------------------------+---------------------+
                       │                                                       │
                       └───────────────────────────┬───────────────────────────┘
                                                   |
+--------------------------------------------------+-------------------------------------------------+
|                     PER-SPEAKER PHRASE DETECTOR (speech_audio.take_speech_phrase)                  |
|  - Slow-average noise floor tracker + 350 ms rolling pre-roll buffer (prevents clipped word onset) |
|  - Opens phrase after 200 ms above floor; closes after 0.7 s silence or 8.0 s max duration         |
+--------------------------------------------------+-------------------------------------------------+
                                                   │
                                  put_nowait() to Background Worker
                                  (Generation Counter Guards Stale Calls)
                                                   |
+--------------------------------------------------+-------------------------------------------------+
|                     SIGNAL CONDITIONING & LOCAL CPU SPEECH-TO-TEXT                                 |
|  1. prepare_speech_audio(): 20 ms frame RMS gate (>= 0.005) drops room hiss; trims quiet tails    |
|  2. _resample_16k(): SciPy Kaiser-windowed (beta=14.0) polyphase resampler to 16 kHz mono          |
|  3. _level(): 99.9th-percentile click-resistant peak normalization to 0.95 (max gain 6.0x)         |
|  4. transcribe_speech(): faster-whisper (int8_float32, temp 0.0) + hallucination & loop filters    |
|  5. is_cross_talk_echo(): SequenceMatcher (>= 0.72) drops acoustic bleed across opposite streams   |
+--------------------------------------------------+-------------------------------------------------+
                                                   │
                                                   │
+----------------------------------+      +--------+-------------------------------------------------+
| CHROMADB VECTOR STORE            |      | GROUNDED INFERENCE ENGINE (Ollama / OpenAI SDK)          |
| ~/.context_assistant/vector_db   |─────| - Substitutes Top-6 deduplicated chunks into {context}   |
| - Isolated prof_<slug> per client|      | - Enforces 1-2 sentence first-person reply at temp 0.0   |
| - Queries current + prev turn    |      | - Outputs strict refusal line if fact is undocumented    |
+----------------------------------+      +--------+-------------------------------------------------+
                                                   │
                         ┌─────────────────────────┴─────────────────────────┐
                         |                                                   |
+------------------------+------------------------+ +------------------------+-----------------------+
| DESKTOP UI EDITIONS (Shared Session Pipeline)   | | POST-CALL ARTIFACTS & EXPORTS                  |
| - app_aurora.py: Aurora UI (Rust/Skia + Signals)| | - review_packet_<timestamp>.md (ChatGPT sync)  |
| - app.py: Elevated Tkinter (Queue + AppKit)     | | - call_export.py: Verbatim MD / TXT / CSV      |
+-------------------------------------------------+ +------------------------------------------------+

Application Architecture & Module Matrix

Module / File Primary Stack Core Responsibility Reliability & Platform Safeguards
app_aurora.py Aurora UI (Rust / Skia / Taffy) Reactive desktop edition driven by Signals, flexbox layout, floating toasts, and citation cards. Background daemon threads update reactive signals; serialized Whisper loading via _whisper_lock.
app.py CPython Tkinter + PyObjC AppKit Multi-page desktop edition with Midnight/Daylight themes, custom ActionButton labels, and packet inspector. Thread-safe ui_queue drained on main loop prevents GIL/Tk crashes; AppKit forces foreground focus on macOS.
audio_devices.py Core Audio (ctypes) + PortAudio Enumerates macOS aggregate/Multi-Output devices and maps multi:<name> to its BlackHole input index. Gracefully falls back to auto-detected BlackHole input or standard microphone when aggregate devices change.
speech_audio.py NumPy, SciPy, faster-whisper Energy VAD state machine, 16 kHz Kaiser resampling, robust leveling, Whisper decoding, and echo suppression. Rejects clips < 350 ms, filters silence before inference, blocks known Whisper hallucinations, and drops cross-talk.
call_export.py Python csv, re, Markdown Exports full call transcripts or structured meeting resumes in Markdown, plain text, or CSV formats. Strictly restates captured turns; labels copilot suggestions separately and never fabricates unstated decisions.
ui_icons.py SVG Byte Vectors + Pillow / AppKit Provides crisp vector iconography directly to Aurora Skia and rasterizes icons for Tkinter PhotoImage. Attempts native macOS AppKit SVG rasterization first, falling back cleanly to Pillow drawing primitives.
test_audio.py sounddevice + NumPy CLI Standalone 8-second terminal VU-meter diagnostic utility for testing single inputs (mic or BlackHole). Flags peak amplitude < 0.005 with actionable macOS Privacy & Security microphone permission guidance.
test_workflow.py & E2E Headless Test Harnesses Exercises ChromaDB ingestion, grounded retrieval, refusal invariants, and both UI editions without live audio. Verifies profile isolation (prof_*), prompt restoration, and zero-hallucination responses in CI/local runs.

Core Implementation Deep Dive

Inspect the key engineering mechanisms from the codebase: resolving hidden macOS Multi-Output devices via Core Audio, trailing-window phrase detection with rolling pre-roll, hallucination-guarded speech conditioning, and verbatim post-call resume rendering.

1. Core Audio Multi-Output Resolution
Python
# audio_devices.py
def multi_output_devices() -> List[Dict[str, object]]:
    """Return Multi-Output / aggregate devices and the input used to record them."""
    try:
        members = _aggregate_members()
    except Exception:
        return []

    listed = []
    for name, member_names in members:
        capture_index = None
        capture_name = None
        ordered = sorted(
            member_names,
            key=lambda item: (0 if "blackhole" in item.lower() else 1, item.lower()),
        )
        for member in ordered:
            found = _input_index_by_name(member)
            if found is not None:
                capture_index = found
                capture_name = member
                break
        listed.append({
            "id": MULTI_PREFIX + name,
            "label": short_device_label(name),
            "capture_index": capture_index,
            "capture_name": capture_name,
        })
    return listed
2. Trailing-Window Phrase Detector
Python
# speech_audio.py
def take_speech_phrase(state: dict, chunk) -> Optional[np.ndarray]:
    sr = int(state["sr"])
    samples = np.asarray(chunk, dtype=np.float32).reshape(-1)
    rms = float(np.sqrt(np.mean(np.square(samples))))
    speaking = bool(state.get("is_speaking"))
    if not speaking:
        floor = float(state.get("noise_floor", 0.0015))
        state["noise_floor"] = (0.95 * floor) + (0.05 * rms)
    floor = max(float(state.get("noise_floor", 0.0015)), 1e-5)
    ceiling = min(max(float(state.get("cfg_thresh") or 0.008), 0.004), 0.01)
    open_at = max(0.004, min(ceiling, max(floor * 3.0, 0.004)))
    is_speech = rms >= (open_at * 0.5 if speaking else open_at)

    # 350ms rolling pre-roll prevents clipping word onsets;
    # 0.7s silence or 8.0s max closes the active utterance
    ended = state["silent_frames"] >= int(sr * 0.7) or len(buffer) >= int(sr * 8.0)
3. Kaiser Resampling & Cross-Talk Guard
Python
# speech_audio.py
def _level(audio: np.ndarray) -> np.ndarray:
    """Bring speech up to a clear peak. A single click must not set the gain."""
    magnitude = np.abs(audio)
    peak = float(np.max(magnitude))
    robust_peak = float(np.quantile(magnitude, 0.999))
    if peak < 1e-4:
        return audio
    reference = robust_peak if peak > robust_peak * 4.0 else peak
    gain = min(TARGET_PEAK / max(reference, 1e-4), MAX_GAIN)
    return np.clip(audio * gain, -0.95, 0.95).astype(np.float32)

def is_cross_talk_echo(previous_speaker: str, previous_text: str, speaker: str, text: str) -> bool:
    if not previous_text or not text or previous_speaker == speaker:
        return False
    prev_line, new_line = " ".join(_words(previous_text)), " ".join(_words(text))
    return SequenceMatcher(None, prev_line, new_line).ratio() >= 0.72
4. Non-Hallucinating Call Resume Export
Python
# call_export.py
def _overview_lines(turns: Sequence[Turn], markdown: bool) -> List[str]:
    heading = "## Overview" if markdown else "Overview"
    lines = [
        "",
        heading,
        "",
        "This resume restates the captured transcript. "
        "It does not add agreements, dates, or decisions that were not spoken.",
        "",
    ]
    if not turns:
        lines.append("No speech was captured.")
        return lines
    lines.append(f"First line: {turns[0][0]}")
    lines.append(f"Last line: {turns[-1][0]}")
    lines.append(f"Turns: {len(turns)}")
    for speaker, count in _speaker_counts(turns):
        lines.append(f"{speaker}: {count} turns")
    return lines