(
userMessage: string,
orgId: number,
conversationIndex: number,
supabase: SupabaseClient<Database>,
)
| 23 | } |
| 24 | |
| 25 | async initialize( |
| 26 | userMessage: string, |
| 27 | orgId: number, |
| 28 | conversationIndex: number, |
| 29 | supabase: SupabaseClient<Database>, |
| 30 | ): Promise<void> { |
| 31 | this.orgId = orgId; |
| 32 | const { data: matchingConvData, error: matchConvError } = await supabase |
| 33 | .from("chat_messages") |
| 34 | .select("conversation_id") |
| 35 | .match({ |
| 36 | role: "user", |
| 37 | org_id: orgId, |
| 38 | content: userMessage, |
| 39 | conversation_index: conversationIndex, |
| 40 | fresh: true, |
| 41 | }) |
| 42 | // Take the most recent matching conversation that isn't the current one |
| 43 | .order("conversation_id", { ascending: false }) |
| 44 | // This will return the current convo & optionally the most recent matching 4 convos |
| 45 | .limit(5); |
| 46 | if (matchConvError) console.error(matchConvError.message); |
| 47 | |
| 48 | if (matchingConvData && matchingConvData?.length > 1) { |
| 49 | console.log("Main hit", matchingConvData.slice(1)); |
| 50 | // Get chat messages for all matching conversations |
| 51 | const { data: matchingChatData, error: chatError } = await supabase |
| 52 | .from("chat_messages") |
| 53 | .select( |
| 54 | "role,content,name,summary,conversation_index,conversation_id,chosen_actions,chosen_route,chat_summary", |
| 55 | ) |
| 56 | .eq("org_id", orgId) |
| 57 | .in( |
| 58 | "conversation_id", |
| 59 | matchingConvData.slice(1).map((c) => c.conversation_id), |
| 60 | ) |
| 61 | .order("conversation_id", { ascending: false }); |
| 62 | if (chatError) console.error(chatError.message); |
| 63 | if (matchingChatData && matchingChatData.length > 1) { |
| 64 | // Iterate through the matching conversations to find if there's a valid one |
| 65 | for (const convId of matchingConvData |
| 66 | .slice(1) |
| 67 | .map((c) => c.conversation_id)) { |
| 68 | const matchingChat = matchingChatData |
| 69 | .filter((c) => c.conversation_id === convId) |
| 70 | .sort((a, b) => a.conversation_index - b.conversation_index); |
| 71 | |
| 72 | // Skip if the conversation is too short or the last message is the same as the user message |
| 73 | if ( |
| 74 | matchingChat.length > 1 && |
| 75 | !["", userMessage].includes(matchingChat[1].content) |
| 76 | ) { |
| 77 | // Sometimes due to errors, there are gaps in the conversation index, we cut |
| 78 | // the history to where these gaps are |
| 79 | const cutIdx = matchingChat.findIndex( |
| 80 | (m, idx) => m.conversation_index !== idx, |
| 81 | ); |
| 82 | if (cutIdx !== -1) { |
no outgoing calls
no test coverage detected