File size: 2,120 Bytes
8d88d9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { isURLLocal } from "../isURLLocal";
import { env } from "$env/dynamic/private";
import { collections } from "$lib/server/database";
import type { Assistant } from "$lib/types/Assistant";
import type { ObjectId } from "mongodb";

export async function processPreprompt(preprompt: string, user_message: string | undefined) {
	const requestRegex = /{{\s?(get|post|url)=(.*?)\s?}}/g;

	for (const match of preprompt.matchAll(requestRegex)) {
		const method = match[1].toUpperCase();
		const urlString = match[2];
		try {
			const url = new URL(urlString);
			if ((await isURLLocal(url)) && env.ENABLE_LOCAL_FETCH !== "true") {
				throw new Error("URL couldn't be fetched, it resolved to a local address.");
			}

			let res;
			if (method == "POST") {
				res = await fetch(url.href, {
					method: "POST",
					body: user_message,
					headers: {
						"Content-Type": "text/plain",
					},
				});
			} else if (method == "GET" || method == "URL") {
				res = await fetch(url.href);
			} else {
				throw new Error("Invalid method " + method);
			}

			if (!res.ok) {
				throw new Error("URL couldn't be fetched, error " + res.status);
			}
			const text = await res.text();
			preprompt = preprompt.replaceAll(match[0], text);
		} catch (e) {
			preprompt = preprompt.replaceAll(match[0], (e as Error).message);
		}
	}

	return preprompt;
}

export async function getAssistantById(id?: ObjectId) {
	return collections.assistants
		.findOne<Pick<Assistant, "rag" | "dynamicPrompt" | "generateSettings" | "tools">>(
			{ _id: id },
			{ projection: { rag: 1, dynamicPrompt: 1, generateSettings: 1, tools: 1 } }
		)
		.then((a) => a ?? undefined);
}

export function assistantHasWebSearch(assistant?: Pick<Assistant, "rag"> | null) {
	return (
		env.ENABLE_ASSISTANTS_RAG === "true" &&
		!!assistant?.rag &&
		(assistant.rag.allowedLinks.length > 0 ||
			assistant.rag.allowedDomains.length > 0 ||
			assistant.rag.allowAllDomains)
	);
}

export function assistantHasDynamicPrompt(assistant?: Pick<Assistant, "dynamicPrompt">) {
	return env.ENABLE_ASSISTANTS_RAG === "true" && Boolean(assistant?.dynamicPrompt);
}