vertex_ai_search-1.0.0-beta4/src/Plugin/Autocomplete/VertexAutocomplete.php

src/Plugin/Autocomplete/VertexAutocomplete.php
<?php

namespace Drupal\vertex_ai_search\Plugin\Autocomplete;

use Drupal\Core\Form\FormStateInterface;
use Drupal\vertex_ai_search\Plugin\VertexAutocompletePluginBase;
use Google\ApiCore\ApiException;
use Google\Cloud\DiscoveryEngine\V1\Client\CompletionServiceClient;
use Google\Cloud\DiscoveryEngine\V1\CompleteQueryRequest;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Handles searching for node entities using the Search module index.
 *
 * @VertexAutocompletePlugin(
 *   id = "vertex_autocomplete_vertex",
 *   title = @Translation("Vertex Autocomplete")
 * )
 */
class VertexAutocomplete extends VertexAutocompletePluginBase {

  /**
   * Logger service object.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * {@inheritdoc}
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    LoggerInterface $logger,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('logger.channel.vertex_ai_search'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getSuggestions($keys) {

    try {
      return $this->doCompleteQuery($keys);
    }
    catch (ApiException $ex) {
      // ApiException Exception.
      $this->logger->error(
        'Vertex AI Search Autocomplete APIException error occurred: @error.
        Message: @message.',
        [
          '@error' => $ex->getStatus(),
          '@message' => $ex->getMessage(),
        ],
      );
    }
    catch (\Exception $ex) {
      $this->logger->error('Vertex AI Search Autocomplete Exception error
        occurred.  Message: @message. Details: @details.',
        [
          '@message' => $ex->getMessage(),
          '@details' => $ex->__toString(),
        ],
      );
    }
    return [];
  }

  /**
   * Protected method to perform the actual Completion API call.
   *
   * @param string $keys
   *   The search keys.
   *
   * @return array
   *   The suggestions array.
   *
   * @throws \Google\ApiCore\ApiException
   * @throws \Exception
   */
  protected function doCompleteQuery($keys) {

    $config = $this->getConfiguration();

    $formattedDataStore = CompletionServiceClient::dataStoreName(
      $config['google_cloud_project_id'],
      $config['google_cloud_location'],
      $config['vertex_ai_data_store_id']
    );

    $credPath = $config['service_account_credentials_file'];
    $transport = $config['transport_method'] ?? NULL;

    $clientParameters['credentials'] = json_decode(
      file_get_contents($credPath),
      TRUE
    );

    if (!empty($transport)) {
      $clientParameters['transport'] = $transport;
    }

    $completionServiceClient = new CompletionServiceClient($clientParameters);

    $request = (new CompleteQueryRequest())
      ->setDataStore($formattedDataStore)
      ->setQuery($keys);

    /** @var \Google\Cloud\DiscoveryEngine\V1\CompleteQueryResponse $response */
    $response = $completionServiceClient->completeQuery($request);
    $jsonResults = $response->serializeToJsonString();
    $suggestionResults = json_decode($jsonResults, TRUE);
    $suggestions = [];

    if (empty($suggestionResults['querySuggestions'])) {
      return $suggestions;
    }

    foreach ($suggestionResults['querySuggestions'] as $suggestion) {
      $suggestions[] = $suggestion['suggestion'];
    }

    return $suggestions;

  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {

    $form['autocomplete_model'] = [
      '#title' => $this->t('Autocomplete Model'),
      '#type' => 'select',
      '#required' => TRUE,
      '#options' => [
        'search_history' => $this->t('Search History'),
      ],
      '#default_value' => $this->configuration['autocomplete_model'] ?? NULL,
    ];

    return $form;

  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc