Spaces:
Running
Running
File size: 2,119 Bytes
98051f8 3b05d51 98051f8 3b05d51 c202241 8aab1a5 d7b4e1d 3b05d51 c554635 c85ac8f 4ae2179 c554635 3b05d51 4ae2179 c554635 3b05d51 c554635 3b05d51 c554635 4ae2179 3b05d51 4ae2179 4a66e10 ab516c8 4ae2179 8aab1a5 c6896b8 3b05d51 c554635 ab516c8 8aab1a5 566c2fc c554635 8aab1a5 98051f8 8aab1a5 98051f8 8aab1a5 a95d8a5 d72b096 a95d8a5 |
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 72 73 74 75 76 77 |
import type { RequestHandler } from "./$types";
import { collections } from "$lib/server/database";
import { ObjectId } from "mongodb";
import { error, redirect } from "@sveltejs/kit";
import { base } from "$app/paths";
import { z } from "zod";
import type { Message } from "$lib/types/Message";
import { models, validateModel } from "$lib/server/models";
export const POST: RequestHandler = async ({ locals, request }) => {
const body = await request.text();
let title = "";
let messages: Message[] = [];
const values = z
.object({
fromShare: z.string().optional(),
model: validateModel(models),
preprompt: z.string().optional(),
})
.parse(JSON.parse(body));
let preprompt = values.preprompt;
if (values.fromShare) {
const conversation = await collections.sharedConversations.findOne({
_id: values.fromShare,
});
if (!conversation) {
throw error(404, "Conversation not found");
}
title = conversation.title;
messages = conversation.messages;
values.model = conversation.model;
preprompt = conversation.preprompt;
}
const model = models.find((m) => m.name === values.model);
if (!model) {
throw error(400, "Invalid model");
}
if (model.unlisted) {
throw error(400, "Can't start a conversation with an unlisted model");
}
// Use the model preprompt if there is no conversation/preprompt in the request body
preprompt = preprompt === undefined ? model?.preprompt : preprompt;
const res = await collections.conversations.insertOne({
_id: new ObjectId(),
title: title || "New Chat",
messages,
model: values.model,
preprompt: preprompt === model?.preprompt ? model?.preprompt : preprompt,
createdAt: new Date(),
updatedAt: new Date(),
...(locals.user ? { userId: locals.user._id } : { sessionId: locals.sessionId }),
...(values.fromShare ? { meta: { fromShareId: values.fromShare } } : {}),
});
return new Response(
JSON.stringify({
conversationId: res.insertedId.toString(),
}),
{ headers: { "Content-Type": "application/json" } }
);
};
export const GET: RequestHandler = async () => {
throw redirect(302, `${base}/`);
};
|