Back to Index
December 1, 202612 min read

How Verix Actually Works: A Grounded Drug-Information Agent, End to End

Verix is a portfolio piece built for a Frontend Developer application to Synthio Labs. Their two products — Ather (an HCP med-info agent) and Helix (patient support) — are both pharma AI copilots, so the point of Verix isn't a flashy demo, it's proving I understand the actual hard problem underneath that category: an agent that talks about drugs has to be grounded, every claim traceable to a real source, with an explicit path to a human when the question goes past what any AI should answer on its own.

This post is the whole thing, end to end — both agent implementations, the data flow, the safety design, and the testing — written so I can walk through it confidently without checking the code first.

Verix's hero section


The core idea, in one paragraph

Ask Verix a question about any FDA-approved drug and it is structurally incapable of answering from memory — it has to call a tool that hits the real openFDA Drug Label API first, and the model only ever sees what that call actually returned. The answer that comes back isn't free text either — it's a validated object (answer, safetyFlag, citations) so the UI never has to regex an essay apart to find out whether something needs a citation card or a clinician warning. And "needs a clinician" is itself a first-class output, not an afterthought: personal dosing, emergency symptoms, and pregnancy-specific risk all get flagged instead of answered.

That idea is implemented twice, deliberately, not once with a second interface bolted on:

  • A text agent in TypeScript, built on the Strands Agents SDK with Google Gemini.
  • A live voice agent in Python, built on LiveKit Agents, running as its own worker process.

They don't share a runtime or a line of agent code. They share the grounding → structured-output → escalation shape, independently implemented in each language's own idiomatic way — which is closer to how a real company with both a web product and a voice product would actually build this, rather than one agent wearing two different frontends.


Path 1: the text demo

UI → REST → agent → tool → structured output → UI, all synchronous, one request per question.

  1. The browser's demo panel (agent-demo.tsx) holds a TanStack Query useMutation that POSTs the question to /api/ask.
  2. The route (src/app/api/ask/route.ts) validates the body with Zod (question: 3–500 chars), then calls askVerix(question).
  3. askVerix (src/lib/agent.ts) builds a fresh Agent instance per request — no shared conversation history across visitors — with one tool attached, lookup_drug_label, and invokes it with a structuredOutputSchema:
export const verixAnswerSchema = z.object({
  answer: z.string().describe("Direct, plain-language answer, 2-5 sentences..."),
  safetyFlag: z.enum(["none", "caution", "escalate"]).describe(
    "'escalate' when the question needs a licensed clinician -- personal dosing changes, " +
    "suspected overdose/emergency symptoms, pregnancy-specific risk, or anything the label " +
    "itself flags as requiring medical supervision."
  ),
  citations: z.array(z.object({
    drug: z.string(),
    section: z.string(),
    snippet: z.string().max(260),
  })).max(5),
});
  1. The tool itself (src/lib/openfda.ts) tries the query three ways against openFDA — brand name, then generic name, then substance name — parses out whichever of nine label sections (boxed warning, dosage, contraindications, drug interactions, pregnancy, etc.) are present, and truncates each to 1,400 characters.
  2. Gemini (via Strands' GoogleModel) reasons over whatever the tool actually returned and emits the validated object above. The system prompt is explicit that every citation snippet must be verbatim text the tool returned, never a paraphrase, and that safetyFlag must be set to "escalate" rather than letting the model invent a personalized recommendation.
  3. The route returns { answer, safetyFlag, citations, toolCalls } as JSON. The frontend renders the answer, a SafetyBadge driven directly by safetyFlag, a citation card per entry, and pushes the whole exchange into a Zustand-backed audit trail (src/lib/store.ts) so you can revisit any past question in the session.

There's a sibling GraphQL endpoint (/api/graphql, via graphql-yoga) that wraps the exact same lookupDrugLabel function behind a drugLabel(name: String!) query — no agent involved. That's what powers the "View raw FDA label" panel under each answer: a way to put the agent's synthesized answer right next to the actual unsynthesized source and compare them directly, which matters a lot for a product whose entire pitch is "trust what it says because you can check it."

There's also a TTS playback path, separate from both agents: /api/speak calls Gemini's native audio generation directly (src/lib/tts.ts) to read the answer aloud through a small audio-reactive orb. It's a plain model call, not a tool loop, which is exactly why it isn't part of agent.ts — mixing "generate structured output" and "turn text into audio" into one agent would be conflating two unrelated capabilities. (This one had its own small war story: the installed @google/genai SDK version serializes this specific request with a mix of snake_case and camelCase keys that the API rejects outright, so tts.ts calls the REST endpoint directly instead of going through the SDK, bypassing the broken serialization for just this one call.)


Path 2: the live voice demo

Browser mic → LiveKit Cloud room → a dispatched Python worker → the same grounding idea, spoken.

  1. Clicking "Start talking to Verix" calls /api/livekit-token (src/app/api/livekit-token/route.ts), which mints a short-lived JWT via livekit-server-sdk. The important part is the RoomConfiguration:
token.roomConfig = new RoomConfiguration({
  agents: [new RoomAgentDispatch({ agentName: "verix" })],
});

Named agents need explicit dispatch — this is what tells LiveKit Cloud "when this room is created, start the verix agent worker in it," rather than the browser just joining an empty room and hoping something's listening.

  1. The browser (livekit-client + @livekit/components-react) uses that token to join the room over WebRTC and publish its microphone track.

  2. On the other side, a separate Python process (agent/src/agent.py) is already running as a LiveKit AgentServer, registered for agent_name="verix". When dispatch happens, its verix_session entrypoint spins up an AgentSession with a full voice pipeline — not a single realtime model, but composed pieces, each swappable independently:

session = AgentSession(
    stt=inference.STT(model="assemblyai/assemblyai-stt-3-7-realtime-agent"),
    stt_context_options=STTContextOptions(
        keyterms=["Verix", "warfarin", "metformin", "atorvastatin", "lisinopril"],
    ),
    tts=inference.TTS(model="fishaudio/s2.1-pro", voice="fa4c9eb3dccc4806b382b40d61c6b10a"),
    turn_handling=TurnHandlingOptions(
        turn_detection=inference.TurnDetector(),
        preemptive_generation={"enabled": True},
    ),
    expressive=True,
)

STT is AssemblyAI's realtime model via LiveKit Inference, with keyterm hints so drug names don't get mangled by a general-purpose speech model. The LLM is Gemma 4 31B (LiveKit's own hosted, voice-tuned model), the TTS is Fish Audio's S2.1 Pro in expressive mode, turn-taking uses LiveKit's own turn detector plus preemptive generation (starting to think before the user has fully finished, to cut perceived latency), and incoming audio runs through ai_coustics background noise cancellation before any of that. None of these are hardcoded provider SDKs with their own API keys — they're all requested by name through LiveKit Inference, so swapping any one of them is a one-line model-name change, not a new dependency and a new secret.

  1. The agent's one tool, lookup_drug_label, is a Python port of the exact same openFDA client logic (agent/src/openfda.py) — same three-way name fallback, same section parsing. The system prompt carries the same rules as the text agent (never answer without calling the tool, say plainly when nothing's found, flag boxed warnings/dosing/emergency/pregnancy questions for a clinician) rewritten for speech: plain spoken sentences, no markdown, two to three sentences unless asked for more, numbers spelled out the way you'd say them aloud.

  2. Here's the part that makes the UI possible at all: a voice reply is just spoken words, so there's no structured object to parse citations out of the way there is in the text path. Instead, the tool call itself publishes the raw citation payload straight to the browser over a LiveKit text data stream, independent of whatever the LLM says out loud:

await self._room.local_participant.send_text(
    json.dumps(payload), topic="verix-citations"
)
  1. The browser's live-voice-panel.tsx registers a handler for that same topic, and renders the same citation-card format the text demo uses as each one arrives — live, mid-conversation, in sync with the spoken answer but not dependent on parsing it. On top of that base design, this session added a running call-duration counter, a "N sections retrieved" count, and a per-turn "Escalate to clinician" badge — computed from whether that turn's citation touched a boxed_warning, contraindications, or pregnancy section, since that's real structural content already sitting in the payload, not a guess at the model's own wording.

The stack, as the landing page actually lists it


Why "the model interprets, the code owns structure" matters here

This is the one architectural principle that explains most of the other decisions. The model's job is to understand what the question means and how to phrase the answer — it is never the thing deciding whether a claim is true, because it has no access to ground truth except what the tool handed it. The code's job is to make sure that boundary can't be crossed:

  • The tool is mandatory, not optional — both system prompts require calling it before any drug-specific claim, and the UI's audit trail records which drugs were actually looked up per question, so a missing tool call would be visible.
  • The output is a typed schema, not prose the UI has to parse for safety-relevant phrases. safetyFlag is a real enum value, not a hope that the word "clinician" appears somewhere in a paragraph.
  • Escalation detection in the live-voice panel's badge is section-presence based, not a keyword search over the model's spoken reply — classifying intent or risk from free text with a regex/keyword list is exactly the kind of brittle heuristic that looks fine in a demo and breaks in ways you never test for.

State and data flow

Two libraries, two very different jobs, deliberately not overlapping:

  • TanStack Query owns the one piece of actual server state: the /api/ask request itself, with its loading/error/success states driving the demo panel directly (including the Retry button on failure, which just re-fires the same mutation with the same variables).
  • Zustand owns everything that's purely client-side session state: the audit trail of past questions/answers/citations in this browser tab, which question is currently "active" for re-viewing. It never touches the network itself — it's just a place to keep what the UI has already seen.

Testing

  • Jest + React Testing Library for component-level tests, run on every push via GitHub Actions (.github/workflows/ci.yml: lint → typecheck → test).
  • Cypress for an end-to-end smoke spec, but it has to run against the production build (next build && next start), not next dev — Turbopack's dev-mode Fast Refresh client interferes with React's click handlers on a second same-URL cy.visit() within one spec run. Confirmed by reproducing it in isolation and watching it disappear against next start; it's a dev-server-only artifact, not something real users would ever hit. Not wired into CI for that reason (it'd need the full build+start+run dance and isn't worth the CI minutes for a portfolio project), but it runs locally without a live API key since it only asserts on the loading state.
  • LiveKit simulations for the voice agent specifically — agent/scenarios.yaml has four scenarios run through lk agent simulate text: a basic grounded lookup (metformin dosing), a boxed-warning drug that must both ground its answer and include escalation language (warfarin), a multi-drug interaction question that should trigger the tool for both drugs (metformin + ibuprofen), and a nonexistent/misspelled drug that must say so rather than invent an answer. These run against the real openFDA API — no mocking — since it's free, keyless, and the entire point is that answers are grounded in real data, not a stand-in for it.

What's actually running where, right now

Both halves run locally, not deployed yet. The text demo is a normal Next.js app (npm run dev). The voice demo needs a second process running at the same time — the Python agent worker (cd agent && uv sync && lk agent dev) — because the browser and the worker are two separate participants joining the same LiveKit Cloud room; the Next.js app alone has nothing to answer with. Forgetting to start the worker is the single most common way to hit a dead end here, and it shows up as a generic WebRTC connection error in the browser console rather than anything that points at "the agent isn't running," which cost real debugging time until it was documented plainly in the README.

Known open items, honestly listed rather than glossed over:

  • The live-voice panel's per-turn escalation badge is implemented and type-checked but hasn't been exercised in a real spoken conversation yet.
  • The text demo's own model-judged safetyFlag came back "none" for a straightforward warfarin boxed-warning question in one test run, despite the citation clearly showing the boxed warning — an open question of whether the system prompt should force the flag up in that case, or whether that's correctly left to model judgment.
  • Neither agent has been load-tested or deployed to a public URL yet — LiveKit Cloud's free Build plan and local GEMINI_API_KEY usage are both fine for demoing live, but this hasn't been run under any real concurrent traffic.

If there's one sentence I'd want to be able to say cold about this project, it's this: the two things that make a pharma AI copilot trustworthy — grounding and escalation — are enforced by code that the model cannot route around, not by prompting the model to behave. Everything else in this writeup is just the specific, boring, correct plumbing that makes that one sentence true.