File size: 2,152 Bytes
770735d
0fc59f9
5b1a9aa
2c00ea8
bf75aa7
6655689
 
 
770735d
f58e466
0fc59f9
6655689
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fc59f9
 
43606a3
0fc59f9
 
5b1a9aa
43606a3
 
 
 
 
 
 
 
59118b8
43606a3
 
 
0fc59f9
bf75aa7
 
 
28b6d44
bf75aa7
 
 
 
 
6d7dd9c
9264459
770735d
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
64
65
66
67
68
69
70
71
import type { Message } from "$lib/types/Message";
import { format } from "date-fns";
import type { EndpointMessage } from "../../endpoints/endpoints";
import { generateFromDefaultEndpoint } from "../../generateFromDefaultEndpoint";
import { getReturnFromGenerator } from "$lib/utils/getReturnFromGenerator";
import { smallModel } from "$lib/server/models";
import type { Tool } from "$lib/types/Tool";
import { getToolOutput } from "$lib/server/tools/getToolOutput";

export async function generateQuery(messages: Message[]) {
	const currentDate = format(new Date(), "MMMM d, yyyy");

	if (smallModel.tools) {
		const webSearchTool = {
			name: "web_search",
			description: "Search the web for information",
			inputs: [
				{
					name: "query",
					type: "str",
					description: "The query to search the web for",
					paramType: "required",
				},
			],
		} as unknown as Tool;

		const endpoint = await smallModel.getEndpoint();
		const query = await getToolOutput({
			messages,
			preprompt: `The user wants you to search the web for information. Give a relevant google search query to answer the question. Answer with only the query. Today is ${currentDate}`,
			tool: webSearchTool,
			endpoint,
		});

		if (query) {
			return query;
		}
	}

	const userMessages = messages.filter(({ from }) => from === "user");
	const previousUserMessages = userMessages.slice(0, -1);

	const lastMessage = userMessages.slice(-1)[0];

	const convQuery: Array<EndpointMessage> = [
		{
			from: "user",
			content:
				(previousUserMessages.length > 0
					? `Previous questions: \n${previousUserMessages
							.map(({ content }) => `- ${content}`)
							.join("\n")}`
					: "") +
				"\n\nCurrent Question: " +
				lastMessage.content,
		},
	];

	const webQuery = await getReturnFromGenerator(
		generateFromDefaultEndpoint({
			messages: convQuery,
			preprompt: `The user wants you to search the web for information. Give a relevant google search query to answer the question. Answer with only the query. Today is ${currentDate}. The conversation follows: \n`,
			generateSettings: {
				max_new_tokens: 30,
			},
		})
	);

	return webQuery.trim();
}