This example demonstrates how to use OpenAI with Twilio Agent Connect (TAC) to build an intelligent conversational agent that works across both SMS and Voice channels.
- Multi-Channel Support: Handles both SMS and Voice conversations in a single application
- OpenAI Integration: Uses GPT-4o-mini for intelligent, context-aware responses
- Memory Integration: Automatically retrieves user profiles and conversation history from Twilio Memory
- Profile Personalization: Incorporates user profile traits into responses for personalized interactions
- Conversation History: Maintains context across multiple message exchanges
- Node.js 22.13.0+ installed
- Twilio Account with a phone number
- OpenAI API Key for GPT-4o-mini access
- ngrok or similar tunneling tool for local development
From the repository root:
npm install
npm run buildThen install the example's dependencies:
cd getting_started/examples/openai
npm installFrom the getting_started/examples/ directory:
cp .env.example .env
# Edit .env with your credentialsRequired variables:
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_API_KEY=SKxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_API_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_PHONE_NUMBER=+1xxxxxxxxxx
TWILIO_CONVERSATION_CONFIGURATION_ID=conv_configuration_xxxxxxxxxxxxxxxxxxxxxxxxxx
OPENAI_API_KEY=sk-proj-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxnpm run devThe server starts on http://localhost:8000 with endpoints:
POST /webhook- SMS webhook endpointPOST /twiml- Voice webhook endpoint (generates TwiML)WS /ws- Voice WebSocket endpointPOST /conversation-relay-callback- Voice callback endpoint
In another terminal, start ngrok:
ngrok http 8000Copy the ngrok URL (e.g., https://abc123.ngrok.app).
SMS:
- In the Console, go to Products & services > Conversation Orchestrator > Conversation Configurations.
- Select your conversation configuration.
- In the Overview tab, click Edit.
- Set Webhook > Callback method to
https://abc123.ngrok.app/webhookwith HTTP methodPOST. - Click Save changes.
Voice:
- In the Console, go to Products & services > Numbers & senders.
- Select your Twilio phone number.
- Under Voice configuration, set the webhook URL to
https://abc123.ngrok.app/twimlwith HTTP methodPOST.
Send an SMS to your Twilio number:
- "Hello!" → AI responds with a personalized greeting
- "What can you help me with?" → AI explains its capabilities
- "Remember my name is John" → AI remembers and uses your name in future conversations
Call your Twilio number:
- Say "Hello" → AI responds via voice
- Have a natural conversation → AI maintains context across the call
- Conversation history is preserved for future calls
getting_started/examples/openai/
├── src/
│ └── index.ts # Main application
├── package.json # Dependencies
├── tsconfig.json # TypeScript config
└── README.md # This file
When Memory is configured and channels are set to memoryMode: 'always', TAC automatically:
- Retrieves user profile information before each message
- Includes profile traits (name, preferences, etc.) in the AI context
- Loads recent conversation history for context continuity
The example configures channels with automatic memory retrieval:
const voiceChannel = new VoiceChannel(tac, { memoryMode: 'always' });
const smsChannel = new SMSChannel(tac, { memoryMode: 'always' });To disable automatic memory retrieval (default is 'never'), omit the memoryMode option or use tac.retrieveMemory() in your callback for conditional retrieval.
The example uses MemoryPromptBuilder to automatically format memory data into structured prompts that include:
- Customer Profile: Profile traits such as name, preferences, and other known customer details when available
- Key Observations: Important notes from previous interactions
- Past Conversation Summaries: Summaries of previous conversations
- Recent Message History: Recent communications with the customer
This context is injected as a system message to help the AI provide context-aware responses.
The application maintains conversation history per conversation ID, allowing the AI to:
- Remember what was said earlier in the conversation
- Provide contextually relevant responses
- Build on previous exchanges
- Error Handling: Add comprehensive error handling and retry logic
- Rate Limiting: Implement rate limiting to prevent abuse
- Monitoring: Add logging and metrics for production debugging
- Security: Enable Twilio webhook signature validation in production
- Scaling: Consider horizontal scaling for high-volume applications
- Cost Management: Monitor OpenAI API usage and implement cost controls
- Customize the system prompt for your specific use case
- Add tool calling to enable agent actions (e.g., look up information, create tickets)
- Implement conversation handoff to human agents
- Add support for additional channels (WhatsApp, etc.)
- OpenAI Errors: Verify your API key and check for rate limits
- Memory Errors: Ensure Memory service credentials are correct
- Webhook Errors: Verify ngrok is running and webhooks are configured correctly
- WebSocket Issues: Check that your ngrok URL uses HTTPS for WebSocket connections