50 lines
1.2 KiB
PHP
50 lines
1.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Knowledge\Retrieval;
|
|
|
|
use Psr\Cache\CacheItemPoolInterface;
|
|
use Psr\Cache\InvalidArgumentException;
|
|
|
|
final readonly class CachedRetriever implements RetrieverInterface
|
|
{
|
|
public function __construct(
|
|
private RetrieverInterface $inner,
|
|
private CacheItemPoolInterface $cache,
|
|
private int $ttlSeconds = 300,
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* @return string[]
|
|
* @throws InvalidArgumentException
|
|
*/
|
|
public function retrieve(string $prompt): array
|
|
{
|
|
$key = $this->buildCacheKey($prompt);
|
|
|
|
$item = $this->cache->getItem($key);
|
|
if ($item->isHit()) {
|
|
$cached = $item->get();
|
|
|
|
return is_array($cached) ? $cached : [];
|
|
}
|
|
|
|
$result = $this->inner->retrieve($prompt);
|
|
|
|
$item->set($result);
|
|
$item->expiresAfter($this->ttlSeconds);
|
|
$this->cache->save($item);
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function buildCacheKey(string $prompt): string
|
|
{
|
|
$normalized = mb_strtolower(trim($prompt));
|
|
$normalized = preg_replace('/\s+/u', ' ', $normalized) ?? $normalized;
|
|
|
|
return 'rag_retrieval_' . sha1($normalized);
|
|
}
|
|
} |