Skip to content

Commit 30c1a02

Browse files
Merge pull request #3 from vijaythecoder/feature/ephemeral-key-implementation
Implement secure ephemeral key generation for OpenAI Realtime API
2 parents 3793306 + a10158a commit 30c1a02

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

app/Http/Controllers/RealtimeController.php

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use App\Services\ApiKeyService;
66
use Illuminate\Http\Request;
7+
use Illuminate\Support\Facades\Http;
78
use Illuminate\Support\Facades\Log;
89

910
class 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

Comments
 (0)