Using Conversation Relay for Graceful AI to Human Handoff

November 25, 2026
Written by

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:

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:

mkdir OwlSupportChat
cd OwlSupportChat
dotnet new web

Add necessary packages:

dotnet add package Twilio
dotnet add package DotNetEnv
dotnet add package OpenAI

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.

Workspace setup form with name, template, and event callback URL fields

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_openai_api_key_here
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TASKROUTER_WORKSPACE_SID=WSxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TASKROUTER_WORKFLOW_SID=WWxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

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:

using System.Net.WebSockets;
using System.Text.Json;
using OpenAI;
using OpenAI.Chat;
namespace OwlSupportChat;
sealed class OpenAiService
{
  const string Model = "gpt-4o-mini";
  const string SystemPrompt = """
      You are Hoot, the AI phone support agent for the IT helpdesk.
      You help callers with:
      - Wi-Fi troubleshooting (restart the router, check cables, forget and reconnect to the network)
      - Basic computer troubleshooting (restart the device, check for updates, clear the browser cache)
      - Password resets (direct callers to the self-service portal at password.company.com, or transfer to a human agent if they are locked out)
      - VPN issues (ensure the VPN client is up to date; reinstall if the connection drops repeatedly)
      Speak naturally, as if talking on the phone. Follow these rules:
      - Use plain sentences only. No bullet points, no markdown, no emojis
      - Spell out all numbers
      - Keep each response to two or three sentences maximum
      - If the caller asks to speak with a human, live agent, or representative, use the transfer_to_agent tool immediately
      - If you cannot help with something, say so briefly and offer to transfer them to a human agent
      - Never make up information not listed above
      """;
  static readonly ChatTool TransferToAgentTool = ChatTool.CreateFunctionTool(
      "transfer_to_agent",
      "Transfer the caller to a live human agent. Use when the caller asks to speak with a person, representative, or agent.",
      BinaryData.FromString("""
          {
            "type": "object",
            "properties": {
              "reason": {
                "type": "string",
                "description": "Brief reason for the transfer, e.g. 'caller requested human agent'"
              }
            },
            "required": ["reason"]
          }
          """)
  );
readonly ChatClient _client;
  public OpenAiService()
  {
      var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
          ?? throw new InvalidOperationException("OPENAI_API_KEY is not set.");
      _client = new OpenAIClient(apiKey).GetChatClient(Model);
  }
  public async Task<(string Response, bool TransferRequested)> StreamResponseAsync(WebSocket ws, string? callSid, List<ChatMessage> messages)
  {
      var openAiMessages = new List<OpenAI.Chat.ChatMessage>
      {
          new SystemChatMessage(SystemPrompt)
      };
      foreach (var m in messages)
          openAiMessages.Add(m.Role == "user"
              ? new UserChatMessage(m.Content)
              : new AssistantChatMessage(m.Content));
      var fullResponse = "";
      var transferRequested = false;
      try
      {
          // Phase 1: stream with tools available
          var options = new ChatCompletionOptions
          {
              MaxOutputTokenCount = 300,
              Tools = { TransferToAgentTool },
          };
          var stream = _client.CompleteChatStreamingAsync(openAiMessages, options);
          ChatFinishReason? finishReason = null;
          var toolCallsAcc = new Dictionary<int, ToolCallAccumulator>();
          await foreach (var update in stream)
          {
              if (update.FinishReason.HasValue)
                  finishReason = update.FinishReason.Value;
              foreach (var part in update.ContentUpdate)
              {
                  if (!string.IsNullOrEmpty(part.Text))
                  {
                      fullResponse += part.Text;
                      await ConversationRelayHandler.SendJsonAsync(ws,
                          new { type = "text", token = part.Text, last = false });
                  }
              }
              foreach (var tc in update.ToolCallUpdates)
              {
                  if (!toolCallsAcc.TryGetValue(tc.Index, out var acc))
                  {
                      acc = new ToolCallAccumulator();
                      toolCallsAcc[tc.Index] = acc;
                  }
                  if (!string.IsNullOrEmpty(tc.ToolCallId)) acc.Id = tc.ToolCallId;
                  if (!string.IsNullOrEmpty(tc.FunctionName)) acc.Name = tc.FunctionName;
                  var argUpdate = tc.FunctionArgumentsUpdate;
                  if (argUpdate != null && !argUpdate.ToMemory().IsEmpty)
                      acc.Arguments += argUpdate.ToString();
              }
          }
          // Phase 2: execute tools and stream follow-up
          if (finishReason == ChatFinishReason.ToolCalls && toolCallsAcc.Count > 0)
          {
              var toolCalls = toolCallsAcc.Values.ToList();
              var assistantMsg = new AssistantChatMessage(
                  toolCalls.Select(tc => ChatToolCall.CreateFunctionToolCall(tc.Id, tc.Name, BinaryData.FromString(tc.Arguments))).ToList()
              );
              openAiMessages.Add(assistantMsg);
              // Check if any tool call is a transfer request
              if (toolCalls.Any(tc => tc.Name == "transfer_to_agent"))
              {
                  transferRequested = true;
                  var transferTc = toolCalls.First(tc => tc.Name == "transfer_to_agent");
                  var transferArgs = JsonSerializer.Deserialize<Dictionary<string, string>>(transferTc.Arguments) ?? new();
                  var reason = transferArgs.TryGetValue("reason", out var r) ? r : "caller requested";
                  Console.WriteLine($"[{callSid}] Transfer requested: {reason}");
                  fullResponse = "Sure, let me connect you with a live agent right now. Please hold for just a moment.";
                  await ConversationRelayHandler.SendJsonAsync(ws,
                      new { type = "text", token = fullResponse, last = false });
              }
          }
      }
      finally
      {
          await ConversationRelayHandler.SendJsonAsync(ws,
              new { type = "text", token = "", last = true });
      }
      Console.WriteLine($"[{callSid}] Hoot: {fullResponse}");
      return (fullResponse, transferRequested);
  }
  public async Task<string> SummarizeAsync(string transcript)
  {
      var completion = await _client.CompleteChatAsync(
          new OpenAI.Chat.ChatMessage[]
          {
              new SystemChatMessage("Summarize this support call in one or two sentences. Focus on the caller's issue and what was tried. Be concise."),
              new UserChatMessage(transcript)
          },
          new ChatCompletionOptions { MaxOutputTokenCount = 100 });
      return completion.Value.Content[0].Text;
  }
  private sealed class ToolCallAccumulator
  {
      public string Id { get; set; } = "";
      public string Name { get; set; } = "";
      public string Arguments { get; set; } = "";
  }
}

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:

using System.Collections.Concurrent;
namespace OwlSupportChat;
sealed class CallContextStore
{
   readonly ConcurrentDictionary<string, CallContext> _store = new();
   public void Save(string callSid, CallContext context) =>
       _store[callSid] = context;
   public CallContext? TakeAndRemove(string callSid) =>
       _store.TryRemove(callSid, out var ctx) ? ctx : null;
}
record CallContext(string Transcript, string LastCallerMessage);

Step 6: Conversation Relay handler

Create another new file in Services, and name it ConversationRelayHandler.cs:

using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
namespace OwlSupportChat;
static class ConversationRelayHandler
{
  public static async Task HandleAsync(WebSocket ws, OpenAiService openAi, CallContextStore store)
  {
      string? callSid = null;
      var messages = new List<ChatMessage>();
      var buffer = new byte[8192];
      try
      {
          while (ws.State == WebSocketState.Open)
          {
              using var ms = new MemoryStream();
              WebSocketReceiveResult result;
              do
              {
                  result = await ws.ReceiveAsync(buffer, CancellationToken.None);
                  if (result.MessageType == WebSocketMessageType.Close)
                  {
                      await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
                      Console.WriteLine($"[{callSid}] Call ended");
                      return;
                  }
                  ms.Write(buffer, 0, result.Count);
              } while (!result.EndOfMessage);
              var json = Encoding.UTF8.GetString(ms.ToArray());
              using var doc = JsonDocument.Parse(json);
              var root = doc.RootElement;
              var msgType = root.TryGetProperty("type", out var t) ? t.GetString() : null;
              switch (msgType)
              {
                  case "setup":
                      callSid = root.TryGetProperty("callSid", out var sid) ? sid.GetString() : null;
                      Console.WriteLine($"[{callSid}] Call connected");
                      break;
                  case "prompt":
                      if (!root.TryGetProperty("last", out var last) || !last.GetBoolean())
                          break;
                      var userText = root.TryGetProperty("voicePrompt", out var vp) ? vp.GetString() ?? "" : "";
                      Console.WriteLine($"[{callSid}] Caller: {userText}");
                      messages.Add(new ChatMessage("user", userText));
                      var (responseText, transferRequested) = await openAi.StreamResponseAsync(ws, callSid, messages);
                      messages.Add(new ChatMessage("assistant", responseText));
                      if (transferRequested)
                      {
                          Console.WriteLine($"[{callSid}] Handing off to human agent");
                          var transcript = string.Join("\n", messages.Select(
                              m => $"{(m.Role == "user" ? "Caller" : "Agent")}: {m.Content}"));
                          var lastCallerMessage = messages.LastOrDefault(m => m.Role == "user")?.Content ?? "";
                          if (callSid != null)
                              store.Save(callSid, new CallContext(transcript, lastCallerMessage));
                          // Wait for TTS to finish speaking before triggering the handoff.
                          // Conversation Relay has no "done speaking" event, so estimate
                          // from word count at ~2.5 words/second plus a small buffer.
                          var wordCount = responseText.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
                          await Task.Delay((int)(wordCount / 2.5 * 1000) + 500);
                          await SendJsonAsync(ws, new { type = "handoff" });
                          return;
                      }
                      break;
                  case "interrupt":
                      var spoken = root.TryGetProperty("utteranceUntilInterrupt", out var u) ? u.GetString() ?? "" : "";
                      Console.WriteLine($"[{callSid}] Interrupted after: '{spoken}'");
                      if (messages.Count > 0 && messages[^1].Role == "assistant")
                          messages.RemoveAt(messages.Count - 1);
                      break;
                  case "error":
                      var desc = root.TryGetProperty("description", out var d) ? d.GetString() : "";
                      Console.WriteLine($"[{callSid}] Conversation Relay error: {desc}");
                      break;
              }
          }
      }
      catch (WebSocketException)
      {
          Console.WriteLine($"[{callSid}] Call ended");
      }
  }
  public static Task SendJsonAsync(WebSocket ws, object payload)
  {
      var text = JsonSerializer.Serialize(payload);
      var bytes = Encoding.UTF8.GetBytes(text);
      return ws.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None);
  }
}
record ChatMessage(string Role, string Content);

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.

using System.Text.Json;
using DotNetEnv;
using OwlSupportChat;
Env.Load();
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<OpenAiService>();
builder.Services.AddSingleton<CallContextStore>();
var app = builder.Build();
app.UseWebSockets();
// Twilio calls this when an inbound call arrives — returns ConversationRelay TwiML
app.MapPost("/twiml", (HttpContext ctx) =>
{
   var host = ctx.Request.Host.Value;
   var xml = $"""
       <?xml version="1.0" encoding="UTF-8"?>
       <Response>
         <Connect action="/handoff">
           <ConversationRelay url="wss://{host}/relay" welcomeGreeting="Hi, thanks for calling IT support. I'm Hoot, an AI assistant. How can I help you today?" />
         </Connect>
       </Response>
       """;
   return Results.Content(xml, "application/xml");
}).DisableAntiforgery();
// Conversation Relay connects here via WebSocket
app.Map("/relay", async (HttpContext ctx, OpenAiService openAi, CallContextStore store) =>
{
   if (!ctx.WebSockets.IsWebSocketRequest)
   {
       ctx.Response.StatusCode = 400;
       return;
   }
   var ws = await ctx.WebSockets.AcceptWebSocketAsync();
   await ConversationRelayHandler.HandleAsync(ws, openAi, store);
});
// Twilio calls this after the handoff message ends ConversationRelay —
// generates a summary then enqueues the live call into TaskRouter with full context
app.MapPost("/handoff", async (IFormCollection form, OpenAiService openAi, CallContextStore store) =>
{
   var workflowSid = Environment.GetEnvironmentVariable("TASKROUTER_WORKFLOW_SID") ?? "";
   var callSid = form["CallSid"].ToString();
   var ctx = store.TakeAndRemove(callSid);
   var summary = "";
   if (ctx != null && !string.IsNullOrEmpty(ctx.Transcript))
   {
       try { summary = await openAi.SummarizeAsync(ctx.Transcript); }
       catch (Exception ex) { Console.WriteLine($"[handoff] Summary failed: {ex.Message}"); }
   }
   Console.WriteLine($"[handoff] Summary for {callSid}: {summary}");
   var taskAttributes = JsonSerializer.Serialize(new
   {
       call_sid = callSid,
       summary,
       caller_last_message = ctx?.LastCallerMessage,
       transcript = ctx?.Transcript
   });
   var xml = $"""
       <?xml version="1.0" encoding="UTF-8"?>
       <Response>
         <Enqueue workflowSid="{workflowSid}">
           <Task><![CDATA[{taskAttributes}]]></Task>
         </Enqueue>
       </Response>
       """;
   return Results.Content(xml, "application/xml");
}).DisableAntiforgery();
// TaskRouter calls this when it assigns a task to a worker —
// responds with dequeue to bridge the queued caller to the worker's phone
app.MapPost("/assignment", (IFormCollection form) =>
{
   var workerAttributesJson = form["WorkerAttributes"].ToString();
   var taskAttributesJson   = form["TaskAttributes"].ToString();
   using var workerDoc = JsonDocument.Parse(workerAttributesJson);
   var contactUri = workerDoc.RootElement.TryGetProperty("contact_uri", out var cu)
       ? cu.GetString() ?? "" : "";
   Console.WriteLine($"[assignment] Connecting caller to {contactUri}");
   Console.WriteLine($"[assignment] Task context: {taskAttributesJson}");
   return Results.Json(new { instruction = "dequeue", to = contactUri });
}).DisableAntiforgery();
app.Run();

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:

dotnet run

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 http 5000

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.

Screenshot of JSON showing a caller asking to transfer from AI to a human agent
Screenshot of JSON showing a caller asking to transfer from AI to a human agent

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.