Asynchronous responses
Speaking up when slow work finishes
An asynchronous response is a message your agent sends on its own, later, when slow work finishes. Booking a flight or running a credit check can take half a minute. Instead of leaving the customer with a spinner, the tool starts the work, the agent says it is underway, and the conversation continues. When the result lands, the agent speaks up with it, unprompted.
- How a tool starts slow work and returns at once
- How completed work joins other results or a newer customer turn
- When to queue a reply, generate an independent reply, or post exact text
- What to do instead when an AI agent speaks for the customer
- How a follow-up reaches chat, voice, and email
Use p.Agent.current.queue_response(...) for background follow-ups. It requests a reply that can combine several completed jobs, or let a newer customer turn answer them, instead of producing one separate reply per job.
The pattern
A tool is a Python function declared with @p.tool. Normally, your agent calls it and uses its p.ToolResult in the reply to the customer. For slow work, the tool returns an initial result while a registered coroutine finishes the job:
- Register the unstarted coroutine with
await agent.queue_response(session, after=...). - Return an “in progress” result so the current turn can finish normally.
- Inside the coroutine, save the completed result with
session.emit_tool_result(...)before returning. Parlant then queues the reply automatically.
Here, airline is your booking-service client, configured with a request timeout. Its confirmation includes a code and a service_fee_usd decimal string; replace these with your integration’s actual result and reported cost. A service error leaves the booking's outcome unknown, so the result tells the agent to direct the customer to the airline before trying again.
import asyncio
from decimal import Decimal
import parlant.sdk as p
@p.tool
async def book_flight(flight_number: str, passenger_name: str) -> p.ToolResult:
agent, session = p.Agent.current, p.Session.current
logger = p.Server.current.logger
async def complete_booking() -> None:
try:
confirmation = await airline.book(flight_number, passenger_name)
except Exception as error:
logger.warning(f"Booking confirmation failed: {type(error).__name__}")
completed = p.ToolResult(data={
"status": "confirmation unavailable",
"booking_outcome": "unknown",
"next_step": "Check with the airline before trying to book again.",
})
else:
completed = p.ToolResult(
data={
"status": "confirmed",
"flight": flight_number,
"code": confirmation.code,
},
costs={"Flight booking": Decimal(confirmation.service_fee_usd)},
)
await session.emit_tool_result(
book_flight,
completed,
arguments={"flight_number": flight_number, "passenger_name": passenger_name},
)
# Register before launch; pass the coroutine, not asyncio.create_task(...).
await agent.queue_response(session, after=complete_booking())
return p.ToolResult(
data={"status": "booking in progress", "flight": flight_number},
rules=[{"content": (
"Tell the customer you're booking the flight now and will confirm in a moment."
)}],
)
The initial result's rules are transient instructions for this turn only. The background result stores the actual outcome in data, which the later reply reads from the session. It does not need a second call to queue_response() at the end of the coroutine.
What happens at each moment
The tool registers the work and returns without waiting for the airline. The customer can ask about baggage or seats while it runs. The coroutine inherits Agent.current and Session.current, and interruption of the originating customer turn does not cancel its registered work.
When the airline answers, the coroutine saves the completed result and any reported cost. The deferred reply waits for all work registered for this session. Normal customer turns remain responsive while those jobs run.
If the booking completes quickly, the current response can include the result instead of first saying it is underway. If several registered jobs finish together, their results can share a reply. Register every job that should participate: arbitrary asyncio.create_task(...) tasks and work that has not yet been registered are invisible to batching.
What queue_response does
await agent.queue_response(...) acknowledges scheduling, not delivery. It returns None, not generated text. With after=..., pass an unstarted coroutine that saves its results before returning; Parlant registers it before starting it.
If the work is already complete, save its result first and request a reply directly:
await session.emit_tool_result(book_flight, completed, arguments=booking_arguments)
await agent.queue_response(session)
Queued background replies read the conversation and completed results. They do not run fresh rule matching or call tools, and queue_response has no rules argument. Include the facts the reply needs in the saved result.
If a response is already in progress
- A customer turn can fulfill a queued request when its loaded history includes the relevant results.
- New results can refresh a reply that has not started showing text yet.
- Once text is visible, it stays. Results it did not cover become one automatic continuation, unless a newer customer turn answers them first.
Three requests made before that delivery boundary combine into one pending reply; they do not require three follow-ups. This cannot combine results from future, unregistered work or rewrite text the customer has already seen.
Manual mode suppresses queued replies, including a handoff during generation. Stopping an active queued reply through the cancellation API also cancels its remaining local jobs and requests. Neither action undoes an external booking already made.
Saving results and costs
session.emit_tool_result(tool, result, arguments=...) saves completed background work as a tool event through the usual tracing and accounting path. It does not call the tool or a model. Capture the session before starting the task and pass the original tool function or its p.ToolId.
Save the result before requesting a reply, or before the registered coroutine returns. Its USD costs remain recorded even if generation fails, the session enters manual mode, or no follow-up is sent. Do not emit the same completion again because its message failed: the initial “in progress” result and the completed result are separate events, and the SDK does not deduplicate repeated application calls.
Each generated reply has its own trace and model usage record. A combined background reply is attributed to the latest pending request's originating turn when generation starts; each contributing tool result keeps its own original attribution. A customer turn that answers the results owns its normal response usage. Costs are not copied into every contributing job. See Spend management.
Finishing reliably
Keep the work's outcome, result storage, and message delivery separate. A successful scheduling call does not prove any of them completed. The booking example catches service failures and saves an explicit unknown-outcome result so the agent can explain what to do next.
If a registered coroutine raises, Parlant logs it and releases its registration. It does not retry the work or invent an answer; other successful jobs can proceed. If reply generation fails, that attempt's queued requests are released without an endless retry. Persisted results and costs remain available for a later explicit request.
A try around queue_response() catches registration failures, not later job or generation failures. Monitor stored results, delivered messages, and server errors separately. If you need a fixed fallback, session.emit_message(...) posts exact text without a model call, but does not participate in reply coordination. Check stored messages before retrying an uncertain delivery, and recover the notification rather than booking a second time.
Prevent duplicate business actions in your application or service, independently of reply coordination. A customer saying “thanks” or “and?” while waiting should not start a second booking. Use a service-supported request identifier for consequential actions and distinguish genuinely changed inputs.
Test fast and slow results, several jobs together, a customer message during the wait, service and delivery failures, handoff, cancellation, and shutdown. Check the saved result and delivered message, rather than treating a successful tool return as proof.
Multiple pods and restarts
The queue and registered coroutines live in one server process. Use routing affinity so a session's requests reach the same process. Traffic split across pods can still produce competing replies; this API does not provide distributed deduplication.
A restart loses pending requests and unfinished coroutines. Completed tool results and costs remain persisted, but are not automatically replayed. For jobs that must survive restarts, keep a durable job queue and delivery state in your application, then save the recovered result and request its reply on the process handling that session. Give service calls timeouts, and never replay a booking just to recover a missed notification.
Calling it from outside a turn
From a webhook or worker there is no current session. Fetch it and pass it explicitly. Here, package_status is your tool function and delivery is the event your integration received:
session = await server.get_session(id=session_id)
await session.emit_tool_result(
package_status,
p.ToolResult(data={"status": "delivered", "tracking_number": delivery.tracking_number}),
arguments={"tracking_number": delivery.tracking_number},
)
await agent.queue_response(session)
When to use utter instead
Use utter() when you deliberately want an independent, immediate generated reply with one-off instructions. Each call generates separately; it does not combine with other queued work or customer turns:
session = await server.get_session(id=session_id)
text = await agent.utter(
session=session,
rules=[{"content": "Ask the customer whether they would like to begin their scheduled review."}],
)
utter returns the generated text after posting it to the session. Each rule is a {"content": ...} mapping scoped to that reply. Like queued background replies, it does not call tools. Use session.emit_message(...) instead when the text must be verbatim, such as a legal notice.
Posting a message event with source: "ai_agent" and rules requests an independent generated reply. It does not queue one. See Managing chat sessions.
Prefer a synchronous tool when the work takes only a second or two, or when the caller needs the final answer in the same turn.
When an AI agent speaks for the customer
Sometimes the other side of the conversation isn't a person typing. It's an AI agent acting for them, such as a personal assistant that books travel on its user's behalf. That caller sends a message and waits for your agent's reply. A message your agent sends later, on its own, doesn't reach it until it writes again, and it may never write again. So for an AI caller, the answer has to come in the same turn.
Whatever creates the session says so, once, when it creates it. Over HTTP, that's a field on POST /sessions:
{ "agent_id": "travel-agent", "customer_represented_by_an_agent": true }
It's fixed for the life of the session, and it defaults to false. It describes this conversation, not the customer: the same person can use their assistant today and your website's chat tomorrow.
In a tool or a hook, p.Customer.current.is_represented_by_an_agent tells you. It reads the current session, so it's only available inside a turn. Outside one, there's no conversation to ask about, and it raises.
The booking tool, adapted. For an AI caller, it waits for the airline and answers in this turn. Everyone else gets the background booking and follow-up from above, unchanged:
IN_TURN_SECONDS = 60 # a safe margin under a 90-second wait for the reply
@p.tool
async def book_flight(flight_number: str, passenger_name: str) -> p.ToolResult:
if p.Customer.current.is_represented_by_an_agent:
try:
confirmation = await asyncio.wait_for(
airline.book(flight_number, passenger_name),
timeout=IN_TURN_SECONDS,
)
except Exception as error:
p.Server.current.logger.warning(
f"In-turn booking failed: {type(error).__name__}"
)
return p.ToolResult(
data={"status": "confirmation unavailable"},
rules=[{"content": (
"Tell the customer you couldn't confirm the booking. Ask them to check "
"with the airline before trying again, because its status is unknown."
)}],
)
return p.ToolResult(
data={"status": "confirmed", "code": confirmation.code},
costs={"Flight booking": Decimal(confirmation.service_fee_usd)},
)
... # the background booking and follow-up shown above
A few things change when an AI agent is on the other end:
- Stay under the caller's timeout. The calling agent waits for your reply only so long, and the proxies in between often cut a request off at 60 to 100 seconds. Your agent also needs time to write the reply after the tool returns, so leave a margin: 60 seconds of in-turn work suits a 90-second wait, the longest Parlant's A2A gateway allows. Treat a timeout like any other failure: its outcome is unknown, so don't report the work as done.
- Skip progress messages. "Still checking…" adds nothing when the reply arrives all at once.
- Use it for timing, not trust. The flag tells your tools how to deliver an answer. It doesn't say who the customer is, or what they've allowed you to do.
Streams, voice, and channels
A queued follow-up is an ordinary agent message event. A chat widget sees it through the usual session stream; in stream output mode, its text arrives piece by piece. Over voice, Parlant speaks it to the caller.
For a channel that delivers whole turns, such as email, a separate follow-up has its own trace id and is delivered as another message. When a customer turn incorporates the completed results instead, they arrive in that turn's reply.
Email & other channels shows how to deliver the agent's completed messages to another channel.