Voice turns, phone calls and grounded speech
Push-to-talk voice turns on shared chat state, recorded and optional local STT/TTS adapters, latency budgets, phone-call media and ledger, and a confirm-before-write voice agent host.
The recohut_kit.voice package groups three related owners. The root package covers push-to-talk voice turns: they share the same conversation store and turn_id as text chat, run speech-to-text and text-to-speech through injectable adapters, record per-stage latency, and store transcripts beside ordinary chat messages. Submodule recohut_kit.voice.agent runs a phone-call agent where an injected decider proposes tool calls or spoken replies and the host enforces palette, schema and confirm-before-write rules. Submodule recohut_kit.voice.calls is a deterministic telephony workflow—media streams, codec, endpointing, barge-in, call state, webhooks and an append-only call ledger—with no model inside the layer.
Most of the code is plain Python workflows and contracts. The injected VoiceModel is the only step that decides the reply text; optional LocalWhisperStt is a separate transcription model. In the agent submodule, a Decider (for example ScriptedDecider in tests or CodexDecider in a live lane) proposes the next action; the host never delegates authority to it. ground_structured validates a drafted reply against observed records before that reply is spoken.
Purpose
Voice and text are different input and output surfaces for a conversation. The underlying turn still needs a stable identity and a recorded result so a user can continue the same work.
What this package owns
- Voice-turn contracts and runner. Typed records for one push-to-talk turn (
VoiceTurn,Transcript, adapter protocols), OpenAI-shaped request and response dataclasses marked as documented vendor shapes, andVoiceTurnRunnerwhich admits a run onConversationStore, transcribes one audio blob, calls your model callable, synthesizes speech, and finishes the run with rolevoice_reply. - Adapters and test fixtures.
RecordedOpenAiAudioserves both transcription and speech endpoints from caller-supplied recordings overhttpx.MockTransport(no network, no API key). OptionalLocalWhisperSttandEdgeTtsTtslanes importfaster_whisperoredge_ttsonly when constructed.fixtures.synthetic_wavandScriptedClocksupport deterministic lanes. - Language, budgets and grounding. Per-turn BCP-47 resolution, voice catalog lookup, and stage budgets compared to
recohut_kit.latency.LatencyFact.ground_structuredrenders shown and spoken text from validated observed records;ground_replychecks passage citations against an assistantContextPack. - Voice agent. Tool palette with
AuthorityClass, immutableCallContextfor the decider,VoiceAgentHostfor execution, confirmation, barge-in and handoff, plus scripted evaluation helpers. - Phone calls. The calls package has eight submodules (call_state, codec, contracts, endpointing, ledger, media, streaming, webhooks); barge-in policy is part of endpointing.
What it deliberately does not own
- The package does not provide live telephony transport, and without
endpoint_msthe turn runner records server-side blob intake rather than end-of-speech. - Choosing what to say inside the turn runner or the calls layer. The calls layer calls no model; the turn runner calls the injected
VoiceModeland does not choose the words itself. - Verified vendor API behaviour. Shapes carry labels such as
documented shape, UNVERIFIEDordocumented shape, unconfirmed against live; recorded adapters arerecorded, not a capture of a real account. - Full chat runtime ownership of text turns.
record_text_turnis a notebook stand-in; production text turns belong toassistant.AssistantRuntime.
Public API
In the model-backed phone workflow, CodexDecider asks its proposal model to choose a tool call or spoken reply. VoiceAgentHost checks tool permission and requires an affirmed readback before a gated write. The example below uses a fixed reply.
Package root recohut_kit.voice
Contracts from recohut_kit.voice.contracts load eagerly. Runner, adapters, budgets, language and ground_structured resolve on first attribute access so importing contracts does not pull optional dependencies.
| Name | Kind | What it does |
|---|---|---|
VoiceTurn, Transcript, SynthesizedSpeech | dataclass | One turn, STT result, and TTS output with validation |
Stage, StageBudget, LatencyVerdict | enum / dataclass | Pipeline stages and observed-versus-budget verdicts |
SttAdapter, TtsAdapter | protocol | transcribe and synthesize seams |
OpenAiTranscriptionRequest, OpenAiSpeechRequest, … | dataclass | Documented OpenAI audio API shapes |
is_bcp47 | function | Shape check for BCP-47 tags, not a registry lookup |
VoiceTurnRunner | class | Runs stt → injected model → tts on ConversationStore |
VoiceTurnResult | dataclass | Turn outcome; replays carry replayed=True and no new facts |
conversation_transcript, record_text_turn | function | Shared text+voice lineage and text-turn stand-in |
RecordedOpenAiAudio | class | Both OpenAI-shaped audio endpoints from recordings |
OpenAiTranscriptionAdapter, OpenAiSpeechAdapter | class | HTTP clients implementing the adapter protocols |
LocalWhisperStt, EdgeTtsTts | class | Optional local STT/TTS lanes |
VoiceBudgets, DEFAULT_BUDGETS | class / constants | Package-root exports; verdicts_for and describe come from recohut_kit.voice.budget |
VoiceCatalog, resolve_language | class / function | Package-root exports; OPENAI_RECORDED_VOICES comes from recohut_kit.voice.language |
ground_structured | function | Package-root lazy export; ground_reply comes from recohut_kit.voice.grounded |
ModelRequest, ModelReply, VoiceModel, speakable | dataclass / type alias / function | Exported from recohut_kit.voice.reply, not from the package root |
Submodules imported directly expose further names (turn.MemoryBlobStore, fixtures.synthetic_wav, reply.TranscriptEntry, and so on).
recohut_kit.voice.agent
| Name | Kind | What it does |
|---|---|---|
VoiceTool, ToolPalette, AuthorityClass | dataclass / class / enum | Trusted tools and authority classes declared by the app |
CallContext, TranscriptTurn, PendingAction | dataclass | Observed call state the decider sees |
VoiceAgentHost | class | Palette checks, handlers, confirm-before-write, barge-in |
ScriptedDecider, CodexDecider, Decider | class / protocol | Deterministic script or Codex-backed proposal source |
classify_answer, resolve_pending | function | Spoken confirmation classification |
build_handoff, HandoffPacket | function / dataclass | Cited handoff packet on transfer |
run_scripted, run_simulated, score_run, … | function / dataclass | Scripted call evaluation |
recohut_kit.voice.calls
Re-exports the union of contracts, codec, media, endpointing, call_state, streaming, webhooks, and ledger.
| Name | Kind | What it does |
|---|---|---|
AudioFrame, UtteranceBoundary, CallState | dataclass / enum | Shared telephony value types |
pcm16_to_mulaw, frame_mulaw, snr_db, … | function | Mu-law codec and framing at 8 kHz |
parse_inbound, StreamChecker, StreamSimulator | function / class | Media-stream wire parsing and sequence checks |
Endpointer, BargeInPolicy | class | Silence endpointing and overlap-based barge-in clear |
CallStateMachine, DtmfCollector | class | Allowed state transitions and DTMF collection |
WebhookNormaliser, twilio_signature | class / function | WebhookNormaliser normalises documented vendor webhook shapes that are unconfirmed against a live account |
CallLedger | class | Append-only SQLite ledger with consent before recording |
How it composes
The voice turn runner sits on conversation and latency kit modules and your injected model:
recohut_kit.conversations.sqlite_storeforConversationStore, run admission and messages.recohut_kit.latency.recordingandrecohut_kit.latency.contractsfor per-stageLatencyFactrecords.recohut_kit.harness.contracts.nonemptyandrecohut_kit.jsonfor validation and stored payloads.recohut_kit.voice.replyfor the model request and reply types; grounding usesrecohut_kit.grounding(and optionallyrecohut_kit.assistant.sessionon the older citation route).- Adapters use
httpxfor the recorded transport; local lanes optionally usefaster_whisper,edge_tts, andnumpyinside whisper preprocessing.
The agent submodule composes with recohut_kit.bounded_agents.contracts.Proposal, recohut_kit.function_calling.schema and validation, and recohut_kit.refusal.CodedRefusal.
The calls package uses standard library audio and SQLite patterns plus kit voice.budget on the ledger path. Those call tests skip when pydantic is missing; the calls contract module does not import pydantic. Numpy appears only in optional codec.resample_numpy.
The package root docstring states that recohut_kit.voice is not imported by other kit modules; consumers import it explicitly.
Minimal usage
Install uv pip install '.[http-tools]' from your Kit checkout. The example records a text turn, runs a voice turn with recorded speech adapters and a scripted reply, and repeats it to check replay.
import hashlib
from pathlib import Path
from tempfile import TemporaryDirectory
from recohut_kit.conversations.sqlite_store import ConversationStore
from recohut_kit.voice.adapters import RecordedOpenAiAudio, RecordedTranscription
from recohut_kit.voice.fixtures import synthetic_wav
from recohut_kit.voice.language import OPENAI_RECORDED_VOICES
from recohut_kit.voice.reply import ModelReply
from recohut_kit.voice.turn import VoiceTurnRunner, record_text_turn
audio = synthetic_wav("question")
digest = hashlib.sha256(audio).hexdigest()
recorded = RecordedOpenAiAudio({digest: RecordedTranscription("And the booking total?", "english", 1.0)})
with TemporaryDirectory() as directory:
store = ConversationStore(Path(directory) / "conversations.sqlite")
store.create_conversation(conversation_id="conv-1")
record_text_turn(store, "conv-1", "t1", user_text="What is booked?", reply_text="Six items.")
runner = VoiceTurnRunner(store, recorded.stt, recorded.tts, voices=OPENAI_RECORDED_VOICES)
def model(request):
return ModelReply(f"Earlier turns seen: {len(request.history)}.")
first = runner.run("conv-1", "t2", audio, mime="audio/wav", model=model)
calls = len(recorded.calls)
again = runner.run("conv-1", "t2", audio, mime="audio/wav", model=model)
assert again.replayed and len(recorded.calls) == callsA second run with the same audio fingerprint replays the stored turn without calling either adapter again.
Limits and gotchas
- One blob per turn.
VoiceTurnRunneris push-to-talk upload semantics, not streaming telephony. Streaming and barge-in live underrecohut_kit.voice.calls. - Model injection only. The runner raises
VoiceTurnErrorif the callable does not returnModelReply. It never opens a model SDK itself. - Message roles. Voice replies persist as
voice_replyso assistant session reply parsers are not applied to voice payloads. - Recorded adapters refuse invention. Unknown audio digests return HTTP 404;
RecordedOpenAiAudiospeech output is a synthetic tone WAV, not real speech. - Optional lanes.
LocalWhisperSttandEdgeTtsTtsraiseOptionalDependencyMissingwhen packages are absent; edge-tts needs network and is not exercised in recorded runs. - Endpoint timing. Omitting
endpoint_msrecords server intake time forStage.ENDPOINT, which is not client end-of-speech detection. - Replay semantics. A completed replay returns stored content and requires the spoken audio blob still be present in the configured
BlobStore. - Budget verdicts.
metis false for failed or cancelled facts;first_audiowithoutfirst_chunk_msyields no verdict for that stage. - Language labels. Vendor names such as
portuguesemap through a small table; unknown labels becomeNoneand fall through to hint or default. - Grounding.
ground_structuredreplaces ungrounded or empty-citation replies withungrounded_textand strips citation markers from spoken text viaspeakable. - Agent writes. Tools with
WRITE_REQUIRES_CONFIRMATIONstop at readback until the transcript affirms; corrections invalidate pending writes. Unknown tools and schema violations are refused, not dispatched. - Call ledger.
start_recordingrefuses untilnotice_playedis recorded; the schema is append-only; duplicate webhook delivery raisesLedgerRefused. - Webhooks. Non-UTF-8 bodies and bad signatures raise
WebhookRefusedwith stablereasoncodes rather than unhandled errors. - Import weight. Contract imports are light; lazy names pull in turn, adapters, or httpx on first use.
Verification
The example checks replay with synthetic audio and recorded adapters. See Verify the examples.
How is this page?
Last updated on