Side Quests
•By Arthur Steijn•Series: Azure AI Foundry Voice Agents

From Voice to Microsoft Fabric and Back: Building a Real-Time Drive-Thru AI Agent

When I was 15, I worked at a fast-food restaurant. Back then, the Drive-Thru team were the cool kids — headsets on, juggling cars, screen orders, and kitchen timing while the rest of us worked the counter. The funny thing is that I haven’t actually been through a drive-thru since getting my driver’s license 20 years ago, yet that workflow always stuck with me as an awesome real-world case to automate with a voice agent!

That side quest became Drive-Thru Z, an interactive ordering app you can try live at drivethruagent.sidequests.blog or inspect in drive-thru-voice-agent-demo. In this post, I will walk through the end-to-end flow: from browser mic capture through FastAPI and Azure AI Foundry to Microsoft Fabric SQL, and back to your speakers and on-screen basket.

Series Note: Want to see how I upgraded the voice layer from prompt metadata hacks to native kind="voice" Voice Agents and fixed real-time barge-in? Read Part 2: From Prompt Metadata Hacks to Native Voice Agents in Azure AI Foundry (Try Both Live).

End-to-End Architecture

In my opinion, the browser should never talk directly to Azure AI Foundry or Microsoft Fabric. Keeping a thin FastAPI relay in the middle keeps Entra ID credentials off the client, runs SQL and analytics tools server-side, and pushes instant UI updates back over the same WebSocket.

Drive-Thru Z end-to-end architecture connecting React AudioWorklet, FastAPI relay, Azure AI Foundry Voice Agent, MAF AnalyticsAgent, and Microsoft Fabric SQL

Here is how the pieces fit together:

  • Browser (src/frontend/src/App.tsx): Captures 48 kHz mic audio via an inline AudioWorklet, resamples to 24 kHz PCM16, streams frames to /ws/voice, and renders a hands-free menu board and basket.
  • FastAPI Relay (src/backend/relay.py & event_handlers.py): Bridges /ws/voice to Foundry (protocols/voice), manages RelaySessionState, dispatches tools, and emits UI events (order_state_updated, menu_stage_updated, order_confirmed).
  • Foundry Voice Agent (src/agents/create_voice_agent.py): Runs a server-side VoiceAgentDefinition (kind="voice", gpt-5.4, bilingual nl-NL,en-US speech input, azure_deep_noise_suppression, azure_semantic_vad, and en-US-Ava:DragonHDLatestNeural).
  • Agent Tools & MAF AnalyticsAgent (src/agent_tools/, src/agents/analytics_agent.py): Exposes get_menu_items, update_order_state, submit_order, and get_order_analytics (delegated to a Microsoft Agent Framework Agent).
  • Microsoft Fabric SQL (src/fabric/db_client.py & schema-setup.sql): Stores Menu, Orders, OrderItems, and Customers, plus the OrderAnalytics view, using passwordless Entra ID tokens.

Drive-Thru Z ordering screen showing the six-stage menu board, Capsule Corp. basket, and voice comm link HUD

Browser Audio and Hands-Free UI Sync

A real drive-thru customer cannot scroll a touchscreen while holding the steering wheel. In App.tsx, STAGE_CONFIGS splits the menu into six stages (burgers, chicken, sides, drinks, desserts, review), and the agent drives the active stage and basket via tool results pushed over /ws/voice.

For audio capture, serving a static processor.js file often trips over cache paths or MIME headers across hosts. Instead, App.tsx embeds CAPTURE_PROCESSOR_CODE as a string and loads it into AudioContext.audioWorklet via a short-lived Blob URL, resamples 48 kHz frames down to 24 kHz PCM16, and queues incoming AudioBufferSourceNode playback chunks in activeSourcesRef.current.

FastAPI Relay and Tool Deferral

Inside src/backend/relay.py, /ws/voice opens an upstream WebSocket to Foundry using DefaultAzureCredential and runs receive_from_browser() and receive_from_voicelive() with asyncio.wait(..., return_when=asyncio.FIRST_COMPLETED).

The tricky part is parallel tool calling. If you fire response.create blindly after every function_call_output, you collide with an active response turn or cut off sibling tool calls. In src/backend/event_handlers.py, state.pending_calls tracks in-flight call_ids and _trigger_response_create() waits until both the turn and all pending tools are clear:

async def _trigger_response_create(
    state: RelaySessionState,
    send_to_voicelive: Callable[[str], Awaitable[None]],
) -> None:
    if not state.response_active and not state.pending_calls and state.has_unresponded_tool_outputs:
        state.has_unresponded_tool_outputs = False
        logger.info("Triggering response.create after tool execution")
        try:
            await send_to_voicelive(json.dumps({"type": "response.create"}))
        except Exception as e:
            logger.warning("Failed to send response.create: %s", e)

Right after handle_function_call runs, event_handlers.py also forwards order_state_updated, menu_stage_updated, or order_confirmed to the browser so the screen flips the moment the tool finishes.

Passwordless Microsoft Fabric SQL

I chose Microsoft Fabric SQL Database because it handles live transactional inserts (Orders, OrderItems) and feeds the OrderAnalytics view (src/fabric/schema-setup.sql) in one place without extra ETL plumbing. In platform/fabric/setup_fabric.py, provisioning the workspace, SQL DB, and schema-setup.sql batches is fully scripted against the Fabric REST API.

Please note: OrderAnalytics filters on OrderStatus IN ('completed', 'preparing', 'ready'), whereas submit_order inserts new voice orders as 'confirmed'. Run python -m src.fabric.seed_demo_data --reset --yes (fast_executemany = True) after schema setup so "What's popular today?" has historical sales data right away!

I would always recommend Managed Identity over SQL passwords or mixed Authentication= connection-string flags that behave differently locally vs. in Linux containers. In src/fabric/db_client.py, FabricDBClient._get_connection() grabs an Entra token for https://database.windows.net/.default, packs it for SQL_COPT_SS_ACCESS_TOKEN (1256), and strips conflicting Authentication= clauses:

cred = DefaultAzureCredential()
db_token = cred.get_token("https://database.windows.net/.default")
token_bytes = db_token.token.encode("utf-16le")
token_struct = struct.pack(f"<I{len(token_bytes)}s", len(token_bytes), token_bytes)
conn_params["attrs_before"] = {1256: token_struct}

for opt in (";Authentication=ActiveDirectoryInteractive", ";Authentication=ActiveDirectoryMsi"):
    conn_str = conn_str.replace(opt, "")
return pyodbc.connect(conn_str, **conn_params)

Microsoft Fabric SQL Database query editor showing confirmed voice orders in dbo.Orders with AgentSessionId and VoiceSessionId

Microsoft Fabric SQL Database data preview of the OrderAnalytics view aggregating revenue, quantities, and average order value per menu item

The Return Trip: MAF AnalyticsAgent

Rather than cramming SQL schemas into the voice agent’s prompt, get_order_analytics in src/agent_tools/analytics_tools.py accepts one natural-language query and delegates to AnalyticsAgent (src/agents/analytics_agent.py), built with Microsoft Agent Framework (agent_framework.Agent + FoundryChatClient) and a single @tool:

Sequence diagram showing a customer asking what is popular today, flowing through get_order_analytics, MAF AnalyticsAgent, Fabric OrderAnalytics view, update_order_state screen highlight, and spoken reply

@tool
def query_database_analytics(
    metric: Annotated[str, "One of: 'popular_items', 'order_count', 'revenue', 'average_order_value'."],
    time_period: Annotated[str, "One of: 'today', 'week', 'month'."] = "today",
) -> str:
    """Query historical sales, orders, revenue, and popular items from Fabric SQL."""
    result = FabricDBClient().get_order_analytics(metric=metric, time_period=time_period)
    return json.dumps(result)

Two small safeguards keep this smooth in production: execute_get_order_analytics() runs asyncio.run(agent.get_insights(query)) inside a ThreadPoolExecutor so it never collides with FastAPI’s event loop, and if FoundryChatClient fails it falls back directly to FabricDBClient().get_order_analytics("popular_items", "today"). Once insights return, the voice agent passes highlighted_item_ids to update_order_state so the top sellers light up on screen while it speaks!

Deep Health Checks and Gotchas

When Fabric SQL capacity is paused or RBAC isn’t ready yet, silent failures ruin live demos. A few guardrails from src/backend/diagnostics.py and relay.py saved me a lot of debugging:

  • Menu fallback: If FABRIC_CONNECTION_STRING is missing or the DB throws, /api/menu and get_menu_items fall back to MENU_SEED (src/fabric/demo_data.py).
  • Parallel /health/deep: run_deep_diagnostics() checks Fabric SQL (SELECT COUNT(*) FROM Menu), Foundry auth, and FoundryChatClient concurrently via asyncio.gather, returning HTTP 200 or 503 with per-component latencies.
  • Container & RBAC checklist: Your container needs msodbcsql18 for pyodbc, and your Managed Identity needs permissions for both https://ai.azure.com/.default and https://database.windows.net/.default.

What’s next?

This setup already powers a smooth end-to-end voice loop 💚. Next up, I want to add per-session timeouts and rate limits on /ws/voice for public demos, and look at syncing live Fabric updates over OneLake for broader reporting.

If you want to see how the voice layer evolved from kind="prompt" metadata chunks to native kind="voice" agents (and try both live!), check out Part 2: From Prompt Metadata Hacks to Native Voice Agents in Azure AI Foundry (Try Both Live).

Agree or miss something?! Let me know!

References

AS

Arthur Steijn

AI & Data Engineer • Focused on Foundry, DevOps, cloud infrastructure, and AI & data platform automation.