openai-php / symfony

⚡️ OpenAI PHP for Symfony is a supercharged PHP API client that allows you to interact with OpenAI API
MIT License
183 stars 26 forks source link

Cannot access service #21

Open globexdigitalentertainment opened 4 days ago

globexdigitalentertainment commented 4 days ago

Hi,

I cannot seem to inject the service or access it in any way, unless I explicitly alias it as public - which I do not want.

Unless I am doing it wrong... please advise.

Example:

<?php

namespace App\Controller;

use OpenAI\Contracts\ClientContract;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

class OpenAIController extends AbstractController
{
    private $openai;

    public function __construct(ClientContract $openai)
    {
        $this->openai = $openai;
    }

    #[Route('/openai/test', name: 'openai_test')]
    public function test(): JsonResponse
    {
        $response = $this->openai->chat()->create([
            'model' => 'gpt-3.5-turbo',
            'messages' => [
                ['role' => 'user', 'content' => 'Hello, OpenAI!'],
            ],
        ]);

        return $this->json(['response' => $response['choices'][0]['message']['content'] ?? 'No response']);
    }
}
globexdigitalentertainment commented 3 days ago

Anyone care to provide a small example?

GromNaN commented 3 days ago

The service for the interface OpenAI\Contracts\ClientContract is not defined. This will be fixed by #22. You can use the OpenAPI\Client class for autowiring.

<?php

  namespace App\Controller;

- use OpenAI\Contracts\ClientContract;
+ use OpenAI\Client;
  use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  use Symfony\Component\HttpFoundation\JsonResponse;
  use Symfony\Component\Routing\Annotation\Route;

  class OpenAIController extends AbstractController
  {
      private $openai;

-    public function __construct(ClientContract $openai)
+    public function __construct(Client $openai)
      {
          $this->openai = $openai;
      }

      #[Route('/openai/test', name: 'openai_test')]
      public function test(): JsonResponse
      {
          $response = $this->openai->chat()->create([
              'model' => 'gpt-3.5-turbo',
              'messages' => [
                  ['role' => 'user', 'content' => 'Hello, OpenAI!'],
              ],
          ]);

          return $this->json(['response' => $response['choices'][0]['message']['content'] ?? 'No response']);
      }
  }