PHP code example of in2code / alternative

1. Go to this page and download the library: Download in2code/alternative library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

in2code / alternative example snippets




declare(strict_types=1);

namespace Vendor\MyExtension\Domain\Repository\Llm;

use In2code\Alternative\Domain\Repository\Llm\AbstractRepository;
use In2code\Alternative\Domain\Repository\Llm\RepositoryInterface;
use In2code\Alternative\Exception\ApiException;
use In2code\Alternative\Exception\ConfigurationException;
use TYPO3\CMS\Core\Http\RequestFactory;
use TYPO3\CMS\Core\Resource\File;

class ChatGptRepository extends AbstractRepository implements RepositoryInterface
{
    private string $apiKey = '';
    private string $apiUrl = 'https://api.openai.com/v1/chat/completions';

    public function __construct(
        protected RequestFactory $requestFactory,
    ) {
        parent::__construct($requestFactory);
        $this->apiKey = getenv('OPENAI_API_KEY') ?: '';
    }

    public function checkApiKey(): void
    {
        if ($this->apiKey === '') {
            throw new ConfigurationException('OpenAI API key not configured', 1735646000);
        }
    }

    public function getApiUrl(): string
    {
        return $this->apiUrl;
    }

    /**
     * Analyze image and return metadata for all requested languages in one API call
     *
     * @param File $file
     * @param array $languageCodes e.g. ['en', 'de', 'fr']
     * @return array e.g. ['en' => ['title' => '...', ...], 'de' => [...], ...]
     */
    public function analyzeImageForLanguages(File $file, array $languageCodes): array
    {
        $this->checkApiKey();
        $imageData = base64_encode($file->getContents());
        return $this->generateMetadataWithChatGpt($imageData, $file->getMimeType(), $languageCodes);
    }

    protected function generateMetadataWithChatGpt(string $imageData, string $mimeType, array $languageCodes): array
    {
        $payload = [
            'model' => 'gpt-4o',
            'messages' => [
                [
                    'role' => 'user',
                    'content' => [
                        ['type' => 'text', 'text' => $this->getPrompt($languageCodes)],
                        [
                            'type' => 'image_url',
                            'image_url' => [
                                'url' => 'data:' . $mimeType . ';base64,' . $imageData,
                            ],
                        ],
                    ],
                ],
            ],
            'temperature' => 0.1,
            'max_tokens' => 2000,
        ];

        $options = [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode($payload),
        ];

        $response = $this->requestFactory->request($this->getApiUrl(), $this->requestMethod, $options);

        if ($response->getStatusCode() !== 200) {
            throw new ApiException(
                'Failed to analyze image with ChatGPT: ' . $response->getBody()->getContents(),
                1735646001
            );
        }

        $responseData = json_decode($response->getBody()->getContents(), true);
        return $this->parseResponse($responseData, $languageCodes);
    }

    protected function parseResponse(array $responseData, array $languageCodes): array
    {
        if (isset($responseData['choices'][0]['message']['content']) === false) {
            throw new ApiException('Invalid ChatGPT API response structure', 1735646002);
        }

        $text = $responseData['choices'][0]['message']['content'];
        $text = $this->extractJsonFromResponse($text);
        $data = json_decode($text, true);
        if ($data === null) {
            throw new ApiException('Could not parse ChatGPT response as JSON', 1735646003);
        }

        $result = [];
        foreach ($languageCodes as $languageCode) {
            $languageData = $data[$languageCode] ?? [];
            $result[$languageCode] = [
                'title' => $languageData['title'] ?? '',
                'description' => $languageData['description'] ?? '',
                'alternativeText' => $languageData['alternativeText'] ?? '',
            ];
        }
        return $result;
    }
}


defined('TYPO3') || die();

// Register custom LLM repository
$GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS']['alternative']['llmRepositoryClass']
    = \Vendor\MyExtension\Domain\Repository\Llm\ChatGptRepository::class;