UNPKG

@prexo/ai-chat-sdk

Version:

AI Chat Component with Persistent History

54 lines (53 loc) 1.36 kB
import { Redis } from "@upstash/redis"; import { DEFAULT_CHAT_SESSION_ID, DEFAULT_HISTORY_LENGTH, DEFAULT_HISTORY_TTL } from "../../lib/constants.js"; class InRedisHistory { client; constructor(config) { const { config: redisConfig, client } = config; if (client) { this.client = client; } else if (redisConfig) { this.client = new Redis(redisConfig); } else { throw new Error( "Redis message stores require either a config object or a pre-configured client." ); } } async addMessage(params) { const { message, sessionId, sessionTTL } = params; let TTL = DEFAULT_HISTORY_TTL; if (sessionTTL) { TTL = sessionTTL; } const sessionID = DEFAULT_CHAT_SESSION_ID(sessionId); await this.client.lpush(sessionID, JSON.stringify(message)); if (sessionTTL) { await this.client.expire(sessionID, TTL); } } async deleteMessages({ sessionId }) { await this.client.del(sessionId); } async getMessages({ sessionId, amount = DEFAULT_HISTORY_LENGTH, startIndex = 0 }) { const sessionID = DEFAULT_CHAT_SESSION_ID(sessionId); const endIndex = startIndex + amount - 1; const messages = await this.client.lrange( sessionID, startIndex, endIndex ); return messages.reverse(); } } export { InRedisHistory };