Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Inline subagents split one large voice-based agent prompt into focused stages inside the same agent, so each turn uses only the active stage's instructions and tools. This article explains the problems that inline subagents solve and how they help, and then walks you through building and testing a voice-based agent with three inline subagents. To compare inline subagents with delegate subagents, see Subagents in voice-based agents.
Important
Items marked preview in this article are currently in preview. This preview is provided without a service-level agreement, and Microsoft doesn't recommend it for production workloads. Certain features might not be supported or might have constrained capabilities. For more information, see Supplemental Terms of Use for Microsoft Azure Previews.
Tip
The microsoft/voice-agent repository on GitHub contains the complete sample for this article and a local playground that you run on your computer. In the playground, you can edit inline subagents and their handoff conditions as a visual graph, publish the voice-based agent to your project, and talk to it to test handoffs. The playground connects to your own Foundry project, so you first need a Foundry project with access to voice-based agents. For setup steps, see the playground README.
Challenges of one large prompt
Most voice-based agents start with one prompt that holds every role, rule, and tool. One prompt works well for a simple conversation. As the business logic grows, the following problems appear:
- Higher cost per turn. Every response reads the whole prompt, including rules for stages that the call never reaches.
- Slower first replies. A longer prompt gives the model more input to process before it starts to speak.
- Wrong tool calls. Every attached tool is a valid choice on every turn. As the tool list grows, the model is more likely to call the wrong tool, call a tool when it shouldn't, or invent tool arguments.
- Unclear conversation stages. Rules for greeting, verification, resolution, and wrap-up are mixed in one prompt. A rule for one stage can change behavior in another, and the prompt can grow past the model's instruction limit.
- Hard to test and debug. Any edit can affect any stage, so each change requires retesting the whole call. When a call fails, it's hard to trace the failure to one rule or one tool.
- No view of where callers drop off. One prompt doesn't report which part of it the conversation is following. When a caller hangs up, gives up, or a call fails, you can't tell at which step it happened, so you don't know which part of the flow to improve.
Inline subagents address each of these problems. Each handoff between subagents also has a cost, which the following sections describe. Some tasks, such as a multistep search, take longer than one conversational turn. For those tasks, use a delegate subagent instead.
How inline subagents help
Inline subagents split one large prompt into stages, and each stage is a focused subagent. The following sections describe how the split works and the benefits that it brings.
How inline subagents split one prompt
An inline subagent is a set of instructions, tools, and voice settings that you define, own, and version inside the voice-based agent. It isn't a separate agent resource. At any time, one inline subagent is active. The model follows the shared top-level instructions plus the active subagent's instructions, and it can call only the active subagent's customer tools, the tools that you attach to that subagent.
To move the conversation to another stage, the model calls a handoff tool that the service generates from the active subagent's handoff conditions. The target subagent then becomes active for subsequent turns. The live session, WebSocket connection, media path, and conversation history continue across the handoff.
Inline subagents organize the instructions of one large prompt by goal. Each subagent gets a short prompt for one stage of the conversation. Handoff conditions describe when the conversation moves to another stage. By default, the shared top-level instructions, such as the persona and global rules, are placed before every subagent's own instructions.
In this example, the triage subagent is $entrypoint, the subagent that's active when the session starts. Each subagent declares its own tools, and its handoff conditions list the subagents that it can hand off to. A subagent can also override the output voice, so the caller hears when a different role takes over.
Note
An inline handoff changes which behavior of the voice-based agent answers the caller. It doesn't transfer a phone call to another number or to a human agent. The caller stays connected to the same voice-based agent and session.
Benefits of inline subagents
Each benefit in the following table solves one of the challenges of one large prompt.
| Benefit | Challenge it solves | Why it works |
|---|---|---|
| Lower cost per turn | Higher cost per turn | Within a stage, each turn reads only the shared instructions and the active subagent's instructions. |
| Faster first replies | Slower first replies | The first reply of the call reads only the entry subagent's instructions as new input, not the whole prompt. |
| Fewer wrong tool calls | Wrong tool calls | The model can call only the active subagent's tools. For example, a billing tool isn't available while the authentication subagent is still verifying the caller. |
| Clear stages and larger business logic | Unclear conversation stages | Each stage has its own instructions, and handoff conditions state when the conversation moves on. A rule for one stage doesn't change behavior in another, and the total business logic can be larger than one prompt allows. |
| Easier testing and debugging | Hard to test and debug | Each behavior and tool belongs to one subagent, so you fix and retest one subagent. |
| Visibility into where callers drop off | No view of where callers drop off | The session reports the active subagent and each handoff, so every call shows the stages that it went through. |
The effect on your agent depends on your instructions, tools, call length, number of handoffs, and model. Test a split with representative calls before you rely on it. The following sections describe the cost, latency, debugging, and drop-off benefits in more detail, including the cost of a handoff.
Lower cost per turn
For every response, the model reads the active instructions plus the conversation so far. With one prompt, every response rereads every rule, including rules for stages that the call never reaches. Input that the model reads through the prompt cache is billed at a lower rate, but it's still billed. By using inline subagents, each response within a stage reads only the shared instructions and the active subagent's instructions, so every turn carries less input.
A handoff has a cost. The prompt cache reuses input only when it's identical to the beginning of an earlier request. A handoff changes the active instructions and tools. The shared instructions can still come from the cache, but the target subagent's instructions and the conversation that follows them are new input. With one prompt, that input could come from the cache. The longer the conversation before a handoff, the more input the reply after it processes again. For the requirements that determine when input comes from the cache, see Prompt caching.
The savings within stages outweigh the cost of handoffs as your business logic grows:
- Calls skip the branches they don't take. When calls follow one of several paths, such as billing or device support, and the entry point routes them on the first turn, a call never reads the other paths' rules.
- Larger rules save more. The more instructions each stage holds, the more input every turn in the other stages avoids.
- Calls that stay in a stage save more. Every turn within a stage saves input, and a stage with several turns spreads the cost of its handoff across them.
Inline subagents also let your business logic exceed the model's instruction limit, because only each subagent's effective instructions must fit within it. One prompt can't do that.
To get the most savings, split where the goal of the call changes, and use the fewest subagents that fit. For guidance, see Design inline subagents.
Faster first replies
Before the model generates audio, it processes its input. Input that isn't in the prompt cache takes longer to process than cached input:
- The first reply of the call reads the entry subagent's instructions as new input. Shorter instructions give it less to process than one large prompt, so it can start sooner.
- The first reply after a handoff reads the target subagent's instructions and the conversation so far as new input. It can start later than a reply from one cached prompt, and the delay grows with the length of the conversation before the handoff.
- Later replies within the same subagent can read the instructions from the cache, as they can with one prompt.
To keep the conversation fast, hand off where the goal of the call changes, place short stages early in the call while the conversation is still short, and keep handoff turns short. For guidance, see Design inline subagents.
Easier testing and debugging
Splitting gives each behavior, tool, and route a single owner:
- Locate the problem. The session state reports the active subagent, and handoff events report each transition. A failure maps to one subagent or one handoff condition instead of the whole prompt.
- Fix one subagent, and retest one subagent. Edit the subagent that owns the behavior, create a new version, and then retest that subagent and the handoffs into and out of it. Changes to the shared top-level instructions or to handoff conditions still need broader tests.
Visibility into where callers drop off
With one prompt, the session doesn't report which part of the prompt the conversation is following. When a caller hangs up early, asks for a person, or a call fails, you can't tell at which step it happened.
With inline subagents, every stage has an ID. The session state reports the active subagent, and handoff events report each transition from one subagent to the next. In your application, record these values with each call, for example in your logs or traces, to learn how callers move through your agent. For the tracing and monitoring options of voice-based agents, see Voice agent tracing, monitoring, and evaluation.
- Find where callers drop off. The last active subagent shows the stage that a call reached before the caller hung up.
- Find where calls fail. Map an aborted handoff or a failed tool call to the subagent that was active at that moment. If your application detects other signals, such as a request for a person, record the active subagent with them too.
- Compare stages across calls. Count how many calls reach and complete each stage to find the stage where most callers drop off.
Use these findings to decide which subagent's instructions or tools to improve first. For the event names, see Read handoff events.
Prerequisites
- A Foundry project with access to voice-based agents.
- Foundry User role on the project.
Important
The Foundry RBAC roles were recently renamed. Foundry User, Foundry Owner, Foundry Account Owner, and Foundry Project Manager were previously named Azure AI User, Azure AI Owner, Azure AI Account Owner, and Azure AI Project Manager. You might still see the previous names in some places while the rename rolls out. The role IDs and core permissions are unchanged by the rename.
- Python 3.11 or later.
- The Azure CLI, signed in with
az login. - A realtime voice model available to the project. The example uses
gpt-realtime. - A microphone and speakers or headphones.
- Backend authorization for every sensitive tool operation that you add.
Important
A handoff condition is natural-language guidance to the model. It isn't an authentication or authorization rule. A sensitive tool must verify identity, permissions, and business requirements even when its inline subagent is active. The conversation history continues across handoffs, so don't use inline subagents to isolate tenants or confidential data from each other.
Set up your environment
Install version 2.11.0 or later of the Azure AI Projects client library with the voice extra, Azure Identity, and PyAudio in the same Python environment. Version 2.11.0 is the first version that includes the inline subagent and handoff models. PyAudio captures microphone audio and plays the agent's response.
python -m pip install \
"azure-ai-projects[voice]>=2.11.0" azure-identity pyaudio
PyAudio builds against the PortAudio library. If the PyAudio installation fails, install PortAudio first, for example sudo apt-get install portaudio19-dev on Ubuntu or brew install portaudio on macOS, and then rerun the command.
Set your project endpoint and a new agent name. Find the endpoint on the Overview page of your project in the Foundry portal. Use a new name so that the example doesn't create a version of an agent used by another application.
In Bash:
export FOUNDRY_PROJECT_ENDPOINT=\
"https://<account>.services.ai.azure.com/api/projects/<project>"
export FOUNDRY_VOICE_AGENT_NAME="appointment-voice-agent"
In PowerShell:
$env:FOUNDRY_PROJECT_ENDPOINT =
"https://<account>.services.ai.azure.com/api/projects/<project>"
$env:FOUNDRY_VOICE_AGENT_NAME = "appointment-voice-agent"
Define the inline subagents
The following example builds one voice-based agent with three inline subagents. A front-desk subagent greets the caller, a scheduling subagent collects an appointment request, and a closing subagent ends the interaction. The example uses no customer tools, so it focuses on the handoffs between stages. The complete example, with a README, is in the handoff_example folder on GitHub.
Create create_inline_voice_agent.py. The script builds the voice agent definition with SDK models, creates an agent version, and reads back the saved inline configuration. VoiceAgentInlineSubagentConfig sets subagent_config.subagent_type to inline. For every property, see Configuration reference.
import os
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
InlineVoiceSubagent,
RealtimeAudioFormatsAudioPcm,
VoiceAgentAudioConfig,
VoiceAgentAudioInputConfig,
VoiceAgentAudioOutputConfig,
VoiceAgentDefinition,
VoiceAgentHandoffCondition,
VoiceAgentHandoffPolicy,
VoiceAgentInlineSubagentConfig,
VoiceAgentInputTranscription,
VoiceAgentServerVadTurnDetection,
VoiceAgentVoiceConfig,
)
from azure.identity import DefaultAzureCredential
endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"]
agent_name = os.environ["FOUNDRY_VOICE_AGENT_NAME"]
definition = VoiceAgentDefinition(
model_type="managed",
model="gpt-realtime",
instructions=(
"You are the voice assistant for a clinic front desk. Follow the shared "
"privacy policy and speak briefly. Never claim that an appointment has "
"been booked, changed, or cancelled."
),
output_modalities=["audio"],
audio=VoiceAgentAudioConfig(
input=VoiceAgentAudioInputConfig(
format=RealtimeAudioFormatsAudioPcm(rate=24000),
turn_detection=VoiceAgentServerVadTurnDetection(
threshold=0.5,
prefix_padding_ms=300,
silence_duration_ms=1000,
),
transcription=VoiceAgentInputTranscription(model="azure-speech"),
),
output=VoiceAgentAudioOutputConfig(
format=RealtimeAudioFormatsAudioPcm(rate=24000),
voice="en-US-AvaNeural",
voice_type="azure-standard",
),
),
subagent_config=VoiceAgentInlineSubagentConfig(
subagents=[
InlineVoiceSubagent(
id="$entrypoint",
display_description="Front desk and request triage",
inherit_base_instructions=True,
instructions=(
"Greet the caller and identify the request. Answer general "
"questions. This stage can't help with appointments: never "
"ask for appointment details here. Routes: scheduling, as "
"soon as the caller mentions an appointment. When you hand "
"off, call the handoff tool without speaking first."
),
tools=[],
parallel_tool_calls=False,
handoff_conditions=[
VoiceAgentHandoffCondition(
id="entry_to_scheduling",
target="scheduling",
condition="The caller wants help with an appointment.",
cancel_on_interruption=True,
target_response="auto",
)
],
),
InlineVoiceSubagent(
id="scheduling",
display_description="Appointment scheduling",
inherit_base_instructions=True,
instructions=(
"Ask whether the caller wants to book, reschedule, or cancel. "
"Collect their preferred date and summarize the request. "
"Explain that this demo doesn't change any appointments. "
"Ask the caller to confirm the summary and answer any "
"follow-up questions. This stage doesn't say goodbye. "
"Routes: end, as soon as the caller confirms the summary "
"and is ready to finish. When you hand off, call the "
"handoff tool without speaking first."
),
tools=[],
parallel_tool_calls=False,
audio_output=VoiceAgentVoiceConfig(
voice="en-US-JennyNeural",
voice_type="azure-standard",
),
handoff_conditions=[
VoiceAgentHandoffCondition(
id="scheduling_to_end",
target="end",
condition=(
"The caller has confirmed the summarized appointment "
"request and is ready to finish the conversation."
),
target_response="auto",
)
],
),
InlineVoiceSubagent(
id="end",
display_description="Request summary and goodbye",
inherit_base_instructions=True,
instructions=(
"Briefly repeat the confirmed request and remind the caller "
"that this demo hasn't changed any appointments. Thank them "
"and say goodbye. Don't ask further questions or offer "
"additional help."
),
tools=[],
handoff_conditions=[],
),
],
handoff_policy=VoiceAgentHandoffPolicy(max_transfers=8, max_attempts=10),
),
)
with (
DefaultAzureCredential() as credential,
AIProjectClient(
endpoint=endpoint,
credential=credential,
allow_preview=True,
) as project_client,
):
created = project_client.agents.create_version(
agent_name=agent_name,
definition=definition,
description="Appointment intake with inline subagents",
)
readback = project_client.agents.get_version(
agent_name=agent_name,
agent_version=created.version,
)
saved_config = readback.definition.subagent_config
if not isinstance(saved_config, VoiceAgentInlineSubagentConfig):
raise RuntimeError("The saved version didn't preserve inline mode.")
print(f"Created '{created.name}', version {created.version}")
for subagent in saved_config.subagents:
voice = subagent.audio_output.voice if subagent.audio_output else "default"
targets = [route.target for route in subagent.handoff_conditions or []]
print(f"{subagent.id}: voice={voice}, routes={targets}")
policy = saved_config.handoff_policy
print(f"max_transfers={policy.max_transfers}, max_attempts={policy.max_attempts}")
Reference: Azure AI Projects client library for Python | create_inline_voice_agent.py on GitHub.
The example follows one path: $entrypoint -> scheduling -> end.
- All three subagents inherit the shared top-level instructions.
- Each
handoff_conditionslist describes routes out of its containing subagent.targetnames the subagent that becomes active, andconditiontells the model when to take the route. - The shared top-level instructions describe only the persona and global rules, not the task of any stage.
- The
$entrypointandschedulinginstructions state what each stage doesn't do and list its route, so the model hands off instead of handling the next stage itself. They also tell the model to call the handoff tool without speaking first, which keeps handoff turns short. parallel_tool_callsmust beFalseon every subagent that has outgoing handoff conditions.endhas none, so it omits the property.- The scheduling subagent uses a different voice to make the change easier to hear. Use the session state, not the voice alone, to confirm a handoff.
endis an ordinary subagent ID, not a reserved keyword. Its emptyhandoff_conditionslist makes it the last stage.- All
toolslists are empty. To book, reschedule, or cancel real appointments, add authorized backend tools to the scheduling subagent. InlineVoiceSubagentsetssourcetoinlineandinterfacetovoicefor you. Itsdisplay_descriptionproperty is sent to the service asdescription.
Create the agent version
Run the script:
python create_inline_voice_agent.py
Each run creates a new immutable version. The three inline subagents are part of this version, not separate agent resources. The script reads back the saved version and raises an error if the version isn't in inline mode. Confirm that the output lists $entrypoint, scheduling, and end, in that order, with their routes, the scheduling subagent's voice, and the handoff limits. The version number increases with each run.
Created 'appointment-voice-agent', version 1
$entrypoint: voice=default, routes=['scheduling']
scheduling: voice=en-US-JennyNeural, routes=['end']
end: voice=default, routes=[]
max_transfers=8, max_attempts=10
If Python can't import InlineVoiceSubagent or VoiceAgentInlineSubagentConfig, the service rejects the inline configuration, or the output differs, confirm that you installed version 2.11.0 or later of the client library and that your project has access to voice-based agents.
Talk to the agent and test handoffs
Create talk_to_inline_voice_agent.py. Run it on a computer with a microphone and audio output, using the same environment variables and Python environment as the creation script. The client waits for the first session.updated event, which carries the handoff state, and then streams microphone audio and prints the active subagent and each handoff event. The earlier session.created event reports handoff as null. The client library delivers each handoff event as its SDK model, such as VoiceAgentServerEventSessionHandoffStarted. The session field of session.updated arrives as a dictionary, so the client reads the handoff state through VoiceAgentSessionResponseConfig. In event and state fields, node means inline subagent: active_node_id, from_node_id, and to_node_id contain the subagent IDs from create_inline_voice_agent.py. Use headphones, and let each response finish before your next request.
import asyncio
import os
from contextlib import closing
import pyaudio
from azure.ai.projects import models
from azure.ai.projects.aio import AIProjectClient
from azure.ai.projects.aio.operations import AsyncRealtimeConnection
from azure.identity.aio import DefaultAzureCredential
RATE = 24000
CHUNK = 2400
def observe_handoff(event) -> None:
if isinstance(event, models.RealtimeServerEventSessionUpdated):
session = models.VoiceAgentSessionResponseConfig(event.session)
if session.handoff is None:
raise RuntimeError(
"The session has no handoff state. Check the saved agent "
"configuration and the client library version."
)
print(f"Active subagent: {session.handoff.active_node_id}")
elif isinstance(
event, models.VoiceAgentServerEventSessionHandoffStarted
):
print(
f"Handoff requested: {event.from_node_id} "
f"-> {event.to_node_id}"
)
elif isinstance(
event, models.VoiceAgentServerEventSessionHandoffCompleted
):
print("Handoff completed.")
elif isinstance(
event, models.VoiceAgentServerEventSessionHandoffAborted
):
if (
event.reason
== models.VoiceAgentHandoffAbortReason.USER_INTERRUPTION
):
print("Handoff cancelled by caller; source stays active.")
else:
detail = event.error.message if event.error else "no details"
raise RuntimeError(f"Handoff aborted: {detail}")
async def wait_until_ready(
connection: AsyncRealtimeConnection,
) -> None:
while True:
event = await connection.recv()
if isinstance(event, models.RealtimeServerEventError):
raise RuntimeError(event.error.message)
if isinstance(event, models.RealtimeServerEventSessionUpdated):
observe_handoff(event)
return
async def send_microphone(
connection: AsyncRealtimeConnection, stream: pyaudio.Stream
) -> None:
while True:
audio = await asyncio.to_thread(
stream.read,
CHUNK,
exception_on_overflow=False,
)
await connection.input_audio_buffer.append(audio=audio)
async def receive_audio(
connection: AsyncRealtimeConnection, stream: pyaudio.Stream
) -> None:
async for event in connection:
observe_handoff(event)
if isinstance(event, models.RealtimeServerEventResponseAudioDelta):
await asyncio.to_thread(stream.write, event.delta)
elif isinstance(
event, models.RealtimeServerEventResponseAudioTranscriptDone
):
print(f"Agent: {event.transcript}")
elif isinstance(event, models.RealtimeServerEventError):
raise RuntimeError(event.error.message)
raise ConnectionError("The voice session closed. Restart to reconnect.")
async def talk() -> None:
audio = pyaudio.PyAudio()
try:
with (
closing(audio.open(
format=pyaudio.paInt16,
channels=1,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
)) as microphone,
closing(audio.open(
format=pyaudio.paInt16,
channels=1,
rate=RATE,
output=True,
frames_per_buffer=CHUNK,
)) as speaker,
):
async with (
DefaultAzureCredential() as credential,
AIProjectClient(
endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
credential=credential,
allow_preview=True,
) as project_client,
project_client.voice_agents.realtime.connect(
agent_name=os.environ["FOUNDRY_VOICE_AGENT_NAME"],
) as connection,
):
await asyncio.wait_for(
wait_until_ready(connection), timeout=30
)
print("Connected. Ask about an appointment. Ctrl+C exits.")
async with asyncio.TaskGroup() as tasks:
tasks.create_task(send_microphone(connection, microphone))
tasks.create_task(receive_audio(connection, speaker))
finally:
audio.terminate()
asyncio.run(talk())
Reference: Azure AI Projects client library for Python | talk_to_inline_voice_agent.py on GitHub.
Run the client:
python talk_to_inline_voice_agent.py
Try the following conversation and compare the console output with the expected result. Response wording can vary because the model interprets the handoff conditions.
| Say to the agent | Expected result |
|---|---|
| "Hello. What can you help me with?" | $entrypoint stays active. |
| "I'd like to reschedule an appointment." | The client prints Handoff requested: $entrypoint -> scheduling, then Active subagent: scheduling and Handoff completed. |
| "I'd prefer Tuesday." | scheduling handles the next turn without returning to the entrypoint. |
| "What day did I just ask for?" | The scheduling subagent can use the earlier conversation history and refer to Tuesday. |
| "Yes, that summary is correct. That's all I need. Goodbye." | The client prints Handoff requested: scheduling -> end, then Active subagent: end and Handoff completed. The closing subagent summarizes the request and says goodbye. |
After the closing message finishes playing, press Ctrl+C to disconnect. Reaching end completes the conversation flow but doesn't close the session.
The demo collects a request but doesn't change an appointment. If you add backend tools, also test that they reject unauthorized actions, regardless of which subagent is active.
To test interruption recovery, the caller must speak while a handoff is still pending. By default, a handoff completes without delay, so add delay_ms=timedelta(seconds=3) to the entry_to_scheduling condition, import timedelta from datetime, and run create_inline_voice_agent.py again to create a new version. Ask about an appointment, and keep talking right after the request. Because the condition sets cancel_on_interruption: true, the client prints Handoff cancelled by caller; source stays active. Remove delay_ms when you finish testing.
Read handoff events
The session reports handoffs through the following state and events, in this order:
session.handoff.startedindicates that the model requested a handoff.session.updatedcontains the committed active subagent insession.handoff.active_node_id.session.handoff.completedindicates successful completion. Iftarget_responseisauto, the target subagent then starts its response.
If the handoff doesn't complete, session.handoff.aborted replaces the last two events, and the source subagent stays active. Its reason field contains one of the following values:
user_interruption: The caller interrupted a pending handoff whose condition setscancel_on_interruption: true.error: The service couldn't prepare the target subagent. The event can include anerrorobject with details. Your application can continue the conversation with the source subagent.
Use the committed session.updated state, not the started event by itself, to determine which inline subagent is active. If your application requests its own responses, wait for session.handoff.completed or session.handoff.aborted first. The service rejects a response request while a handoff is pending.
When a session reaches a limit in handoff_policy, the service stops offering the handoff tool for routes that it can no longer take. No event reports this, and the active subagent continues the conversation.
Configuration reference
In Python, pass subagents and handoff_policy to VoiceAgentInlineSubagentConfig, and pass that object as subagent_config of VoiceAgentDefinition, not at the root of the definition. The following tables list the property names that the service uses. The Python models use the same names, except that description is display_description on InlineVoiceSubagent. In Python, set delay_ms with datetime.timedelta.
Subagent properties
The first member of subagents must be $entrypoint, the subagent that's active when the session starts. Add from 1 through 31 more subagents after it. Every subagent, including $entrypoint, uses the following properties.
| Property | Required | Description |
|---|---|---|
id |
Yes | Identifies the inline subagent. The first member must be $entrypoint. Other IDs must match ^[a-z][a-z0-9_-]{0,63}$. |
source |
Yes | Use inline for a behavior owned and versioned with the parent voice-based agent. InlineVoiceSubagent sets this value. |
interface |
Yes | Use voice for the current inline subagent experience. InlineVoiceSubagent sets this value. |
description |
Yes | Provides display and debugging metadata. The model never reads it, so describe when to move to a subagent in the condition of each handoff that leads to it. |
model |
No | Selects a model for this subagent. Supported only with a cascaded pipeline and a compatible model. With a realtime model, all inline subagents use the voice-based agent's model. |
instructions |
No | Adds focused instructions for the inline subagent. |
inherit_base_instructions |
No | Controls whether top-level instructions are placed before this subagent's instructions. The default is true. |
tools |
No | Selects the customer tools available while this inline subagent is active. The generated handoff tool isn't part of this list, and a customer tool can't be named handoff. Omission or null selects no customer tools. |
tool_choice |
No | Controls tool selection for the active inline subagent. The default is auto. |
audio_output |
No | Overrides the output voice while this subagent is active, by using the same flat field names as top-level audio.output. Audio format settings stay session-wide, and the voice must be compatible with the session's output path. If you omit it, the subagent uses the $entrypoint voice, which is the top-level audio.output voice unless $entrypoint sets its own audio_output. |
parallel_tool_calls |
No | Controls parallel customer tool calls. The default is false. The value must be false for a subagent with outgoing handoff conditions. |
handoff_conditions |
No | Declares outgoing transitions from this inline subagent. |
A cascaded pipeline runs speech recognition, the language model, and text to speech as separate steps.
Handoff conditions
Add each outgoing handoff condition to the handoff_conditions list of its source subagent. A condition doesn't repeat a source property. You can configure up to 128 handoff conditions across the agent.
| Property | Required | Description |
|---|---|---|
id |
Yes | Provides a stable condition identifier that's unique across the voice-based agent. |
target |
Yes | Names another configured inline subagent or $entrypoint. |
condition |
Yes | Tells the model in natural language when to take this route. It's not an executable Boolean predicate. |
cancel_on_interruption |
No | Cancels a pending handoff if the caller interrupts before the target becomes active. The default is false. |
delay_ms |
No | Sets a minimum delay, from 0 through 10,000 milliseconds, before the target becomes active. The default is 0. |
transfer_message |
No | Provides a fixed announcement that the source subagent's voice speaks before the target becomes active. Supported when an Azure text to speech voice speaks the audio: in a cascaded pipeline, or with a realtime model and an Azure voice, such as the azure-standard voice in this article's example. Omit it or use null when the realtime model generates the voice itself. |
target_response |
No | Use auto to start a target response after activation, or none to wait for the next caller turn. The default is auto. |
Write each condition to describe observable caller intent or completion state, such as "The caller wants help with an appointment." The model reads only the conditions of the active subagent, so each condition must make clear when the target subagent should take over.
Handoff limits
Set handoff_policy to limit handoffs in one session.
| Property | Description |
|---|---|
max_transfers |
Limits successfully completed handoffs in one session. The supported range is 1 through 100, and the default is 16. |
max_attempts |
Limits all attempted handoffs, including failures. The supported range is 1 through 100. It defaults to max_transfers and must be greater than or equal to it. |
These limits keep an unclear condition or a cyclic route from switching subagents indefinitely. When a session reaches a limit, the active subagent continues the conversation without the routes that it can no longer take.
Design inline subagents
Base the design on the business logic of the conversation: the stages that a call goes through, the paths that calls can take, the tools and permissions that each stage needs, and the facts that must carry over between stages. The following principles are grouped by design area.
Decide whether to split
Split one prompt into inline subagents when any of the following situations applies to your conversation. Each situation is a reason to split on its own.
| Situation | How inline subagents help |
|---|---|
| A stage handles sensitive steps, such as caller verification. | Put the verification instructions and tools in a dedicated authentication subagent, usually at the start of the call. Only that subagent reads the rules for collecting and checking credentials, such as an access code, and only it can call the verification tool. After verification succeeds, it hands off to the stage that serves the caller. The other subagents don't read those rules and can't call that tool. |
| Stages need different tools or permissions. | The model can call only the active subagent's tools. For example, account tools are available only in the subagents that become active after the caller is verified. |
| Calls take one of several paths, each with its own rules. | Each path, such as billing or device support, gets its own subagents, so the rules of one path can't change the behavior of another. |
| The prompt is long, and a rule that you add doesn't reliably take effect. | In a long prompt, a new rule competes with every other rule, so the model can follow it in some calls but not in others. Repeating or emphasizing the rule makes the prompt even longer. Put the rule in the subagent that owns the behavior, where it competes only with the shared instructions and that stage's instructions. |
| The instructions don't fit within the model's instruction limit. | Only each subagent's effective instructions must fit within the limit, so your total business logic can be larger than one prompt allows. |
| Failures are hard to debug. | When many rules and tools interact in one prompt, a failure can come from any of them, and a fix for one case can break another. After a split, each behavior has one owner. The active subagent and the handoff events show which stage a failure happened in, so you fix and retest that subagent. For details, see Easier testing and debugging. |
| You need to know which stage each call reached. | The session reports the active subagent and each handoff, so you can see where calls drop off or fail. For details, see Visibility into where callers drop off. |
Note
An authentication subagent limits which instructions and tools are active. It isn't a security boundary. The conversation history, including what the caller said during verification, continues across handoffs, and your backend must still verify identity and permissions for every sensitive operation.
Keep one prompt when the rules are short, the tools are few and the same for the whole conversation, and calls don't split into separate paths, as in a simple FAQ. With one prompt, enforce any required order of business steps in your backend tools.
Split the conversation into subagents
| Principle | How to apply |
|---|---|
| Split only where something changes. | Place a boundary only where the path, the available tools or permissions, the business state, or the goal of the stage changes. Confirm a change of business state with a tool result, such as a successful identity check. Don't split at every step or at every section of your original prompt. Each boundary adds a handoff, a routing decision, and facts that must carry over. |
| Split by path first, and route early. | When calls follow one of several paths, give each path its own subagents, so the rules and tools of one path can't change the behavior of another. Route from $entrypoint as soon as the caller's need is clear, ideally on the first turn, and design each call to follow one path. |
| Use the fewest subagents that fit. | Give each subagent a meaningful stage, such as verification, billing, or wrap-up, rather than a single step. Most paths need only a few subagents. Every extra subagent adds a handoff and another point where the call can lose a fact. |
| Put small, permission-bound steps at the start. | A step that needs its own tools or permissions, such as sign-in, works well as a small subagent at the start of the call. Avoid small subagents in the middle of the call that don't change the tools, permissions, or goal. For example, to answer in the caller's language, add that rule to the existing instructions instead of adding a subagent. |
| Keep every subagent within the model's instruction limit. | A subagent's effective instructions are the inherited top-level instructions plus its own instructions. Before you create a version, measure the effective instructions of each subagent in tokens, and keep each one within the limit. |
| Keep shared rules in the top-level instructions. | Put the persona, language, and global rules, including shared safety and compliance instructions, in the top-level instructions. Keep inherit_base_instructions set to true, the default, so every subagent reads the same rules first and the prompt cache can reuse them after a handoff. For the caching requirements, see Prompt caching. Don't turn off inheritance to paste an edited copy. Don't describe the task of one stage in the shared instructions: every subagent reads them and can treat that task as its own instead of handing off. |
Merge subagents when two adjacent subagents have the same tools and goal and differ only in what they say, when a subagent has no tools or decisions of its own and only speaks a line or two, or when calls often move back and forth between two subagents. Before you split or merge to fix a failure, confirm where the failure happens. A missing tool call can come from a tool or from your application, not from the split. After a merge, recheck which tools the merged subagent can call and which routes it can take.
Scope tools and handoff conditions
| Principle | How to apply |
|---|---|
| Assign each tool to the subagent that owns it. | Attaching a tool to a subagent grants a permission. Give each subagent only the customer tools that its stage needs. Attach a tool with an irreversible effect, such as issuing a refund, only to the subagent that owns that decision, not to subagents that are still collecting information. Don't collect many tools in the final subagent. |
| Enforce required business order in your backend. | Subagents limit which tools the model can call, but they can't guarantee that a step was completed. When one step must happen before another, such as verification before account access, have the backend check the order and return a named error, such as authentication_required. The rule then holds even if you later split, merge, or rewrite subagents. |
| Define when each stage is done. | Start each subagent's instructions with its goal, and name the tool result that completes the stage. A caller's spoken "yes" alone doesn't complete a stage that must record something. Tell the model to hand off when the stage is done, because a handoff condition alone might not move the conversation forward. Describe one caller intent or completion state in each condition, and use the same wording in the instructions and in the condition. |
| Give every subagent a way out. | From every subagent, add a route to the closing subagent for callers who want to stop or who reached the wrong person. A subagent with no outgoing handoff conditions can't hand off, so a subagent whose tool can fail needs at least one outgoing route. Configure return routes only when the conversation needs them, and give the closing subagent no outgoing handoff conditions. |
Use required tool choice only where a tool call is mandatory. |
Set tool_choice to required only on a subagent that must call one of its tools before it leaves. Keep the default, auto, on the closing subagent and on subagents that only need to speak. |
Handle the wait during a handoff
A handoff turn takes longer than a reply within one subagent. The model first decides to hand off and calls the handoff tool. Then the target subagent starts a new response, and it processes its instructions and the conversation so far as new input before it speaks. Unless something covers this wait, the caller hears silence.
| Principle | How to apply |
|---|---|
| Keep handoffs few. | Each handoff adds a wait. Don't add a handoff that doesn't change the path, the tools, the permissions, or the goal, as described in Split the conversation into subagents. |
| Hand off early in the call. | Early in the call, the conversation that the target subagent processes as new input is still short, so its first reply can start sooner. |
| Avoid two handoffs in one caller turn. | A subagent that only routes and immediately hands off again makes the caller wait through two handoffs. Route directly to the subagent that answers. |
| Let the target subagent answer right away. | Keep target_response set to auto, the default, so the target subagent starts its answer as soon as it becomes active. With none, the caller must speak again first. Set delay_ms only for testing or a deliberate pause, because it delays activation of the target subagent. |
| Use one way to cover the wait in each subagent. | Choose one of the options in the following table. If a subagent's instructions ask the model to speak before a handoff and its handoff condition also sets transfer_message, the caller can hear two phrases. |
Use the following options to improve the caller's experience during a handoff.
| What the caller hears during the handoff | Effect | When to use it |
|---|---|---|
| Nothing | The target subagent's answer arrives soonest, but the caller hears silence until then. | The caller expects a short pause. Instruct the model to call the handoff tool without speaking first, as the example in this article does. |
A fixed transfer_message |
The service speaks the same message every time the route is taken, so the caller hears audio sooner. The answer plays after the message finishes. | Routes where the target subagent answers the caller, when your voice supports it. Keep the message short, make it fit every reason for taking the route, and don't repeat the target subagent's first line. For voice support, see Handoff conditions. |
| A phrase that the model speaks before it hands off | The phrase can respond to what the caller said, and audio can start sooner. Whether the model speaks it, and how long it is, varies between calls, and long instructions make it less likely. The model can also speak the phrase and then not hand off. The answer plays after the phrase finishes. | Subagents with short instructions, when you can test the route over many calls. In the instructions, give an example phrase of a few words. |
Instructions guide whether the model speaks before a handoff, but they don't guarantee it. The model can still say a short sentence before it calls the handoff tool. When you measure a handoff turn, record both when the caller first hears audio and when the target subagent's answer starts. A cover phrase or message makes the first audio earlier, but it delays the answer. To see how long each handoff took, read duration_ms in the session.handoff.completed event.
Test and evaluate your design
- Test each subagent and each important handoff condition, and then run end-to-end calls for each path.
- Compare the path that each call took, from the active subagent and the handoff events, with the path that you designed. For the event names, see Read handoff events.
- For tools that change data, check the result in your backend, not only the transcript. For example, confirm that an irreversible action ran exactly once.
- Run each scenario several times. Model behavior varies between runs, especially when a handoff happens and whether the model speaks before it.
Important
These principles summarize practical experience from building voice-based agents with inline subagents. They aren't rules or guarantees. The right design depends on your business logic, instructions, tools, model, and callers. Test and evaluate every design with representative conversations, and base your decisions on your own results.