TwilioAmanda Lange, Matthew Setter11 min readtutorialintermediate
How to Connect Your Twilio Agent to External APIs with PHP
Summary
A step‑by‑step tutorial showing how to build a Twilio voice agent in PHP (using OpenSwoole) that calls OpenAI’s gpt‑4o‑mini model and can invoke an external REST API (Cat Facts) via tool‑calling, wiring everything together with Twilio Conversation Relay and a WebSocket server.
- Set up a PHP 8.5+ project with Composer and install openai‑php/client, guzzlehttp/guzzle, vlucas/phpdotenv, and twilio/sdk.
- Use a .env file for the OpenAI API key and server host/port.
- Run an OpenSwoole WebSocket server (Swoole\\WebSocket\Server) that serves a TwiML endpoint at /voice, which returns a <Connect><ConversationRelay> pointing to the WS endpoint.
- ConversationRelayHandler manages per‑connection state, handling setup, prompt, interrupt, and error messages from Twilio’s Conversation Relay.
Shows a concrete integration pattern for voice‑first LLM agents that need real‑time data, combining Twilio Conversation Relay, a coroutine‑based PHP server, and OpenAI function calling. The code is complete and runnable, making it a useful reference for engineers building similar voice‑AI products.
6/10



