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
This commit is contained in:
@@ -12,12 +12,18 @@ interface EmbeddingClientInterface {
|
||||
/**
|
||||
* Returns the vector of one text.
|
||||
*
|
||||
* @param string $text
|
||||
* The text to vectorize.
|
||||
* @param float|null $timeout
|
||||
* Longest wait in seconds; the configured timeout by default. A search
|
||||
* passes a short one (search_timeout, H8).
|
||||
*
|
||||
* @return float[]
|
||||
* A vector of getDimension() values.
|
||||
*
|
||||
* @throws \Drupal\materio_ai\Exception\EmbeddingException
|
||||
*/
|
||||
public function embed(string $text): array;
|
||||
public function embed(string $text, ?float $timeout = NULL): array;
|
||||
|
||||
/**
|
||||
* Returns the vectors of several texts, in the same order and with the same keys.
|
||||
|
||||
@@ -23,13 +23,13 @@ final class OllamaEmbeddingClient implements EmbeddingClientInterface {
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function embed(string $text): array {
|
||||
public function embed(string $text, ?float $timeout = NULL): array {
|
||||
$text = trim($text);
|
||||
if ($text === '') {
|
||||
throw new EmbeddingException('Cannot vectorize an empty text.');
|
||||
}
|
||||
$config = $this->config();
|
||||
$timeout = max(1, (int) $config->get('timeout'));
|
||||
$timeout ??= (float) max(1, (int) $config->get('timeout'));
|
||||
$url = rtrim((string) $config->get('url'), '/') . '/api/embed';
|
||||
|
||||
try {
|
||||
@@ -42,7 +42,7 @@ final class OllamaEmbeddingClient implements EmbeddingClientInterface {
|
||||
'options' => ['num_thread' => max(1, (int) $config->get('num_thread'))],
|
||||
],
|
||||
'timeout' => $timeout,
|
||||
'connect_timeout' => min($timeout, 3),
|
||||
'connect_timeout' => min($timeout, 3.0),
|
||||
]);
|
||||
}
|
||||
catch (GuzzleException $e) {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Drupal\materio_ai\Exception;
|
||||
|
||||
/**
|
||||
* The model is not called: it failed less than QueryEmbedder::PAUSE seconds ago.
|
||||
*
|
||||
* The failure itself was already logged; this one is not worth a log line.
|
||||
*/
|
||||
final class ModelPausedException extends EmbeddingException {}
|
||||
@@ -63,6 +63,15 @@ final class SettingsForm extends ConfigFormBase {
|
||||
'#required' => TRUE,
|
||||
'#config_target' => 'materio_ai.settings:timeout',
|
||||
];
|
||||
$form['search_timeout'] = [
|
||||
'#type' => 'number',
|
||||
'#title' => $this->t('Search timeout (seconds)'),
|
||||
'#description' => $this->t('Longest wait for the vector of a search. Past it, the search answers with keywords only.'),
|
||||
'#min' => 0.1,
|
||||
'#step' => 0.1,
|
||||
'#required' => TRUE,
|
||||
'#config_target' => 'materio_ai.settings:search_timeout',
|
||||
];
|
||||
$form['num_thread'] = [
|
||||
'#type' => 'number',
|
||||
'#title' => $this->t('Threads per call'),
|
||||
|
||||
@@ -7,7 +7,6 @@ namespace Drupal\materio_ai\Search;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Language\LanguageManagerInterface;
|
||||
use Drupal\materio_ai\Embedding\EmbeddingClientInterface;
|
||||
use Drupal\search_api\Utility\Utility;
|
||||
|
||||
/**
|
||||
@@ -41,7 +40,7 @@ final class NeighbourSearch {
|
||||
private readonly EntityTypeManagerInterface $entityTypeManager,
|
||||
private readonly LanguageManagerInterface $languageManager,
|
||||
private readonly ConfigFactoryInterface $configFactory,
|
||||
private readonly EmbeddingClientInterface $client,
|
||||
private readonly QueryEmbedder $embedder,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -55,16 +54,21 @@ final class NeighbourSearch {
|
||||
* Number of neighbours (topK).
|
||||
*
|
||||
* @return array<int, float>
|
||||
* Scores keyed by nid, best first. Solr score of a cosine kNN query:
|
||||
* Scores keyed by nid, best first, none when materio_ai is switched off.
|
||||
* Solr score of a cosine kNN query:
|
||||
* (1 + cosine) / 2.
|
||||
*
|
||||
* @throws \Drupal\materio_ai\Exception\EmbeddingException
|
||||
* When the model fails.
|
||||
* When the model fails or is too slow (QueryEmbedder).
|
||||
* @throws \Drupal\search_api\SearchApiException
|
||||
* When Solr fails.
|
||||
*/
|
||||
public function search(string $phrase, ?string $langcode = NULL, int $limit = 100): array {
|
||||
return $this->searchVector($this->client->embed($phrase), $langcode, $limit);
|
||||
// Switched off: no text is sent to the model, keyword results only.
|
||||
if (!$this->embedder->isEnabled()) {
|
||||
return [];
|
||||
}
|
||||
return $this->searchVector($this->embedder->embed($phrase), $langcode, $limit);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
<?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;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user