Skip to content

Instantly share code, notes, and snippets.

@samgutentag-deepgram
Created September 29, 2026 23:07
Show Gist options
  • Select an option

  • Save samgutentag-deepgram/af54e45924dbb25adb8857e6d8623904 to your computer and use it in GitHub Desktop.

Select an option

Save samgutentag-deepgram/af54e45924dbb25adb8857e6d8623904 to your computer and use it in GitHub Desktop.
Guess early, commit late: Flux eager end of turn with Jev
// Guess early, commit late: call Jev on Flux's EagerEndOfTurn, hold the
// answer, and act only on EndOfTurn.
//
// npm install
// DEEPGRAM_API_KEY=... TYPESAFE_API_KEY=... node flux-eager-jev.ts room.wav
//
// The wav must be 16 kHz, 16-bit, mono PCM. Node 22.6 or later runs this
// TypeScript file directly. Get a Deepgram key at console.deepgram.com/signup.
import { readFileSync } from 'node:fs'
import { DeepgramClient } from '@deepgram/sdk'
for (const name of ['DEEPGRAM_API_KEY', 'TYPESAFE_API_KEY']) {
if (!process.env[name]) throw new Error(`Missing ${name}`)
}
const wavPath = process.argv[2]
if (!wavPath) throw new Error('Usage: node flux-eager-jev.ts <16khz-mono.wav>')
// One Choice question. The none option is the relevance gate: reject the turn
// when its probability is above 0.5.
async function askJev(utterance: string) {
const res = await fetch('https://api.typesafe.ai/v1/systemone', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.TYPESAFE_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
state: utterance,
model: 'jev-latest',
questions: {
dir_1: {
type: 'choice',
instructions: 'Which direction is the first maze move? Use none if the speaker is not addressing the maze.',
criteria: {
up: 'Move the maze marker up. A bare command like "up" or "go up two" counts.',
down: 'Move the maze marker down. A bare command like "down" counts.',
left: 'Move the maze marker left. A bare command like "go left" counts.',
right: 'Move the maze marker right. A bare command like "go right two" counts.',
none: 'No move. The speaker is talking to another person, or about a document, a webpage, a schedule, a deadline, or a price, even when they use a direction word.',
},
},
},
}),
})
if (!res.ok) throw new Error(`jev ${res.status}: ${await res.text()}`)
return res.json()
}
function commit(answer: any) {
const dir = answer.answers.dir_1
const pNone = dir.probabilities?.none ?? 0
console.log(pNone > 0.5 ? `not for me (P(none) ${pNone.toFixed(2)})` : `move ${dir.choice} (P(none) ${pNone.toFixed(2)})`)
}
function reportError(error: unknown) {
console.error('jev call failed:', error instanceof Error ? error.message : error)
}
// DeepgramClient reads DEEPGRAM_API_KEY from the environment.
const deepgram = new DeepgramClient()
const flux = await deepgram.listen.v2.connect({
model: 'flux-general-en',
encoding: 'linear16',
sample_rate: 16000,
eot_threshold: 0.7,
eager_eot_threshold: 0.3,
})
const held = new Map<number, { transcript: string; answer: ReturnType<typeof askJev> }>()
// The SDK keeps one handler per event, so all turn logic lives here.
flux.on('message', m => {
if (m.type !== 'TurnInfo') return
const text = (m.transcript ?? '').trim()
if (!text) return
// Eager: ask now, commit nothing. The sentence may still be arriving.
if (m.event === 'EagerEndOfTurn') {
const answer = askJev(text)
answer.catch(() => {}) // a discarded guess should not raise, the settled pass reports errors
held.set(m.turn_index, { transcript: text, answer })
return
}
// Settled: reuse the held answer if the words did not change.
if (m.event === 'EndOfTurn') {
console.log(`\n"${text}"`)
const spec = held.get(m.turn_index)
held.delete(m.turn_index)
const answer = spec && spec.transcript === text ? spec.answer : askJev(text)
answer.then(commit).catch(reportError)
}
})
flux.connect()
await flux.waitForOpen()
// Stream the file in real time, 80 ms at a time, the way a mic would.
const wav = readFileSync(wavPath)
const pcm = wav.subarray(wav.indexOf('data') + 8)
const CHUNK = 2560
let offset = 0
const timer = setInterval(() => {
if (offset >= pcm.length) {
clearInterval(timer)
// A room that never goes quiet may never close its last turn, so end it.
flux.sendForceEndTurn({ type: 'ForceEndTurn' })
setTimeout(() => flux.close(), 2000)
return
}
flux.sendMedia(pcm.subarray(offset, offset + CHUNK))
offset += CHUNK
}, 80)
{
"name": "flux-eager-jev",
"private": true,
"type": "module",
"dependencies": {
"@deepgram/sdk": "5.13.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment