Using Conversation Relay for Graceful AI to Human Handoff
Time to read:
Using Conversation Relay for Graceful AI to Human Handoff
An AI agent can help with users who have basic questions. But you've likely been in the scenario where an AI agent wasn't able to handle your specific query. According to recent 2026 data, 65% of handoffs from an AI to a human still require the customer to repeat themselves. Twilio's Conversation Relay can help with this problem. By storing context from your call, the AI will hand off your call to a human agent along with information from your conversation with the AI. Your users will appreciate a graceful hand off, and the more context that the human agent has, the better the experience will be.
In this post you will use Twilio's Conversation Relay to create a graceful hand off between human and AI agent. You will use Twilio's TaskRouter service to store the information from the call, and seamlessly hand off the call to the next agent.
Prerequisites
To complete this tutorial, be sure to have:
- The . NET 10 or later SDK
- A Twilio Account (with a voice-enabled phone number)
- An OpenAI API Key
- ngrok (to tunnel your local development server to the internet)
Building the app
Step 1: Set up your project
You will be making a .NET web project for this tutorial. In your IDE of choice, create a new .NET web application. You can do this in the terminal by using:
Add necessary packages:
The Twilio package does necessary setup for Twilio, and the DotNetEnv package will let you save environment variables securely in your application. The OpenAI package is for the API for your AI agent, which will answer the initial call for your user. Move on to setting up your TaskRouter configuration.
Step 2: Set up Twilio TaskRouter
Go to the Twilio dashboard and sign in to your account. In the left hand navigation, look for Builder Tools, then choose Builder Tools > TaskRouter > Overview. You can also use the search function to get to TaskRouter.
Click the button to create a new workspace. For this application, choose 'Standard Workspace'. Leave the Event Callback URL blank.
Now, you will need to add a Worker to your workspace to receive your messages for testing. Click on your workspace, and click on the Worker tab. Create a new Worker using the create button. All you need to do is give your worker a name. For Activity, choose Available. Then create. This will be your sample customer service agent to receive messages from the call.
Now that your Workspace is created, you will need to create a Workflow. Click on Create New Workflow and type in a friendly name for your workflow. You will need the Workflow SID for your .env file. Later, when you have an ngrok URL for testing, that will need to be entered here.
In your Workflow you will need to add a Filter. Click Add a Filter, and set the filter name to "Default". The other default values here are fine. Click Save.
Once you have the necessary values, you can move on to create your .env file.
Step 3: Get environment variables ready
You will need a .env file that includes necessary environment variables for your solution. In this solution, your environment variables will include your OpenAI API key and your Twilio credentials. Here is the format of the .env file, with placeholders for the respective keys that you will need. Create this file in your project folder and fill in the placeholders with appropriate real values.
OPENAI_API_KEY: your key from OpenAI
TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN: both of these values are available on your logged in Twilio dashboard.
TASKROUTER_WORKSPACE_SID and TASKROUTER_WORKFLOW_SID: These are found in the Taskrouter that you created above. Enter the corresponding values.
Step 4: Creating an interface for OpenAI
Create a Services folder, and then, in that folder, a file called OpenAiService.cs:
Here, you have created a friendly AI agent. The agent is going to masquerade as a tech support assistant, helping users with computer problems and outages. The AI is instructed to be friendly and try to help users, using plain language and OpenAI's APIs.
You have also created a transfer_to_agent tool. In this tool, the agent you're referring to is a human agent on the other side of the line, for problems the AI support assistant cannot help with. This tool will track a reason for the agent transfer and briefly summarize the problem the user was having, so that the AI agent provides context to the human again.
One thing to notice here is that a friendly transfer message, fullResponse, has been hard-coded into the AI agent. In the next step, you will include a slight delay so that the agent gets the entire message out before transferring. Having this small pause reassures the user that the call will be going forward to the agent. Without it, they might be transferred to the next line without understanding that they'll be put on hold.
Your file will have some errors because you have not yet created the handler for Conversation Relay. This will be created in the following steps.
Step 5: Store call context
In this step, you will create a dictionary that stores the information from the call and the last caller message in memory. This will be keyed by the call SID and hold the transcript before the call is passed to the human agent.
Call this file CallContextStore.cs, and place it in the Services folder with your other files:
Step 6: Conversation Relay handler
Create another new file in Services, and name it ConversationRelayHandler.cs:
This code handles the WebSocket connection that Twilio Conversation Relay maintains for the duration of a call, reading incoming messages and routing them by type: setup captures the call SID, prompt feeds the caller's speech to OpenAI and streams the response back, and interrupt trims the last assistant message if the caller talks over the AI.
When OpenAI signals a transfer, the handler formats the conversation transcript and saves it along with the caller's last message in CallContextStore, keyed by the call SID. After pausing briefly so the text-to-speech engine can finish speaking the transfer message, it sends a { type = "handoff" } message over the WebSocket to end the AI session and trigger Twilio's /handoff webhook (where SummarizeAsync from OpenAiService.cs will summarize the saved transcript). The SendJsonAsync helper at the bottom is shared with OpenAiService for sending structured JSON messages back over the WebSocket.
Step 7: Set up Program.cs
Your .NET project will contain a Program.cs file already created. You will need to adjust this code to call the services that you have added. Replace the starting code in that file with the following code.
This will wire up your code to the call itself. When a call comes in, Twilio will return ConversationRelay TwiML via the WebSocket. The /handoff action generates a summary, then passes off the call to TaskRouter. /assignment assigns your Task to the TaskRouter Worker.
Step 8: Set up your ngrok tunneling
Open your terminal in your IDE and type:
Take note of what port (usually 5000 or 5100) your server is running on. Now, in a separate terminal, expose your local port using ngrok:
Ngrok will provide you with a secure url to hit with your web endpoint. You will use this in your Twilio console in the next step.
Step 9: Set up your Twilio phone number in console
Point your Twilio Phone Number’s "A Call Comes In" webhook to your ngrok domain. In the Twilio Console, navigate to your phone number under Numbers and Senders. Then click Configure. Under A Call Comes In, choose Webhook, and for URL, paste the webhook url from your ngrok endpoint, followed by /twiml (as in https://1234abcd.ngrok.app/twiml). Set Method to "HTTP POST" from the dropdown menu. Then click Save.
Your bot is now pointed to the webhook associated with your phone number.
To forward the call to your TaskRouter, you will also need to set that up in the Twilio Console. Go to the Workflow you created earlier, click on your workflow, Edit, and look for Assignment Callback. Set this value to your ngrok URL, followed by /assignment. Save.
Testing and troubleshooting
Now you are finally ready to test your solution.
Call your Twilio phone number.
The AI agent will pick up the phone and give a brief greeting. Chat with the AI as much as you like, then ask to be transferred to a human agent.
Look for the output in your console. You should see a short summary of your issue passed on, which would show up for the agent on the other side. This is delivered in raw JSON, but a full solution could parse this content using a custom dashboard, or, Twilio Flex.
While the call is still active and on hold, you can also see this information in the Twilio console under your TaskRouter. Go to your Workspace and click on the Tasks tab. Then click on the Task ID of the call to view the call details.
This view will disappear in a while, after the task has concluded, so it's easiest to look for this while the call is still actively on hold.
Troubleshooting
This solution has a lot of moving parts. If you run into any errors, here are some places to check:
- Make sure your Worker is set up properly in the Twilio console, with the proper queue, and that your Worker's availability is set to Available in the console.
- Make sure that the ngrok URL is in both necessary places: the A Call Comes In webhook (
/twiml) and the workflow's Assignment callback URL (/assignment). - Check your API keys to make sure they are correct and active. If the OpenAI API key isn't correct, the call will not connect to the AI agent.
- If your Task has already disappeared from the Task view, try the call again.
Conclusion
In this tutorial, you used Twilio Conversation Relay to create a conversation with an improved flow for your user. This AI bot will now forward your call to your call center with some context for the customer. For next steps, consider creating a dashboard solution to elegantly process the transfer information for your call center.
For more information, check out the documentation for Conversation Relay and human handoff.
Amanda Lange is a .NET Engineer of Technical Content. She is here to teach how to create great things using C# and .NET programming. She can be reached at amlange [ at] twilio.com.
Related Posts
Related Resources
Twilio Docs
From APIs to SDKs to sample apps
API reference documentation, SDKs, helper libraries, quickstarts, and tutorials for your language and platform.
Resource Center
The latest ebooks, industry reports, and webinars
Learn from customer engagement experts to improve your own communication.
Ahoy
Twilio's developer community hub
Best practices, code samples, and inspiration to build communications and digital engagement experiences.