File size: 1,371 Bytes
a1c5622
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fd8446
 
a1c5622
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Message } from '@prisma/client';
import { MessageAssistantResponse, MessageUI } from '../types';
import { ChunkBody } from './content';

/**
 * The Message we saved to database consists of a prompt and a response
 * for the UI to use, we need to break them to 2 messages, User and Assistant(if responded)
 */
export const convertDBMessageToUIMessage = (
  messages: Message[],
): MessageUI[] => {
  return messages.reduce((acc, message) => {
    const { id, mediaUrl, prompt, response, result } = message;
    if (mediaUrl && prompt) {
      acc.push({
        id: id + '-user',
        role: 'user',
        content: prompt,
        mediaUrl,
      });
    }
    if (response) {
      acc.push({
        id: id + '-assistant',
        role: 'assistant',
        content: response,
      });
    }
    return acc;
  }, [] as MessageUI[]);
};

export const convertAssistantUIMessageToDBMessageResponse = (
  message: MessageUI,
): MessageAssistantResponse => {
  let result = null;
  const lines = message.content.split('\n');
  for (let line of lines) {
    try {
      const json = JSON.parse(line) as ChunkBody;
      if (json.type == 'final_code') {
        result = json as PrismaJson.FinalChatResult;
        break;
      }
    } catch (e) {
      console.error((e as Error).message);
    }
  }
  return {
    response: message.content,
    result,
  };
};