{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    }
  },
  "cells": [
    {
      "id": "intro",
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# JetBase live twin rail\n",
        "Real Phi-2 and Qwen tokens, followed by native Rex P3Q (14700) and governed Jupiter receipts. Use your existing operator key; no keys are embedded in this notebook.\n",
        "For Gateway 92 on your host set `BASE_URL = \"http://127.0.0.1:8092\"`.\n"
      ]
    },
    {
      "id": "consumer",
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "\"\"\"Consume real GGUF tokens and native P3Q/Jupiter receipts from JetBase.\"\"\"\n",
        "import json\n",
        "import os\n",
        "from getpass import getpass\n",
        "from urllib.request import Request, urlopen\n",
        "from urllib.error import HTTPError\n",
        "\n",
        "BASE_URL = os.environ.get(\"JETBASE_URL\", \"https://jetbase-production.up.railway.app\").rstrip(\"/\")\n",
        "\n",
        "\n",
        "def sse_events(response):\n",
        "    event, data, event_id = \"message\", [], None\n",
        "    for raw in response:\n",
        "        line = raw.decode(\"utf-8\").rstrip(\"\\r\\n\")\n",
        "        if not line:\n",
        "            if data:\n",
        "                yield event, json.loads(\"\\n\".join(data)), event_id\n",
        "            event, data = \"message\", []\n",
        "        elif line.startswith(\"event:\"):\n",
        "            event = line[6:].strip()\n",
        "        elif line.startswith(\"data:\"):\n",
        "            data.append(line[5:].lstrip())\n",
        "        elif line.startswith(\"id:\"):\n",
        "            event_id = line[3:].strip()\n",
        "\n",
        "\n",
        "def run_twin_rail(prompt, key=None, targets=(\"phi2\", \"qwen\"), run_id=None,\n",
        "                  include_lattice=True, on_event=None, max_tokens=128):\n",
        "    \"\"\"One concurrent token stream; native lattice results arrive as typed events.\n",
        "\n",
        "    Token generation and the native Rex P3Q computation are distinct operations.\n",
        "    Native receipts carry the documented models, source hashes and material IDs.\n",
        "    \"\"\"\n",
        "    key = key or os.environ.get(\"AURA_OPERATOR_KEY\") or getpass(\"Existing AURA operator key: \")\n",
        "    payload = {\"prompt\": prompt, \"targets\": list(targets), \"max_tokens\": max_tokens,\n",
        "               \"include_lattice\": include_lattice}\n",
        "    if run_id:\n",
        "        payload[\"run_id\"] = run_id\n",
        "    request = Request(BASE_URL + \"/api/clinical/quantum/stream\", method=\"POST\",\n",
        "                      data=json.dumps(payload).encode(), headers={\n",
        "                          \"Content-Type\": \"application/json\", \"Accept\": \"text/event-stream\",\n",
        "                          \"x-aura-operator-key\": key})\n",
        "    state = {\"phi2\": \"\", \"qwen\": \"\", \"receipts\": [], \"errors\": [], \"completed\": False}\n",
        "    try:\n",
        "        with urlopen(request, timeout=930) as response:\n",
        "            if \"text/event-stream\" not in response.headers.get(\"Content-Type\", \"\"):\n",
        "                raise RuntimeError(\"Expected a live SSE response\")\n",
        "            for event, value, event_id in sse_events(response):\n",
        "                if event == \"token\":\n",
        "                    seat = value[\"seat\"]\n",
        "                    content = value.get(\"content\") or value.get(\"reasoning_content\") or \"\"\n",
        "                    state[seat] += content\n",
        "                    if on_event is None and content:\n",
        "                        print(f\"[{seat}] {content}\", end=\"\", flush=True)\n",
        "                elif event in (\"lattice\", \"jupiter\"):\n",
        "                    state[\"receipts\"].append({\"event\": event, \"data\": value})\n",
        "                elif event == \"error\":\n",
        "                    state[\"errors\"].append(value.get(\"error\", \"stream error\"))\n",
        "                elif event == \"done\":\n",
        "                    state[\"completed\"] = value.get(\"ok\") is True\n",
        "                if on_event:\n",
        "                    on_event(event, value, event_id)\n",
        "    except HTTPError as error:\n",
        "        detail = error.read().decode(\"utf-8\", errors=\"replace\")\n",
        "        raise RuntimeError(f\"JetBase HTTP {error.code}: {detail}\") from error\n",
        "    if state[\"errors\"] or not state[\"completed\"]:\n",
        "        raise RuntimeError(\"; \".join(state[\"errors\"]) or \"Stream ended before verified completion\")\n",
        "    return state\n",
        "\n",
        "\n",
        "def notebook_twin_rail(prompt, **options):\n",
        "    \"\"\"Optional notebook widgets; no background worker touches notebook UI.\"\"\"\n",
        "    import ipywidgets as widgets\n",
        "    from IPython.display import display\n",
        "    rails = {seat: widgets.Textarea(description=seat, layout={\"width\": \"48%\", \"height\": \"220px\"})\n",
        "             for seat in (\"phi2\", \"qwen\")}\n",
        "    status = widgets.Label(value=\"Connecting live twin rail\u2026\")\n",
        "    receipt = widgets.Textarea(description=\"Receipts\", layout={\"width\": \"100%\", \"height\": \"220px\"})\n",
        "    display(status, widgets.HBox(list(rails.values())), receipt)\n",
        "\n",
        "    def update(event, value, event_id):\n",
        "        if event == \"token\":\n",
        "            rails[value[\"seat\"]].value += value.get(\"content\") or value.get(\"reasoning_content\") or \"\"\n",
        "        elif event in (\"lattice\", \"jupiter\"):\n",
        "            receipt.value += json.dumps({\"event\": event, \"data\": value}, indent=2) + \"\\n\"\n",
        "        elif event == \"done\":\n",
        "            status.value = \"Verified completion\" if value.get(\"ok\") else \"Execution requires attention\"\n",
        "        elif event == \"error\":\n",
        "            status.value = value.get(\"error\", \"Stream error\")\n",
        "    return run_twin_rail(prompt, on_event=update, **options)\n"
      ]
    },
    {
      "id": "run",
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Uncomment to run a short live check.\n",
        "# result = notebook_twin_rail(\"Reply with READY only.\", max_tokens=16)\n"
      ]
    }
  ]
}
