OpenAI.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Webkul\MagicAI\Services;
  3. use OpenAI\Laravel\Facades\OpenAI as BaseOpenAI;
  4. class OpenAI
  5. {
  6. /**
  7. * New service instance.
  8. */
  9. public function __construct(
  10. protected string $model,
  11. protected string $prompt,
  12. protected float $temperature,
  13. protected bool $stream = false
  14. ) {
  15. $this->setConfig();
  16. }
  17. /**
  18. * Sets OpenAI credentials.
  19. */
  20. public function setConfig(): void
  21. {
  22. config([
  23. 'openai.api_key' => core()->getConfigData('general.magic_ai.settings.api_key'),
  24. 'openai.organization' => core()->getConfigData('general.magic_ai.settings.organization'),
  25. ]);
  26. }
  27. /**
  28. * Set LLM prompt text.
  29. */
  30. public function ask(): string
  31. {
  32. $result = BaseOpenAI::chat()->create([
  33. 'model' => $this->model,
  34. 'temperature' => $this->temperature,
  35. 'messages' => [
  36. [
  37. 'role' => 'user',
  38. 'content' => $this->prompt,
  39. ],
  40. ],
  41. ]);
  42. return $result->choices[0]->message->content;
  43. }
  44. /**
  45. * Generate image.
  46. */
  47. public function images(array $options): array
  48. {
  49. $result = BaseOpenAI::images()->create([
  50. 'model' => $this->model,
  51. 'prompt' => $this->prompt,
  52. 'n' => intval($options['n'] ?? 1),
  53. 'size' => $options['size'],
  54. 'quality' => $options['quality'] ?? 'standard',
  55. 'response_format' => 'b64_json',
  56. ]);
  57. $images = [];
  58. foreach ($result->data as $image) {
  59. $images[]['url'] = 'data:image/png;base64,'.$image->b64_json;
  60. }
  61. return $images;
  62. }
  63. }