New AssemblyAI-TTS-1: Text-to-speech for voice agents. Learn more
Insights & Use Cases

How to build a voice agent for IT helpdesk and technical support

A step-by-step tutorial for building an IT support voice agent that routes, looks up docs, and handles ITSM tickets.

Abstract green mobius illustration

Written by

Kelsey Foster

Published on

28 October 2026

Tier-1 IT support is the most universal use case in the enterprise, and it’s the one people still reach by phone. The reason is almost funny: the moment someone genuinely needs IT, the channels you’d rather they use are often the ones that are broken. You can’t open the self-service portal when you’re locked out of SSO. You can’t chat the helpdesk when the VPN is down and the chat tool is behind it. So the phone rings — “I can’t log in,” “my laptop won’t connect to the network,” “what’s the status on my ticket” — and a human reads from the same runbook for the four-hundredth time this month.

That repetitive front line is exactly what a voice agent should absorb. This tutorial builds an IT helpdesk voice agent that does four things real support lines need: it routes by issue type, looks up answers in your internal knowledge base, creates and checks tickets in your ITSM system, and escalates to a human when an issue needs one. It runs on three AssemblyAI APIs that share one key: Universal-3.6 Pro Realtime for streaming speech-to-text, LLM Gateway for the model that routes and calls your tools, and the Text-to-Speech API for the agent's voice. The Text-to-Speech API delivers frontier-level quality, runs faster and costs less than other production voice agent TTS models, and has unlimited concurrency. Every component is a plain API call in your own Python, so swapping in a specific LLM or a cloned brand voice later is a one-line change.

One framing to set up front, because it drives every design decision below: in IT support, the speech-to-text layer is the part most likely to break the whole interaction. Helpdesk speech is dense with alphanumerics — ticket numbers like INC0012345, error codes like 0x80070005, asset tags, employee IDs, VLAN numbers, license keys. A general-purpose transcription model fumbles exactly those strings, and a single wrong character means the agent looks up the wrong ticket or files a useless one. Universal-3.6 Pro Realtime posts a 14.4% entity error rate on AssemblyAI's English voice-agent benchmark, and 10.0% on codes and IDs, the category ticket numbers and error codes fall into. On a helpdesk, that's the difference between a contained call and an escalated one.

What the agent needs to do

Strip an IT helpdesk call down and there are four jobs. Map each to a concrete capability:

Job How the agent does it
Route the caller by issue type The LLM classifies the request from the system prompt's routing rules, then picks the right tool or escalation queue
Answer known questions A search_knowledge_base tool returns grounded snippets from your runbooks and docs
Act in the ITSM system create_ticket and check_ticket_status tools call ServiceNow, Jira Service Management, or Zendesk
Escalate when needed A terminal escalate_to_human tool hands off to the right queue with a written summary

The conversation loop is three streaming pieces and your code in the middle. Universal-3.6 Pro Realtime transcribes the caller and tells you when they've finished a turn. LLM Gateway takes the conversation plus the four tool definitions and either answers or asks for a tool. AssemblyAI Text-to-Speech speaks the answer on the phone line, and stops the moment the caller cuts in. Your job is to define the four tools and write a system prompt that knows when to use them.

Architecture

Caller (phone)
   |
Twilio  <Connect><Stream>: 8 kHz mu-law audio in both directions
   |
bridge_server.py (FastAPI)
   |-- Universal-3.6 Pro Realtime   wss://streaming.assemblyai.com/v3/ws
   |      caller audio in -> Turn events out (end_of_turn = the caller finished)
   |
   |-- LLM Gateway                  https://llm-gateway.assemblyai.com/v1
   |      conversation + 4 tools in -> reply text or tool calls out
   |         search_knowledge_base              -> your knowledge base
   |         create_ticket, check_ticket_status -> your ITSM
   |         escalate_to_human                  -> Twilio transfer (ends the session)
   |
   |-- AssemblyAI Text-to-Speech    wss://tts.us.assemblyai.com/v1/ws
          reply text in -> 8 kHz mu-law audio out, back through Twilio

The bridge server sits between Twilio and the three AssemblyAI connections. Phone audio arrives as 8 kHz mu-law and goes to speech-to-text as-is; replies come back from text-to-speech in the same format, so nothing is transcoded. The three data tools (search_knowledge_base, create_ticket, check_ticket_status) are ordinary function calls inside the LLM request: the model asks, your code answers, the conversation continues. The fourth, escalate_to_human, is terminal: it ends the agent's session and hands the call to a person.

Before you start

You’ll need:

  • An AssemblyAI account and API key. The same key authenticates speech-to-text, LLM Gateway, and text-to-speech.
  • A Twilio account with a voice-capable phone number
  • Read/write API access to your ITSM (ServiceNow, Jira Service Management, or Zendesk) and a searchable knowledge base
  • Python 3.11+

Install the dependencies. Text-to-speech is in the AssemblyAI Python SDK from version 1.8.2:

pip install fastapi "uvicorn[standard]" "assemblyai>=1.8.2" "websockets>=14" python-dotenv twilio

Then create a .env file:

ASSEMBLYAI_API_KEY=your_assemblyai_key_here
# Optional: without these, escalate_to_human logs the hand-off instead of dialing
TWILIO_ACCOUNT_SID=
TWILIO_AUTH_TOKEN=
HUMAN_TRANSFER_NUMBER=
QUEUE_SECURITY=

Step 1: Define the helpdesk tools

Tools are JSON Schema function definitions in the OpenAI format, which LLM Gateway accepts for Claude, GPT, Gemini, and the other tool-capable models it serves. They travel with every chat completion request, and the model answers with a tool call when it decides to use one. Good tool descriptions are the highest-leverage thing you’ll write — the description is when to call this, and when not to, in plain language, because that’s the only instruction the model gets at call time.

# tools.py: the four helpdesk tools, in the OpenAI function format that
# LLM Gateway accepts. They travel with every chat completion request.
CATEGORIES = ["access", "network", "hardware", "software", "security"]


def tool(name, description, properties, required):
    return {
        "type": "function",
        "function": {
            "name": name,
            "description": description,
            "parameters": {
                "type": "object",
                "properties": properties,
                "required": required,
            },
        },
    }


SEARCH_KB = tool(
    "search_knowledge_base",
    "Search the internal IT knowledge base for how-to steps and known fixes. "
    "Call this for any 'how do I' or 'why is X happening' question: VPN setup, "
    "password policy, software install steps, printer config, known outages. "
    "Do NOT call this to look up a specific ticket; use check_ticket_status for that.",
    {
        "query": {
            "type": "string",
            "description": "The caller's question, rephrased as a search query.",
        },
        "category": {"type": "string", "enum": CATEGORIES},
    },
    ["query"],
)

CREATE_TICKET = tool(
    "create_ticket",
    "Open a new support ticket. Call this only after you have a clear, "
    "one-line problem description and the caller's employee ID. Read the "
    "returned ticket number back to the caller exactly as digits.",
    {
        "employee_id": {"type": "string"},
        "category": {"type": "string", "enum": CATEGORIES},
        "priority": {"type": "string", "enum": ["low", "normal", "high", "urgent"]},
        "summary": {"type": "string", "description": "One-line problem statement."},
    },
    ["employee_id", "category", "summary"],
)

CHECK_STATUS = tool(
    "check_ticket_status",
    "Look up the status of an existing ticket by its number "
    "(for example INC0012345). Use this whenever the caller asks "
    "'what's the status of my ticket' or gives you a ticket number.",
    {"ticket_id": {"type": "string"}},
    ["ticket_id"],
)

ESCALATE = tool(
    "escalate_to_human",
    "Transfer the caller to a human technician. Call this when the caller "
    "asks for a person, when the issue is a security incident, when a system "
    "is down for many users, or when you cannot resolve the issue after two "
    "attempts. Always write a one-line summary first.",
    {
        "queue": {
            "type": "string",
            "enum": ["service_desk", "identity_access", "network", "security", "on_call"],
            "description": "Which team should take the call.",
        },
        "summary": {
            "type": "string",
            "description": (
                "One sentence a technician can read in two seconds. Example: "
                "'Dana Okafor (emp 4471) locked out of SSO after a password "
                "reset, MFA not arriving, needs urgent access.'"
            ),
        },
    },
    ["queue", "summary"],
)

HELPDESK_TOOLS = [SEARCH_KB, CREATE_TICKET, CHECK_STATUS, ESCALATE]

Two design points worth calling out. First, the category enum is your routing key — it appears in the KB search, the ticket, and the escalation queue, so the same classification the LLM makes for one tool carries through the whole call. Second, escalate_to_human is defined like the others but handled differently: the moment the model calls it, the bridge speaks a short hand-off line and transfers the call, and no result ever goes back to the model. The LLM Gateway tool-calling docs cover the request and response format in full.

Step 2: The tool loop lives in the LLM request

This is the piece the conversational tutorials gloss over and the piece you have to get exactly right. Each caller turn is one call to respond(). It sends the conversation and the tools to LLM Gateway; if the model asks for tools, your code runs them, appends each result as a tool message keyed by the same tool_call_id, with the result encoded as a JSON string, and asks again. The loop ends when the model answers in words.

# agent_loop.py: one assistant turn. The LLM sees the tools on every request,
# your code runs the ones it calls, and the results go back into the same
# conversation until the model answers in words.
import json
from typing import List, Optional, Tuple

from integrations import itsm_create_ticket, itsm_get_ticket, kb_search
from tools import HELPDESK_TOOLS

LLM_MODEL = "claude-haiku-4-5-20251001"  # any tool-capable model on LLM Gateway
MAX_TOOL_ROUNDS = 4
HANDOFF_LINE = "Let me get a technician on the line for you. One moment."


def _arguments(tool_call) -> dict:
    args = tool_call.function.arguments
    if isinstance(args, str):
        args = json.loads(args or "{}")
    return args or {}


async def run_tool(name: str, args: dict) -> dict:
    if name == "search_knowledge_base":
        return await kb_search(args["query"], args.get("category"))
    if name == "create_ticket":
        return await itsm_create_ticket(args)
    if name == "check_ticket_status":
        return await itsm_get_ticket(args["ticket_id"])
    return {"error": f"unknown tool {name}"}


async def respond(llm, messages: List[dict]) -> Tuple[str, Optional[dict]]:
    """Returns (what to say, escalation). `escalation` is the escalate_to_human
    arguments when the model hands the call off, otherwise None.
    `messages` is updated in place."""
    for _ in range(MAX_TOOL_ROUNDS):
        completion = await llm.chat.completions.create(
            model=LLM_MODEL,
            messages=messages,
            tools=HELPDESK_TOOLS,
            max_tokens=300,
        )
        # Some providers put the text and the tool calls in separate choices.
        text = " ".join(
            c.message.content for c in completion.choices if c.message.content
        ).strip()
        calls = [
            tc for c in completion.choices for tc in (c.message.tool_calls or [])
        ]

        # escalate_to_human is terminal: no result goes back to the model,
        # because the transfer ends this conversation.
        for tc in calls:
            if tc.function.name == "escalate_to_human":
                return HANDOFF_LINE, _arguments(tc)

        if not calls:
            messages.append({"role": "assistant", "content": text})
            return text, None

        # Run every tool first, then record the calls and their results
        # together, so an interrupted turn never leaves a call unanswered.
        results = [await run_tool(tc.function.name, _arguments(tc)) for tc in calls]
        messages.append(
            {
                "role": "assistant",
                "content": None,
                "tool_calls": [
                    {
                        "id": tc.id,
                        "type": "function",
                        "function": {
                            "name": tc.function.name,
                            "arguments": json.dumps(_arguments(tc)),
                        },
                    }
                    for tc in calls
                ],
            }
        )
        for tc, result in zip(calls, results):
            print(f"[tool] {tc.function.name} -> {result}")
            messages.append(
                {"role": "tool", "tool_call_id": tc.id, "content": json.dumps(result)}
            )

    return "Sorry, I lost track of that. Could you tell me once more what's going on?", None

A few details matter. Some providers return the model's text and its tool calls as separate entries in choices, so respond() collects both across every choice. Tool results are recorded together with the calls that produced them, after every tool has run, so a caller who barges in mid-lookup never leaves the history with a call that has no answer. And messages is the whole state of the conversation: the KB snippets and ticket numbers the model saw two turns ago are still in it.

escalate_to_human is the exception to all of this. respond() returns its arguments instead of running it. Transferring the call ends the <Connect><Stream>, which tears down the agent's session, so there's nothing left to receive a result. It’s a terminal tool. The deep mechanics of doing the transfer warmly (keeping a live transcript running for the technician across a conference bridge) are their own subject; the bridge below does the straight hand-off, and the voice agents solution page covers the warm-handoff variant.

Step 3: Bridge Twilio to speech-to-text, the LLM, and text-to-speech

Now wire it together. A few specifics for each connection:

  • Speech-to-text connects to wss://streaming.assemblyai.com/v3/ws with speech_model=universal-3-6-pro, encoding=pcm_mulaw and sample_rate=8000. Twilio's mu-law goes in exactly as it arrives, and keeping it at 8 kHz is the accurate choice for phone audio. The API key goes in the Authorization header as-is. Each audio message must hold 50 to 1,000 ms, so the bridge batches Twilio's 20 ms frames into 100 ms chunks.
  • Turn detection comes from the speech model. A Turn event with end_of_turn set means the caller has finished; that's when the transcript goes to respond(). The defaults are tuned for conversation, so leave the turn-silence settings alone unless testing gives you a reason.
  • Text-to-speech opens one AsyncTTSSession per call with encoding="pcm_mulaw" and sample_rate=8000, the format Twilio plays. The model's native output is 24 kHz; the server resamples before it encodes. Each reply is one speak() call, and the bridge paces the audio out at the phone line's 8,000 bytes a second. See the TTS quickstart for the session lifecycle.
  • Barge-in takes three moves: cancel() on the text-to-speech session so the server drops the rest of the reply, cancel the reply task, and send Twilio a clear message so audio it has already queued stops playing.
# bridge_server.py: Twilio on one side; speech-to-text, the LLM, and
# text-to-speech on the other. Phone audio stays 8 kHz mu-law end to end.
import asyncio
import base64
import json
import os
import string
import time
from urllib.parse import urlencode

import assemblyai as aai
import websockets
from dotenv import load_dotenv
from fastapi import FastAPI, Request, WebSocket
from fastapi.responses import Response

from agent_loop import respond
from prompts import GREETING, SYSTEM_PROMPT

load_dotenv()

ASSEMBLYAI_KEY = os.environ["ASSEMBLYAI_API_KEY"]

STT_URL = "wss://streaming.assemblyai.com/v3/ws?" + urlencode(
    {
        "speech_model": "universal-3-6-pro",
        "encoding": "pcm_mulaw",  # Twilio's G.711 mu-law, sent as-is
        "sample_rate": 8000,
        # Boost the jargon a helpdesk hears all day.
        "keyterms_prompt": json.dumps(
            ["Okta", "VPN", "MFA", "VLAN", "Kerberos", "SSO", "ServiceNow",
             "Active Directory", "GlobalProtect"]
        ),
    }
)
STT_CHUNK_BYTES = 800  # 100 ms of 8 kHz mu-law (send 50-1000 ms per message)

TTS_CONFIG = aai.TTSConfig(
    voice_id="49c443a4-8a1d-5f7e-b70b-98bdbd9823c3",  # Audrey
    language="english",
    encoding="pcm_mulaw",  # what Twilio plays back
    sample_rate=8000,
)

BACKCHANNELS = frozenset(
    {"mhm", "mm", "uh", "um", "hmm", "ah", "oh", "okay", "ok", "right", "yeah", "yep"}
)
_STRIP = str.maketrans("", "", string.punctuation)

QUEUE_NUMBERS = {
    queue: os.environ.get(f"QUEUE_{queue.upper()}")
    for queue in ["service_desk", "identity_access", "network", "security", "on_call"]
}

app = FastAPI()


def is_interruption(text: str) -> bool:
    words = text.lower().translate(_STRIP).split()
    return len(words) >= 2 and not all(w in BACKCHANNELS for w in words)


async def start_transfer(call_sid, args: dict) -> None:
    """Redirect the live call to a human queue. The new TwiML replaces
    <Connect><Stream>, which ends the media stream and this agent session."""
    queue = args.get("queue", "service_desk")
    number = QUEUE_NUMBERS.get(queue) or os.environ.get("HUMAN_TRANSFER_NUMBER")
    # In production, push the summary to the technician's screen-pop or ticket.
    print(f"[transfer] queue={queue} summary={args.get('summary', '')!r}")

    sid = os.environ.get("TWILIO_ACCOUNT_SID")
    token = os.environ.get("TWILIO_AUTH_TOKEN")
    if not (sid and token and call_sid and number):
        print("[transfer] mock mode: set Twilio credentials and a queue number to dial")
        return

    from twilio.rest import Client

    client = Client(sid, token)
    await asyncio.to_thread(
        client.calls(call_sid).update, twiml=f"<Response><Dial>{number}</Dial></Response>"
    )


class Call:
    def __init__(self, twilio_ws, stt_ws, tts, llm):
        self.twilio_ws = twilio_ws
        self.stt_ws = stt_ws
        self.tts = tts
        self.llm = llm
        self.stream_sid = None
        self.call_sid = None
        self.messages = [
            {
                "role": "system",
                "content": f'{SYSTEM_PROMPT}\nYou opened the call by saying: "{GREETING}"',
            }
        ]
        self.reply_task = None
        self.in_tts = False         # a TTS request is in flight
        self.playing_until = 0.0    # when Twilio finishes playing what we sent
        self.transferring = False

    @property
    def speaking(self) -> bool:
        return self.in_tts or time.monotonic() < self.playing_until

    async def say(self, text: str):
        print(f"Agent: {text}")
        # Tell the speech model what the agent just asked, so a short answer
        # (an employee ID, a ticket number, "yes") is heard in context.
        await self.stt_ws.send(
            json.dumps({"type": "UpdateConfiguration", "agent_context": text[-1750:]})
        )
        self.in_tts = True
        try:
            async for chunk in self.tts.speak(text):
                await self.twilio_ws.send_text(
                    json.dumps(
                        {
                            "event": "media",
                            "streamSid": self.stream_sid,
                            "media": {"payload": base64.b64encode(chunk).decode()},
                        }
                    )
                )
                # Pace the audio at the phone line's rate (8,000 bytes a
                # second), keeping about half a second queued at Twilio.
                now = time.monotonic()
                self.playing_until = max(self.playing_until, now) + len(chunk) / 8000
                ahead = self.playing_until - now - 0.5
                if ahead > 0:
                    await asyncio.sleep(ahead)
        finally:
            self.in_tts = False

    async def handle_turn(self, text: str):
        if self.messages[-1]["role"] == "user":
            self.messages[-1]["content"] += " " + text  # caller kept talking
        else:
            self.messages.append({"role": "user", "content": text})
        try:
            reply, escalation = await respond(self.llm, self.messages)
        except Exception as err:  # an LLM or network failure: recover out loud
            print(f"[llm] {err}")
            reply, escalation = "Sorry, I didn't catch that. Could you say it again?", None

        if escalation:
            self.transferring = True  # stop listening for new turns
        await self.say(reply)
        if escalation:
            # Let the hand-off line finish playing, then transfer.
            await asyncio.sleep(max(0.0, self.playing_until - time.monotonic()))
            await start_transfer(self.call_sid, escalation)

    async def barge_in(self):
        if self.in_tts:
            self.in_tts = False
            await self.tts.cancel()  # the server drops the rest of the reply
        if self.reply_task and not self.reply_task.done():
            self.reply_task.cancel()
        if time.monotonic() < self.playing_until:
            # Drop the audio Twilio has queued but not played yet.
            await self.twilio_ws.send_text(
                json.dumps({"event": "clear", "streamSid": self.stream_sid})
            )
            self.playing_until = 0.0

    def start_reply(self, coro):
        self.reply_task = asyncio.create_task(coro)

    async def on_turn(self, event: dict):
        text = event.get("transcript", "").strip()
        if not text or self.transferring:
            return
        if self.speaking and not is_interruption(text):
            return  # "mhm", "okay": the caller is listening, not interrupting
        await self.barge_in()
        if event.get("end_of_turn"):
            print(f"Caller: {text}")
            self.start_reply(self.handle_turn(text))


@app.post("/twilio/voice")
async def twilio_voice(request: Request):
    host = request.url.hostname
    twiml = f"""<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Connect>
    <Stream url="wss://{host}/media-stream" />
  </Connect>
</Response>"""
    return Response(content=twiml, media_type="application/xml")


@app.websocket("/media-stream")
async def media_stream(twilio_ws: WebSocket):
    await twilio_ws.accept()
    async with websockets.connect(
        STT_URL, additional_headers={"Authorization": ASSEMBLYAI_KEY}
    ) as stt_ws, aai.AsyncTTSSession(
        TTS_CONFIG, api_key=ASSEMBLYAI_KEY
    ) as tts, aai.AsyncLLMGateway(api_key=ASSEMBLYAI_KEY) as llm:
        call = Call(twilio_ws, stt_ws, tts, llm)

        async def twilio_to_stt():
            buffer = bytearray()
            async for raw in twilio_ws.iter_text():
                event = json.loads(raw)
                kind = event.get("event")
                if kind == "start":
                    call.stream_sid = event["start"]["streamSid"]
                    call.call_sid = event["start"]["callSid"]
                    call.start_reply(call.say(GREETING))
                elif kind == "media":
                    # Twilio sends 20 ms frames; batch them into 100 ms.
                    buffer += base64.b64decode(event["media"]["payload"])
                    if len(buffer) >= STT_CHUNK_BYTES:
                        await stt_ws.send(bytes(buffer))
                        buffer.clear()
                elif kind == "stop":
                    return

        async def stt_to_agent():
            async for raw in stt_ws:
                event = json.loads(raw)
                if event.get("type") == "Turn":
                    await call.on_turn(event)

        async def keep_tts_alive():
            while True:  # a TTS session closes after two idle minutes
                await asyncio.sleep(60)
                if not call.speaking:
                    await tts.keep_alive()

        background = [asyncio.create_task(stt_to_agent()), asyncio.create_task(keep_tts_alive())]
        try:
            await twilio_to_stt()  # the call is over when Twilio stops streaming
        finally:
            for task in background:
                task.cancel()
            if call.reply_task:
                call.reply_task.cancel()
            try:
                await stt_ws.send(json.dumps({"type": "Terminate"}))
            except websockets.ConnectionClosed:
                pass


@app.get("/")
async def root():
    return {"ok": True, "service": "voice-agent-it-helpdesk"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8000)))

That’s the whole bridge. Notice the asymmetry in handle_turn(): when respond() comes back with an escalation, the bridge stops listening for new turns, speaks the hand-off line, waits for it to finish playing, and transfers. The three data tools never surface here at all; they were resolved inside respond().

Two smaller pieces are doing quiet but important work. The keyterms_prompt list nudges the recognizer toward the product names a helpdesk hears all day, so “Okta” doesn’t come back as “octa” and “VLAN” doesn’t become “v-land.” And before each reply plays, say() sends the agent's own words to the speech model as agent_context, so when the agent asks for an employee ID or a ticket number, the short answer that follows is heard as an answer to that question. is_interruption() keeps a listening "mhm" from cutting the agent off mid-sentence, following the backchannel guidance in the docs.

Step 4: The system prompt does the routing

There’s no separate “router” component. Routing is the system prompt plus the tool descriptions — the LLM reads the caller’s problem, classifies it, and either resolves it with a tool or escalates to the right queue. Write the prompt as an operations runbook, not a personality.

# prompts.py: routing is the system prompt plus the tool descriptions.

GREETING = "IT support, this line is recorded for quality. What can I help you with?"

SYSTEM_PROMPT = """You are the IT helpdesk voice agent for Northwind Corp.
You are calm, fast, and precise. One or two sentences per turn. Never lecture.

WHAT YOU HANDLE DIRECTLY (use search_knowledge_base, then guide the caller):
- Access: password policy, SSO setup, MFA enrollment, account unlock STEPS
- Network: VPN setup and troubleshooting, Wi-Fi, known outages
- Hardware: printer setup, monitor/dock issues, loaner requests
- Software: install/license steps for approved apps

TICKETS:
- Open a ticket with create_ticket when the issue needs follow-up or you cannot
  resolve it live. Always get the employee ID first. Read the returned ticket
  number back digit by digit and confirm it.
- For "what's the status of my ticket," use check_ticket_status with the number.

ROUTING / ESCALATION (call escalate_to_human with the right queue):
- "identity_access": account lockouts you cannot clear, suspicious login activity
- "network": a system or site down for MANY users
- "security": anything that sounds like a security incident, phishing, or breach
- "on_call": production outage outside business hours
- "service_desk": caller asks for a person, or two resolution attempts failed

HARD RULES:
- NEVER ask for or accept a password, PIN, or MFA code over the phone. To reset
  credentials, trigger the self-service reset (it sends a secure link) or escalate
  to identity_access for verified identity checks.
- NEVER invent a ticket number, an error-code meaning, or a fix. If the knowledge
  base doesn't have it, say so and open a ticket or escalate.
- Confirm ticket numbers and error codes by reading them back before acting.
- For a security incident, escalate immediately. Do not troubleshoot.
- Speak in plain sentences: no lists, markdown, or symbols. Everything you
  say is read aloud on a phone line.
"""

Three things in that prompt earn their place. The routing block maps issue types to escalation queues, so “the whole sales floor lost network ten minutes ago” goes to network while “I think I clicked a phishing link” goes straight to security with no troubleshooting. The credential rule is a security boundary, not a nicety — a voice agent should never collect passwords or MFA codes; it triggers a self-service reset link or routes to a verified human check. And the anti-fabrication rule (“never invent a ticket number, an error-code meaning, or a fix”) is what keeps the agent trustworthy: it answers from the knowledge base or it says it doesn’t know and opens a ticket. An IT agent that confidently makes up a fix is worse than no agent.

Step 5: Ground every answer in the knowledge base

The search_knowledge_base handler is where “looks up answers in your docs” becomes real. The pattern that matters: return source snippets, and instruct the model to answer only from them. This is retrieval-augmented generation applied to a phone call — the LLM’s job is to read your runbook back conversationally, not to recall IT trivia from its training data. These are in-memory mocks so you can hear the agent work end to end today; swap each body for your real KB and ITSM calls and keep the returned keys the same.

# integrations.py: MOCK, in-memory knowledge base and ITSM, so the agent runs
# end to end before you wire up ServiceNow, Jira Service Management, or Zendesk.
# Swap each body for a real API call and keep the returned keys the same:
# the LLM reads these dicts as tool results.
import itertools
from typing import Dict, Optional

# ── Mock knowledge base ──────────────────────────────────────────────────────
# A tiny runbook keyed by category. A real KB call returns ranked snippets; the
# agent is instructed (in the system prompt) to answer only from these.
_KB = {
    "access": [
        {
            "title": "Reset your password (self-service)",
            "summary": "Go to id.northwind.example/reset and follow the secure "
                       "link sent to your registered device. IT never asks for "
                       "your password over the phone.",
            "url": "https://kb.northwind.example/access/password-reset",
        },
        {
            "title": "Enroll in MFA",
            "summary": "Open the Okta Verify app, tap Add Account, and scan the "
                       "QR code shown at id.northwind.example/mfa.",
            "url": "https://kb.northwind.example/access/mfa-enrollment",
        },
    ],
    "network": [
        {
            "title": "Connect to the corporate VPN",
            "summary": "Open GlobalProtect, enter vpn.northwind.example as the "
                       "portal, and sign in with SSO. If it hangs at 'Connecting', "
                       "toggle Wi-Fi off and on once.",
            "url": "https://kb.northwind.example/network/vpn-setup",
        },
    ],
    "hardware": [
        {
            "title": "Add a network printer",
            "summary": "Settings > Printers > Add, then choose the printer named "
                       "for your floor (e.g. NW-3F-Canon). Driver installs "
                       "automatically on the corporate network.",
            "url": "https://kb.northwind.example/hardware/add-printer",
        },
    ],
    "software": [
        {
            "title": "Install approved software",
            "summary": "Open the Company Portal app and pick from the approved "
                       "catalog. Anything not listed needs a software request "
                       "ticket for license review.",
            "url": "https://kb.northwind.example/software/self-service-install",
        },
    ],
    "security": [
        {
            "title": "Report a phishing email",
            "summary": "Use the 'Report Phishing' button in Outlook. Do not click "
                       "links or reply. Security triages reports within 15 minutes.",
            "url": "https://kb.northwind.example/security/report-phishing",
        },
    ],
}


async def kb_search(query: str, category: Optional[str] = None) -> dict:
    """Return grounded snippets. The agent answers only from these."""
    if category and category in _KB:
        hits = _KB[category]
    else:
        # No category given: naive keyword scan across the whole KB.
        q = (query or "").lower()
        hits = [
            item
            for items in _KB.values()
            for item in items
            if any(word in (item["title"] + item["summary"]).lower()
                   for word in q.split())
        ]
    return {
        "found": bool(hits),
        "snippets": [{"title": h["title"], "text": h["summary"], "url": h["url"]}
                     for h in hits[:3]],
    }


# ── Mock ITSM (ticket store) ─────────────────────────────────────────────────
# Tickets live in a dict for the lifetime of the process. Two are pre-seeded so
# "what's the status of my ticket" works in a demo. Real ITSM numbers are
# server-generated; we mimic the ServiceNow `INC` format here.
_ticket_counter = itertools.count(20001)
_TICKETS: Dict[str, dict] = {
    "INC0019001": {
        "number": "INC0019001",
        "state": "in_progress",
        "assigned_to": "Service Desk",
        "updated_at": "2026-06-03T09:14:00Z",
    },
    "INC0019044": {
        "number": "INC0019044",
        "state": "resolved",
        "assigned_to": "Identity & Access",
        "updated_at": "2026-06-02T17:40:00Z",
    },
}


async def itsm_create_ticket(args: dict) -> dict:
    number = f"INC{next(_ticket_counter):07d}"
    _TICKETS[number] = {
        "number": number,
        "state": "new",
        "requester_id": args["employee_id"],
        "category": args["category"],
        "priority": args.get("priority", "normal"),
        "short_description": args["summary"],
        "channel": "voice_agent",  # tag so you can measure containment later
        "assigned_to": None,
        "updated_at": None,
    }
    return {"ticket_id": number, "state": "new"}


async def itsm_get_ticket(ticket_id: str) -> dict:
    t = _TICKETS.get((ticket_id or "").strip().upper())
    if not t:
        return {"found": False}
    return {
        "found": True,
        "ticket_id": t["number"],
        "state": t["state"],
        "assigned_to": t.get("assigned_to"),
        "updated": t.get("updated_at"),
    }

The create_ticket handler returns the system-generated ticket number, and the prompt tells the agent to read it back digit by digit and confirm. That read-back loop is where Universal-3.6 Pro Realtime's accuracy on codes and IDs pays off twice: once when the agent hears the caller’s existing ticket number correctly, and again when the caller confirms the new one. Tag tickets with "channel": "voice_agent" so you can measure containment later — you’ll want to know how many of these the agent closed without a human.

Swapping in your own LLM, voice, or framework

Every piece of this agent is a separate API call, so each one can change on its own. Three swaps come up most often.

A different LLM. Change LLM_MODEL to any tool-capable model on LLM Gateway's available models list. If you'd rather call a provider directly, with a fine-tuned model that knows your internal systems, for example, any async client with an OpenAI-style chat.completions.create() works with respond() as written:

# In bridge_server.py: any client with an OpenAI-style chat.completions.create()
# works with respond() unchanged. For example, OpenAI directly:
import os

from openai import AsyncOpenAI

import agent_loop

agent_loop.LLM_MODEL = "gpt-4.1-mini"
llm = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"])

# ...then build the call with it instead of the gateway:
# call = Call(twilio_ws, stt_ws, tts, llm)

A different voice. Change voice_id in TTS_CONFIG to another voice from the voice library, or clone your brand's voice in the dashboard and use its ID. Voice cloning covers the consent requirements.

An orchestration framework. If your team has already standardized on LiveKit or Pipecat, both have AssemblyAI integrations for speech-to-text and text-to-speech: see the LiveKit and Pipecat guides. Your tools, prompt, and integrations carry over unchanged.

Whatever you swap, keep the order of operations in mind. A voice stack is a chain — speech-to-text, then the LLM, then text-to-speech — and its accuracy ceiling is set by the first link. If transcription mishears INC0012345 as INC0012845, no downstream LLM or voice can recover; the agent confidently looks up the wrong ticket. The speech-to-text layer is the foundation, and the part to change last.

Measuring whether it’s working

Four numbers tell you if the helpdesk agent is earning its keep:

  • Containment rate: the share of calls the agent resolved without escalating. Tag voice-agent tickets (we set channel: "voice_agent" above) and compare closed-without-transfer against total. This is the headline ROI number.
  • Escalation precision: of the calls the agent escalated, how many genuinely needed a human. Too many means your routing rules are too eager; too few (callers asking twice for a person) means they’re too conservative.
  • Alphanumeric accuracy: sample calls with ticket numbers and error codes, and check how often the agent captured them correctly. This is the metric most directly tied to your speech-to-text model, and the one to watch when you change its settings or your keyterms list.
  • First-contact resolution: of contained calls, how many didn’t generate a repeat call within 48 hours. A high containment rate with low first-contact resolution means the agent is closing calls it didn’t actually fix.

Run it against a real phone number

Start the bridge with python bridge_server.py (it listens on port 8000), expose it with a tunnel such as ngrok, and point your Twilio number's incoming-call webhook at https://<your-host>/twilio/voice. Twilio fetches the TwiML, opens the media stream to /media-stream, and the agent answers with its greeting. The mock KB and ITSM in integrations.py are enough to try every path: ask how to connect to the VPN, open a ticket with an employee ID, check the status of INC0019001, and report a phishing email to hear the hand-off.

Build your IT helpdesk agent

The fastest way to feel the difference accuracy makes on helpdesk speech is to call your own number and read it a ticket number. Create an AssemblyAI account to get an API key, then start from the streaming speech-to-text and text-to-speech quickstarts — the four tools above are the whole agent.

Frequently asked questions

How do I build a voice agent for IT helpdesk and technical support?

Connect three pieces through a small bridge server: Universal-3.6 Pro Realtime streaming speech-to-text, an LLM through AssemblyAI's LLM Gateway, and the AssemblyAI Text-to-Speech API. Define four function tools — search_knowledge_base for grounded how-to answers, create_ticket and check_ticket_status for your ITSM system, and escalate_to_human for transfers — send them with every LLM request, and write a system prompt that classifies each call by issue type and picks the right tool or escalation queue. Bridge it to telephony with Twilio Media Streams, keeping the audio at 8 kHz mu-law in both directions, so the agent transcribes ticket numbers, error codes, and asset tags accurately.

Can a voice agent create and look up tickets in ServiceNow, Jira, or Zendesk?

Yes. Define create_ticket and check_ticket_status as function tools in your LLM request. When the model calls one, your code makes the corresponding REST request to your ITSM platform (ServiceNow, Jira Service Management, or Zendesk) and returns the result to the model as a tool message, keyed by the same tool_call_id and encoded as a JSON string. The agent then reads the ticket number back to the caller. Tag tickets with a voice_agent channel so you can measure containment afterward. The ITSM platform is yours to choose, because the agent only ever calls the functions you define.

How does the voice agent route calls by issue type?

Routing happens in the system prompt and the tool descriptions, not in a separate component. The LLM reads the caller’s problem, classifies it into a category (access, network, hardware, software, security), and either resolves it with a knowledge-base lookup and a ticket, or escalates to the matching human queue. You encode the routing rules as plain instructions — for example, “a system down for many users goes to the network queue; anything that sounds like a security incident goes to security immediately with no troubleshooting.” Because the same category drives the KB search, the ticket, and the escalation queue, one classification carries through the whole call.

How do I stop the voice agent from making up answers about IT issues?

Two mechanisms. First, ground every answer: the search_knowledge_base tool returns source snippets from your runbooks, and the system prompt instructs the agent to answer only from those snippets and to say it doesn’t know (then open a ticket or escalate) when the knowledge base has nothing. This is retrieval-augmented generation on a phone call. Second, add explicit anti-fabrication rules to the prompt — “never invent a ticket number, an error-code meaning, or a fix” — and require the agent to read ticket numbers and error codes back to the caller for confirmation before acting.

Accurate transcription matters here too: if the agent mishears the input, even a grounded answer is about the wrong thing.

Can I use my own LLM or a cloned voice for an IT support agent?

Yes. The LLM call is a standard OpenAI-style chat completion, so you can switch models on LLM Gateway by changing the model name, or point the same code at your own provider client for a fine-tuned model. For the voice, set voice_id to any voice from the AssemblyAI voice library, or to a voice you've cloned in the dashboard. If you already run LiveKit or Pipecat, both integrate AssemblyAI speech-to-text and text-to-speech. Keep Universal-3.6 Pro Realtime as the speech-to-text layer either way: if it mishears a ticket number, no downstream LLM or voice can recover.

Why does speech-to-text accuracy matter so much for IT support voice agents?

Because IT support speech is unusually dense with alphanumerics — ticket numbers like INC0012345, error codes like 0x80070005, asset tags, employee IDs, VLAN numbers, and license keys. A single wrong character means the agent looks up the wrong ticket, files a useless one, or troubleshoots the wrong error. General-purpose transcription models tend to fumble exactly these strings. Universal-3.6 Pro Realtime posts a 14.4% entity error rate on AssemblyAI's English voice-agent benchmark, with 10.0% on codes and IDs, which on a helpdesk is the difference between a call the agent contains and one it has to escalate. Adding domain key terms (product names like Okta, VLAN, Kerberos) with keyterms_prompt sharpens recognition further.