Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add api assistants endpoints #951

Merged
merged 2 commits into from Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
50 changes: 50 additions & 0 deletions src/routes/api/assistants/+server.ts
@@ -0,0 +1,50 @@
import { collections } from "$lib/server/database.js";
import type { Assistant } from "$lib/types/Assistant";
import type { User } from "$lib/types/User";
import { generateQueryTokens } from "$lib/utils/searchTokens.js";
import type { Filter } from "mongodb";

const NUM_PER_PAGE = 24;

export async function GET({ url, locals }) {
const modelId = url.searchParams.get("modelId");
const pageIndex = parseInt(url.searchParams.get("p") ?? "0");
const username = url.searchParams.get("user");
const query = url.searchParams.get("q")?.trim() ?? null;
const createdByCurrentUser = locals.user?.username && locals.user.username === username;

let user: Pick<User, "_id"> | null = null;
if (username) {
user = await collections.users.findOne<Pick<User, "_id">>(
{ username },
{ projection: { _id: 1 } }
);
if (!user) {
return Response.json({ message: `User "${username}" doesn't exist` }, { status: 404 });
}
}

// fetch the top assistants sorted by user count from biggest to smallest, filter out all assistants with only 1 users. filter by model too if modelId is provided
const filter: Filter<Assistant> = {
...(modelId && { modelId }),
...(!createdByCurrentUser && { userCount: { $gt: 1 } }),
...(user ? { createdById: user._id } : { featured: true }),
...(query && { searchTokens: { $all: generateQueryTokens(query) } }),
};
const assistants = await collections.assistants
.find(filter)
.skip(NUM_PER_PAGE * pageIndex)
.sort({ userCount: -1 })
.limit(NUM_PER_PAGE)
.toArray();

const numTotalItems = await collections.assistants.countDocuments(filter);

return Response.json({
assistants,
selectedModel: modelId ?? "",
numTotalItems,
numItemsPerPage: NUM_PER_PAGE,
query,
});
}
43 changes: 43 additions & 0 deletions src/routes/api/user/assistants/+server.ts
@@ -0,0 +1,43 @@
import { authCondition } from "$lib/server/auth";
import type { Conversation } from "$lib/types/Conversation";
import { collections } from "$lib/server/database";
import { ObjectId } from "mongodb";

export async function GET({ locals }) {
if (locals.user?._id || locals.sessionId) {
const settings = await collections.settings.findOne(authCondition(locals));

const conversations = await collections.conversations
.find(authCondition(locals))
.sort({ updatedAt: -1 })
.project<Pick<Conversation, "assistantId">>({
assistantId: 1,
})
.limit(300)
.toArray();

const userAssistants = settings?.assistants?.map((assistantId) => assistantId.toString()) ?? [];
const userAssistantsSet = new Set(userAssistants);

const assistantIds = [
...userAssistants.map((el) => new ObjectId(el)),
...(conversations.map((conv) => conv.assistantId).filter((el) => !!el) as ObjectId[]),
];

const assistants = await collections.assistants.find({ _id: { $in: assistantIds } }).toArray();

const res = assistants
.filter((el) => userAssistantsSet.has(el._id.toString()))
.map((el) => ({
...el,
_id: el._id.toString(),
createdById: undefined,
createdByMe:
el.createdById.toString() === (locals.user?._id ?? locals.sessionId).toString(),
}));

return Response.json(res);
} else {
return Response.json({ message: "Must have session cookie" }, { status: 401 });
}
}