File size: 1,845 Bytes
6434339
ebac87f
6434339
447c0ca
6434339
447c0ca
ebac87f
 
 
 
 
 
 
 
 
6434339
ebac87f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6434339
 
 
 
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
import type { Message } from "$lib/types/Message";
import { format } from "date-fns";
import { generateFromDefaultEndpoint } from "../generateFromDefaultEndpoint";
import { defaultModel } from "../models";

export async function generateQuery(messages: Message[]) {
	const currentDate = format(new Date(), "MMMM d, yyyy");
	const userMessages = messages.filter(({ from }) => from === "user");
	const previousUserMessages = userMessages.slice(0, -1);
	const lastMessage = userMessages.slice(-1)[0];
	const promptSearchQuery = defaultModel.webSearchQueryPromptRender({
		message: lastMessage,
		previousMessages: previousUserMessages.map(({ content }) => content).join(" "),
		currentDate,
	});
	const searchQuery = await generateFromDefaultEndpoint(promptSearchQuery).then((query) => {
		// example of generating google query:
		// case 1
		// user: tell me what happened yesterday
		// LLM: google query is "news september 12, 2023"
		// the regex below will try to capture the last "phrase" (i.e. words between quotes or double quotes or ticks)
		// in this case, it is "news september 12, 2023"
		// if there is no "phrase", we will just use the user query, which was "tell me what happened yesterday"
		const regexLastPhrase = /("|'|`)((?:(?!\1).)+)\1$/;
		let match = query.match(regexLastPhrase);
		if (match) {
			return match[2];
		}

		// case 2
		// user: tell me what happened yesterday
		// LLM: Here is a query: news september 12, 2023
		// the regex below will try to capture the last sentences starting from :
		// in this case, it is "news september 12, 2023"
		// if there is no math, we will just use the user query, which was "tell me what happened yesterday"
		const regexColon = /:\s(.*)$/;
		match = query.match(regexColon);
		if (match) {
			return match[1];
		}

		return lastMessage.content;
	});

	return searchQuery;
}