Lab: Voice Agent and Document Agent

One agent hears things that were not said. The other must admit what it cannot find. Build both and watch.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

Build a voice support agent that works from typed or synthesized speech, and discover why a spoken "yes" is not enough for a consequential action. Then build a document agent that answers policy questions from PDFs, cites file and page, ignores drafts, prefers the newest approved rule and says "not found" when it cannot answer.

What you will learn: separate decision logic from audio, handle misrecognition, confirm through a second channel, index documents with provenance and measure answers with cases.
Prerequisites: Set Up Your Agent Development Lab and Python. Background: Voice Agent Architecture and Real-Time Audio and Multimodal, Vision, Video and Document Agents. About 90 minutes.

Versions used

Run in November 2026 on Linux with Python 3.13, eSpeak NG 1.51, FFmpeg, PocketSphinx 5.1.1, reportlab 5.0.1 and pdfplumber 0.11.10. Everything runs offline after installation. No language model is used; the logic is plain code so that every behavior is visible.

Beginner Lab 1: voice support agent

Goal

Let a caller check or cancel an order. Never cancel without a deliberate confirmation. Hand over to a person after two failures to understand, or on request.

Inputtyped or synthesized speech
Recognizerfixed phrase grammar
Support logicstate and rules
Effectsrequest or handoff

Build

python -m pip install pocketsphinx
# also install the eSpeak NG and FFmpeg programs with your package manager
python support_lab.py              # all four conversations
python support_lab.py --text-only  # no audio tools needed

Save as support_lab.py:

"""Lab 4a: a support agent you can drive by text, then by synthesized speech."""
import subprocess
import sys
import tempfile
from pathlib import Path

ORDERS = {"one two": "arriving Tuesday", "three four": "delayed to Friday"}
PHRASES = ["where is my order", "cancel the order", "talk to a person", "yes", "no",
           *(f"order number {k}" for k in ORDERS)]


class Support:
    def __init__(self, confirm_with):
        self.confirm_with = confirm_with          # "yes" by voice, or "key 1"
        self.want, self.order, self.misses, self.outbox = None, None, 0, []

    def hear(self, text):
        """One turn: recognized text in, reply out. All decisions live here."""
        if text == "talk to a person":
            return self.handoff("asked")
        if text in ("where is my order", "cancel the order"):
            self.want = text.split()[0]
            return "Tell me the order number." if not self.order else self.act()
        if text.startswith("order number ") and text[13:] in ORDERS:
            self.order = text[13:]
            return self.act() if self.want else "How can I help with that order?"
        if self.want == "cancel" and self.order and text in (self.confirm_with, "no"):
            self.want = None
            if text == "no":
                return "Nothing was changed."
            self.outbox.append(f"cancel request for order {self.order}")
            return "I have sent a cancel request."
        self.misses += 1
        if self.misses >= 2:
            return self.handoff("not understood twice")
        return "Sorry, I did not catch that."

    def act(self):
        if self.want == "where":
            return f"Order {self.order} is {ORDERS[self.order]}."
        how = "Say yes" if self.confirm_with == "yes" else "Press 1"
        return f"Cancel order {self.order}? {how} to confirm."

    def handoff(self, why):
        self.outbox.append(f"handoff ({why}), order {self.order or 'unknown'}")
        return "I will connect you to a person."


def speech_to_text(lines):
    """Optional audio mode: eSpeak NG speaks, PocketSphinx listens for known phrases."""
    from pocketsphinx import Decoder
    with tempfile.TemporaryDirectory() as tmp:
        grammar = Path(tmp) / "g.gram"
        grammar.write_text("#JSGF V1.0;\ngrammar g;\npublic <p> = "
                           + " | ".join(PHRASES) + ";\n")
        decoder = Decoder(samprate=16000, loglevel="FATAL", lm=None, jsgf=str(grammar))
        for line in lines:
            wav = subprocess.run(["espeak-ng", "-v", "en-us", "-s", "120", "--stdout", line],
                                 check=True, capture_output=True).stdout
            pcm = subprocess.run(
                ["ffmpeg", "-loglevel", "quiet", "-i", "pipe:0", "-ar", "16000", "-ac", "1",
                 "-f", "s16le", "pipe:1"], input=wav, check=True, capture_output=True).stdout
            decoder.start_utt()
            decoder.process_raw(pcm, full_utt=True)
            decoder.end_utt()
            yield line, decoder.hyp().hypstr if decoder.hyp() else ""


def converse(title, pairs, confirm_with="yes"):
    print(title)
    agent = Support(confirm_with)
    for said, heard in pairs:
        mark = "" if said == heard else f"   (said {said!r})"
        print(f"  heard: {heard!r}{mark}")
        reply = agent.hear(heard)
        print(f"  agent: {reply}")
        if "connect you" in reply:                # the person takes over from here
            break
    print("  effects:", agent.outbox or "none")


if __name__ == "__main__":
    typed = ["cancel the order", "order number three four", "yes"]
    converse("1. typed input", zip(typed, typed))
    if "--text-only" not in sys.argv:
        spoken = ["cancel the order", "order number three four", "guess not"]
        converse("2. audio, voice confirmation", speech_to_text(spoken))
        converse("3. audio, keypad confirmation", speech_to_text(spoken), "key 1")
        converse("4. audio, hard to understand", speech_to_text(
            ["order number one two", "what about the blue lamp"]))

Run it

1. typed input
  heard: 'cancel the order'
  agent: Tell me the order number.
  heard: 'order number three four'
  agent: Cancel order three four? Say yes to confirm.
  heard: 'yes'
  agent: I have sent a cancel request.
  effects: ['cancel request for order three four']
2. audio, voice confirmation
  heard: 'cancel the order'
  agent: Tell me the order number.
  heard: 'order number three four'
  agent: Cancel order three four? Say yes to confirm.
  heard: 'yes'   (said 'guess not')
  agent: I have sent a cancel request.
  effects: ['cancel request for order three four']
3. audio, keypad confirmation
  heard: 'cancel the order'
  agent: Tell me the order number.
  heard: 'order number three four'
  agent: Cancel order three four? Press 1 to confirm.
  heard: 'yes'   (said 'guess not')
  agent: Sorry, I did not catch that.
  effects: none
4. audio, hard to understand
  heard: 'order'   (said 'order number one two')
  agent: Sorry, I did not catch that.
  heard: ''   (said 'what about the blue lamp')
  agent: I will connect you to a person.
  effects: ['handoff (not understood twice), order unknown']
Intermediate Understand the failure

The most important line in this lab

In conversation 2 the synthesized caller says "guess not". The recognizer, limited to the phrases it was given, returns "yes", and the order is canceled. Nothing crashed and no log shows an error. A recognizer constrained to a few phrases will often force unfamiliar speech into the nearest one.

Conversation 3 uses the same audio and requires a key press instead. The misheard "yes" no longer counts, and nothing changes. In a phone system, key presses are detected as signaling events or tones rather than by speech recognition, so a misheard word cannot produce one. The script does not send a key press; add a conversation containing key 1 to see the confirmed path.

Do not blame only the small recognizer

Better recognizers make fewer of these errors, not none. Background voices, bad lines and unusual phrasing affect them too. Choose confirmation strength from the harm a false "yes" could cause.

DefenseHow it helpsCost
Keypad or app confirmationIndependent of recognitionExtra effort; offer an accessible alternative
Confidence thresholdRejects weak matchesScores need calibration
Out-of-grammar modelLets the recognizer say "something else"More setup and tuning
Ask for a specific phraseHarder to match by accidentFrustrating if too strict
Reversible action with noticeMistakes can be undoneNeeds a real undo

Conversation 4

The recognizer returns part of one phrase and nothing for another. The agent apologizes once, then hands over. It also records the handoff as an effect, so you can test for it.

Voice exercises

  1. Add "order status" as a phrase and a test for it.
  2. Try other voices and speeds, and record which phrases fail.
  3. Change the cancel confirmation to require two turns and measure how often it now fails for the right phrase.
  4. Require verification before revealing order status.
  5. Add a spoken disclosure that this is an automated assistant.
  6. Replace the logic with a model-driven agent but keep the confirmation rule in code.
Beginner Lab 2: document agent

Goal

Answer questions only from approved policy documents that are in effect, with file and page. Prefer the newest. If nothing matches well enough, say so.

PDFsstatus and date
Indexsentence plus source
Retrieveapproved and in effect
Answer or declinewith citation

Build and run

python -m pip install reportlab pdfplumber
python policy_lab.py

Save as policy_lab.py:

"""Lab 4b: answer questions from PDFs with a page citation, or say it cannot."""
import re
import tempfile
from pathlib import Path

import pdfplumber
from reportlab.pdfgen import canvas

DOCS = {
    "travel-2025.pdf": ["Status: approved", "Effective: 2025-01-01",
                        "Hotel limit per night is 120 pounds.",
                        "Rail travel must be booked in standard class."],
    "travel-2026.pdf": ["Status: approved", "Effective: 2026-04-01",
                        "Hotel limit per night is 140 pounds."],
    "travel-idea.pdf": ["Status: draft", "Effective: 2027-01-01",
                        "Hotel limit per night is 500 pounds."],
}
STOP = set("the a an is are be in of per for to what how much may i can my do must".split())


def words(text):
    return {w for w in re.findall(r"[a-z]+", text.lower()) if w not in STOP}


def make(folder):
    for name, lines in DOCS.items():
        pdf = canvas.Canvas(str(folder / name))
        for i, line in enumerate(lines):
            pdf.drawString(72, 770 - 20 * i, line)
        pdf.save()


def index(folder):
    """One record per sentence, carrying where it came from. Drafts stay out."""
    records = []
    for path in sorted(folder.glob("*.pdf")):
        with pdfplumber.open(path) as pdf:
            pages = [page.extract_text() or "" for page in pdf.pages]
        header = dict(re.findall(r"^(Status|Effective): (.+)$", pages[0], re.M))
        if header.get("Status") != "approved":
            continue
        for number, text in enumerate(pages, 1):
            for line in text.splitlines():
                if line.endswith("."):
                    records.append({"text": line, "source": f"{path.name} p.{number}",
                                    "effective": header["Effective"]})
    return records


def answer(question, records, today="2026-11-28", needed=0.6):
    asked = words(question)
    scored = [(len(asked & words(r["text"])) / len(asked), r) for r in records
              if r["effective"] <= today]
    matches = [r for score, r in scored if score >= needed]
    if not matches:
        return "NOT FOUND - ask the policy owner"
    best = max(matches, key=lambda r: r["effective"])
    older = [r["source"] for r in matches if r is not best]
    note = f" (replaces {', '.join(older)})" if older else ""
    return f"{best['text']} [{best['source']}, from {best['effective']}]{note}"


CASES = [("What is the hotel limit per night?", "140"),
         ("Which class must rail travel be booked in?", "standard"),
         ("What is the taxi limit?", "NOT FOUND"),
         ("How much may I spend on a room?", "140")]


def main():
    with tempfile.TemporaryDirectory() as tmp:
        make(Path(tmp))
        records = index(Path(tmp))
    passed = 0
    for question, expected in CASES:
        reply = answer(question, records)
        good = expected in reply
        passed += good
        print(f"{'PASS' if good else 'FAIL'}  {question}\n      {reply}")
    print(f"{passed} of {len(CASES)} cases passed")


if __name__ == "__main__":
    main()

Output:

PASS  What is the hotel limit per night?
      Hotel limit per night is 140 pounds. [travel-2026.pdf p.1, from 2026-04-01] (replaces travel-2025.pdf p.1)
PASS  Which class must rail travel be booked in?
      Rail travel must be booked in standard class. [travel-2025.pdf p.1, from 2025-01-01]
PASS  What is the taxi limit?
      NOT FOUND - ask the policy owner
FAIL  How much may I spend on a room?
      NOT FOUND - ask the policy owner
3 of 4 cases passed
Intermediate Improve it honestly

Three passes and one failure

  • The newest approved hotel limit wins, and the older source is named.
  • The draft with a limit of 500 never enters the index, even though it is the newest file.
  • The taxi question is declined because no sentence matches enough words.
  • The room question fails. The policy says "hotel" and "night"; the question says "room". Word matching cannot connect them.

Leave the failing case in place and fix it properly. Options include a short synonym list, embedding search or both (Embeddings, Vector and Hybrid Search, Reranking). Whatever you choose, rerun every case: looser matching can turn the correct taxi refusal into a wrong answer. That tension is the real lesson.

Simplifications to remove

Real documents have tables, columns, scans and headers. "Newest wins" is wrong when policies apply to different regions or roles. The status line here is trusted text inside the file; in a real system, take status and effective dates from your document management system.

Document exercises

  1. Add a second page to one file and check the citation points to it.
  2. Add a region field, and ask the user for the region when it matters.
  3. Pass a date for today before April 2026 and predict the answer first.
  4. Add a scanned page and route it through OCR with a confidence check.
  5. Add a sentence in a document that gives instructions to an AI, then connect a model and verify it has no effect on actions.
  6. Let a model write the answer from retrieved sentences, then check that every number in the answer appears in a cited sentence.
Expert Evaluate and combine

Measures for both agents

AgentMeasureWhy
VoiceFalse confirmations per attemptsThe harmful error
VoiceTask completion and handoffsWhether it helps
VoiceResults by voice, speed and noiseWho it fails
DocumentCorrect answer with correct citationUsefulness and trust
DocumentCorrect refusals and wrong answersHonesty
DocumentRetrieval of the right sentenceSeparates search from writing

Stretch goal: a spoken policy line

Let the voice agent answer policy questions using the document agent. Speak a short answer and offer to send the citation by message. Do not read file names aloud in full. If the document agent says "not found", say so and offer a person. Test the join: recognized question, retrieved sentence, spoken reply and the case where recognition is wrong but the retrieval still returns a confident sentence. Read back the question you understood before answering when the cost of a wrong answer is high.

Record your result

# Lab record: voice and document agents
Recognizer and version, voices and speeds tested:
False confirmations found:
Confirmation method chosen and why:
Document cases passed / total, before and after your change:
Wrong answers introduced by the change:
Known limits:
Next change:

Test data and consent

Use synthetic voices and invented documents for the lab. If you record real people to improve it, tell them what you record, why, where it is kept and when it is deleted, and let them refuse (Voice Latency, Turn-Taking, Quality and Privacy). Do not copy real company policies or customer files into a personal project.

Troubleshooting

SymptomCheck
espeak-ng or ffmpeg not foundInstall the program and make sure it is on your path
Different words recognizedVersions of the synthesizer and recognizer; note them
Grammar errorOnly plain words in phrases; no punctuation
Empty text from a PDFThe page is an image: use OCR
Every question declinedLower needed with care, and rerun the refusal cases

Common mistakes

MistakeBetter practice
Acting on a single spoken "yes"Match confirmation strength to harm
Putting rules inside the audio layerKeep logic testable in text
Indexing drafts and old versions togetherFilter by status and date
Fixing a miss by lowering all thresholdsRerun refusal cases
Answers without sourcesCite file, page and effective date

Lab complete when

  • You reproduced the false confirmation or documented what your versions did instead
  • No consequential action depends on recognition alone
  • The room question passes and the taxi question is still declined
  • Your record lists tested conditions and limits

Frequently asked questions

Can I use a cloud speech service instead?

Yes. Keep the support logic and confirmation rule, replace the recognizer function and rerun the same cases. Check the data terms before sending audio.

Why not use a language model in the document lab?

Retrieval, provenance and refusal come first. Add a model to phrase answers once those pass.

My recognizer output differs from the page.

That can happen with other versions or platforms. Record it, then find your own failing phrases.

How do I test with real speech?

Record consenting volunteers in varied conditions, keep the files secure and delete them on schedule.

References and further reading

Next steps