Multilingual Voice Loan Advisor
A 14-agent voice advisor that qualifies loan leads in Derja, French and English.
- Voice AI
- Multi-agent systems
- Fintech
- Role
- Architect and lead engineer (SoluGent)
- Client
- A Tunisian lending intermediary (name withheld)
- Timeline
- Jun 2025 - Mar 2026
- Status
- Pilot

- LiveKit agents with typed hand-offs
- 14
- LiveKit agents with typed hand-offs
- function tools across the agents
- 84
- function tools across the agents
- per conversation-minute, measured on a 9.45-min session
- $0.116
- per conversation-minute, measured on a 9.45-min session
- voice architectures built and compared
- 4
- voice architectures built and compared
- client policy and product documents in the knowledge base
- 24
- client policy and product documents in the knowledge base
The problem
Loan seekers in Tunisia ask the same qualification questions again and again: contract type, how the salary is paid, existing debt, which product they qualify for. They ask in a mix of Tunisian Derja, French and English, by chat and by phone, and the intermediary's advisors could not answer every lead quickly.
The agent had to follow the client's decision tree exactly (a 700 TND minimum salary, fixed-term contract rules after the March 2025 law, half of an existing loan repaid first), never invent a banking or legal fact, compute repayment capacity deterministically, never mix languages in a reply, and sound natural in Derja with low latency.
Architecture
Caller joins a room
The browser client gets a LiveKit token and joins a WebRTC room. Background-voice cancellation strips noise and other speakers before audio reaches the agent worker.
- Service
- Data
- AI model
- External
Hard problems I solved
A cascaded voice pipeline that was too slow
The first voice version chained Azure Speech STT (ar-TN), GPT and Gemini 2.5 Pro TTS. A measured three-turn test took 31.1 s, 8.7 s and 34.8 s per turn, and STT alone took 18.8 s for 1.2 s of audio.
Approach. Fixed the STT stream (declared 16 kHz mono PCM, stopped closing the push stream before recognition, moved to continuous recognition), streamed TTS sentence by sentence and capped reply length. The remaining latency was structural, so the design moved to speech-to-speech: a WebSocket proxy to Azure Realtime, then browser WebRTC with ephemeral tokens, then LiveKit Agents.
A Realtime session that forgot and re-greeted
After moving to the GA Realtime protocol, the model greeted the caller again on every turn and user speech was not transcribed.
Approach. session.update now sends type: realtime with the nested audio.input.transcription model (whisper-1). Memory is kept with an instruction-only pattern, and the input audio buffer is cleared so accumulated audio tokens stop inflating cost.
Three languages, no mixing, one hard dialect
Inline French, Derja and English examples in the system prompt were copied verbatim: a French speaker got Arabic replies, and some replies mixed French and Arabic in one sentence. TTS engines also mispronounced heavy Derja.
Approach. A hard gate in the prompt: check the language of the user's last message and answer only in it, with examples marked as reference. For the cascaded TTS, a softer Derja register closer to Modern Standard Arabic was chosen after phrase-set tests. The final agents detect language per call and pass user_language through every hand-off. v1 handled it at the data layer with one collection and one prompt per language.
Eligibility rules too large for one prompt
11 borrower profiles by 12 products of rules (6 months minimum on a fixed-term contract, 35-40% debt-ratio caps by profile, 20 or 40% down payments, age 65 at loan end, cars at most 5 years old) do not fit one reliable voice prompt.
Approach. One agent per profile and per product, each owning its rules and tools. A hand-off is a function tool that maps free speech ('CDI', 'voiture') to enums, checks the matrix, records state on a shared CustomerData object and returns the next agent. Each agent gets only the compact context it needs from to_context_for(), and two entry agents were merged into Triage to cut a hand-off.
14 agents and 84 typed function tools in the final package.
Grounding answers in a regulated domain
A loan advisor that invents a rate, a rule or a legal fact is a liability. The client's rules lived in 24 PDF and text files in French and Arabic, and central-bank rules sit on top of them.
Approach. A section-aware PyMuPDF chunker maps each policy PDF to a borrower profile and stores 1536-d embeddings in pgvector with HNSW cosine indexes. Search filters on profile_type and service_type in JSONB metadata, with a separate central-bank knowledge base. Prompts forbid manual calculation, label every figure an estimate and offer a human advisor on request.
Knowing what a voice minute costs
Realtime audio tokens cost far more than text, and the client needed a per-minute figure, not an estimate from a price sheet.
Approach. Per-turn token accounting over a real session, plus per-call cost logs for GPT, Gemini and Azure STT with daily and date-range reports.
A 9.45-minute, 33-turn session cost $1.09, or $0.116 per minute: 44.8% audio out, 43.7% audio in. About 71% of text input tokens were served from cache.
Code
Free speech is normalised to enums, the profile x product matrix is checked, and state is written before control moves. Returning an Agent from a tool is the hand-off; returning a string sends the model back to the caller. (norm() abridges an inline upper/replace.)
@function_tool()
async def profile_identified(self, context: RunContext[CustomerData],
profile_type: str, service_type: str,
user_language: str = "Tunisian Arabic"):
profile_type_upper = profile_mapping.get(norm(profile_type), norm(profile_type)) # "CDI" -> SALARIE_PERMANENT
service_type_upper = service_mapping.get(norm(service_type), norm(service_type)) # "VOITURE" -> CREDIT_AUTO
try:
profile_enum = ProfileType(profile_type_upper.lower())
except ValueError:
return f"Unknown profile type: {profile_type}. Please ask the user to clarify their professional status."
... # same for service_enum
context.userdata.profile_type = profile_enum
context.userdata.service_type = service_enum
context.userdata.detected_language = user_language
context.userdata.agent_history.append("TriageAgent")
context.userdata.handoff_count += 1
if not context.userdata.is_service_available(service_enum):
available = [s.value for s in context.userdata.get_available_services()]
return (f"Service {service_enum.value} is not available for profile "
f"{profile_enum.value}. Available: {', '.join(available)}. "
"Ask the user to choose another service.")
if profile_enum == ProfileType.SALARIE_PERMANENT:
return SalariePermanentAgent(rag_tool=self.rag_tool)
...query_embedding = await embedding_client.aembed_query(query_text)
distance = KnowledgeDocument.embedding.cosine_distance(query_embedding)
similarity = (1 - distance).label("similarity")
query = select(KnowledgeDocument, similarity).where(
KnowledgeDocument.is_active == True,
KnowledgeDocument.embedding.isnot(None))
if language:
query = query.where(KnowledgeDocument.language == language)
if profile_type:
query = query.where(
cast(KnowledgeDocument.metadata_["profile_type"], String) == profile_type)
if service_type:
query = query.where(
cast(KnowledgeDocument.metadata_["service_type"], String) == service_type)
query = query.where(similarity >= similarity_threshold).order_by(
desc("similarity")).limit(limit)
result = await session.execute(query)turn_detection = TurnDetection(
type="server_vad",
threshold=0.7,
prefix_padding_ms=300,
silence_duration_ms=700,
interrupt_response=True,
)
llm = openai.realtime.RealtimeModel.with_azure(
azure_endpoint=azure_endpoint, azure_deployment=azure_deployment,
api_key=azure_api_key, api_version=api_version,
voice=voice, turn_detection=turn_detection, temperature=0.7,
)
session = AgentSession(llm=llm)
session.userdata = CustomerData(conversation_id=conversation_id, channel="web",
started_at=datetime.utcnow())
rag_tool = ctx.proc.userdata.get("rag_tool") # built once in prewarm()
await session.start(
room=ctx.room,
agent=TriageAgent(rag_tool=rag_tool),
room_options=room_io.RoomOptions(audio_input=room_io.AudioInputOptions(
noise_cancellation=noise_cancellation.BVC(), # removes background noise and other voices
)),
)What I built
v1: text RAG chatbot (2025)
- FastAPI /ask and /new_session endpoints with a Streamlit chat and lead dashboard
- One Qdrant collection and one natively written system prompt per language
- gpt-4o-mini function calling at temperature 0 feeding deterministic loan calculators
- Per-session lead summary JSON generated in the background for sales staff
Real-time voice system
- Four voice architectures in sequence, from a cascaded STT, LLM and TTS pipeline to LiveKit
- 14 agents: triage, 6 borrower profiles, 6 loan products, finalization
- Azure gpt-realtime with tuned server VAD, barge-in and background-voice cancellation
- RAG tool loaded once per worker in prewarm() to avoid a slow first turn
Grounding and loan math
- Two pgvector knowledge bases: client policies and central-bank rules, HNSW cosine indexes
- Metadata filters over 11 profile types and 12 service types
- Amortisation, maximum-credit and debt-ratio tools; the model never does arithmetic
- Rule-based 0-100 lead score saved with the voice session in Postgres
Channels and operations
- Text channel: FastAPI BackgroundTask, LangChain agent with the same loan tools, status polling
- LLM lead analyzer (HIGH / MEDIUM / LOW) with validated JSON output
- Per-call cost tracking for GPT, Gemini and Azure STT with daily reports
- Two 4-day Derja voice prototypes for bank pitches on the same LiveKit + gpt-realtime base (175 pytest tests)
Screens
Turn-taking on a speech-to-speech model: server VAD, barge-in and background-voice cancellation.
One language per call, and answers retrieved from policy and central-bank documents filtered by profile and product.
Stack
Voice
- LiveKit Agents
- Azure OpenAI gpt-realtime
- Server VAD + barge-in
- LiveKit BVC noise cancellation
- Next.js 15 LiveKit client
Retrieval
- PostgreSQL 16 + pgvector (HNSW, cosine)
- text-embedding-ada-002
- PyMuPDF section-aware chunker
- Qdrant 1.12 (v1)
Backend
- Python 3.11
- FastAPI
- SQLModel / async SQLAlchemy
- Alembic
- LangChain (text channel)
Earlier voice stacks
- Azure Speech STT (ar-TN)
- Gemini 2.5 Pro TTS
- FastRTC + Gradio
- WebRTC ephemeral tokens
Ops
- Docker (python:3.11-slim)
- LiveKit Cloud agent deploy
- Per-call cost logging
How it was built
I designed the architecture and wrote the specs and research notes behind each decision (latency, Realtime protocol, telephony options, TTS register, cost), with Claude Code as the implementation tool and PLANNING.md / TASK.md logs from October 2025. My git history is 4 large snapshot commits with no co-author trailers, so no AI share is claimed, and the final LiveKit package is not yet committed. A fifth commit, a system-prompt update on a side branch, is a teammate's; the web client is LiveKit's agent-starter-react template, rebranded with an EN/AR toggle.
The client, its branding and its documents are withheld, and the code is private.