The idea is a voice line and a text line that share one conversation. Answers come from a document you can edit. A change to a record is written only after a person agrees. A dental clinic is a useful stand-in while you try that: it has hours, people, and a request that should not be written down until someone says yes. The same shape fits a company, a shop, a restaurant, a barbershop, a public service, a help line, or a desk that collects leads.
What follows is one way to implement it. The code is from a proof of concept built to try the idea with real audio and real messages. Asterisk, on a local PC, is one way to hear the result from a desk phone, and the pattern for an edge you swap when the same core points at an external service. Twilio is that service: connect a Twilio number and the gateway receives live calls and SMS from the public network. Plivo and Telnyx plug in the same way.
01. What to leave out on purpose
A production call center has queues, recording policy, and a vendor contract. Those can wait. The constraints that change the shape of the code are:
- Facts come from the catalog: A fact about the business comes strictly from the catalog. If nothing matches, the caller hears a fixed fallback, not a paragraph the language model invented.
- Mutation requires an explicit yes: A visit is written only after an explicit yes. The model may name a doctor, a day, and an hour. It does not insert the row into the database.
- One contact, one future record: One phone number holds exactly one future visit at any given time.
- Dynamic language following: The reply follows the language of that turn. A caller who switches between Spanish and English is answered in that same language on that specific turn.
- Polite, immediate hangup: Saying goodbye thanks the caller and immediately hangs up the line, rather than triggering a stray catalog search.
Everything else is a seam so those rules can be tried with a real microphone and a real chat window.
02. System Architecture & The 5 Core Decisions
The stack runs in Docker Compose. Docker packages each process with the same Python image so your local PC
and a CI run
see the same interpreters, the same system libraries (ffmpeg, libsndfile),
and the exact same port map. Compose is the file that coordinates which processes start together and which
environment
variables they share.
Audio and text do not travel the same road, and that split is the foundation of the architecture:
softphone ──SIP/RTP──Asterisk ──AudioSocket──sip-gateway ──WebSocket──telephony-gateway
carrier webhooks (Twilio, Plivo, Telnyx, or a JSON stream) ───────────────telephony-gateway
│
│
voice orchestrator
STT · dialog · TTS
│
┌────────────────────────────────────────────────────┤
| |
clinic MCP ──HTTP──clinic schedule knowledge catalog (file)
│
|
NATS (after the call) ──CRM, analytics, compliance workers
Five fundamental architectural decisions sit directly under that drawing:
The websockets library serves one long-lived socket per call on the
orchestrator. PCM stays on that socket until the call ends. Audio does not go on a queue. A
transcript can be late. A syllable cannot.
Asterisk, the SIP gateway, and carrier webhooks all terminate in the telephony gateway. From there the orchestrator sees the same socket. Asterisk runs without an external account; Twilio, Plivo, or Telnyx connect the public PSTN.
The dental booking API and the MCP server in front of it are the worked example. Any real operation
joins the call without the voice session importing business logic. MCP (Model Context Protocol) is
that JSON-RPC tools/call door.
When a turn is ambiguous, a chat model (local Ollama or OpenAI/Anthropic over HTTPS) returns a concise JSON routing object. The spoken response is either catalog text or a template the dialog already built.
NATS is the message broker. JetStream, its persistence layer, manages key-value buckets and an object store. The call publishes "this call finished" along with a transcript blob. CRM, analytics, and compliance workers subscribe later with idempotency keys. Redis is absent.
The orchestrator process is where those pieces meet. On startup it builds the engines once and then hands each incoming socket an isolated session:
async def _shared_engines() -> dict:
global _engines
if _engines is not None:
return _engines
config = load_config()
hardware = auto_tune_environment(config)
bus = await get_bus(config)
loop = asyncio.get_running_loop()
stt = await loop.run_in_executor(None, lambda: STTFactory.create_engine(config, hardware))
tts = await loop.run_in_executor(None, lambda: TTSFactory.create_engine(config, hardware))
rag = await loop.run_in_executor(None, lambda: LocalRAGEngine(load_intents()))
llm = HybridAdaptiveLLM(config, hardware)
_engines = {
"config": config,
"hardware": hardware,
"bus": bus,
"stt": stt,
"tts": tts,
"rag": rag,
"llm": llm,
}
asyncio is Python’s cooperative concurrency. Loading Whisper and Kokoro
in an executor
keeps that slow model import off the event loop that is about to accept live incoming calls. Sharing one
STT engine and one
TTS engine across calls is a deliberate memory choice: the neural models are large, and an asyncio lock
around inference is
far cheaper than loading duplicate weights per caller. The very first call after a restart pays the load
latency; later calls
reuse it instantly.
config/config.json acts as the switchboard. Setting PLATFORM_MODE=local
keeps the hybrid path completely offline. Preferences for speech-to-text, speech synthesis, and optional
cloud LLMs live right
alongside the NATS bucket definitions.
03. One Turn on the Socket: Speech, Guardrails & Routing
Faster-Whisper is a CTranslate2 port of OpenAI’s Whisper. It converts chunks of 16 kHz signed linear PCM into text and a language probability. Critically, the session does not blindly lock the next chunk to the previous language. A caller who switches from Spanish to English must be answered in English on that exact turn.
However, the raw model guess cannot be trusted blindly. prefer_language
lets whole words in
the transcribed text overrule a confident but mistaken recognizer label. For instance, "Cancel" must not
count as English inside
the Spanish word "cancelar", so markers are matched as full word boundaries, not substrings. A Whisper
probability under 0.6
falls through to the previous turn's language, and then to default English:
def prefer_language(
text: str,
*,
whisper_language: str | None = None,
whisper_probability: float = 0.0,
previous: str | None = None,
) -> str:
"""Trust words in the transcript over a conflicting recognizer label."""
marked = marked_language(text)
if marked:
return marked
short = normalize_language(whisper_language, default="")
if short and whisper_probability >= 0.6:
return short
return previous or DEFAULT_LANGUAGE
The turn execution is a lean, prioritized cascade. Guardrails run first: regular expressions for prompt-injection phrases, and a PII scrub only if the turn is slated for an external cloud model. PyJWT (the library behind the initial handshake) has already validated the incoming socket during connection setup, so it is never a per-turn cost.
Then comes the cascade order: goodbye first, then the clinic, then the catalog:
if is_farewell(user_text):
await self._say_and_hangup(farewell_reply(language), language)
return
clinic_reply = await asyncio.to_thread(
handle_clinic_turn,
user_text,
caller_key=self.conversation_id,
language=language,
)
If a clinic reply is generated, it is synthesized and the turn ends. Otherwise, the session reloads intents and scores the grounded catalog:
self.intents = load_intents()
intent = match_intent(user_text, self.intents)
Notice that conversation_id is the caller's normalized phone number,
not the
transient AudioSocket UUID. Two people can be on the phone at the same time. Each person's pending
"shall I book Friday at four?"
lives under their unique telephone number. An AudioSocket id would collide the moment the PBX recycled a
media channel.
Farewell is checked before the clinic so words like "bye" are never parsed as a booking request. "Hang on"
is deliberately
excluded from farewells, because that phrase asks the agent to pause and wait. When goodbye fires, the
session queues the
spoken thank-you, waits until the playback queue drains, and then enqueues {"event": "hangup"}.
Kokoro, executed via kokoro-onnx and ONNX Runtime,
synthesizes the audio.
ONNX Runtime executes neural nets directly from an .onnx weight file
without requiring a heavy
PyTorch installation in the container. Voices in config are af_heart
(English) and
ef_dora (Spanish)—both female and lightweight enough to execute smoothly
on CPU. A short filler
tone is warmed at process startup so the first speech generation has playback ready within a few hundred
milliseconds.
04. A Business Service on the Call: The MCP Tool Door
The dental appointment schedule is a tangible stand-in for any real desk: a restaurant reserving a table, a barbershop booking a chair, an insurance agency opening a claim, or a public counter registering a citizen inquiry. The shape is always two clean pieces: an HTTP API that owns the domain rules, and a concise MCP tool contract the dialog is allowed to call.
The sample schedule is an aiohttp application listening on port 5091.
Doctors, weekday hours
(09, 10, 11, 12, 16, 17, 18), and timezones (Europe/Bratislava) are pure
data in that service,
never prompt trivia.
Booking refuses a second future visit for the same caller before it checks if the requested hour is taken. That ordering is essential: the caller must immediately hear "you already have an appointment" even if the newly requested slot happens to be open:
if hour not in data["openHours"]:
raise ValueError(f"{hour} is outside the hourly schedule")
if not _is_open_day(parsed):
raise ValueError("The clinic is closed that day")
if not _is_future_slot(parsed, hour, now):
raise ValueError("That time is in the past")
if _taken(data, doctor_id, day, hour):
raise ValueError("That hour is already booked")
if _future_for_contact(data, contact, now):
raise ValueError("This number already has an appointment")
The dialog never directly imports the schedule module. Instead, it posts standard Model Context Protocol
(MCP) JSON-RPC
calls to port 5092. Those names define the universal contract: list_doctors,
check_availability, book_appointment,
list_appointments, cancel_appointment,
and
reschedule_appointment:
def _call_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
url = mcp_url()
if not url:
raise RuntimeError("CLINIC_MCP_URL is not set")
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {"name": name, "arguments": arguments},
}
request = urllib.request.Request(
url,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json", "Accept": "application/json"},
method="POST",
)
Using Python's standard urllib here is deliberate simplicity. The dialog
turn already executes
inside a worker thread (asyncio.to_thread). A synchronous blocking POST
keeps the dialog code
dependency-free and avoids running a second asynchronous HTTP stack inside code that also parses calendar
dates.
Dates and hours are parsed deterministically whenever phrasing is clear ("next Friday", "a las cuatro").
When user input is
messy, decide_turn prompts the model for JSON only. While an offer is
pending, a specialized
prompt (classify_pending_reply) classifies responses strictly into accept,
reject, or other. If the caller mumbles
something unrelated,
other repeats the confirmation question rather than dumping the caller
into a random catalog search.
Pending dialog state lives in data/clinic/dialogs.json, keyed by
normalized telephone number.
Because voice and SMS share that exact file, a caller can be offered an appointment on a voice call, hang
up, and reply
"yes" over SMS to confirm the booking.
05. The Knowledge Catalog: Grounded Answers Without Hallucinations
Seed intents live in a baseline JSON file, while the live editable copy resides in the catalog file. On
every knowledge turn,
load_intents merges them. A document with deleteTime set or
enabled: false completely suppresses the matching seed intent:
for document in catalog.get("documents") or []:
intent_id = str(document.get("intentId") or document.get("documentId") or "")
if document.get("deleteTime") or document.get("enabled") is False:
if intent_id:
retired.add(intent_id)
continue
intent = document_to_intent(document)
if not intent:
continue
by_id[str(intent["intent_id"])] = intent
for intent_id in retired:
by_id.pop(intent_id, None)
Each document carries text, groundingContext, and
groundingContextI18n—a dictionary mapping language codes to the exact
sentence that must be spoken.
Having English in text and localized Spanish beside it is why a single
text box was rejected in
favor of structured internationalization.
An admin API (aiohttp on port 5090) handles document listing, creation,
patching, and file ingestion.
Uploaded PDFs, Word documents, Excel sheets, CSVs, RTF, and text are parsed using pypdf,
python-docx, openpyxl, xlrd,
and striprtf. The extracted text is added directly to the catalog while
preserving the original file.
Because voice and telephony mount the same shared volume, edits take effect on the very next turn without
restarting the stack.
A Streamlit dashboard on port 8501 provides the visual operator interface. The UI features three explicit actions: Details, Edit, and Delete. Details displays stored metadata and multilingual text in disabled inputs so operators can review an entry safely before modifying it:
def _render_details(document: dict) -> None:
st.subheader(str(document.get("title") or "Untitled"))
enabled = "Enabled" if document.get("enabled", True) else "Disabled"
st.caption(
f"Language {document.get('language') or 'en'} · "
f"Source {document.get('source') or 'manual'} · {enabled}"
)
tags = _tags_to_text(document.get("semanticTags"))
st.write("Tags: " + (tags or "none"))
for code, value in _language_texts(document):
st.text_area(f"Stored text ({code})", value=value or "(empty)", height=180, disabled=True)
In Streamlit, form IDs must incorporate the unique document ID and input widgets should avoid sticky session keys. Otherwise, Streamlit caches the empty state from initial rendering and stubbornly presents blank inputs when inspecting documents full of text.
06. The Same Dialog as an SMS Message
SMS skips voice sockets and TTS entirely. reply_for_sms evaluates the
clinic dialog and,
failing that, matches the knowledge catalog. Language is detected from the message tokens, and the caller
key is
the sender's E.164 phone number:
def reply_for_sms(sms: NormalizedSms) -> tuple[str, str, dict]:
intents = load_intents()
language = detect_language(sms.body, default=DEFAULT_LANGUAGE)
clinic_reply = handle_clinic_turn(
sms.body,
caller_key=normalize_contact(sms.from_number) or sms.from_number or sms.message_id,
language=language,
)
intent = None if clinic_reply else match_intent(sms.body, intents)
if clinic_reply:
text = clinic_reply
elif not intent:
text = unknown_reply(language)
else:
grounded = intent_grounding(intent, language)
text = reply_in_language(grounded, language, "local")
NormalizedSms represents the core value of the gateway. Twilio delivers
form fields.
Plivo and Telnyx send custom payloads. A softphone transmits SIP MESSAGE (which Asterisk converts into an
HTTP POST).
A test script can POST {"from", "to", "body"} directly to /sms.
All inbound text is normalized into a single dataclass before reply_for_sms runs. The response
is packaged into the appropriate envelope on egress: TwiML for Twilio, JSON for SIP.
Audio media streams follow the same modular design. The gateway adapter knows how to convert μ-law audio for telecom carriers and how to signal call teardown. SIP and WebSockets receive an explicit JSON hangup event, while Twilio, Plivo, and Telnyx hang up automatically when the media stream WebSocket is closed:
if event == "hangup":
logger.info("Hanging up telephony stream provider=%s", self.provider)
if self.provider in {"sip", "generic", "webrtc"}:
await self.websocket.send(json.dumps({"event": "hangup"}))
return
await self.close(reason="goodbye")
return
07. Hearing It: Asterisk as a Local PBX Test Harness
Asterisk is a battle-tested telephone switch. PJSIP is its SIP signaling stack. SIP negotiates call setup and registration, while RTP streams the raw audio. AudioSocket is an Asterisk channel driver that pipes bidirectional 16-bit signed linear audio over a simple TCP socket to your backend process.
This switch is a test harness, not the core product. It gives you a way to dial extension 2000 from a softphone (like Linphone) and talk to the AI agent with a real headset. Extension 600 provides an echo test (so you can verify microphone audio independently from AI logic), and extension 1002 registers a second line so you can test overlapping concurrent calls:
exten => 2000,1,NoOp(Voice AI agent from ${CHANNEL} read=${CHANNEL(audioreadformat)})
same => n,Answer()
same => n,Set(FROM=${FILTER(0-9+,${CALLERID(num)})})
same => n,Set(CALLUUID=${UUID()})
same => n,Set(NOTE=${CURL(http://telephony-gateway:5080/sip/caller?callId=${CALLUUID}&from=${FROM})})
same => n,Dial(AudioSocket/sip-gateway:9092/${CALLUUID}/c(slin))
same => n,Hangup()
Notice the dialplan syntax: Dial(AudioSocket/...). In Asterisk, the
AudioSocket application
(AudioSocket(...)) does not play synthesized audio back onto the PJSIP
channel while RTP is actively flowing.
The channel form (Dial(AudioSocket/...)) does! That
single distinction was the
difference between a call that connected in silence and a call where the agent spoke clearly.
The gateway reads 8 kHz slin from Asterisk, and sip_bridge resamples it
to 16 kHz for Whisper
and back to 8 kHz for playback. Using Python’s audioop.ratecv preserves
filter state across frames,
preventing audio clicks on packet boundaries.
Another classic telecom trap is SDP addressing: SIP_EXTERNAL_IP must be
written into the SDP invite
to indicate where the phone should stream RTP packets. If left at 127.0.0.1, a softphone on the local
network streams its voice back into its own loopback interface. Setting it to your machine's LAN IP allows
the agent to hear you.
The companion CLI connect_phone prints webhook URLs for Twilio, Plivo,
Telnyx, or custom JSON streams,
and can push webhook configurations directly to Twilio accounts. An ngrok tunnel exposing port 5080 lets
external carriers reach your local machine instantly.
08. After the Caller Has Gone: NATS JetStream & Worker Pools
When the telephony socket closes, the orchestrator stores the complete raw transcript into a NATS
JetStream object store
bucket and broadcasts the event voice.event.call.completed.
Three independent worker groups subscribe to that event subject. Each worker claims an idempotency key so that redeliveries or duplicate events never double-post records:
async def _wrapped(payload: dict[str, Any]) -> None:
claimed = await bus.try_claim_idempotency(str(payload.get("call_id")), task_type)
if not claimed:
logger.info("Skipping duplicate %s for %s", task_type, payload.get("call_id"))
return
| Worker Service | Trigger Subject | Responsibility |
|---|---|---|
| CRM Sync | voice.event.call.completed |
Posts call summary, duration, and transcript to CRM_WEBHOOK_URL
|
| Analytics | voice.event.call.completed |
Extracts sentiment scores, caller intent keywords, and response latencies |
| Compliance | voice.event.call.completed |
Redacts credit card numbers, phone numbers, and PII before archiving to cold storage |
These are prime examples of "things that should happen because a call concluded," not because an audio packet arrived. A production deployment can swap out the mock CRM URL and analytics scorers; the NATS subject structure and idempotency claims remain rock-solid.
09. What Listening Showed: Real Lessons from Audio Calls
Edge cases only reveal themselves when you pick up a handset and speak. Automated WebSocket tests and unit test suites cannot substitute for hearing how the system behaves under imperfect acoustics:
- Substring collisions: Spanish language detection flipped to English because the word "cancel" was matched inside the Spanish verb "cancelar". The subsequent turn was locked into English until whole-word token matching was enforced.
- Farewell vs Search: Saying "Goodbye" must be an immediate hangup command, never another knowledge catalog search.
- Database-level rejection: Multiple bookings from the same contact number must fail deterministically in the store logic, not merely in prompt instructions.
- UI inspection visibility: The Streamlit knowledge editor must explicitly display stored localized sentences in disabled text areas; otherwise, empty states can lead operators to accidentally overwrite valid documents.
10. Architectural References & Technology Stack
The platform integrates open standards and modern Python concurrency:
| Component | Library / Tool | Documentation / Project | Role in Platform |
|---|---|---|---|
| Runtime & Concurrency | Python 3.10+ / asyncio | python.org/asyncio | Cooperative asynchronous event loop for high-concurrency telephony sockets |
| Containerization | Docker & Compose | docs.docker.com | Reproducible multi-container deployment (Dockerfile, docker-compose.yml) |
| HTTP & WebSockets | aiohttp & websockets | aiohttp.org / websockets | Telephony gateway (port 5080), clinic API (5091), MCP (5092), and persistent audio stream |
| Speech Recognition (STT) | faster-whisper (CTranslate2) | github.com/SYSTRAN/faster-whisper | Local 16 kHz speech-to-text with quantized INT8 CPU inference |
| Speech Synthesis (TTS) | Kokoro ONNX & ONNX Runtime | github.com/thewh1teagle/kokoro-onnx | Lightweight neural text-to-speech (af_heart, ef_dora) on CPU |
| Tool Protocol | Model Context Protocol (MCP) | modelcontextprotocol.io | JSON-RPC 2.0 tools/call boundary separating dialog from
business logic |
| Event Streaming | NATS & JetStream (nats-py) | docs.nats.io | Durable event publish/subscribe, transcript object store, and worker idempotency |
| PBX Test Harness | Asterisk 22 & AudioSocket | asterisk.org | SIP signaling (port 5060), RTP media (10000-10019), and TCP audio piping to the gateway |
| Knowledge UI | Streamlit | streamlit.io | Interactive catalog editor with Details, Edit, and Soft-Delete operations (port 8501) |
| Document Parsers | pypdf, python-docx, openpyxl, striprtf | PyPI standard tools | Automated text extraction from PDF, DOCX, XLSX, and RTF knowledge uploads |
11. Repository & Getting Started
The complete architecture is available in the companion open-source repository. To spin up the stack locally with Docker Compose:
# Clone repository
git clone https://github.com/fpupoperez/conversational_platform.git
cd conversational_platform
# Configure environment (default local mode)
cp .env.example .env
# Build and start all services
docker compose -f deploy/docker-compose.yml up --build
Once running:
- Asterisk PBX: Register a softphone (such as Linphone) to extension
1001(secrettestpass1001) on port 5060, then dial extension2000to speak with the agent. - Knowledge Dashboard: Navigate to
http://localhost:8501to view, edit, or upload catalog documents. - SMS & Webhooks: Run
python -m connect_phone.mainto inspect webhook endpoints for Twilio or generic JSON test callers.
20+ years building industrial SCADA telemetries, microcontrollers, and autonomous AI-driven systems.
About Félix