OpenAiController.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Support\Facades\Http;
  5. use Illuminate\Http\Request;
  6. class OpenAiController extends Controller
  7. {
  8. public function getCompletion(Request $request)
  9. {
  10. $apiKey = env('OPENAI_API_KEY');
  11. $userMessage = $request->input('message');
  12. if (empty($userMessage)) {
  13. return response()->json(['error' => 'Message is required'], 400);
  14. }
  15. try {
  16. $response = Http::withHeaders([
  17. 'Authorization' => "Bearer {$apiKey}",
  18. 'Content-Type' => 'application/json'
  19. ])->post('https://api.openai.com/v1/chat/completions', [
  20. 'model' => 'gpt-3.5-turbo',
  21. 'messages' => [
  22. [
  23. 'role' => 'user',
  24. 'content' => $userMessage
  25. ]
  26. ],
  27. 'max_tokens' => 1200,
  28. ]);
  29. $data = $response->json();
  30. $text = isset($data['choices'][0]['message']['content']) ? $data['choices'][0]['message']['content'] : 'No response text found';
  31. // $text = $data;
  32. // dd($text);
  33. return response()->json(['text' => $text]);
  34. } catch (\Exception $e) {
  35. \Log::error('OpenAI API request failed', ['exception' => $e]);
  36. return response()->json(['error' => 'OpenAI API request failed'], 500);
  37. }
  38. }
  39. }