File size: 13,395 Bytes
6111b2b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | import { getSettings } from "@/lib/db/settings";
import { createEmbeddingResponse } from "@/lib/embeddings/service";
type JsonRecord = Record<string, unknown>;
export type QdrantConfig = {
enabled: boolean;
host: string;
port: number;
apiKey: string | null;
collection: string;
embeddingModel: string;
};
export function normalizeQdrantConfig(settings: Record<string, unknown>): QdrantConfig {
const host = typeof settings.qdrantHost === "string" ? settings.qdrantHost.trim() : "";
const portRaw = settings.qdrantPort;
const port =
typeof portRaw === "number" && Number.isFinite(portRaw)
? Math.round(portRaw)
: typeof portRaw === "string"
? Math.round(Number(portRaw) || 6333)
: 6333;
const apiKey =
typeof settings.qdrantApiKey === "string" && settings.qdrantApiKey.trim().length > 0
? settings.qdrantApiKey.trim()
: null;
const collection =
typeof settings.qdrantCollection === "string" && settings.qdrantCollection.trim().length > 0
? settings.qdrantCollection.trim()
: "omniroute_memory";
const embeddingModel =
typeof settings.qdrantEmbeddingModel === "string" &&
settings.qdrantEmbeddingModel.trim().length > 0
? settings.qdrantEmbeddingModel.trim()
: "openai/text-embedding-3-small";
const enabled = settings.qdrantEnabled === true;
return { enabled, host, port, apiKey, collection, embeddingModel };
}
export async function getQdrantConfig(): Promise<QdrantConfig> {
const settings = (await getSettings()) as Record<string, unknown>;
return normalizeQdrantConfig(settings);
}
function baseUrl(cfg: QdrantConfig): string {
const host = cfg.host.replace(/\/+$/, "");
const withProto =
host.startsWith("http://") || host.startsWith("https://") ? host : `http://${host}`;
try {
const url = new URL(withProto);
if (!url.port) url.port = String(cfg.port);
return url.toString().replace(/\/+$/, "");
} catch {
return `${withProto}:${cfg.port}`;
}
}
async function qdrantFetch(cfg: QdrantConfig, path: string, init?: RequestInit): Promise<Response> {
const headers: Record<string, string> = {
"content-type": "application/json",
...(init?.headers as Record<string, string> | undefined),
};
if (cfg.apiKey) headers["api-key"] = cfg.apiKey;
return fetch(`${baseUrl(cfg)}${path}`, {
...init,
headers,
});
}
export async function checkQdrantHealth(): Promise<{
ok: boolean;
latencyMs: number;
error?: string;
}> {
const cfg = await getQdrantConfig();
const start = Date.now();
if (!cfg.enabled || !cfg.host) {
return { ok: false, latencyMs: 0, error: "not_configured" };
}
try {
const res = await qdrantFetch(cfg, "/readyz", { method: "GET" });
const latencyMs = Date.now() - start;
if (!res.ok) {
const text = await res.text().catch(() => "");
return { ok: false, latencyMs, error: text.slice(0, 200) || `HTTP ${res.status}` };
}
return { ok: true, latencyMs };
} catch (err) {
return {
ok: false,
latencyMs: Date.now() - start,
error: err instanceof Error ? err.message : String(err),
};
}
}
async function ensureCollection(cfg: QdrantConfig, vectorSize: number): Promise<void> {
const getRes = await qdrantFetch(cfg, `/collections/${encodeURIComponent(cfg.collection)}`, {
method: "GET",
});
if (getRes.ok) return;
const createRes = await qdrantFetch(cfg, `/collections/${encodeURIComponent(cfg.collection)}`, {
method: "PUT",
body: JSON.stringify({
vectors: { size: vectorSize, distance: "Cosine" },
}),
});
if (!createRes.ok) {
const text = await createRes.text().catch(() => "");
throw new Error(text.slice(0, 300) || `Failed to create collection (${createRes.status})`);
}
}
async function getCollectionVectorName(cfg: QdrantConfig): Promise<string | null> {
const res = await qdrantFetch(cfg, `/collections/${encodeURIComponent(cfg.collection)}`, {
method: "GET",
});
if (!res.ok) return null;
const data = (await res.json().catch(() => null)) as any;
const vectors = data?.result?.config?.params?.vectors;
if (!vectors || typeof vectors !== "object" || Array.isArray(vectors)) {
return null;
}
// Unnamed/single-vector config: { size, distance, ... } (not a named map)
if (
Object.prototype.hasOwnProperty.call(vectors, "size") &&
(typeof vectors.size === "number" || typeof vectors.size === "string")
) {
return null;
}
const names = Object.keys(vectors);
if (names.length === 0) return null;
return names[0] || null;
}
async function embedText(cfg: QdrantConfig, text: string): Promise<number[]> {
const modelStr = cfg.embeddingModel.trim();
if (!modelStr.includes("/")) {
throw new Error(`Invalid embedding model '${modelStr}'. Use provider/model format.`);
}
const res = await createEmbeddingResponse({
model: modelStr,
input: text,
});
if (!res.ok) {
const txt = await res.text().catch(() => "");
throw new Error(txt.slice(0, 300) || `Embeddings request failed (${res.status})`);
}
const data = (await res.json().catch(() => null)) as any;
const vec = data?.data?.[0]?.embedding;
if (!Array.isArray(vec) || vec.length === 0) {
throw new Error("Embedding response missing vector");
}
return vec as number[];
}
export async function upsertSemanticMemoryPoint(input: {
id: string;
apiKeyId: string;
sessionId: string;
key: string;
content: string;
metadata: JsonRecord;
createdAt: string;
expiresAt: string | null;
}): Promise<{ ok: boolean; latencyMs: number; error?: string }> {
const cfg = await getQdrantConfig();
if (!cfg.enabled || !cfg.host) return { ok: false, latencyMs: 0, error: "not_configured" };
const start = Date.now();
try {
const vector = await embedText(cfg, `${input.key}\n\n${input.content}`);
await ensureCollection(cfg, vector.length);
const vectorName = await getCollectionVectorName(cfg);
const createdAtUnix = Math.floor(new Date(input.createdAt).getTime() / 1000);
const expiresAtUnix = input.expiresAt
? Math.floor(new Date(input.expiresAt).getTime() / 1000)
: null;
const payload = {
kind: "omniroute_memory",
memoryId: input.id,
apiKeyId: input.apiKeyId || "",
sessionId: input.sessionId || "",
type: "semantic",
key: input.key || "",
content: input.content || "",
metadata: input.metadata || {},
createdAtUnix,
expiresAtUnix,
};
const res = await qdrantFetch(
cfg,
`/collections/${encodeURIComponent(cfg.collection)}/points?wait=true`,
{
method: "PUT",
body: JSON.stringify({
points: [
{
id: input.id,
vector: vectorName ? { [vectorName]: vector } : vector,
payload,
},
],
}),
}
);
const latencyMs = Date.now() - start;
if (!res.ok) {
const text = await res.text().catch(() => "");
return { ok: false, latencyMs, error: text.slice(0, 300) || `HTTP ${res.status}` };
}
return { ok: true, latencyMs };
} catch (err) {
return {
ok: false,
latencyMs: Date.now() - start,
error: err instanceof Error ? err.message : String(err),
};
}
}
export async function searchSemanticMemory(
query: string,
topK = 5,
scope?: { apiKeyId?: string; sessionId?: string | null }
): Promise<{
ok: boolean;
latencyMs: number;
results?: Array<{ id: string; score: number; payload?: JsonRecord }>;
error?: string;
}> {
const cfg = await getQdrantConfig();
if (!cfg.enabled || !cfg.host) return { ok: false, latencyMs: 0, error: "not_configured" };
const start = Date.now();
try {
const vector = await embedText(cfg, query);
await ensureCollection(cfg, vector.length);
const vectorName = await getCollectionVectorName(cfg);
const res = await qdrantFetch(
cfg,
`/collections/${encodeURIComponent(cfg.collection)}/points/search`,
{
method: "POST",
body: JSON.stringify({
vector: vectorName ? { name: vectorName, vector } : vector,
limit: Math.max(1, Math.min(20, topK)),
filter: {
must: [
{ key: "kind", match: { value: "omniroute_memory" } },
...(scope?.apiKeyId ? [{ key: "apiKeyId", match: { value: scope.apiKeyId } }] : []),
...(scope?.sessionId
? [{ key: "sessionId", match: { value: String(scope.sessionId) } }]
: []),
],
},
with_payload: true,
}),
}
);
const latencyMs = Date.now() - start;
if (!res.ok) {
const text = await res.text().catch(() => "");
return { ok: false, latencyMs, error: text.slice(0, 300) || `HTTP ${res.status}` };
}
const data = (await res.json().catch(() => null)) as any;
const result = Array.isArray(data?.result) ? data.result : [];
return {
ok: true,
latencyMs,
results: result.map((r: any) => ({
id: String(r.id),
score: typeof r.score === "number" ? r.score : 0,
payload: r.payload && typeof r.payload === "object" ? (r.payload as JsonRecord) : undefined,
})),
};
} catch (err) {
return {
ok: false,
latencyMs: Date.now() - start,
error: err instanceof Error ? err.message : String(err),
};
}
}
export async function deleteSemanticMemoryPoint(
id: string
): Promise<{ ok: boolean; latencyMs: number; error?: string }> {
const cfg = await getQdrantConfig();
if (!cfg.enabled || !cfg.host) return { ok: false, latencyMs: 0, error: "not_configured" };
const start = Date.now();
try {
const res = await qdrantFetch(
cfg,
`/collections/${encodeURIComponent(cfg.collection)}/points/delete?wait=true`,
{
method: "POST",
body: JSON.stringify({ points: [id] }),
}
);
const latencyMs = Date.now() - start;
if (!res.ok) {
const text = await res.text().catch(() => "");
return { ok: false, latencyMs, error: text.slice(0, 300) || `HTTP ${res.status}` };
}
return { ok: true, latencyMs };
} catch (err) {
return {
ok: false,
latencyMs: Date.now() - start,
error: err instanceof Error ? err.message : String(err),
};
}
}
export async function cleanupSemanticMemoryPoints(input: {
retentionDays: number;
}): Promise<{ ok: boolean; deletedCount: number; latencyMs: number; error?: string }> {
const cfg = await getQdrantConfig();
if (!cfg.enabled || !cfg.host)
return { ok: false, deletedCount: 0, latencyMs: 0, error: "not_configured" };
const retentionDays =
typeof input.retentionDays === "number" && Number.isFinite(input.retentionDays)
? Math.max(1, Math.min(3650, Math.round(input.retentionDays)))
: 30;
const start = Date.now();
try {
const nowUnix = Math.floor(Date.now() / 1000);
const cutoffUnix = nowUnix - retentionDays * 24 * 60 * 60;
const filter: Record<string, unknown> = {
must: [{ key: "kind", match: { value: "omniroute_memory" } }],
should: [
{ key: "expiresAtUnix", range: { lt: nowUnix } },
{ key: "createdAtUnix", range: { lt: cutoffUnix } },
],
};
// Count first (so we can show an actual number in the dashboard)
const countRes = await qdrantFetch(
cfg,
`/collections/${encodeURIComponent(cfg.collection)}/points/count`,
{
method: "POST",
body: JSON.stringify({ filter, exact: true }),
}
);
if (!countRes.ok) {
const text = await countRes.text().catch(() => "");
return {
ok: false,
deletedCount: 0,
latencyMs: Date.now() - start,
error: text.slice(0, 300) || `HTTP ${countRes.status}`,
};
}
const countData = (await countRes.json().catch(() => null)) as any;
const toDelete =
typeof countData?.result?.count === "number" && Number.isFinite(countData.result.count)
? Math.max(0, Math.round(countData.result.count))
: 0;
if (toDelete === 0) {
return { ok: true, deletedCount: 0, latencyMs: Date.now() - start };
}
const delRes = await qdrantFetch(
cfg,
`/collections/${encodeURIComponent(cfg.collection)}/points/delete?wait=true`,
{
method: "POST",
body: JSON.stringify({
filter,
}),
}
);
if (!delRes.ok) {
const text = await delRes.text().catch(() => "");
return {
ok: false,
deletedCount: 0,
latencyMs: Date.now() - start,
error: text.slice(0, 300) || `HTTP ${delRes.status}`,
};
}
return { ok: true, deletedCount: toDelete, latencyMs: Date.now() - start };
} catch (err) {
return {
ok: false,
deletedCount: 0,
latencyMs: Date.now() - start,
error: err instanceof Error ? err.message : String(err),
};
}
}
|