EverydayTech Platform - Developer Reference
Complete Source Code Documentation - All Applications
Loading...
Searching...
No Matches
llmRedis.js
Go to the documentation of this file.
1// llmRedis.js - Redis-backed LLM utilities for llama.cpp
2const Redis = require('ioredis');
3const crypto = require('crypto');
4const redisConfig = require('../config/redis');
5const redis = new Redis(redisConfig);
6
7/**
8 * Generate SHA-256 hash of text.
9 * @param {string} text - Text to hash
10 * @returns {string} Hex-encoded hash
11 */
12function hash(text) {
13 return crypto.createHash('sha256').update(text).digest('hex');
14}
15
16/**
17 * Get cached LLM result from Redis.
18 * @param {string} type - LLM operation type (e.g., 'summarize', 'classify')
19 * @param {string} text - Input text
20 * @returns {Promise<string|null>} Cached result or null
21 */
22async function getCachedLLMResult(type, text) {
23 const key = `llm:${type}:${hash(text)}`;
24 return await redis.get(key);
25}
26
27/**
28 * Set cached LLM result in Redis.
29 * @param {string} type - LLM operation type
30 * @param {string} text - Input text
31 * @param {string} result - LLM result to cache
32 * @param {number} [ttl] - Time to live in seconds (default: 604800 = 7 days)
33 * @returns {Promise<void>}
34 */
35async function setCachedLLMResult(type, text, result, ttl = 604800) {
36 const key = `llm:${type}:${hash(text)}`;
37 await redis.set(key, result, 'EX', ttl);
38}
39
40/**
41 * Check rate limit for tenant.
42 * @param {number} tenantId - Tenant ID
43 * @param {number} [limit] - Maximum requests allowed (default: 20)
44 * @param {number} [window] - Time window in seconds (default: 60)
45 * @returns {Promise<boolean>} True if rate limit exceeded
46 */
47async function rateLimit(tenantId, limit = 20, window = 60) {
48 const key = `llm:rate:${tenantId}`;
49 const count = await redis.incr(key);
50 if (count === 1) await redis.expire(key, window);
51 return count > limit;
52}
53
54/**
55 * Acquire lock for document processing.
56 * @param {string} docId - Document ID
57 * @param {number} [ttl] - Lock TTL in seconds (default: 3)
58 * @returns {Promise<boolean>} True if lock acquired
59 */
60async function acquireLock(docId, ttl = 3) {
61 const key = `llm:lock:${docId}`;
62 const lock = await redis.set(key, 1, 'NX', 'EX', ttl);
63 return !!lock;
64}
65
66module.exports = {
67 getCachedLLMResult,
68 setCachedLLMResult,
69 rateLimit,
70 acquireLock,
71};