ai_accessibility-1.0.2/src/Provider/OpenAIProvider.php
src/Provider/OpenAIProvider.php
<?php
namespace Drupal\ai_accessibility\Provider;
use Drupal\Core\Config\ConfigFactoryInterface;
class OpenAIProvider implements AIProviderInterface {
protected $httpClient;
protected $configFactory;
public function __construct($http_client, ConfigFactoryInterface $config_factory) {
$this->httpClient = $http_client;
$this->configFactory = $config_factory;
}
public function suggest(string $issue_id, string $html = ''): array {
$config = $this->configFactory->get('ai_accessibility.settings');
$api_key = $config->get('api_key');
if (empty($api_key)) {
return [[ 'text' => 'API key no configurada', 'action' => 'none' ]];
}
// Build a small prompt based on issue id.
$prompt = '';
if ($issue_id === 'img-alt-1') {
$prompt = "Provide a concise alt attribute for the following image. Context:\n$html";
}
else {
$prompt = "Provide an accessibility suggestion for the issue: $issue_id\nContext:\n$html";
}
try {
$response = $this->httpClient->post('https://api.openai.com/v1/chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . $api_key,
'Content-Type' => 'application/json',
],
'body' => json_encode([
'model' => 'gpt-3.5-turbo',
'messages' => [[ 'role' => 'user', 'content' => $prompt ]],
'max_tokens' => 60,
]),
]);
$body = json_decode((string) $response->getBody(), TRUE);
$text = $body['choices'][0]['message']['content'] ?? '';
return [[ 'text' => trim($text), 'action' => 'set_alt' ]];
}
catch (\Exception $e) {
return [[ 'text' => 'Error calling OpenAI: ' . $e->getMessage(), 'action' => 'none' ]];
}
}
}
