How to Orchestrate Multi-Call Conversations with an LLM and Twilio Conversation in Node.js Memory

September 14, 2026
Written by

Have you ever been on the phone with an AI voice agent and gotten frustrated with its lack of memory? Maybe your agent hung up on you, or it got disconnected, forcing you to start a conversation all over again. This kind of interruption can waste time for you and your users, and cause a lot of frustration.

Twilio Conversation Memory is your solution. Conversation Memory allows context to be persisted between calls. This means that if you call the Twilio agent back, it won’t lose the context of what you were talking about when you hung up, and can pick up right where you left off. This can save you a lot of frustration and help you get things done better and faster when you’re talking to an agent.

In this tutorial, you will make a Node.js Express service that retains caller context, preferences, and action history across multiple separate inbound calls.

This tutorial is geared towards Node.js developers, but you can find other languages below:

Prerequisites

To complete this tutorial you will need:

  • A free Twilio account with a voice-capable phone number
  • Node.js v18 or higher installed on your machine
  • An OpenAI API key
  • ngrok to expose local webhooks to Twilio
  • An IDE or text editor such as Visual Studio Code

Building the app

Step 1 - Set up the Node.js project

To get started, create a new Node.js project by running the following commands in your terminal:

mkdir twilio-multi-call-memory
cd twilio-multi-call-memory
npm init -y

The mkdir and cd commands create the project folder and move into it. The npm init -y command generates a package.json file with default values, which will track your dependencies.

Step 2 - Install required dependencies

Install the Express, WebSocket, OpenAI, dotenv, and axios packages via npm.

npm install express express-ws openai dotenv axios

The express package is a minimal web framework for handling HTTP requests. The express-ws package adds WebSocket support to Express, which is required to receive Twilio’s Conversation Relay stream. The openai package is the official OpenAI SDK, used to talk to gpt-4o-mini. The dotenv package lets you import environment variables from a .env file. You’ll add those variables in a later step. The axios package is used to make HTTP requests to Twilio’s Conversation Memory REST API.

Step 3 - Create a Twilio Memory Store

For this tutorial, you will need a Conversation Memory Store. Go into your Twilio console and look for Memory Stores. You can use the console search, or look for Data > Conversation Memory > Memory stores.

Memory Stores use machine learning, and you may have to agree to a warning before proceeding. Keep in mind that Conversation Memory is not intended for use with sensitive information. Conversation products are only available on the new Twilio Console, so make sure your account has been migrated. For more information about Conversation Memory, you may want to read the documentation, including the Getting Started Guide.

Once you have found the correct tab, click on Create New Store.

Memory Stores in 1console
Memory Stores in 1console

Now follow the steps to set up your memory store.

The console gives you a setup checklist to get you started. Click on Connect Conversation Orchestrator, and give it a friendly name. Write a short description (this can be anything), then you can move on to Messaging and Chat Traffic. For the remainder of the items in this checklist, you can select the default values for now.

You don’t have any customer profiles yet, so you can skip the rest of the checklist. However, you will need your memory store ID, which is at the top left of the memory store screen. There should be a convenient button to copy-paste that ID. Keep that ID for the next step.

Step 4 - Configure environment variables

Now that you have a memory store created, you will need to be able to access that from your application. For this, you will need to get your Memory Store ID and paste that into your secrets file. Create a .env file in the root directory of your project. Add the following values, replacing the placeholders.

OPENAI_API_KEY=sk-...
TWILIO_API_KEY=SK...
TWILIO_API_SECRET=...
TWILIO_CONFIGURATION_ID=cnv_config_...
TWILIO_MEMORY_STORE_ID=mem_store_...
TWILIO_PHONE_NUMBER=+15551234567

Get your API key from your Twilio console, created under Settings > Account Settings > API Keys & Auth Tokens. Because other types of API keys do not have access to the Conversation Memory features, creating a Main API key is required for this tutorial. Keep in mind that the secret key will only be shown once, so be sure you save it. You get your memory store key from the previous step and paste it in here. Your OpenAI API Key is generated from OpenAI’s dashboard. You will also need your Twilio voice-capable phone number, which is in E.164 format.

Save the file, and move on to the next step, creating your services.

Step 5 - Set up the OpenAI service

This demonstration uses the fiction of an auto repair shop as the agent that you are calling. However, Conversation Memory would be useful in lots of different scenarios, such as tech support, travel, and more. Feel free to adjust the audio prompts as you see fit for your own personal projects.

Create a file called openaiService.js in your project’s root directory to handle interaction with gpt-4o-mini.

Paste the following into your new file:

const OpenAI = require('openai');
const MODEL = 'gpt-4o-mini';
const BASE_SYSTEM_PROMPT = `You are the phone assistant for Owlbert's Auto Repair. You are friendly, concise, and speak naturally as if on the phone.
Do not use lists, bullet points, or emojis — respond in plain sentences.
If the caller mentions their name, vehicle, or a problem with their car, remember it and refer back to it naturally as the conversation continues.
If you do not know something, say so honestly rather than guessing.
You have access to memory of previous conversations with this caller, which may include their name, vehicle, and prior issues.
Use that information to provide helpful and personalized responses.`;
const SUMMARIZER_PROMPT = `You are summarizing a phone call between a caller and Owlbert's Auto Repair.
Write a concise summary in 4-8 sentences that captures: the caller's name if given, their vehicle if mentioned, the reason for the call, any symptoms or diagnostic detail discussed, any prices or estimates mentioned, and any commitments or next steps agreed upon.
Write in plain prose (no lists or bullets). If the caller did not share meaningful information (e.g. the call was very short or unclear), respond with a single sentence noting that.
Maximum 4000 characters.`;
if (!process.env.OPENAI_API_KEY) {
  throw new Error('OPENAI_API_KEY is not set.');
}
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const streamResponse = async (ws, callSid, memoryContext, messages) => {
  const systemPrompt = memoryContext
    ? `${BASE_SYSTEM_PROMPT}\n\nPrior context on this customer (from previous calls):\n${memoryContext}`
    : BASE_SYSTEM_PROMPT;
  const openAiMessages = [
    { role: 'system', content: systemPrompt },
    ...messages.map((m) => ({ role: m.role, content: m.content })),
  ];
  let fullResponse = '';
  try {
    const stream = await client.chat.completions.create({
      model: MODEL,
      messages: openAiMessages,
      max_tokens: 400,
      stream: true,
    });
    for await (const chunk of stream) {
      const token = chunk.choices[0]?.delta?.content;
      if (token) {
        fullResponse += token;
        ws.send(JSON.stringify({ type: 'text', token, last: false }));
      }
    }
  } finally {
    ws.send(JSON.stringify({ type: 'text', token: '', last: true }));
  }
  console.log(`[${callSid}] Assistant: ${fullResponse}`);
  return fullResponse;
};
const summarizeConversation = async (messages) => {
  if (messages.length === 0) return '';
  const transcript = messages
    .map((m) => `${m.role.toUpperCase()}: ${m.content}`)
    .join('\n');
  const result = await client.chat.completions.create({
    model: MODEL,
    max_tokens: 500,
    messages: [
      { role: 'system', content: SUMMARIZER_PROMPT },
      { role: 'user', content: `Transcript:\n${transcript}\n\nSummary:` },
    ],
  });
  const summary = result.choices[0]?.message?.content ?? '';
  console.log(`Call summary (${summary.length} chars): ${summary}`);
  return summary;
};
module.exports = { streamResponse, summarizeConversation };

This code handles your initial connection to OpenAI. Its function is to parse the information from a caller and stream it to the OpenAI API. Notice the system prompt here, which explains the functionality of the agent. It contains some useful instructions for the agent, such as to avoid bullet points and emojis when speaking on the phone. It also reminds the agent that it will have access to memory, in case the call is dropped.

This code also has an additional call to OpenAI to summarize the call itself. This will parse the conversation into a quick summary that will be stored in Twilio’s Conversation Memory. You can adjust this prompt according to your application’s needs. Keep in mind that if you don’t say anything meaningful, nothing will be stored.

Next, create the webhook for Twilio’s connection.

Step 6 - Build the Twilio webhook and Conversation Memory pipeline

Create another new file called conversationRelayHandler.js. Paste in this code:

const { streamResponse, summarizeConversation } = require('./openaiService');
const { startCall, finishCall } = require('./conversationMemoryService');
const handle = (ws) => {
  let callSid = null;
  let callerPhone = '';
  let profileId = null;
  let conversationId = null;
  let memoryContext = null;
  const messages = [];
  ws.on('message', async (data) => {
    let msg;
    try {
      msg = JSON.parse(data.toString());
    } catch (err) {
      console.warn('Invalid JSON received:', err);
      return;
    }
    switch (msg.type) {
      case 'setup': {
        callSid = msg.callSid ?? null;
        callerPhone = msg.from ?? '';
        console.log(`[${callSid}] Call connected from ${callerPhone}`);
        try {
          const ctx = await startCall(callerPhone);
          if (ctx) {
            conversationId = ctx.conversationId;
            profileId = ctx.profileId || null;
            memoryContext = ctx.memoryContext;
            console.log(
              `[${callSid}] Conversation ${conversationId}, profile ${profileId ?? '(none)'}, memory ${memoryContext?.length ?? 0} chars`
            );
          }
        } catch (err) {
          console.warn(`[${callSid}] startCall failed — continuing without memory:`, err);
        }
        break;
      }
      case 'prompt': {
        if (!msg.last) break;
        const userText = msg.voicePrompt ?? '';
        console.log(`[${callSid}] Caller: ${userText}`);
        messages.push({ role: 'user', content: userText });
        const responseText = await streamResponse(ws, callSid, memoryContext, messages);
        messages.push({ role: 'assistant', content: responseText });
        break;
      }
      case 'interrupt': {
        const spoken = msg.utteranceUntilInterrupt ?? '';
        console.log(`[${callSid}] Interrupted after: '${spoken}'`);
        if (messages.length > 0 && messages[messages.length - 1].role === 'assistant') {
          messages.pop();
        }
        break;
      }
      case 'error': {
        console.warn(`[${callSid}] Conversation Relay error: ${msg.description ?? ''}`);
        break;
      }
    }
  });
  ws.on('close', async () => {
    console.log(`[${callSid}] Call ended`);
    if (profileId && conversationId && messages.length > 0) {
      try {
        const summary = await summarizeConversation(messages);
        if (summary && summary.trim()) {
          await finishCall(profileId, conversationId, summary);
        }
      } catch (err) {
        console.warn(`[${callSid}] Failed to persist call summary to memory:`, err);
      }
    }
  });
};
module.exports = { handle };

conversationRelayHandler.js is the bridge between Twilio’s WebSocket and the rest of the app. When Twilio opens the socket after a <ConversationRelay> TwiML directive, handle attaches listeners that parse each incoming JSON frame. A prompt frame carries the caller’s transcribed speech. The handler appends the text to an in-memory conversation history and hands the whole history plus the memory context off to streamResponse in the OpenAI service, which streams tokens back out through the same socket.

The code also contains interruption handling for your agent. If the agent is interrupted during a conversation, it pops the last message off of the history so the agent realizes the full message was not sent and was incomplete. This will allow the customer to continue talking and handle the interruption in a more human way, without your user missing context.

Step 7 - Process multi-turn historical context

Now you will create one more file to handle the context and memory processing. You’ll call this file conversationMemoryService.js. Paste the following into the file:

const axios = require('axios');
const MEMORY_BASE = 'https://memory.twilio.com';
const CONVERSATIONS_BASE = 'https://conversations.twilio.com';
const requireEnv = (name) => {
  const value = process.env[name];
  if (!value) throw new Error(`${name} not set.`);
  return value;
};
const apiKey = requireEnv('TWILIO_API_KEY');
const apiSecret = requireEnv('TWILIO_API_SECRET');
const storeId = requireEnv('TWILIO_MEMORY_STORE_ID');
const configurationId = requireEnv('TWILIO_CONFIGURATION_ID');
const twilioNumber = requireEnv('TWILIO_PHONE_NUMBER');
const http = axios.create({
  auth: { username: apiKey, password: apiSecret },
  validateStatus: () => true,
});
const startCall = async (callerPhone) => {
  if (!callerPhone) return null;
  const conversationId = await createConversation(callerPhone);
  if (!conversationId) return null;
  const profileId = await ensureProfile(callerPhone);
  if (!profileId) return { conversationId, profileId: '', memoryContext: '' };
  const memoryContext = await recall(profileId);
  return { conversationId, profileId, memoryContext };
};
const finishCall = async (profileId, conversationId, summary) => {
  if (!profileId || !conversationId || !summary) return;
  const body = {
    summaries: [
      {
        conversationId,
        content: summary.length > 4096 ? summary.slice(0, 4096) : summary,
        occurredAt: new Date().toISOString(),
        source: 'voice-agent',
      },
    ],
  };
  const resp = await http.post(
    `${MEMORY_BASE}/v1/Stores/${storeId}/Profiles/${profileId}/ConversationSummaries`,
    body
  );
  if (resp.status < 200 || resp.status >= 300) {
    console.warn(`ConversationSummaries write failed (${resp.status}):`, resp.data);
    return;
  }
  console.log(
    `Saved conversation summary for profile ${profileId} (conv ${conversationId}, ${summary.length} chars)`
  );
};
const createConversation = async (callerPhone) => {
  const payload = {
    configurationId,
    name: `Voice call ${new Date().toISOString()}`,
    participants: [
      {
        name: 'Caller',
        type: 'CUSTOMER',
        addresses: [{ channel: 'VOICE', address: callerPhone }],
      },
      {
        name: 'Owlbert Agent',
        type: 'AI_AGENT',
        addresses: [{ channel: 'VOICE', address: twilioNumber }],
      },
    ],
  };
  const resp = await http.post(`${CONVERSATIONS_BASE}/v2/Conversations`, payload);
  if (resp.status === 409) {
    const existing = extractConversationIdFromConflict(JSON.stringify(resp.data));
    if (existing) {
      console.log(`Reusing existing conversation ${existing} (previous call still open)`);
      return existing;
    }
    console.warn('Create Conversation 409 but could not extract existing id:', resp.data);
    return null;
  }
  if (resp.status < 200 || resp.status >= 300) {
    console.warn(`Create Conversation failed (${resp.status}):`, resp.data);
    return null;
  }
  return resp.data?.id ?? resp.data?.conversationId ?? null;
};
const extractConversationIdFromConflict = (body) => {
  const match = body.match(/conv_conversation_[0-9a-z]+/);
  return match ? match[0] : null;
};
const ensureProfile = async (callerPhone) => {
  const existing = await lookupProfileId(callerPhone);
  if (existing) return existing;
  const resp = await http.post(`${MEMORY_BASE}/v1/Stores/${storeId}/Profiles`, {
    traits: {
      Contact: { phone: callerPhone },
    },
  });
  if (resp.status < 200 || resp.status >= 300) {
    console.warn(`Create Profile failed (${resp.status}):`, resp.data);
    return null;
  }
  return resp.data?.id ?? null;
};
const lookupProfileId = async (phone) => {
  const resp = await http.post(
    `${MEMORY_BASE}/v1/Stores/${storeId}/Profiles/Lookup`,
    { idType: 'phone', value: phone }
  );
  if (resp.status === 404) return null;
  if (resp.status < 200 || resp.status >= 300) {
    console.warn(`Profile lookup failed (${resp.status}):`, resp.data);
    return null;
  }
  console.log('Profile lookup raw response:', resp.data);
  const rootId = extractProfileId(resp.data);
  if (rootId) return rootId;
  if (Array.isArray(resp.data?.profiles)) {
    for (const el of resp.data.profiles) {
      const found = extractProfileId(el);
      if (found) return found;
    }
  }
  return null;
};
const extractProfileId = (el) => {
  if (typeof el === 'string') return el.trim() || null;
  if (!el || typeof el !== 'object') return null;
  for (const name of ['profileId', 'id', 'profile_id']) {
    if (typeof el[name] === 'string' && el[name].trim()) return el[name];
  }
  return null;
};
const recall = async (profileId) => {
  const resp = await http.post(
    `${MEMORY_BASE}/v1/Stores/${storeId}/Profiles/${profileId}/Recall`,
    {
      observationsLimit: 20,
      summariesLimit: 5,
      communicationsLimit: 0,
    }
  );
  if (resp.status < 200 || resp.status >= 300) {
    console.warn(`Recall failed (${resp.status}):`, resp.data);
    return '';
  }
  console.log('Recall raw response:', resp.data);
  return formatRecall(resp.data);
};
const formatRecall = (data) => {
  const lines = [];
  if (Array.isArray(data?.summaries)) {
    for (const s of data.summaries) {
      const text = extractText(s, 'content', 'text', 'summary', 'value');
      if (text) lines.push(`Summary: ${text}`);
    }
  }
  if (Array.isArray(data?.observations)) {
    for (const o of data.observations) {
      const text = extractText(o, 'text', 'content', 'observation', 'value');
      if (text) lines.push(`- ${text}`);
    }
  }
  return lines.join('\n');
};
const extractText = (el, ...candidates) => {
  if (typeof el === 'string') return el;
  if (!el || typeof el !== 'object') return '';
  for (const name of candidates) {
    if (typeof el[name] === 'string') return el[name];
  }
  return '';
};
module.exports = { startCall, finishCall };

This part of the code is what will handle your multi-turn conversation.

The first thing this code does is bring in all your environment variables from .env. It then defines a startCall function that returns an object with conversationId, profileId, and memoryContext to store some information about the call. Making an API call to Conversation Summaries, it stores a Customer ID to the Memory Store that you created earlier. It also creates a profile for your caller that stores their phone number. When the call is disconnected, the summary of the call generated by OpenAI will be stored to Twilio.

If the caller calls the number back too soon, the previous call memory may still be active and trying to log. This code accounts for that by checking to see if a call is finished with finishCall. If the old call has closed out, but it recognizes the caller’s profile, the API will retrieve the summary and context of the previous call from the Memory Store. The conversation can then resume on the same topic right where it left off!

Step 8 - Finalize your application

To complete your project you will need to create an index.js file that starts the Express server, exposes the /voice webhook, and upgrades incoming WebSocket requests. Create index.js in your project’s root directory and paste in the following:

require('dotenv').config();
const express = require('express');
const expressWs = require('express-ws');
const { handle } = require('./conversationRelayHandler');
const app = express();
expressWs(app);
app.post('/voice', (req, res) => {
  const host = req.headers.host;
  const twiml = `<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Connect>
        <ConversationRelay url="wss://${host}/ws" welcomeGreeting="Thanks for calling Owlbert's Auto Repair. How can I help you today?" />
    </Connect>
</Response>`;
  res.type('application/xml').send(twiml);
});
app.ws('/ws', (ws) => {
  handle(ws);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

This sets up the WebSocket route to call your conversationRelayHandler, and includes the initial greeting for your user. Feel free to change the greeting according to your needs.

Testing, troubleshooting, or product demonstration

It is now time to test your voice application. Save your files and run the project with:

node index.js

You should see Server listening on port 3000 in your terminal. Once your webhook is running, you will need to expose it to the internet by using ngrok or another tunneling service. In a new terminal window, run:

ngrok http 3000

Replace 3000 with whatever port your application is running on if you have a different port shown.

Now ngrok will provide you with a URL for utilizing in your Twilio console. Go into your Twilio console and find the Twilio phone number that you prepared. Under the option A Call Comes In, choose Webhook, and fill in your ngrok URL followed by /voice, as shown in the graphic below:

configuration for webhooks in the Twilio console
configuration for webhooks in the Twilio console

To put your AI to the test, you’ll have to make two phone calls and check the conversation memory.

  • Make call #1: Talk to the agent about a car repair issue, including some details such as make and model.
  • Hang up and make call #2 from the same phone number.
  • Verify the agent greets you and remembers the details of your first call without any prompting.

If your Conversation Memory feature is working properly, you should also see details and a summary of the conversation saved to your Twilio dashboard. Check your Memory Store and it should show you the logged number you called from, as well as a stored conversation under Summaries:

screenshot showing conversation summary
screenshot showing conversation summary

Conclusion

Today you have learned how Twilio Conversation Memory simplifies maintaining state across separate voice calls in Node.js. This should provide value to any phone AI agent, storing information that keeps conversations feeling more convenient and human.

Do you want to do more with Twilio Conversations? Explore the possibilities by checking out the conversations documentation, where you can find blueprints for Conversational Agents, AI-to-Human handoff, and more.

Dhruv Patel is a Developer on Twilio’s Developer Voices team. You can find Dhruv working in a coffee shop with a glass of cold brew or he can be reached at dhrpatel [at] twilio.com.