garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/lib/live.ts

raw

import {post} from '@/lib/api'

/**
 * A voice call, talked with as with a person, cutting in and all. The hub
 * signs the call (`/v1/hosted/discuss`, discuss.rs) and says which engine it
 * is on; the audio and the events go between this page and OpenAI, and the
 * tool calls come here to run. On GPT-Live (gpt-live-1, as Podium's feedback
 * coach talks) a backend model runs the tools for the voice, and the events
 * are `session.*` and `response.event`; on the realtime model
 * (gpt-realtime-2.1) the voice calls them itself, with the realtime events.
 */

/** Which of OpenAI's voice APIs a call talks on. */
export type Engine = 'live' | 'realtime'

export interface LiveEvents {
    /** A finished line of the person's or of the voice's, cut at pauses in its transcript. */
    onYou: (text: string) => void
    /** The person is talking: their transcript grows. */
    onHearing?: () => void
    onVoice: (text: string) => void
    onSpeaking: (speaking: boolean) => void
    onToolCall: (name: string, args: string, callId: string) => void
    onClosed: (reason: string) => void
}

export class LiveCall {
    private pc = new RTCPeerConnection()
    private dc = this.pc.createDataChannel('oai-events')
    private audio = new Audio()
    private mic: MediaStreamTrack | null = null
    private you = new Line()
    private voice = new Line()
    /** The person's line in the transcriber's pieces: when it sends none, its whole line comes at the end. */
    private heard = false
    /** Tool calls of the last answer still running: it goes on once all are back. */
    private pending = 0
    /** A call of this turn wants no answer after it. */
    private quiet = false
    /** The last turn said something, beside its calls. */
    private spoke = false
    private closed = false
    /** An answer is being made, its audio plays, or the person talks: a told answer waits for it. */
    private responding = false
    private playing = false
    private hearing = false
    /** Something told (`tell`) waits to be said once nobody talks. */
    private owed = false
    private owedTimer: ReturnType<typeof setTimeout> | undefined
    engine: Engine = 'realtime'
    /** GPT-Live sends no audio events over WebRTC: its transcript says when it speaks. */
    private speakingTimer: ReturnType<typeof setTimeout> | undefined

    constructor(private events: LiveEvents) {
        this.audio.autoplay = true
        this.pc.ontrack = (e) => (this.audio.srcObject = e.streams[0] ?? null)
        this.dc.onmessage = (m) => this.receive(JSON.parse(m.data))
        this.you.onLine = events.onYou
        this.voice.onLine = events.onVoice
        // A network gone (a phone between masts), or the session's hour up, ends the call without a word from OpenAI.
        this.dc.onclose = () => {
            if (this.closed) return
            this.close()
            this.events.onClosed('the channel closed')
        }
        this.pc.onconnectionstatechange = () => {
            if (this.closed || this.pc.connectionState !== 'failed') return
            this.close()
            this.events.onClosed('the connection was lost')
        }
    }

    /** `opening`: what it starts with, in its own words; it waits for the other side otherwise. `tools`: which of the hub's. */
    async start(mic: MediaStreamTrack, instructions: string, opening: string, tools: string[], voice: 'female' | 'male' = 'female'): Promise<void> {
        this.mic = mic
        this.pc.addTrack(mic)
        await this.pc.setLocalDescription(await this.pc.createOffer())
        const {sdp, engine} = (await post('/v1/hosted/discuss', {sdp: this.pc.localDescription!.sdp, instructions, tools, voice})) as {sdp: string; engine?: Engine}
        this.engine = engine === 'live' ? 'live' : 'realtime'
        await this.pc.setRemoteDescription({type: 'answer', sdp})
        await new Promise<void>((resolve, reject) => {
            const timeout = setTimeout(() => reject(new Error("the voice didn't answer")), 15_000)
            this.dc.addEventListener('open', () => (clearTimeout(timeout), resolve()), {once: true})
        })
        if (this.engine === 'live') {
            // What it starts with, in its own words: GPT-Live waits for the other side otherwise.
            this.live('session.commentary.append', opening)
            return
        }
        this.system(opening)
        this.send({type: 'response.create'})
    }

    /** Context for its next replies, not to be said now (the brief, edited by hand); `images`: pictures it is to see with it, as data URLs. */
    note(text: string, images: string[] = []): void {
        if (this.engine === 'live') {
            this.live('session.thinking.append', text)
            this.look(images)
            return
        }
        this.system(text)
        this.look(images)
    }

    /**
     * Something it is to say now, that came late (a code question's answer):
     * said at once when nobody talks, else after the answer or the person's
     * words in the way, unless an answer made meanwhile already took it in.
     */
    tell(text: string, images: string[] = []): void {
        if (this.engine === 'live') {
            // Full duplex: it finds the moment itself, as with its opening.
            this.look(images)
            this.live('session.commentary.append', text)
            return
        }
        this.system(text)
        this.look(images)
        this.owed = true
        this.sayOwed()
    }

    private sayOwed(): void {
        clearTimeout(this.owedTimer)
        if (!this.owed || this.responding || this.playing || this.hearing || this.pending > 0) return
        this.owed = false
        this.send({type: 'response.create'})
    }

    /** Off the record: it stops hearing the person. */
    mute(muted: boolean): void {
        if (this.mic) this.mic.enabled = !muted
        if (this.engine === 'live') this.send({type: muted ? 'session.input_audio.mute' : 'session.input_audio.unmute', event_id: crypto.randomUUID()})
    }

    /**
     * A function call's result back to the model, which answers once every call
     * of its turn is back. `answer` false: no answer if that turn said
     * something (a hang-up: it said goodbye, and would say a second one), and
     * one if it went quiet (the goodbye it skipped).
     */
    toolResult(callId: string, output: object, answer = true): void {
        if (this.engine === 'live') {
            // To the backend, which carries on from it and reports to the voice; a hang-up wants nothing after it.
            const item = {type: 'function_call_output', call_id: callId, output: JSON.stringify(output)}
            this.send({type: 'response.item.create', event_id: crypto.randomUUID(), item})
            if (answer) this.send({type: 'response.create', event_id: crypto.randomUUID()})
            return
        }
        this.send({type: 'conversation.item.create', item: {type: 'function_call_output', call_id: callId, output: JSON.stringify(output)}})
        this.pending = Math.max(0, this.pending - 1)
        if (!answer && this.spoke) this.quiet = true
        if (this.pending === 0 && !this.quiet) this.send({type: 'response.create'})
        if (this.pending === 0) this.quiet = false
    }

    close(): void {
        if (this.closed) return
        this.closed = true
        clearTimeout(this.owedTimer)
        clearTimeout(this.speakingTimer)
        this.you.flush()
        this.voice.flush()
        if (this.engine === 'live') this.send({type: 'session.close', event_id: crypto.randomUUID()})
        // The mic too, or the browser keeps showing it in use.
        for (const sender of this.pc.getSenders()) sender.track?.stop()
        setTimeout(() => this.pc.close(), 300)
        this.audio.srcObject = null
        this.events.onSpeaking(false)
    }

    private receive(event: any): void {
        if (this.engine === 'live') return this.receiveLive(event)
        switch (event.type) {
            case 'input_audio_buffer.speech_started':
                this.hearing = true
                this.voice.flush()
                this.events.onHearing?.()
                break
            case 'input_audio_buffer.speech_stopped':
                this.hearing = false
                // Its answer to them takes in what was told; when it makes none (a thought not finished), say it anyway.
                clearTimeout(this.owedTimer)
                this.owedTimer = setTimeout(() => this.sayOwed(), 4000)
                break
            case 'response.created':
                this.responding = true
                this.owed = false
                break
            case 'conversation.item.input_audio_transcription.delta':
                this.voice.flush()
                this.heard = true
                this.you.add(event.delta ?? '')
                this.events.onHearing?.()
                break
            case 'conversation.item.input_audio_transcription.completed':
                if (!this.heard) this.you.add(event.transcript ?? '')
                this.heard = false
                this.you.flush()
                break
            case 'response.output_audio_transcript.delta':
                this.you.flush()
                this.voice.add(event.delta ?? '')
                break
            case 'response.output_audio_transcript.done':
                this.voice.flush()
                break
            case 'output_audio_buffer.started':
                this.playing = true
                this.events.onSpeaking(true)
                break
            case 'output_audio_buffer.stopped':
            case 'output_audio_buffer.cleared':
                this.playing = false
                this.events.onSpeaking(false)
                this.sayOwed()
                break
            case 'response.done': {
                this.responding = false
                const calls = (event.response?.output ?? []).filter((o: any) => o.type === 'function_call')
                this.spoke = (event.response?.output ?? []).some((o: any) => o.type === 'message')
                this.pending += calls.length
                for (const c of calls) this.events.onToolCall(c.name, c.arguments ?? '{}', c.call_id)
                // An answer that said nothing plays nothing: what waits is said now. One that spoke waits for its audio to end.
                if (!this.spoke && !calls.length) this.sayOwed()
                if (event.response?.status === 'failed') console.warn('realtime: an answer failed', event.response.status_details)
                break
            }
            case 'error':
                console.warn('realtime:', event.error?.code, event.error?.message)
                break
        }
    }

    /** GPT-Live's events: both transcripts, its backend's tool calls, its end. */
    private receiveLive(event: any): void {
        switch (event.type) {
            case 'session.input_transcript.delta':
                this.voice.flush()
                this.you.add(event.delta ?? '')
                this.events.onHearing?.()
                break
            case 'session.output_transcript.delta':
                this.you.flush()
                this.voice.add(event.delta ?? '')
                this.events.onSpeaking(true)
                clearTimeout(this.speakingTimer)
                this.speakingTimer = setTimeout(() => this.events.onSpeaking(false), 1200)
                break
            case 'response.event': {
                const inner = event.event
                if (inner?.type === 'response.output_item.done' && inner.item?.type === 'function_call') {
                    this.events.onToolCall(inner.item.name, inner.item.arguments ?? '{}', inner.item.call_id)
                }
                break
            }
            case 'session.closed':
                if (this.closed) return
                // Its microphone too: a call made again takes a new one.
                this.close()
                this.events.onClosed(event.reason ?? 'closed')
                break
            case 'error':
                console.warn('GPT-Live:', event.code ?? event.error?.code, event.message ?? event.error?.message)
                break
        }
    }

    /** A line for GPT-Live: `session.commentary.append` it says, `session.thinking.append` it keeps in mind. */
    private live(type: string, content: string): void {
        this.send({type, event_id: crypto.randomUUID(), delegation_id: null, content})
    }

    /** Said to it, not by the person: what to open with, and what changed on the page. */
    private system(text: string): void {
        this.send({type: 'conversation.item.create', item: {type: 'message', role: 'system', content: [{type: 'input_text', text}]}})
    }

    /**
     * Pictures for it to see (a session's screenshot, the person's sketch): the
     * realtime model takes images only in a user's message, so they come in one,
     * marked as the page's, after the system line that says what they are. One
     * a message: the data channel takes a message of some 256 KB at most.
     */
    private look(images: string[]): void {
        for (const url of images) {
            const content = [{type: 'input_text', text: '[The page, not the person: a picture just described.]'}, {type: 'input_image', image_url: url}]
            // GPT-Live's voice takes no pictures: its backend sees them, and says what matters when asked.
            if (this.engine === 'live') this.send({type: 'response.item.create', event_id: crypto.randomUUID(), item: {type: 'message', role: 'user', content}})
            else this.send({type: 'conversation.item.create', item: {type: 'message', role: 'user', content}})
        }
    }

    private send(event: object): void {
        if (this.dc.readyState === 'open') this.dc.send(JSON.stringify(event))
    }
}

/** Transcript deltas joined into lines: a line ends after a pause, or when the other side starts talking. */
class Line {
    onLine: (text: string) => void = () => {}
    private text = ''
    private timer: ReturnType<typeof setTimeout> | undefined

    add(delta: string): void {
        this.text += delta
        clearTimeout(this.timer)
        this.timer = setTimeout(() => this.flush(), 1500)
    }

    flush(): void {
        clearTimeout(this.timer)
        const line = this.text.trim()
        this.text = ''
        if (line) this.onLine(line)
    }
}