Skip to content

An AI-powered search engine with a generative UI

Add chat functionality using Redis

Yoshiki Miurae213c0421260
diff --git a/bun.lockb b/bun.lockb
index 3bba42e9..de40b9ef 100755
Binary files a/bun.lockb and b/bun.lockb differ
diff --git a/lib/actions/chat.ts b/lib/actions/chat.ts
new file mode 100644
index 00000000..d118094d
--- /dev/null
+++ b/lib/actions/chat.ts
@@ -0,0 +1,79 @@
+'use server'
+
+import { type Chat } from '@/lib/types'
+import { Redis } from '@upstash/redis'
+
+const redis = new Redis({
+ url: process.env.UPSTASH_REDIS_REST_URL || '',
+ token: process.env.UPSTASH_REDIS_REST_TOKEN || ''
+})
+
+export async function getChats(userId?: string | null) {
+ if (!userId) {
+ return []
+ }
+
+ try {
+ const pipeline = redis.pipeline()
+ const chats: string[] = await redis.zrange(`user:chat:${userId}`, 0, -1, {
+ rev: true
+ })
+
+ for (const chat of chats) {
+ pipeline.hgetall(chat)
+ }
+
+ const results = await pipeline.exec()
+
+ return results as Chat[]
+ } catch (error) {
+ return []
+ }
+}
+
+export async function getChat(id: string, userId: string = 'morphic') {
+ const chat = await redis.hgetall<Chat>(`chat:${id}`)
+
+ if (!chat) {
+ return null
+ }
+
+ return chat
+}
+
+export async function getSharedChat(id: string) {
+ const chat = await redis.hgetall<Chat>(`chat:${id}`)
+
+ if (!chat || !chat.sharedPath) {
+ return null
+ }
+
+ return chat
+}
+
+export async function shareChat(id: string) {
+ const chat = await redis.hgetall<Chat>(`chat:${id}`)
+
+ if (!chat) {
+ return null
+ }
+
+ const payload = {
+ ...chat,
+ sharedPath: `/share/${chat.id}`
+ }
+
+ await redis.hmset(`chat:${id}`, payload)
+
+ return payload
+}
+
+export async function saveChat(chat: Chat, userId: string = 'morphic') {
+ const pipeline = redis.pipeline()
+ pipeline.hmset(`chat:${chat.id}`, chat)
+ pipeline.zadd(`user:chat:${chat.userId}`, {
+ score: Date.now(),
+ member: `chat:${chat.id}`
+ })
+ await pipeline.exec()
+}
diff --git a/lib/types/index.ts b/lib/types/index.ts
index 43cb522a..1341b647 100644
--- a/lib/types/index.ts
+++ b/lib/types/index.ts
@@ -1,3 +1,5 @@
+import { Message } from 'ai'
+
export type SearchResults = {
images: string[]
results: SearchResultItem[]
@@ -9,3 +11,13 @@ export type SearchResultItem = {
url: string
content: string
}
+
+export interface Chat extends Record<string, any> {
+ id: string
+ title: string
+ createdAt: Date
+ userId: string
+ path: string
+ messages: Message[]
+ sharePath?: string
+}
diff --git a/package.json b/package.json
index ed46964a..165dbc23 100644
--- a/package.json
+++ b/package.json
@@ -24,7 +24,8 @@
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tooltip": "^1.0.7",
"@tailwindcss/typography": "^0.5.12",
- "ai": "^3.0.14",
+ "@upstash/redis": "^1.30.0",
+ "ai": "3.0.14",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"embla-carousel-react": "^8.0.0",