# DuplexVoice Gateway: A FastAPI Barge-In Session Service

## PURPOSE
Build a WebSocket gateway that keeps a full-duplex voice conversation alive the
way OpenAI's UK demo of ChatGPT voice (powered by GPT Live) shows it: the model
listens and speaks at the same time, and the user can cut in mid-sentence —
"Hang on, what are you wittering about?" — without destroying the session. The
service tracks the assistant's in-flight output, detects a barge-in, cancels
synthesis, and re-enters listening mode with the conversation context intact.

## WHY THIS MATTERS
Half-duplex assistants are walkie-talkies: you wait your turn. The transcript's
central claim is a *bidirectional* partner that can also hold multiple bits of
information at once (a Casablanca trip, an emailed restaurant list, September
weather in Morocco) while the user changes plans mid-stream. That is a session
state problem, not only a model problem. Students learn that "full duplex" is an
engineering contract: cancellable output, resumable topics, and a bounded
interrupt budget.

## HOW TO BUILD
1. Serve a WebSocket at `/ws/session/{session_id}` with FastAPI.
2. Model each session as an explicit state machine:
   `IDLE -> LISTENING -> SPEAKING -> INTERRUPTED -> LISTENING`.
3. Keep turns on a LIFO topic stack so an abandoned request (the guitar price,
   the vegan restaurant list) can be resumed instead of restarted.
4. Replace the GPT Live call with a deterministic stub so tests never hit a
   network.

```python
@app.websocket("/ws/session/{session_id}")
async def session(ws: WebSocket, session_id: str):
    await ws.accept()
    s = Session(session_id)
    async for raw in ws.iter_text():
        evt = json.loads(raw)
        if evt["type"] == "speech_started":
            await s.barge_in()          # cancel in-flight synthesis
        reply = s.respond(evt.get("text", ""))
        await ws.send_json({"type": "assistant_delta", **reply})
```

## WHEN TO USE IN PRODUCTION
Use it for live voice agents: call-centre triage, in-car assistants, screen
reader companions, and any kiosk where users talk over the machine. Do NOT use
it for batch transcription jobs, push-to-talk radio style UX, or when the
downstream model exposes no cancellation handle — you would burn inference
budget on output nobody hears.

## HOW IT HELPS STUDENTS
Async Python, WebSockets, explicit state machines, cancellation semantics, and
defensive input handling. It teaches the difference between a demo that talks
and a service that survives being interrupted.

## STARTER CODE
See `starter/main.py` for the runnable skeleton: session state machine, topic
stack, deterministic reply stub, and a main entry point.
