Overview
An outbound call often reaches a machine before it reaches a person, such as an IVR menu, call screening, or a voicemail greeting. Answering machine detection (AMD) identifies each machine, and your agent handles it: the agent picks a menu option, answers the screening questions, or leaves a voicemail message. When a person answers, AMD completes and your agent continues the call.
How AMD works
AMD repeats these steps for each turn of the call:
- The participant speaks.
- AMD gives the turn a category, such as
machine-ivr. - Most categories also set the stage. The stage persists until a later turn changes it, and it determines how the agent replies. For example, in the
machine-ivrstage, the agent picks a menu option. - When a person answers or the call can't continue, AMD completes.
AMD works on transcripts only. It doesn't detect beeps, tones, or hold music from audio.
Categories
Each classified turn gets one of these categories:
| Category | Effect | Description |
|---|---|---|
machine-screening | Sets the stage | Call screening asks who is calling or why, for example on iOS or Android. The agent answers the screening questions and waits for the next prompt. |
machine-ivr | Sets the stage | An IVR menu asks for a spoken choice or a DTMF key. The agent picks an option with the built-in DTMF tool or a short spoken answer, then waits for the next prompt. |
machine-vm | Sets the stage | A voicemail greeting asks for a message. The agent leaves a message. |
wait | This turn only | Speech that asks nothing, such as a hold or transfer announcement, an ad, or a notice. The agent stays silent. The stage doesn't change. |
uncertain | This turn only | Not enough evidence. The agent replies by the rules of the current stage. The stage doesn't change. |
human | Completes AMD | A person is ready to talk. AMD completes and your agent continues the call. |
machine-unavailable | Completes AMD | The call can't complete, for example the mailbox is full or the number is out of service. AMD completes and cancels pending speech. |
A call can move between stages in any order, for example from machine-ivr to machine-screening to human. When a prediction doesn't fit the current stage, AMD changes the stage to match the prediction.
Replies during AMD
While the call is in a machine stage (machine-screening, machine-ivr, or machine-vm), AMD controls how your agent replies:
- Stage instructions: AMD adds short instructions for that stage to the reply. These instructions don't enter the chat history of your agent. To replace or turn off the instructions for a stage, see Handle a stage yourself.
- Wait for silence: A reply plays only after the participant is silent for 1.5 seconds by default. The agent doesn't talk over a menu or a greeting.
- One voicemail message: The agent leaves one voicemail message at most. After the message, AMD keeps listening for a short time, so the agent can answer a menu that follows, such as "press 1 to send."
- DTMF in menus only: The built-in DTMF tool
send_dtmf_eventsis available only in themachine-ivrstage. - Confirm a person after a machine: A short greeting such as "Hi, you've reached Sam" can be a person or a voicemail greeting. After a menu or call screening, AMD waits for one more turn before it completes as
human. The agent replies to the first turn as usual.
Call screening
Many iOS and Android phones can screen calls: the phone answers and asks who is calling and why. In the machine-screening stage, the agent answers these questions. To help the agent answer well, include the caller name, the business, and the reason for the call in the agent's instructions.
To hang up at call screening instead, set the screening instructions to None in Python or null in Node.js. To learn more, see Handle a stage yourself.
Usage
AMD listens to the audio of one participant, the callee. When you start AMD depends on how the call reaches the room:
- SIP call: Start AMD before you create the SIP participant.
- Twilio Connector: Start AMD after the callee answers.
- Other participants: Start AMD after the audio track of the participant arrives.
SIP call
Start AMD before you create the SIP participant, so detection is ready before audio starts to arrive. By default, AMD starts listening when the call is answered and ignores audio before the answer. To change this, set the AMD option wait_until_answered to False (waitUntilAnswered: false in Node.js).
Open the async context manager, then create the SIP participant inside it. Pass participant_identity so AMD listens to that participant. The execute() method returns an AMDCompletedEvent when AMD completes.
import asynciofrom livekit import apifrom livekit.agents import AMD, AMDCategory, AMDReasonawait session.start(agent=MyAgent(), room=ctx.room)async with AMD(session, participant_identity=participant_identity) as detector:try:await ctx.api.sip.create_sip_participant(api.CreateSIPParticipantRequest(room_name=ctx.room.name,sip_trunk_id=outbound_trunk_id,sip_call_to=phone_number,participant_identity=participant_identity,wait_until_answered=True,),timeout=45,)except (api.SipCallError, asyncio.TimeoutError):ctx.shutdown("call not answered")return# The call may end just before wait_until_answered returns.if participant_identity not in ctx.room.remote_participants:ctx.shutdown("participant missing")returnresult = await detector.execute()logger.info("amd completed", extra={"category": result.category, "reason": result.reason})if result.is_error or result.reason == AMDReason.PARTICIPANT_DISCONNECTED:ctx.shutdown(result.reason.value)elif result.voicemail_message_played and result.category != AMDCategory.HUMAN:ctx.shutdown("voicemail completed")elif result.category == AMDCategory.MACHINE_UNAVAILABLE:ctx.shutdown("machine unavailable")
Create the detector, call start(), then create the SIP participant. Pass participantIdentity so AMD listens to that participant. The execute() method returns an AMDCompletedEvent when AMD completes. Call aclose() in a finally block so AMD cleans up on every path.
import { voice } from '@livekit/agents';import { SipClient, TwirpError } from 'livekit-server-sdk';await session.start({ agent: new MyAgent(), room: ctx.room });const sip = new SipClient(process.env.LIVEKIT_URL!,process.env.LIVEKIT_API_KEY,process.env.LIVEKIT_API_SECRET,);const detector = new voice.AMD(session, { participantIdentity });let result: voice.AMDCompletedEvent;await detector.start();try {try {await sip.createSipParticipant(outboundTrunkId, phoneNumber, ctx.room.name!, {participantIdentity,waitUntilAnswered: true,timeout: 45,});} catch (error) {// Only a call that failed with a SIP status, such as busy, or timed out ends here.// Other errors, such as a wrong trunk ID, propagate.const callFailed =error instanceof TwirpError && error.metadata?.sip_status_code !== undefined;const timedOut = error instanceof Error && error.name === 'TimeoutError';if (!callFailed && !timedOut) {throw error;}ctx.shutdown('call not answered');return;}// The call may end just before waitUntilAnswered returns.if (!ctx.room.remoteParticipants.has(participantIdentity)) {ctx.shutdown('participant missing');return;}result = await detector.execute();} finally {await detector.aclose();}logger.info({ category: result.category, reason: result.reason }, 'amd completed');if (result.isError || result.reason === voice.AMDReason.PARTICIPANT_DISCONNECTED) {ctx.shutdown(result.reason);} else if (result.voicemailMessagePlayed && result.category !== voice.AMDCategory.HUMAN) {ctx.shutdown('voicemail completed');} else if (result.category === voice.AMDCategory.MACHINE_UNAVAILABLE) {ctx.shutdown('machine unavailable');}
The examples use a stored outbound trunk (sip_trunk_id in Python, the first argument of createSipParticipant in Node.js). You can also use inline trunk configuration. To learn more, see Outbound trunk. The examples work with any SIP provider. To use Twilio, see Create and configure a Twilio SIP trunk.
Twilio Connector
The Twilio Connector bridges a Twilio call into the room over a media stream instead of SIP. The connector participant publishes audio only after the callee answers. Place the call first, wait for the audio track of the participant, and then start AMD.
Also turn off the acoustic echo cancellation (AEC) warmup. During the warmup, the callee can't interrupt the agent. The session skips the warmup for outbound SIP calls, but it can't tell that a connector call is outbound.
import asynciofrom xml.sax.saxutils import quoteattrfrom livekit import api, rtcfrom livekit.agents import AMD, AgentSession, utilssession = AgentSession(# ... your STT, LLM, and TTSaec_warmup_duration=None,)await session.start(agent=MyAgent(), room=ctx.room)connect = await ctx.api.connector.connect_twilio_call(api.ConnectTwilioCallRequest(twilio_call_direction=api.ConnectTwilioCallRequest.TwilioCallDirection.TWILIO_CALL_DIRECTION_OUTBOUND,room_name=ctx.room.name,participant_identity=participant_identity,))twiml = f"<Response><Connect><Stream url={quoteattr(connect.connect_url)}/></Connect></Response>"# Place the call through the Twilio Calls API with this TwiML.await place_twilio_call(to=phone_number, from_=twilio_number, twiml=twiml)try:await asyncio.wait_for(utils.wait_for_track_publication(ctx.room, identity=participant_identity, kind=rtc.TrackKind.KIND_AUDIO),timeout=45,)except asyncio.TimeoutError:ctx.shutdown("call not answered")returnasync with AMD(session, participant_identity=participant_identity) as detector:result = await detector.execute()
import { voice, waitForTrackPublication } from '@livekit/agents';import { TrackKind } from '@livekit/rtc-node';import { ConnectTwilioCallRequest_TwilioCallDirection, ConnectorClient } from 'livekit-server-sdk';const session = new voice.AgentSession({// ... your STT, LLM, and TTSaecWarmupDuration: null,});await session.start({ agent: new MyAgent(), room: ctx.room });const connector = new ConnectorClient(process.env.LIVEKIT_URL!,process.env.LIVEKIT_API_KEY,process.env.LIVEKIT_API_SECRET,);const { connectUrl } = await connector.connectTwilioCall({twilioCallDirection: ConnectTwilioCallRequest_TwilioCallDirection.OUTBOUND,roomName: ctx.room.name!,participantIdentity,});const streamUrl = connectUrl.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');const twiml = `<Response><Connect><Stream url="${streamUrl}"/></Connect></Response>`;// Place the call through the Twilio Calls API with this TwiML.await placeTwilioCall({ to: phoneNumber, from: twilioNumber, twiml });try {await waitForTrackPublication({room: ctx.room,identity: participantIdentity,kind: TrackKind.KIND_AUDIO,signal: AbortSignal.timeout(45_000),});} catch {ctx.shutdown('call not answered');return;}const detector = new voice.AMD(session, { participantIdentity });let result: voice.AMDCompletedEvent;await detector.start();try {result = await detector.execute();} finally {await detector.aclose();}
Twilio reports an unanswered call only through status webhooks, so the examples cap the wait for the answer. Handle the result as you would for a SIP call. For the Twilio Calls API request and for ending the Twilio call on shutdown, see the full examples in Additional resources.
Other participants
AMD works with any participant that publishes audio. After AMD starts, it waits 5 seconds for the audio track of the participant. If the track doesn't arrive in that time, AMD completes with participant_missing. If the participant publishes audio only after the call is answered, start AMD after its audio track arrives, as in the Twilio Connector example.
Completion
AMD completes when one of these happens. The reason field of the result tells you which one:
| Reason | Trigger |
|---|---|
finished | A human or machine-unavailable prediction, or a prediction that enters a stage you handle yourself. |
max_uncertain_turns | Too many consecutive uncertain predictions (3 by default). |
inference_timeout | Too many classifications in a row passed their deadline (3 by default). |
idle_timeout | No speech or agent activity for the idle timeout (10 seconds by default), or for the voicemail idle timeout in the machine-vm stage. After a wait prediction, such as hold music, the idle timer pauses until the next prediction. |
timeout | The overall timeout (60 seconds by default) passed since AMD started listening. |
participant_missing | No participant or audio track arrived within 5 seconds. |
participant_disconnected | The participant disconnected, or the room disconnected before the participant joined. |
agent_changed | The session switched to a different agent while AMD was active. |
internal_error | A background task or a prediction listener raised an error. |
cancelled | AMD was closed, or the session closed, before AMD completed. |
The category field of the result is the stage when AMD completed. If the voicemail message played and the mailbox then said goodbye, the category is the stage before it, such as machine-vm, not machine-unavailable.
The is_error field of the result (isError in Node.js) is true when AMD stopped without detecting the call. The reasons are internal_error, participant_missing, agent_changed, and cancelled.
After AMD completes, the session replies to later turns as usual. AMD doesn't end the call. If the category is machine-unavailable, or if is_error is true, end the call in your own code, as the SIP call example shows.
Handle a stage yourself
Set the screening, voicemail, or IVR instructions to None in Python or null in Node.js to handle that stage in your own code. When the call enters that stage, AMD completes with reason finished and the stage as the category. The agent doesn't reply to that turn, and AMD cancels pending speech. Before the next participant turn, hang up or continue the call in your own code, for example with a handoff to another agent.
For example, to hang up at the first voicemail prediction instead of leaving a message:
async with AMD(session, voicemail_instructions=None) as detector:# Create the SIP participant here.result = await detector.execute()if result.category is AMDCategory.MACHINE_VM:ctx.shutdown("voicemail")
const detector = new voice.AMD(session, { voicemailInstructions: null });await detector.start();try {// Create the SIP participant here.const result = await detector.execute();if (result.category === voice.AMDCategory.MACHINE_VM) {ctx.shutdown('voicemail');}} finally {await detector.aclose();}
To change what the agent says in a stage, pass your own instructions instead. For example, pass a voicemail script that your compliance team approved as the voicemail instructions.
Let the agent speak first
By default, the callee speaks first, and the agent replies after AMD classifies the callee's first turn. To have the agent speak first, set an opening. Use fixed text, which the agent says as written, or instructions for a reply that the agent generates. Set at most one of the two.
async with AMD(session, opening_text="Hi, this is Alex from Acme Dental.") as detector:# Create the SIP participant here.result = await detector.execute()
const detector = new voice.AMD(session, { openingText: 'Hi, this is Alex from Acme Dental.' });await detector.start();try {// Create the SIP participant here.const result = await detector.execute();} finally {await detector.aclose();}
The opening follows these rules:
- Start: The opening starts when AMD starts listening. For a SIP participant with the default answer wait, that is after the call is answered.
- Callee first: If the callee is already speaking, or starts to speak before the opening plays, AMD drops the opening and doesn't retry it. The callee's turn gets a normal reply.
- Other replies: The opening is the only speech that plays before AMD classifies a turn. After it plays, the session's normal interruption handling applies.
- No other early speech: Don't also start speech before AMD, such as a reply in
on_enter(onEnterin Node.js). AMD holds that speech, and the opening waits behind it. - Models: Fixed text needs a TTS model. In Python, a realtime model that supports
say()also works. A generated opening needs an LLM or a realtime model, and it can't call tools. With a realtime model, a cancelled opening can stay in the model's server-side history.
Events
AMD emits events while it runs. Use them for logging and analytics. Only the execute() method and the stage instructions control the call. The table uses Python field names, and durations are in seconds. In Node.js, the fields use camelCase, such as turnId and voicemailMessagePlayed, and durations such as speechDuration, delay, and inferenceDuration are in milliseconds.
| Event | Description |
|---|---|
amd_prediction | An AMDPredictionEvent for each classified turn, with turn_id, category, stage (the stage after this prediction), reason, transcript, speech_duration, delay (time from the end of the turn to the prediction), and inference_duration. A turn that a newer turn replaces before its prediction arrives gets no event, so turn IDs can skip numbers. For the reason values, see the list after this table. |
amd_menu_observed | An AMDMenuObservedEvent for each IVR menu that AMD extracts, with the menu text and its options (label, dtmf, spoken_response). This event is for observability. AMD doesn't act on it. |
amd_completed | An AMDCompletedEvent with category, reason, voicemail_message_played, last_prediction, and is_error. The execute() method returns this event. |
The reason field of an amd_prediction event is one of these values:
prediction: The classifier returned a result.reused: An empty turn reused the last prediction.inference_timeout: The classification passed its deadline.inference_error: The classification failed.
A timeout or an error gives an uncertain prediction. Only timeouts count toward the maximum number of inference timeouts.
from livekit.agents import AMD, AMDPredictionEventdetector = AMD(session, participant_identity=participant_identity)@detector.on("amd_prediction")def on_prediction(event: AMDPredictionEvent) -> None:logger.info("amd prediction", extra={"category": event.category, "stage": event.stage})async with detector:...
const detector = new voice.AMD(session, { participantIdentity });detector.on('amd_prediction', (event) => {logger.info({ category: event.category, stage: event.stage }, 'amd prediction');});await detector.start();try {// ...} finally {await detector.aclose();}
Predictions also appear in Agent Console as ANSWERING MACHINE DETECTION events.
Models
AMD uses two models: a classifier for each turn (an LLM or a decision model), and its own streaming STT.
AMD runs its STT on the participant audio, in addition to the session STT. The classifier gets both transcripts of each turn. Two STT models make different errors on short, noisy phone audio, and either transcript can be empty or late. With both, the classifier has more to go on. If the AMD STT fails, AMD uses the session transcript alone.
On LiveKit Cloud, AMD uses these defaults through LiveKit Inference:
- LLM:
google/gemma-4-31b-it - STT:
cartesia/ink-whisper
You can change either model:
llm: A LiveKit Inference model ID string (see LLM models), anLLMinstance, or a decision model that supports choice decisions. With a decision model, AMD doesn't extract IVR menus. PassNonein Python ornullin Node.js to use the agent's own LLM. The LLM must support required function calls.stt: A LiveKit Inference model ID string (see STT models) or a streamingSTTinstance. PassNonein Python ornullin Node.js to use only the session transcripts.
AMD doesn't close models that you pass in. It closes models that it creates from strings.
Realtime models
Your agent can use a realtime model when the built-in turn detection of the model is off and the model supports per-response tool choice and client-controlled tool replies. The session must have an STT, or AMD must have its own STT. A realtime model can't be the AMD classifier. If you pass None or null as the AMD LLM, or if AMD can't use the LiveKit Inference defaults, the agent must use an LLM.
Parameters
llmLLM | DecisionModel | str | NoneClassifier model. If not set, AMD uses google/gemma-4-31b-it through LiveKit Inference when LiveKit Cloud credentials are available, and otherwise the agent's own LLM. Pass None to always use the agent's own LLM. To learn more, see Models.
sttSTT | str | NoneStreaming STT for AMD. If not set, AMD uses cartesia/ink-whisper through LiveKit Inference when LiveKit Cloud credentials are available, and otherwise only the session transcripts. Pass None to always use only the session transcripts.
participant_identitystrIdentity of the callee participant. If not set, AMD listens to the participant that the room I/O of the session links. Set this in rooms with other participants. When set, AMD also links the room I/O of the session to this participant.
wait_until_answeredboolDefault: TrueFor a SIP participant, wait until the call is answered before AMD starts listening, and discard audio before the answer. The overall timeout starts at the answer. When False, AMD and the agent hear early media that the SIP provider sends before the answer. This option is separate from the wait_until_answered field of CreateSIPParticipantRequest.
screening_instructionsstr | NoneReply instructions in the machine-screening stage. The default tells the agent to answer the screening questions briefly with who it is and why it's calling. Set to None to make AMD complete when the call enters screening. To learn more, see Handle a stage yourself.
voicemail_instructionsstr | NoneInstructions for the voicemail message. The default tells the agent to leave one concise message with who it is, why it's calling, and the next step. Set to None to make AMD complete at the first voicemail prediction, without a message.
ivr_instructionsstr | NoneReply instructions in the machine-ivr stage. The default tells the agent to choose an option with send_dtmf_events or a short spoken answer, based on the purpose of the call. Set to None to make AMD complete when the call enters an IVR, without a reply.
human_instructionsstr | NoneInstructions for the reply to the first human turn after a machine stage. The default tells the agent that a person answered and that earlier automated prompts no longer apply. Set to None to keep the agent's own instructions.
opening_textstr | NoneFixed text that the agent says first, when AMD starts listening. Requires a TTS model or a realtime model that supports say(). Set at most one of opening_text and opening_instructions. Not set (the default), the callee speaks first. See Let the agent speak first.
opening_instructionsstr | NoneInstructions for a reply that the agent generates and says first, when AMD starts listening. The reply can't call tools. Set at most one of opening_text and opening_instructions. See Let the agent speak first.
idle_timeoutfloatDefault: 10.0Seconds without speech or agent activity before AMD completes, outside the machine-vm stage. After a wait prediction, such as hold music, the timer pauses until the next prediction.
voicemail_idle_timeoutfloatDefault: 10.0Seconds without speech or agent activity before AMD completes in the machine-vm stage. The timer restarts after the voicemail message plays, so the agent can answer a menu that follows the message.
timeoutfloatDefault: 60.0Maximum seconds from the start of listening until AMD completes. Raise it to get through long call screening, IVR menus, or hold queues.
inference_timeoutfloatDefault: 2.0Deadline in seconds for each classification. A turn without a result by the deadline gets an uncertain prediction and counts toward max_inference_timeouts.
machine_silence_thresholdfloatDefault: 1.5Seconds of participant silence before a reply plays in a machine stage. 0 turns off the wait. With an STT-LLM-TTS pipeline, reply generation starts during the wait, so the wait doesn't add model latency. A realtime model starts to generate only after the silence.
max_uncertain_turnsintDefault: 3Consecutive uncertain predictions before AMD completes. After a menu or call screening, the first human prediction also counts as uncertain.
max_inference_timeoutsintDefault: 3Consecutive classification timeouts before AMD completes. A classification that returns in time resets the count.
Times are in milliseconds.
llmLLM | DecisionModel | string | nullClassifier model. If not set, AMD uses google/gemma-4-31b-it through LiveKit Inference when LiveKit Cloud credentials are available, and otherwise the agent's own LLM. Pass null to always use the agent's own LLM. To learn more, see Models.
sttSTT | string | nullStreaming STT for AMD. If not set, AMD uses cartesia/ink-whisper through LiveKit Inference when LiveKit Cloud credentials are available, and otherwise only the session transcripts. Pass null to always use only the session transcripts.
participantIdentitystringIdentity of the callee participant. If not set, AMD listens to the participant that the room I/O of the session links. Set this in rooms with other participants. When set, AMD also links the room I/O of the session to this participant.
waitUntilAnsweredbooleanDefault: trueFor a SIP participant, wait until the call is answered before AMD starts listening, and discard audio before the answer. The overall timeout starts at the answer. When false, AMD and the agent hear early media that the SIP provider sends before the answer. This option is separate from the waitUntilAnswered option of createSipParticipant.
screeningInstructionsstring | nullReply instructions in the machine-screening stage. The default tells the agent to answer the screening questions briefly with who it is and why it's calling. Set to null to make AMD complete when the call enters screening. To learn more, see Handle a stage yourself.
voicemailInstructionsstring | nullInstructions for the voicemail message. The default tells the agent to leave one concise message with who it is, why it's calling, and the next step. Set to null to make AMD complete at the first voicemail prediction, without a message.
ivrInstructionsstring | nullReply instructions in the machine-ivr stage. The default tells the agent to choose an option with send_dtmf_events or a short spoken answer, based on the purpose of the call. Set to null to make AMD complete when the call enters an IVR, without a reply.
humanInstructionsstring | nullInstructions for the reply to the first human turn after a machine stage. The default tells the agent that a person answered and that earlier automated prompts no longer apply. Set to null to keep the agent's own instructions.
openingTextstring | nullFixed text that the agent says first, when AMD starts listening. Requires a TTS model. Set at most one of openingText and openingInstructions. Not set (the default), the callee speaks first. See Let the agent speak first.
openingInstructionsstring | nullInstructions for a reply that the agent generates and says first, when AMD starts listening. The reply can't call tools. Set at most one of openingText and openingInstructions. See Let the agent speak first.
idleTimeoutnumberDefault: 10000Milliseconds without speech or agent activity before AMD completes, outside the machine-vm stage. After a wait prediction, such as hold music, the timer pauses until the next prediction.
voicemailIdleTimeoutnumberDefault: 10000Milliseconds without speech or agent activity before AMD completes in the machine-vm stage. The timer restarts after the voicemail message plays, so the agent can answer a menu that follows the message.
timeoutnumberDefault: 60000Maximum milliseconds from the start of listening until AMD completes. Raise it to get through long call screening, IVR menus, or hold queues.
inferenceTimeoutnumberDefault: 2000Deadline in milliseconds for each classification. A turn without a result by the deadline gets an uncertain prediction and counts toward maxInferenceTimeouts.
machineSilenceThresholdnumberDefault: 1500Milliseconds of participant silence before a reply plays in a machine stage. 0 turns off the wait. With an STT-LLM-TTS pipeline, reply generation starts during the wait, so the wait doesn't add model latency. A realtime model starts to generate only after the silence.
maxUncertainTurnsnumberDefault: 3Consecutive uncertain predictions before AMD completes. After a menu or call screening, the first human prediction also counts as uncertain.
maxInferenceTimeoutsnumberDefault: 3Consecutive classification timeouts before AMD completes. A classification that returns in time resets the count.
Limitations
AMD has these limitations:
- AMD runs at the start of the call. It doesn't detect a transfer to voicemail later in the call.
- While AMD is active,
say(),generate_reply(), andupdate_agent()(generateReply()andupdateAgent()in Node.js) raise an error, and AMD cancels handoffs that tools return. To have the agent speak first, set an opening. Start handoffs after AMD completes. - You can't start AMD while an
AgentTaskruns. Finish the task first. - While AMD is active, it turns on interruptions for the session and the agent, even if you turned them off. AMD restores your settings when it completes.
- A split greeting at the start of the call, such as "Hi!" and then a voicemail greeting, can still complete as
humanon the first turn. - Console mode can't place a phone call, so the AMD examples don't run in console mode.
Migrate from single-turn AMD
Multi-turn AMD replaces single-turn AMD in both SDKs. To migrate, make these changes:
- Handle the result after AMD completes. The
execute()method returns when AMD completes, which can take several turns. To see each prediction, listen foramd_predictionevents. - Remove your own voicemail and IVR handling. The agent now handles these stages. To keep your own handling for a stage, set its instructions to
Nonein Python ornullin Node.js. - Update code that checks the category. The result category can now be
machine-screening. Inamd_predictionevents, a turn can also have the newwaitcategory. - Check the classifier. The default LLM is
google/gemma-4-31b-it. To use another model, setllm. - Expect a result when AMD closes early. If AMD closes before it completes,
execute()returns a result with reasoncancelled. It no longer raisesRuntimeErrorin Python or rejects in Node.js. - Create a new
AMDfor each call. AnAMDinstance runs once. A second run raises an error.
- Read
categoryinstead ofis_machine. Theexecute()method returns anAMDCompletedEvent, not anAMDPredictionEvent. - Update
reasonchecks. Thereasonfield is now anAMDReasonvalue. The valuesllm,short_greeting,detection_timeout, andno_speech_timeoutno longer exist. - Turn off session IVR detection. AMD raises
ValueErrorwhen the session hasivr_detection=True. - Remove the old parameters. These parameters no longer exist:
detection_options,ivr_detection,interrupt_on_machine,wait_until_finished, andsuppress_compatibility_warning. Use the timeouts and the stage instructions.
- Call
start()andaclose(). Callawait detector.start()before you create the SIP participant, andawait detector.aclose()in afinallyblock. - Read
categoryinstead ofisMachine. Theexecute()method returns anAMDCompletedEvent, not anAMDPredictionEvent. - Update prediction event fields.
speechDurationMsis nowspeechDuration, anddelayMsis nowdelay. Both stay in milliseconds.rawResponseandisMachineno longer exist. Thereasonfield is now avoice.AMDReasonvalue, not free text. - Remove the old options. These options no longer exist:
interruptOnMachine,humanSpeechThresholdMs,humanSilenceThresholdMs,noSpeechTimeoutMs,detectionTimeoutMs,waitUntilFinished,maxEndpointingDelayMs,prompt, andsuppressCompatibilityWarning. Use the timeouts and the stage instructions. - Rename
machineSilenceThresholdMs. The option is nowmachineSilenceThreshold. The value stays in milliseconds.
Additional resources
AMD example (Python)
Outbound voice agent that places a call with multi-turn AMD and ends the job after a voicemail message.
AMD example (Node.js)
Outbound voice agent that places a call with multi-turn AMD and ends the job after a voicemail message.
AMD with Twilio Connector (Python)
The same outbound agent, with the call placed through Twilio and the Twilio Connector instead of a SIP trunk.
AMD with Twilio Connector (Node.js)
The same outbound agent, with the call placed through Twilio and the Twilio Connector instead of a SIP trunk.
DTMF and IVR navigation
Send and receive DTMF tones, and navigate IVR systems.
Outbound calls
Create SIP participants and place outbound calls that AMD can classify.