Skip to Content
Recodocs

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.

7 min read

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, and VoiceTurnRunner which admits a run on ConversationStore, transcribes one audio blob, calls your model callable, synthesizes speech, and finishes the run with role voice_reply.
  • Adapters and test fixtures. RecordedOpenAiAudio serves both transcription and speech endpoints from caller-supplied recordings over httpx.MockTransport (no network, no API key). Optional LocalWhisperStt and EdgeTtsTts lanes import faster_whisper or edge_tts only when constructed. fixtures.synthetic_wav and ScriptedClock support deterministic lanes.
  • Language, budgets and grounding. Per-turn BCP-47 resolution, voice catalog lookup, and stage budgets compared to recohut_kit.latency.LatencyFact. ground_structured renders shown and spoken text from validated observed records; ground_reply checks passage citations against an assistant ContextPack.
  • Voice agent. Tool palette with AuthorityClass, immutable CallContext for the decider, VoiceAgentHost for 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_ms the 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 VoiceModel and does not choose the words itself.
  • Verified vendor API behaviour. Shapes carry labels such as documented shape, UNVERIFIED or documented shape, unconfirmed against live; recorded adapters are recorded, not a capture of a real account.
  • Full chat runtime ownership of text turns. record_text_turn is a notebook stand-in; production text turns belong to assistant.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.

NameKindWhat it does
VoiceTurn, Transcript, SynthesizedSpeechdataclassOne turn, STT result, and TTS output with validation
Stage, StageBudget, LatencyVerdictenum / dataclassPipeline stages and observed-versus-budget verdicts
SttAdapter, TtsAdapterprotocoltranscribe and synthesize seams
OpenAiTranscriptionRequest, OpenAiSpeechRequest, …dataclassDocumented OpenAI audio API shapes
is_bcp47functionShape check for BCP-47 tags, not a registry lookup
VoiceTurnRunnerclassRuns stt → injected model → tts on ConversationStore
VoiceTurnResultdataclassTurn outcome; replays carry replayed=True and no new facts
conversation_transcript, record_text_turnfunctionShared text+voice lineage and text-turn stand-in
RecordedOpenAiAudioclassBoth OpenAI-shaped audio endpoints from recordings
OpenAiTranscriptionAdapter, OpenAiSpeechAdapterclassHTTP clients implementing the adapter protocols
LocalWhisperStt, EdgeTtsTtsclassOptional local STT/TTS lanes
VoiceBudgets, DEFAULT_BUDGETSclass / constantsPackage-root exports; verdicts_for and describe come from recohut_kit.voice.budget
VoiceCatalog, resolve_languageclass / functionPackage-root exports; OPENAI_RECORDED_VOICES comes from recohut_kit.voice.language
ground_structuredfunctionPackage-root lazy export; ground_reply comes from recohut_kit.voice.grounded
ModelRequest, ModelReply, VoiceModel, speakabledataclass / type alias / functionExported 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

NameKindWhat it does
VoiceTool, ToolPalette, AuthorityClassdataclass / class / enumTrusted tools and authority classes declared by the app
CallContext, TranscriptTurn, PendingActiondataclassObserved call state the decider sees
VoiceAgentHostclassPalette checks, handlers, confirm-before-write, barge-in
ScriptedDecider, CodexDecider, Deciderclass / protocolDeterministic script or Codex-backed proposal source
classify_answer, resolve_pendingfunctionSpoken confirmation classification
build_handoff, HandoffPacketfunction / dataclassCited handoff packet on transfer
run_scripted, run_simulated, score_run, …function / dataclassScripted call evaluation

recohut_kit.voice.calls

Re-exports the union of contracts, codec, media, endpointing, call_state, streaming, webhooks, and ledger.

NameKindWhat it does
AudioFrame, UtteranceBoundary, CallStatedataclass / enumShared telephony value types
pcm16_to_mulaw, frame_mulaw, snr_db, …functionMu-law codec and framing at 8 kHz
parse_inbound, StreamChecker, StreamSimulatorfunction / classMedia-stream wire parsing and sequence checks
Endpointer, BargeInPolicyclassSilence endpointing and overlap-based barge-in clear
CallStateMachine, DtmfCollectorclassAllowed state transitions and DTMF collection
WebhookNormaliser, twilio_signatureclass / functionWebhookNormaliser normalises documented vendor webhook shapes that are unconfirmed against a live account
CallLedgerclassAppend-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_store for ConversationStore, run admission and messages.
  • recohut_kit.latency.recording and recohut_kit.latency.contracts for per-stage LatencyFact records.
  • recohut_kit.harness.contracts.nonempty and recohut_kit.json for validation and stored payloads.
  • recohut_kit.voice.reply for the model request and reply types; grounding uses recohut_kit.grounding (and optionally recohut_kit.assistant.session on the older citation route).
  • Adapters use httpx for the recorded transport; local lanes optionally use faster_whisper, edge_tts, and numpy inside 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) == calls

A second run with the same audio fingerprint replays the stored turn without calling either adapter again.

Limits and gotchas

  • One blob per turn. VoiceTurnRunner is push-to-talk upload semantics, not streaming telephony. Streaming and barge-in live under recohut_kit.voice.calls.
  • Model injection only. The runner raises VoiceTurnError if the callable does not return ModelReply. It never opens a model SDK itself.
  • Message roles. Voice replies persist as voice_reply so assistant session reply parsers are not applied to voice payloads.
  • Recorded adapters refuse invention. Unknown audio digests return HTTP 404; RecordedOpenAiAudio speech output is a synthetic tone WAV, not real speech.
  • Optional lanes. LocalWhisperStt and EdgeTtsTts raise OptionalDependencyMissing when packages are absent; edge-tts needs network and is not exercised in recorded runs.
  • Endpoint timing. Omitting endpoint_ms records server intake time for Stage.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. met is false for failed or cancelled facts; first_audio without first_chunk_ms yields no verdict for that stage.
  • Language labels. Vendor names such as portuguese map through a small table; unknown labels become None and fall through to hint or default.
  • Grounding. ground_structured replaces ungrounded or empty-citation replies with ungrounded_text and strips citation markers from spoken text via speakable.
  • Agent writes. Tools with WRITE_REQUIRES_CONFIRMATION stop at readback until the transcript affirms; corrections invalidate pending writes. Unknown tools and schema violations are refused, not dispatched.
  • Call ledger. start_recording refuses until notice_played is recorded; the schema is append-only; duplicate webhook delivery raises LedgerRefused.
  • Webhooks. Non-UTF-8 bodies and bad signatures raise WebhookRefused with stable reason codes 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