Files
materio-d9/web/modules/custom/materio_ai/src/Search/QueryEmbedder.php
T
bachirandClaude Opus 5.5 6d8c64c94f materio_ai: cached search vectors, 1 s delay, pause and cron warm-up (H8)
- QueryEmbedder: vector of a search phrase cached 30 days (cache bin
  materio_ai), model given search_timeout seconds (1 by default, new
  setting, update 11001), left alone 60 s after a failure
  (ModelPausedException, not logged).
- NeighbourSearch honours the enabled setting: the search called the model
  even when materio_ai was switched off.
- materio_ai_cron() loads the model with the normal timeout: after a
  restart, loading (2.9 s) exceeds the search delay and Ollama drops it,
  so searches alone would never load it. Ultimate cron job exported.
- On any model failure the search answers with the keyword results only.
- QueryEmbedderTest: cache, delay, pause, cache during the pause, warm-up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ShDspHaZGwHoRZCsPBJzsM
2026-11-17 18:26:19 +01:00

106 lines
3.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Drupal\materio_ai\Search;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\materio_ai\Embedding\EmbeddingClientInterface;
use Drupal\materio_ai\Exception\EmbeddingException;
use Drupal\materio_ai\Exception\ModelPausedException;
/**
* Vector of a search phrase: cached, with a short delay and a pause (H8).
*
* A search must answer even when the model is slow or stopped:
* - vectors are cached by model and phrase (cache bin materio_ai, Redis on
* the servers); they hold nothing about the user, so one entry serves
* everybody;
* - the model gets search_timeout seconds (1 by default);
* - after a failure the model is left alone for PAUSE seconds: the searches
* of that time do not each wait for the delay again.
*
* On failure an EmbeddingException is thrown, and the caller answers with
* the keyword results.
*
* A model that took longer than the delay to load is unloaded again by
* Ollama when the call is dropped: searches alone would never load it after
* a restart (2.9 s measured locally). warmUp(), run by cron with the normal
* timeout, loads it.
*/
final class QueryEmbedder {
/**
* Lifetime of a cached vector, in seconds (30 days).
*/
public const LIFETIME = 2592000;
/**
* Seconds without calling the model after a failure.
*/
public const PAUSE = 60;
public function __construct(
private readonly EmbeddingClientInterface $client,
private readonly CacheBackendInterface $cache,
private readonly ConfigFactoryInterface $configFactory,
private readonly TimeInterface $time,
) {}
/**
* Whether the model may be called (setting « enabled »).
*/
public function isEnabled(): bool {
return (bool) $this->configFactory->get('materio_ai.settings')->get('enabled');
}
/**
* Loads the model with the normal timeout, and ends the pause.
*
* Uses the client options of the searches (num_thread): with other options
* Ollama would load the model again.
*
* @throws \Drupal\materio_ai\Exception\EmbeddingException
* When the model fails.
*/
public function warmUp(): void {
$this->client->embed('materiO');
$this->cache->delete('pause:' . $this->client->getModel());
}
/**
* Returns the vector of a phrase.
*
* @return float[]
* The vector.
*
* @throws \Drupal\materio_ai\Exception\EmbeddingException
* When the model fails or is too slow; ModelPausedException when it
* failed less than PAUSE seconds ago.
*/
public function embed(string $phrase): array {
$model = $this->client->getModel();
$cid = 'query:' . $model . ':' . hash('sha256', $phrase);
if ($cached = $this->cache->get($cid)) {
return $cached->data;
}
$pause_cid = 'pause:' . $model;
if ($this->cache->get($pause_cid)) {
throw new ModelPausedException(sprintf('Model %s paused after a failure.', $model));
}
$timeout = (float) ($this->configFactory->get('materio_ai.settings')->get('search_timeout') ?? 1.0);
try {
$vector = $this->client->embed($phrase, max(0.1, $timeout));
}
catch (EmbeddingException $e) {
$this->cache->set($pause_cid, TRUE, $this->time->getRequestTime() + self::PAUSE);
throw $e;
}
$this->cache->set($cid, $vector, $this->time->getRequestTime() + self::LIFETIME);
return $vector;
}
}