Spaces:
Running
Running
File size: 1,573 Bytes
01b06a3 98051f8 0c6af63 a7f2fe0 92a7501 0c6af63 a7f2fe0 0c6af63 a7f2fe0 0c6af63 f58e466 0c6af63 f58e466 11983d2 f58e466 c202241 f58e466 92a7501 |
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 |
import type { BackendModel } from "./server/models";
import type { Message } from "./types/Message";
import { collections } from "$lib/server/database";
import { ObjectId } from "mongodb";
import { authCondition } from "./server/auth";
/**
* Convert [{user: "assistant", content: "hi"}, {user: "user", content: "hello"}] to:
*
* <|assistant|>hi<|endoftext|><|prompter|>hello<|endoftext|><|assistant|>
*/
interface buildPromptOptions {
messages: Pick<Message, "from" | "content">[];
model: BackendModel;
locals?: App.Locals;
webSearchId?: string;
preprompt?: string;
}
export async function buildPrompt({
messages,
model,
locals,
webSearchId,
preprompt,
}: buildPromptOptions): Promise<string> {
if (webSearchId) {
const webSearch = await collections.webSearches.findOne({
_id: new ObjectId(webSearchId),
});
if (!webSearch) throw new Error("Web search not found");
if (!locals) throw new Error("User not authenticated");
const conversation = await collections.conversations.findOne({
_id: webSearch.convId,
...authCondition(locals),
});
if (!conversation) throw new Error("Conversation not found");
if (webSearch.summary) {
messages = [
{
from: "assistant",
content: `The following context was found while searching the internet: ${webSearch.summary}`,
},
...messages,
];
}
}
return (
model
.chatPromptRender({ messages, preprompt })
// Not super precise, but it's truncated in the model's backend anyway
.split(" ")
.slice(-(model.parameters?.truncate ?? 0))
.join(" ")
);
}
|