File size: 1,754 Bytes
c59d808
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { LOCAL_STORAGE_KEY } from "@/constants/chat";
import { ChatPart } from "@/types/chat";
import { UIMessage, UIDataTypes, UITools, generateId } from "ai";

export const getTextMessagesFromParts = (
  messages: UIMessage<unknown, UIDataTypes, UITools>[]
) => {
  return messages.flatMap(
    (message: UIMessage<unknown, UIDataTypes, UITools>) => {
      // Get all text parts
      const textParts =
        message.parts?.filter((p: ChatPart) => p.type === "text") || [];
      return textParts.map((textPart: ChatPart) => {
        let text = textPart.text || "";
        // If assistant, try to parse JSON response
        if (message.role === "assistant") {
          try {
            const parsed = JSON.parse(text);
            text = parsed.response || "I didn't get that. Could you rephrase?";
          } catch {
            text = "Something went wrong. Please try again.";
          }
        }
        return {
          id: message.id,
          text,
          isSender: message.role === "user",
        };
      });
    }
  );
};

export function generateChatId() {
  return generateId();
}

export function getStoredChats() {
  if (typeof window === "undefined") return {};
  const storedMessages = JSON.parse(
    localStorage.getItem(LOCAL_STORAGE_KEY) || "{}"
  );
  return storedMessages;
}

export function saveChat(
  id: string,
  messages: UIMessage<unknown, UIDataTypes, UITools>[]
) {
  if (!id) return;
  const chats = getStoredChats();
  chats[id] = messages;
  localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(chats));
}

export function deleteChat(id: string) {
  const chats = getStoredChats();
  if (chats[id]) {
    delete chats[id];
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(chats));
  }
}