44
55use App \Services \ApiKeyService ;
66use Illuminate \Http \Request ;
7+ use Illuminate \Support \Facades \Http ;
78use Illuminate \Support \Facades \Log ;
89
910class RealtimeController extends Controller
@@ -30,13 +31,35 @@ public function generateEphemeralKey(Request $request)
3031 ], 422 );
3132 }
3233
33- // Return the actual API key for now
34- // OpenAI Realtime API uses the API key directly in WebSocket connection
34+ // Generate ephemeral key from OpenAI Realtime API
35+ $ response = Http::withHeaders ([
36+ 'Authorization ' => 'Bearer ' . $ apiKey ,
37+ 'Content-Type ' => 'application/json ' ,
38+ ])->post ('https://api.openai.com/v1/realtime/sessions ' , [
39+ 'model ' => 'gpt-4o-realtime-preview-2024-12-17 ' ,
40+ 'voice ' => $ request ->input ('voice ' , 'alloy ' ),
41+ ]);
42+
43+ if (!$ response ->successful ()) {
44+ Log::error ('OpenAI API error: ' . $ response ->body ());
45+ throw new \Exception ('Failed to generate ephemeral key from OpenAI: ' . $ response ->status ());
46+ }
47+
48+ $ data = $ response ->json ();
49+
50+ // Validate response structure
51+ if (!isset ($ data ['client_secret ' ]['value ' ]) || !isset ($ data ['client_secret ' ]['expires_at ' ])) {
52+ Log::error ('Invalid response structure from OpenAI API ' , ['response ' => $ data ]);
53+ throw new \Exception ('Invalid response structure from OpenAI API ' );
54+ }
55+
56+ // Return ephemeral key data
3557 return response ()->json ([
3658 'status ' => 'success ' ,
37- 'ephemeralKey ' => $ apiKey , // Use actual API key
38- 'expiresAt ' => now ()->addMinutes (60 )->toIso8601String (),
39- 'model ' => 'gpt-4o-realtime-preview-2024-12-17 ' ,
59+ 'ephemeralKey ' => $ data ['client_secret ' ]['value ' ],
60+ 'expiresAt ' => $ data ['client_secret ' ]['expires_at ' ],
61+ 'sessionId ' => $ data ['id ' ] ?? null ,
62+ 'model ' => $ data ['model ' ] ?? 'gpt-4o-realtime-preview-2024-12-17 ' ,
4063 ]);
4164
4265 } catch (\Exception $ e ) {
0 commit comments