### Project Setup and Management with Makefile Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Makefile commands for initializing the project, installing dependencies, starting servers, building for production, updating submodules, and cleaning artifacts. ```bash # Check prerequisites (git, php, composer) make check-prereqs # Initialize project: clone submodules and install all dependencies make init # Copy and configure environment cp sample.env .env # Edit .env and add your DEEPGRAM_API_KEY # Start both backend (port 8081) and frontend (port 8080) servers make start # Or start servers individually make start-backend # PHP WebSocket server on port 8081 make start-frontend # Frontend dev server on port 8080 # Build frontend for production make build # Update submodules to latest versions make update # Clean all build artifacts make clean # Show git and submodule status make status # Eject frontend submodule for standalone development make eject-frontend ``` -------------------------------- ### Initialize and Start Application Source: https://github.com/deepgram-starters/php-voice-agent/blob/main/AGENTS.md Commands to initialize submodules, install dependencies, and launch the development servers. ```bash # Initialize (clone submodules + install deps) make init # Set up environment test -f .env || cp sample.env .env # then set DEEPGRAM_API_KEY # Start both servers make start # Backend: http://localhost:8081 # Frontend: http://localhost:8080 ``` -------------------------------- ### Manage Server Lifecycle Source: https://github.com/deepgram-starters/php-voice-agent/blob/main/AGENTS.md Commands for starting, stopping, and rebuilding the application environment. ```bash make start ``` ```bash # Terminal 1 — Backend php server.php # Terminal 2 — Frontend cd frontend && corepack pnpm run dev -- --port 8080 --no-open ``` ```bash lsof -ti:8080,8081 | xargs kill -9 2>/dev/null ``` ```bash rm -rf vendor frontend/node_modules frontend/.vite make init ``` -------------------------------- ### Initialize and Start PHP Voice Agent Source: https://github.com/deepgram-starters/php-voice-agent/blob/main/README.md Use these make commands to initialize the project, set up your Deepgram API key, and start the local development server. ```bash make init cp sample.env .env # Add your DEEPGRAM_API_KEY make start ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Example of a .env file for configuring the server. It specifies the required Deepgram API key and optional settings for port, host, and session secret. ```bash # .env file configuration # Required: Your Deepgram API key from https://console.deepgram.com DEEPGRAM_API_KEY=your_deepgram_api_key_here # Optional: Backend server port (default: 8081) PORT=8081 # Optional: Server host binding (default: 0.0.0.0) HOST=0.0.0.0 # Optional: JWT signing secret (auto-generated if not set) # Set this in production for consistent token validation across restarts SESSION_SECRET=your_secure_random_secret_here ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/deepgram-starters/php-voice-agent/blob/main/AGENTS.md Examples of commit messages following the conventional commits format. Ensure all commits adhere to this standard. ```git feat(php-voice-agent): add diarization support ``` ```git fix(php-voice-agent): resolve WebSocket close handling ``` ```git refactor(php-voice-agent): simplify session endpoint ``` ```git chore(deps): update frontend submodule ``` -------------------------------- ### Update Agent Settings Live Source: https://github.com/deepgram-starters/php-voice-agent/blob/main/AGENTS.md Examples of messages sent to the agent to modify behavior during an active conversation. ```json { "type": "UpdateSpeak", "model": "aura-2-luna-en" } ``` ```json { "type": "UpdatePrompt", "prompt": "New instructions..." } ``` ```json { "type": "InjectUserMessage", "content": "text" } ``` -------------------------------- ### GET /api/metadata - Retrieve Project Metadata Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Returns project metadata from the deepgram.toml configuration file, including title, description, author, and tags. Useful for displaying project information in the frontend UI. ```APIDOC ## GET /api/metadata - Retrieve Project Metadata ### Description Returns project metadata from the deepgram.toml configuration file, including title, description, author, and tags. Useful for displaying project information in the frontend UI. ### Method GET ### Endpoint /api/metadata ### Request Example ```bash curl -X GET http://localhost:8081/api/metadata ``` ### Response #### Success Response (200) - **title** (string) - The title of the project. - **description** (string) - A brief description of the project. - **author** (string) - Information about the project author. - **repository** (string) - URL to the project's repository. - **useCase** (string) - The primary use case of the project. - **language** (string) - The programming language used. - **framework** (string) - The framework used. - **sdk** (string) - The SDK used (if any). - **tags** (array of strings) - Tags associated with the project. #### Response Example ```json { "title": "PHP Voice Agent", "description": "Get started using Deepgram's Voice Agent with this PHP demo app", "author": "Deepgram DX Team (https://developers.deepgram.com)", "repository": "https://github.com/deepgram-starters/php-voice-agent", "useCase": "voice-agent", "language": "PHP", "framework": "php", "sdk": "N/A", "tags": ["voice-agent", "conversational-ai", "voice-ai", "voice-bot", "php", "ratchet"] } ``` ``` -------------------------------- ### GET /health - Health Check Endpoint Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Simple health check endpoint for monitoring and container orchestration. Returns a JSON status object indicating the server is operational. ```APIDOC ## GET /health - Health Check Endpoint ### Description Simple health check endpoint for monitoring and container orchestration. Returns a JSON status object indicating the server is operational. ### Method GET ### Endpoint /health ### Request Example ```bash curl -X GET http://localhost:8081/health ``` ### Response #### Success Response (200) - **status** (string) - Indicates the operational status of the server. #### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- ### GET /api/session - Issue JWT Session Token Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Issues a signed JWT token for authenticating WebSocket connections. The token is valid for 1 hour and must be passed as a WebSocket subprotocol when connecting to the voice agent endpoint. ```APIDOC ## GET /api/session - Issue JWT Session Token ### Description Issues a signed JWT token for authenticating WebSocket connections. The token is valid for 1 hour and must be passed as a WebSocket subprotocol when connecting to the voice agent endpoint. ### Method GET ### Endpoint /api/session ### Request Example ```bash curl -X GET http://localhost:8081/api/session ``` ### Response #### Success Response (200) - **token** (string) - A signed JWT token for WebSocket authentication. #### Response Example ```json { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MzU4NDgwMDAsImV4cCI6MTczNTg1MTYwMH0.signature" } ``` ### Usage Notes Use the token in a WebSocket connection via subprotocol: `ws://localhost:8081/api/voice-agent` Subprotocol: `access_token.` ``` -------------------------------- ### Deploy to Fly.io Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Deploy the application to the Fly.io platform using the configured fly.toml. ```bash flyctl deploy ``` -------------------------------- ### Configure Agent Settings Source: https://github.com/deepgram-starters/php-voice-agent/blob/main/AGENTS.md JSON structure for initializing the agent connection with specific audio and model parameters. ```json { "type": "Settings", "audio": { "input": { "encoding": "linear16", "sample_rate": 16000 }, "output": { "encoding": "linear16", "sample_rate": 16000 } }, "agent": { "listen": { "provider": { "type": "deepgram", "model": "nova-3" } }, "speak": { "provider": { "type": "deepgram", "model": "aura-2-thalia-en" } }, "think": { "provider": { "type": "open_ai", "model": "gpt-4o-mini" }, "prompt": "You are a helpful assistant." } } } ``` -------------------------------- ### Run Conformance Tests Source: https://github.com/deepgram-starters/php-voice-agent/blob/main/AGENTS.md Execute conformance tests for the application. This requires the application to be running. ```bash make test ``` -------------------------------- ### Deploy Voice Agent with Docker Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Commands to run the PHP voice agent container using environment variables or a configuration file. ```bash docker run -d \ -p 8080:8080 \ -e DEEPGRAM_API_KEY=your_api_key \ -e SESSION_SECRET=your_secure_secret \ php-voice-agent ``` ```bash docker run -d \ -p 8080:8080 \ --env-file .env \ php-voice-agent ``` -------------------------------- ### Build Docker Image for Production Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Command to build a Docker image for the PHP Voice Agent application using a multi-stage Dockerfile, suitable for production deployment. ```bash # Build the Docker image docker build -t php-voice-agent -f deploy/Dockerfile . ``` -------------------------------- ### Verify Deployment Health Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Check the health status of the running voice agent service. ```bash curl http://localhost:8080/api/health ``` -------------------------------- ### Retrieve Project Metadata Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Fetches project configuration details from deepgram.toml for use in frontend UI displays. ```bash # Fetch project metadata curl -X GET http://localhost:8081/api/metadata # Response: # { # "title": "PHP Voice Agent", # "description": "Get started using Deepgram's Voice Agent with this PHP demo app", # "author": "Deepgram DX Team (https://developers.deepgram.com)", # "repository": "https://github.com/deepgram-starters/php-voice-agent", # "useCase": "voice-agent", # "language": "PHP", # "framework": "php", # "sdk": "N/A", # "tags": ["voice-agent", "conversational-ai", "voice-ai", "voice-bot", "php", "ratchet"] # } ``` -------------------------------- ### Extend VoiceAgentProxy for Custom Logic Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Override onMessage and handleDeepgramMessage to implement custom logging, message transformation, or metrics tracking. ```php isBinary()) { $data = json_decode($msg->getPayload(), true); error_log("Client message type: " . ($data['type'] ?? 'unknown')); } else { error_log("Audio chunk: " . strlen($msg->getPayload()) . " bytes"); } } // Call parent to forward to Deepgram parent::onMessage($clientConn, $msg); } // Add custom handling for Deepgram responses protected function handleDeepgramMessage($deepgramConn, $msg, $clientConn) { if (!$msg->isBinary()) { $data = json_decode($msg->getPayload(), true); // Log agent responses if ($data['type'] === 'AgentStartedSpeaking') { error_log("Agent said: " . ($data['text'] ?? '')); } // Track conversation metrics if ($data['type'] === 'ConversationText') { $this->trackUtterance($data); } } // Forward to client $clientConn->send($msg->isBinary() ? new \Ratchet\RFC6455\Messaging\Frame($msg->getPayload(), true, 2) : $msg->getPayload() ); } } ``` -------------------------------- ### Define Agent Functions Source: https://github.com/deepgram-starters/php-voice-agent/blob/main/AGENTS.md JSON structure for adding function calling capabilities to the agent configuration. ```json { "agent": { "think": { "functions": [ { "name": "get_weather", "description": "Get current weather", "parameters": { "type": "object", "properties": { "city": { "type": "string" } } } } ] } } } ``` -------------------------------- ### Health Check Endpoint Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Verifies that the server is operational for monitoring and orchestration purposes. ```bash # Check server health curl -X GET http://localhost:8081/health # Response: # {"status":"ok"} ``` -------------------------------- ### Manual Endpoint Checks Source: https://github.com/deepgram-starters/php-voice-agent/blob/main/AGENTS.md Perform manual checks on the API endpoints using curl. The output is formatted using Python's json.tool for readability. ```bash curl -sf http://localhost:8081/api/metadata | python3 -m json.tool ``` ```bash curl -sf http://localhost:8081/api/session | python3 -m json.tool ``` -------------------------------- ### Connect to Deepgram Voice Agent WebSocket Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Client-side JavaScript code to establish a WebSocket connection to the voice agent. It includes steps for obtaining a session token, sending configuration settings, streaming microphone audio, and handling messages from Deepgram. ```javascript // JavaScript client example for connecting to the voice agent // Step 1: Get a session token const sessionResponse = await fetch('http://localhost:8081/api/session'); const { token } = await sessionResponse.json(); // Step 2: Connect to WebSocket with token as subprotocol const ws = new WebSocket( 'ws://localhost:8081/api/voice-agent', [`access_token.${token}`] ); ws.onopen = () => { console.log('Connected to voice agent'); // Step 3: Send configuration message to Deepgram ws.send(JSON.stringify({ type: 'SettingsConfiguration', audio: { input: { encoding: 'linear16', sample_rate: 16000 }, output: { encoding: 'linear16', sample_rate: 24000, container: 'none' } }, agent: { listen: { model: 'nova-2' }, think: { provider: { type: 'anthropic' }, model: 'claude-3-haiku-20240307' }, speak: { model: 'aura-asteria-en' } } })); }; ws.onmessage = (event) => { if (event.data instanceof Blob) { // Binary audio data from Deepgram - play through audio context console.log('Received audio chunk:', event.data.size, 'bytes'); } else { // JSON control message const message = JSON.parse(event.data); console.log('Control message:', message.type); // Handle different message types switch (message.type) { case 'Welcome': console.log('Session ID:', message.session_id); break; case 'UserStartedSpeaking': console.log('User started speaking'); break; case 'AgentThinking': console.log('Agent is processing...'); break; case 'AgentStartedSpeaking': console.log('Agent response:', message.text); break; case 'Error': console.error('Error:', message.description); break; } } }; // Step 4: Stream microphone audio to the voice agent navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => { const audioContext = new AudioContext({ sampleRate: 16000 }); const source = audioContext.createMediaStreamSource(stream); const processor = audioContext.createScriptProcessor(4096, 1, 1); processor.onaudioprocess = (e) => { if (ws.readyState === WebSocket.OPEN) { const inputData = e.inputBuffer.getChannelData(0); const pcmData = new Int16Array(inputData.length); for (let i = 0; i < inputData.length; i++) { pcmData[i] = Math.max(-32768, Math.min(32767, inputData[i] * 32768)); } ws.send(pcmData.buffer); } }; source.connect(processor); processor.connect(audioContext.destination); }); ws.onclose = (event) => { console.log('Disconnected:', event.code, event.reason); }; ws.onerror = (error) => { console.error('WebSocket error:', error); }; ``` -------------------------------- ### Issue JWT Session Token Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Retrieves a signed JWT token required for authenticating WebSocket connections to the voice agent. ```bash # Request a session token for WebSocket authentication curl -X GET http://localhost:8081/api/session # Response: # {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MzU4NDgwMDAsImV4cCI6MTczNTg1MTYwMH0.signature"} # Use the token in a WebSocket connection via subprotocol: # WebSocket URL: ws://localhost:8081/api/voice-agent # Subprotocol: access_token.eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9... ``` -------------------------------- ### Validate JWT for WebSocket Connections Source: https://context7.com/deepgram-starters/php-voice-agent/llms.txt Extract and verify JWT tokens from WebSocket subprotocols to secure client connections. ```php * Returns the protocol string if valid, null if invalid. */ function validateWsToken(?string $protocols): ?string { global $SESSION_SECRET; if (!$protocols) { return null; } // Parse comma-separated subprotocols $list = array_map('trim', explode(',', $protocols)); $tokenProto = null; foreach ($list as $proto) { if (str_starts_with($proto, 'access_token.')) { $tokenProto = $proto; break; } } if (!$tokenProto) { return null; } // Extract and validate JWT $token = substr($tokenProto, strlen('access_token.')); try { $decoded = JWT::decode($token, new Key($SESSION_SECRET, 'HS256')); // Token is valid - contains iat and exp claims return $tokenProto; } catch (\Exception $e) { // Invalid or expired token error_log("Token validation failed: " . $e->getMessage()); return null; } } // Usage in WebSocket connection handler public function onOpen(ConnectionInterface $clientConn) { $protocols = $clientConn->httpRequest->getHeader('Sec-WebSocket-Protocol'); $protocolStr = !empty($protocols) ? implode(', ', $protocols) : null; $validProto = validateWsToken($protocolStr); if (!$validProto) { echo "WebSocket auth failed: invalid or missing token\n"; $clientConn->close(); return; } echo "Client connected (authenticated)\n"; // Proceed with Deepgram connection... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.