insonl
← journal

Pass Conversation Context From a Chatbot Into Twilio Flex

date
21 November 2026
by
Insonl
read
7 min read

A customer finishes four turns with a support bot on webchat, SMS, or WhatsApp—for instance, hitting a dispute or partial-refund edge case like those in Shopify return-status support automation—and asks for a person. In a Zendesk handoff, you can update ticket fields and add an internal note (see Zendesk AI handoff ticket fields). Twilio Flex works differently: Twilio Flex chatbot handoff context has to attach an agent to a live, persistent message thread while moving compact routing and session data through the Flex Interactions API and TaskRouter.

Based on Twilio’s third-party developer documentation (not an Insonl client), this guide covers Flex Conversations on Flex UI 2.x.x (Flex UI 1.x.x uses legacy Messaging). It defines what an agent needs at handoff, where each field belongs across Conversations, Conversation attributes, and TaskRouter Task attributes, how to keep one thread open, and which API behaviors drop context or orphan conversations.

Keep one Twilio Conversation SID from bot to agent

Continuing the conversation requires running both the chatbot and Flex inside one Twilio Conversation (CH...) under Flex Chat Service, which Twilio requires as the default Conversations service.

A new Conversation has a separate message history. Reuse the existing CH... SID to give the agent the original thread. On SMS and WhatsApp, Twilio rejects adding the same customer-address/proxy-address pair to a second Conversation while the binding exists in an active or inactive Conversation.

Two patterns preserve the CH... thread:

  1. Twilio Studio handoff (Webchat 3.x.x, SMS, WhatsApp). For SMS and WhatsApp, configure a Conversations Address to create a Conversation for unmatched inbound messages and send it to your Studio Flow. For Webchat 3.x.x, configure your Chat Address to use a Studio Flow. A custom chat client can create the Conversation, add the customer with an opaque non-PII identity (avoiding names, emails, phone numbers, and reserved URI characters ! * ' ( ) ; : @ & = + $ , / ? % # [ ]), and attach a scoped Studio webhook with Configuration.FlowSid and Configuration.Filters=onMessageAdded. On escalation, Studio’s Send to Flex widget calls POST https://flex-api.twilio.com/v1/Interactions, binding the Task to that Conversation SID.
  2. Direct Interactions API handoff from an external bot. If your AI service receives turns via a Conversation Scoped Webhook (target=webhook; up to five per Conversation, with Configuration.ReplayAfter when attaching mid-thread), escalate via POST https://flex-api.twilio.com/v1/Interactions. Set Channel.initiated_by to "customer" and pass the existing CH... SID in Channel.properties.media_channel_sid—required when initiated_by is "customer", with the customer participant already present.

Enforce two boundaries at escalation:

  • Never add a Flex agent directly to the Conversation. Flex does not support adding agent Chat identities straight to a Conversation. Route through POST /v1/Interactions (initial handoff) or POST /v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Invites (re-routing or unparking) so Flex creates the reservation and joins the agent with the agent role on acceptance.
  • Stop the bot after handoff. Remove the bot’s scoped webhook (DELETE https://conversations.twilio.com/v1/Conversations/{ConversationSid}/Webhooks/{Sid}) or check participant state before replying.

If your chatbot ran outside Twilio Conversations before escalation, do not try to silently import turns with POST /v1/Conversations/{ConversationSid}/Messages—that endpoint creates live messages that can be delivered to participants. Instead, keep the historical transcript in your application and pass a lookup ID in Task or Conversation attributes so the agent can open it from Flex UI.

Split handoff context across three Twilio surfaces

Every Flex Conversations escalation spans three storage surfaces:

Surface Hard limit (Twilio docs) Read by What belongs here
Conversation Messages (CH...) Body: 32KB inbound/chat, 1,600 chars outbound SMS/WhatsApp; Message Attributes: 4KB Flex agent chat canvas (via conversationSid) Customer and bot turns only
Conversation Attributes 16KB JSON string (FriendlyName: optional, max 256 chars) Studio (trigger.conversation.ChannelAttributes), backend, Flex plugins Pre-engagement data, durable session/CRM pointers, full bot state
TaskRouter Task Attributes (Routing.properties.attributes) 4,096 chars incl. whitespace (non-changeable); Studio Send to Flex Attributes input has a separate 1,024-char limit TaskRouter Workflows, Flex UI, Flex Insights Routing keys, customer display fields, compact summary, verification flag, lookup IDs

Two Twilio rules govern how data moves across surfaces:

  • Studio parses Conversation attributes as JSON, not message attributes. On an Incoming Conversation trigger, message attributes are plain strings; only ChannelAttributes (including Webchat 3.x.x’s conversation.ChannelAttributes.pre_engagement_data) are parsed as JSON by default. In Studio’s Send to Flex widget, serialize nested objects with Liquid’s to_json filter ("handoff": {{widgets.BotSummary.parsed | to_json}}) and stay inside the widget’s 1,024-character Attributes limit.
  • Task attributes feed three consumers. Everything in Routing.properties.attributes is copied “as is” onto the TaskRouter Task. Flex also maps Channel.type → channelType, Channel.initiated_by → direction, and Channel.properties.media_channel_sid → conversationSid, and adds generated flexInteractionSid, flexInteractionChannelSid, and flexChannelInviteSid.

Within the 4,096-character Task limit, send four compact blocks:

  1. Routing keys. Normalized intent, escalation reason code, language, and skill tags for TaskRouter Workflows.
  2. Customer identity and verification. Set from (Flex UI’s preferred display label on non-email tasks), plus customerName and customerAddress (populating Flex Insights customers). Include an authenticated CRM account ID and identity_verified boolean—especially on WhatsApp, where Flex Conversations does not show WhatsApp Profile Name and WhatsApp usernames can put a Business-Scoped User ID (BSUID) in MessagingBinding.Address and Author instead of a phone number. Use an opaque non-PII customer identity for custom chat participants (FriendlyName is optional and limited to 256 characters).
  3. Compact summary and last bot action. One or two sentences covering what the customer asked, what the bot checked or blocked, and any order, return, or case IDs.
  4. Insights-safe reporting fields. Put low-cardinality categories in conversations.conversation_attribute_1…10 (for example, conversation_attribute_1 for escalation reason, conversation_attribute_2 for bot topic) and high-cardinality IDs in a label-only slot with no matching attribute slot (conversation_label_3, with no conversation_attribute_3). Insights loads the first 128 characters of custom attribute values (this 128-character rule is documented for attributes, not labels), and Twilio warns that high-cardinality attribute values can slow Historical Reporting.

Keep full order payloads, transcripts, and tool traces out of Task attributes. Pass a lookup ID and load details from your CRM integration inside a Flex UI plugin, or store mid-size session state in the 16KB Conversation Attributes.

A made-up Interactions API handoff payload and Flex UI panel

The JSON below is a made-up example (not from a real company or Insonl client) showing decoded values of the Channel and Routing fields for an external chatbot escalating a webchat Conversation (CH...). A raw POST https://flex-api.twilio.com/v1/Interactions request requires each value to be JSON-serialized and sent as application/x-www-form-urlencoded fields:

{
  "Channel": {
    "type": "web",
    "initiated_by": "customer",
    "properties": { "media_channel_sid": "CH00000000000000000000000000000001" }
  },
  "Routing": {
    "properties": {
      "workspace_sid": "WS00000000000000000000000000000001",
      "workflow_sid": "WW00000000000000000000000000000001",
      "task_channel_unique_name": "chat",
      "attributes": {
        "from": "Minh Tran",
        "customerName": "Minh Tran",
        "customerAddress": "[email protected]",
        "conversations": {
          "conversation_attribute_1": "policy_blocked",
          "conversation_attribute_2": "returns_dispute",
          "conversation_label_3": "ORD-4108"
        },
        "handoff": {
          "intent": "return_dispute",
          "escalation_reason": "policy_blocked",
          "identity_verified": true,
          "crm_account_id": "ACCT-8821",
          "order_id": "ORD-4108",
          "last_action": "lookup_return:partial_restock_pending_refund",
          "summary": "Customer disputes restock status on item 2 of return #4108-R1; bot confirmed item 1 refund pending and stopped before manual override."
        }
      }
    }
  }
}

In Flex UI 2.x.x, agents see prior turns in the chat canvas on acceptance, while custom handoff fields need a React plugin. Wrap your summary component with withTaskContext() from @twilio/flex-ui to read props.task?.attributes?.handoff, then mount it in flex.TaskInfoPanel.Content.add(...) or flex.CRMContainer.Content.replace(...) (where it can fetch CRM records via crm_account_id). Twilio’s documented withTaskContext() example does not work when mounted to Supervisor.TaskCanvas.

Operational traps that drop context or orphan conversations

  1. Async creation and rate limits. POST /v1/Interactions is asynchronous: HTTP 200 confirms acceptance, not completed setup. Subscribe to TaskRouter task.canceled events (and check Console Debugger) to catch failures. Back off on HTTP 429—Twilio limits Interactions API endpoints to 20 RPS per endpoint per account and the Webchat orchestrator to 5 RPS.
  2. Parked interactions drop original Task attributes. When an agent parks a conversation—closing their participant (POST /v1/Interactions/{InteractionSid}/Channels/{ChannelSid}/Participants/{ParticipantSid}, Status=closed) while leaving the Conversation open—and your backend later calls POST .../Invites, Twilio states that original Task attributes do not carry over to the new Task. Re-read handoff state from Conversation.Attributes (or your database) and re-send it on every /Invites call. Twilio deletes an Interaction Channel (UO...) after 180 days without an update to that channel; an update to the Interaction Channel, such as an agent accepting a new task, resets the timer (Conversation updates do not). Twilio documents 404 Not Found when retrieving a deleted channel.
  3. Orphaned conversations and Task API misuse. Never cancel or delete a Flex Conversations Task through the TaskRouter Task API; close the channel via POST /v1/Interactions/{InteractionSid}/Channels/{ChannelSid} with Status=closed, which closes the Conversation and moves the Task to wrapping. To complete the Task in the same request, also send Routing set to {"status":"closed"}. Handle workflow.timeout, task.canceled, and task.deleted so timed-out escalations re-route or notify the customer. Use known-agent routing rather than targeting a raw worker_sid alone—if that worker declines, the Task cancels while the Conversation stays open. On non-long-lived channels, set timers (Timers.Inactive min 1 minute; Timers.Closed min 10 minutes) to avoid hitting the 1,000 active/inactive Conversations-per-identity cap.
  4. Permanent closure and reporting lock-in. In the standard Flex completion flow, Flex completes the Task, removes the agent, and closes the Conversation (which cannot be reactivated); TaskRouter deletes the completed Task shortly afterward. Write final reporting attributes before completion or cancellation. Twilio documents a separate two-minute window after completion for updating an Insights recording link.
  5. WhatsApp PDF splits. Inbound WhatsApp PDFs arrive as two Conversation Messages—filename first, then PDF media—so Studio’s Incoming Conversation trigger fires only on the filename message. Inspect messages via webhook or API before assuming no attachment arrived.

Before wiring a chatbot into Twilio Flex

Insonl is a Ho Chi Minh City engineering studio offering CRM solutions. Before connecting a bot to Twilio Flex, map your escalation boundaries, attribute schema, and agent desktop views with our free AI workflow audit.

The audit is free; follow-on implementation work is charged separately.

Sources