Skip to content

Commit bebf446

Browse files
committed
feat: experimental semantic cache
1 parent 99357ea commit bebf446

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

src/Experiments/SemanticCache.php

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<?php
2+
3+
namespace Upstash\Vector\Experiments;
4+
5+
use Upstash\Vector\DataQuery;
6+
use Upstash\Vector\DataUpsert;
7+
use Upstash\Vector\IndexNamespace;
8+
9+
readonly class SemanticCache
10+
{
11+
public function __construct(
12+
private IndexNamespace $index,
13+
public float $minScore = 0.95,
14+
) {
15+
//
16+
}
17+
18+
public function get(string $key): ?string
19+
{
20+
$result = $this->index->queryData(new DataQuery(
21+
data: $key,
22+
topK: 1,
23+
includeMetadata: true,
24+
));
25+
26+
if ($result->count() === 0) {
27+
return null;
28+
}
29+
30+
$result = $result->offsetGet(0);
31+
if ($result->score < $this->minScore) {
32+
return null;
33+
}
34+
35+
$value = $result->metadata['value'];
36+
if ($value === null) {
37+
return null;
38+
}
39+
40+
return $value;
41+
}
42+
43+
/**
44+
* @param string|array<string> $keys
45+
*/
46+
public function set(string|array $keys, string $value): void
47+
{
48+
if (is_string($keys)) {
49+
$keys = [$keys];
50+
}
51+
52+
$upserts = array_map(fn ($key) => new DataUpsert(
53+
id: md5($key),
54+
data: $key,
55+
metadata: ['value' => $value],
56+
), $keys);
57+
58+
$this->index->upsertDataMany($upserts);
59+
}
60+
61+
/**
62+
* @param string|array<string> $keys
63+
*/
64+
public function delete(string|array $keys): void
65+
{
66+
if (is_string($keys)) {
67+
$keys = [$keys];
68+
}
69+
70+
$this->index->delete(
71+
ids: array_map(fn ($key) => md5($key), $keys),
72+
);
73+
}
74+
75+
public function clear(): void
76+
{
77+
$this->index->reset();
78+
}
79+
}

0 commit comments

Comments
 (0)