index
int64
0
0
repo_id
stringclasses
351 values
file_path
stringlengths
26
186
content
stringlengths
1
990k
0
hf_public_repos/chat-ui/src/routes/settings/(nav)/assistants/[assistantId]
hf_public_repos/chat-ui/src/routes/settings/(nav)/assistants/[assistantId]/edit/+page.server.ts
import { base } from "$app/paths"; import { requiresUser } from "$lib/server/auth"; import { collections } from "$lib/server/database"; import { fail, type Actions, redirect } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; import { z } from "zod"; import { sha256 } from "$lib/utils/sha256"; import sharp from "sharp"; import { parseStringToList } from "$lib/utils/parseStringToList"; import { generateSearchTokens } from "$lib/utils/searchTokens"; import { toolFromConfigs } from "$lib/server/tools"; const newAsssistantSchema = z.object({ name: z.string().min(1), modelId: z.string().min(1), preprompt: z.string().min(1), description: z.string().optional(), exampleInput1: z.string().optional(), exampleInput2: z.string().optional(), exampleInput3: z.string().optional(), exampleInput4: z.string().optional(), avatar: z.union([z.instanceof(File), z.literal("null")]).optional(), ragLinkList: z.preprocess(parseStringToList, z.string().url().array().max(10)), ragDomainList: z.preprocess(parseStringToList, z.string().array()), ragAllowAll: z.preprocess((v) => v === "true", z.boolean()), dynamicPrompt: z.preprocess((v) => v === "on", z.boolean()), temperature: z .union([z.literal(""), z.coerce.number().min(0.1).max(2)]) .transform((v) => (v === "" ? undefined : v)), top_p: z .union([z.literal(""), z.coerce.number().min(0.05).max(1)]) .transform((v) => (v === "" ? undefined : v)), repetition_penalty: z .union([z.literal(""), z.coerce.number().min(0.1).max(2)]) .transform((v) => (v === "" ? undefined : v)), top_k: z .union([z.literal(""), z.coerce.number().min(5).max(100)]) .transform((v) => (v === "" ? undefined : v)), tools: z .string() .optional() .transform((v) => (v ? v.split(",") : [])) .transform(async (v) => [ ...(await collections.tools .find({ _id: { $in: v.map((toolId) => new ObjectId(toolId)) } }) .project({ _id: 1 }) .toArray() .then((tools) => tools.map((tool) => tool._id.toString()))), ...toolFromConfigs .filter((el) => (v ?? []).includes(el._id.toString())) .map((el) => el._id.toString()), ]) .optional(), }); const uploadAvatar = async (avatar: File, assistantId: ObjectId): Promise<string> => { const hash = await sha256(await avatar.text()); const upload = collections.bucket.openUploadStream(`${assistantId.toString()}`, { metadata: { type: avatar.type, hash }, }); upload.write((await avatar.arrayBuffer()) as unknown as Buffer); upload.end(); // only return the filename when upload throws a finish event or a 10s time out occurs return new Promise((resolve, reject) => { upload.once("finish", () => resolve(hash)); upload.once("error", reject); setTimeout(() => reject(new Error("Upload timed out")), 10000); }); }; export const actions: Actions = { default: async ({ request, locals, params }) => { const assistant = await collections.assistants.findOne({ _id: new ObjectId(params.assistantId), }); if (!assistant) { throw Error("Assistant not found"); } if (assistant.createdById.toString() !== (locals.user?._id ?? locals.sessionId).toString()) { throw Error("You are not the author of this assistant"); } const formData = Object.fromEntries(await request.formData()); const parse = await newAsssistantSchema.safeParseAsync(formData); if (!parse.success) { // Loop through the errors array and create a custom errors array const errors = parse.error.errors.map((error) => { return { field: error.path[0], message: error.message, }; }); return fail(400, { error: true, errors }); } // can only create assistants when logged in, IF login is setup if (!locals.user && requiresUser) { const errors = [{ field: "preprompt", message: "Must be logged in. Unauthorized" }]; return fail(400, { error: true, errors }); } const exampleInputs: string[] = [ parse?.data?.exampleInput1 ?? "", parse?.data?.exampleInput2 ?? "", parse?.data?.exampleInput3 ?? "", parse?.data?.exampleInput4 ?? "", ].filter((input) => !!input); const deleteAvatar = parse.data.avatar === "null"; let hash; if (parse.data.avatar && parse.data.avatar !== "null" && parse.data.avatar.size > 0) { let image; try { image = await sharp(await parse.data.avatar.arrayBuffer()) .resize(512, 512, { fit: "inside" }) .jpeg({ quality: 80 }) .toBuffer(); } catch (e) { const errors = [{ field: "avatar", message: (e as Error).message }]; return fail(400, { error: true, errors }); } const fileCursor = collections.bucket.find({ filename: assistant._id.toString() }); // Step 2: Delete the existing file if it exists let fileId = await fileCursor.next(); while (fileId) { await collections.bucket.delete(fileId._id); fileId = await fileCursor.next(); } hash = await uploadAvatar(new File([image], "avatar.jpg"), assistant._id); } else if (deleteAvatar) { // delete the avatar const fileCursor = collections.bucket.find({ filename: assistant._id.toString() }); let fileId = await fileCursor.next(); while (fileId) { await collections.bucket.delete(fileId._id); fileId = await fileCursor.next(); } } const { acknowledged } = await collections.assistants.updateOne( { _id: assistant._id, }, { $set: { name: parse.data.name, description: parse.data.description, modelId: parse.data.modelId, preprompt: parse.data.preprompt, exampleInputs, avatar: deleteAvatar ? undefined : hash ?? assistant.avatar, updatedAt: new Date(), rag: { allowedLinks: parse.data.ragLinkList, allowedDomains: parse.data.ragDomainList, allowAllDomains: parse.data.ragAllowAll, }, tools: parse.data.tools, dynamicPrompt: parse.data.dynamicPrompt, searchTokens: generateSearchTokens(parse.data.name), generateSettings: { temperature: parse.data.temperature, top_p: parse.data.top_p, repetition_penalty: parse.data.repetition_penalty, top_k: parse.data.top_k, }, }, } ); if (acknowledged) { redirect(302, `${base}/settings/assistants/${assistant._id}`); } else { throw Error("Update failed"); } }, };
0
hf_public_repos/chat-ui/src/routes/settings/(nav)/assistants/[assistantId]
hf_public_repos/chat-ui/src/routes/settings/(nav)/assistants/[assistantId]/edit/+page@settings.svelte
<script lang="ts"> import type { PageData, ActionData } from "./$types"; import { page } from "$app/stores"; import AssistantSettings from "$lib/components/AssistantSettings.svelte"; export let data: PageData; export let form: ActionData; let assistant = data.assistants.find((el) => el._id.toString() === $page.params.assistantId); </script> <AssistantSettings bind:form {assistant} models={data.models} />
0
hf_public_repos/chat-ui/src/routes/settings/(nav)/assistants/[assistantId]
hf_public_repos/chat-ui/src/routes/settings/(nav)/assistants/[assistantId]/avatar.jpg/+server.ts
import { collections } from "$lib/server/database"; import { error, type RequestHandler } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; export const GET: RequestHandler = async ({ params }) => { const assistant = await collections.assistants.findOne({ _id: new ObjectId(params.assistantId), }); if (!assistant) { error(404, "No assistant found"); } if (!assistant.avatar) { error(404, "No avatar found"); } const fileId = collections.bucket.find({ filename: assistant._id.toString() }); const content = await fileId.next().then(async (file) => { if (!file?._id) { error(404, "Avatar not found"); } const fileStream = collections.bucket.openDownloadStream(file?._id); const fileBuffer = await new Promise<Buffer>((resolve, reject) => { const chunks: Uint8Array[] = []; fileStream.on("data", (chunk) => chunks.push(chunk)); fileStream.on("error", reject); fileStream.on("end", () => resolve(Buffer.concat(chunks))); }); return fileBuffer; }); return new Response(content, { headers: { "Content-Type": "image/jpeg", "Content-Security-Policy": "default-src 'none'; script-src 'none'; style-src 'none'; sandbox;", }, }); };
0
hf_public_repos/chat-ui/src/routes/settings/(nav)/assistants
hf_public_repos/chat-ui/src/routes/settings/(nav)/assistants/new/+page.server.ts
import { base } from "$app/paths"; import { authCondition, requiresUser } from "$lib/server/auth"; import { collections } from "$lib/server/database"; import { fail, type Actions, redirect } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; import { z } from "zod"; import { sha256 } from "$lib/utils/sha256"; import sharp from "sharp"; import { parseStringToList } from "$lib/utils/parseStringToList"; import { usageLimits } from "$lib/server/usageLimits"; import { generateSearchTokens } from "$lib/utils/searchTokens"; import { toolFromConfigs } from "$lib/server/tools"; import { ReviewStatus } from "$lib/types/Review"; const newAsssistantSchema = z.object({ name: z.string().min(1), modelId: z.string().min(1), preprompt: z.string().min(1), description: z.string().optional(), exampleInput1: z.string().optional(), exampleInput2: z.string().optional(), exampleInput3: z.string().optional(), exampleInput4: z.string().optional(), avatar: z.instanceof(File).optional(), ragLinkList: z.preprocess(parseStringToList, z.string().url().array().max(10)), ragDomainList: z.preprocess(parseStringToList, z.string().array()), ragAllowAll: z.preprocess((v) => v === "true", z.boolean()), dynamicPrompt: z.preprocess((v) => v === "on", z.boolean()), temperature: z .union([z.literal(""), z.coerce.number().min(0.1).max(2)]) .transform((v) => (v === "" ? undefined : v)), top_p: z .union([z.literal(""), z.coerce.number().min(0.05).max(1)]) .transform((v) => (v === "" ? undefined : v)), repetition_penalty: z .union([z.literal(""), z.coerce.number().min(0.1).max(2)]) .transform((v) => (v === "" ? undefined : v)), top_k: z .union([z.literal(""), z.coerce.number().min(5).max(100)]) .transform((v) => (v === "" ? undefined : v)), tools: z .string() .optional() .transform((v) => (v ? v.split(",") : [])) .transform(async (v) => [ ...(await collections.tools .find({ _id: { $in: v.map((toolId) => new ObjectId(toolId)) } }) .project({ _id: 1 }) .toArray() .then((tools) => tools.map((tool) => tool._id.toString()))), ...toolFromConfigs .filter((el) => (v ?? []).includes(el._id.toString())) .map((el) => el._id.toString()), ]) .optional(), }); const uploadAvatar = async (avatar: File, assistantId: ObjectId): Promise<string> => { const hash = await sha256(await avatar.text()); const upload = collections.bucket.openUploadStream(`${assistantId.toString()}`, { metadata: { type: avatar.type, hash }, }); upload.write((await avatar.arrayBuffer()) as unknown as Buffer); upload.end(); // only return the filename when upload throws a finish event or a 10s time out occurs return new Promise((resolve, reject) => { upload.once("finish", () => resolve(hash)); upload.once("error", reject); setTimeout(() => reject(new Error("Upload timed out")), 10000); }); }; export const actions: Actions = { default: async ({ request, locals }) => { const formData = Object.fromEntries(await request.formData()); const parse = await newAsssistantSchema.safeParseAsync(formData); if (!parse.success) { // Loop through the errors array and create a custom errors array const errors = parse.error.errors.map((error) => { return { field: error.path[0], message: error.message, }; }); return fail(400, { error: true, errors }); } // can only create assistants when logged in, IF login is setup if (!locals.user && requiresUser) { const errors = [{ field: "preprompt", message: "Must be logged in. Unauthorized" }]; return fail(400, { error: true, errors }); } const createdById = locals.user?._id ?? locals.sessionId; const assistantsCount = await collections.assistants.countDocuments({ createdById }); if (usageLimits?.assistants && assistantsCount > usageLimits.assistants) { const errors = [ { field: "preprompt", message: "You have reached the maximum number of assistants. Delete some to continue.", }, ]; return fail(400, { error: true, errors }); } const newAssistantId = new ObjectId(); const exampleInputs: string[] = [ parse?.data?.exampleInput1 ?? "", parse?.data?.exampleInput2 ?? "", parse?.data?.exampleInput3 ?? "", parse?.data?.exampleInput4 ?? "", ].filter((input) => !!input); let hash; if (parse.data.avatar && parse.data.avatar.size > 0) { let image; try { image = await sharp(await parse.data.avatar.arrayBuffer()) .resize(512, 512, { fit: "inside" }) .jpeg({ quality: 80 }) .toBuffer(); } catch (e) { const errors = [{ field: "avatar", message: (e as Error).message }]; return fail(400, { error: true, errors }); } hash = await uploadAvatar(new File([image], "avatar.jpg"), newAssistantId); } const { insertedId } = await collections.assistants.insertOne({ _id: newAssistantId, createdById, createdByName: locals.user?.username ?? locals.user?.name, ...parse.data, tools: parse.data.tools, exampleInputs, avatar: hash, createdAt: new Date(), updatedAt: new Date(), userCount: 1, review: ReviewStatus.PRIVATE, rag: { allowedLinks: parse.data.ragLinkList, allowedDomains: parse.data.ragDomainList, allowAllDomains: parse.data.ragAllowAll, }, dynamicPrompt: parse.data.dynamicPrompt, searchTokens: generateSearchTokens(parse.data.name), last24HoursCount: 0, generateSettings: { temperature: parse.data.temperature, top_p: parse.data.top_p, repetition_penalty: parse.data.repetition_penalty, top_k: parse.data.top_k, }, }); // add insertedId to user settings await collections.settings.updateOne(authCondition(locals), { $addToSet: { assistants: insertedId }, }); redirect(302, `${base}/settings/assistants/${insertedId}`); }, };
0
hf_public_repos/chat-ui/src/routes/settings/(nav)/assistants
hf_public_repos/chat-ui/src/routes/settings/(nav)/assistants/new/+page@settings.svelte
<script lang="ts"> import type { ActionData, PageData } from "./$types"; import AssistantSettings from "$lib/components/AssistantSettings.svelte"; export let data: PageData; export let form: ActionData; </script> <AssistantSettings bind:form models={data.models} />
0
hf_public_repos/chat-ui/src/routes/settings/(nav)
hf_public_repos/chat-ui/src/routes/settings/(nav)/[...model]/+page.ts
import { base } from "$app/paths"; import { redirect } from "@sveltejs/kit"; export async function load({ parent, params }) { const data = await parent(); const model = data.models.find((m: { id: string }) => m.id === params.model); if (!model || model.unlisted) { redirect(302, `${base}/settings`); } return data; }
0
hf_public_repos/chat-ui/src/routes/settings/(nav)
hf_public_repos/chat-ui/src/routes/settings/(nav)/[...model]/+page.svelte
<script lang="ts"> import { page } from "$app/stores"; import { base } from "$app/paths"; import { env as envPublic } from "$env/dynamic/public"; import type { BackendModel } from "$lib/server/models"; import { useSettingsStore } from "$lib/stores/settings"; import CopyToClipBoardBtn from "$lib/components/CopyToClipBoardBtn.svelte"; import TokensCounter from "$lib/components/TokensCounter.svelte"; import CarbonArrowUpRight from "~icons/carbon/arrow-up-right"; import CarbonLink from "~icons/carbon/link"; import CarbonChat from "~icons/carbon/chat"; import CarbonCode from "~icons/carbon/code"; import { goto } from "$app/navigation"; const settings = useSettingsStore(); $: if ($settings.customPrompts[$page.params.model] === undefined) { $settings.customPrompts = { ...$settings.customPrompts, [$page.params.model]: $page.data.models.find((el: BackendModel) => el.id === $page.params.model)?.preprompt || "", }; } $: hasCustomPreprompt = $settings.customPrompts[$page.params.model] !== $page.data.models.find((el: BackendModel) => el.id === $page.params.model)?.preprompt; $: model = $page.data.models.find((el: BackendModel) => el.id === $page.params.model); </script> <div class="flex flex-col items-start"> <div class="mb-5 flex flex-col gap-1.5"> <h2 class="text-lg font-semibold md:text-xl"> {$page.params.model} </h2> {#if model.description} <p class="whitespace-pre-wrap text-gray-600"> {model.description} </p> {/if} </div> <div class="flex flex-wrap items-center gap-2 md:gap-4"> {#if model.modelUrl} <a href={model.modelUrl || "https://huggingface.co/" + model.name} target="_blank" rel="noreferrer" class="flex items-center truncate underline underline-offset-2" > <CarbonArrowUpRight class="mr-1.5 shrink-0 text-xs " /> Model page </a> {/if} {#if model.datasetName || model.datasetUrl} <a href={model.datasetUrl || "https://huggingface.co/datasets/" + model.datasetName} target="_blank" rel="noreferrer" class="flex items-center truncate underline underline-offset-2" > <CarbonArrowUpRight class="mr-1.5 shrink-0 text-xs " /> Dataset page </a> {/if} {#if model.websiteUrl} <a href={model.websiteUrl} target="_blank" class="flex items-center truncate underline underline-offset-2" rel="noreferrer" > <CarbonArrowUpRight class="mr-1.5 shrink-0 text-xs " /> Model website </a> {/if} {#if model.hasInferenceAPI} <a href={"https://huggingface.co/playground?modelId=" + model.name} target="_blank" rel="noreferrer" class="flex items-center truncate underline underline-offset-2" > <CarbonCode class="mr-1.5 shrink-0 text-xs " /> API Playground </a> {/if} <CopyToClipBoardBtn value="{envPublic.PUBLIC_ORIGIN || $page.url.origin}{base}/models/{model.id}" classNames="!border-none !shadow-none !py-0 !px-1 !rounded-md" > <div class="flex items-center gap-1.5 hover:underline"> <CarbonLink />Copy direct link to model </div> </CopyToClipBoardBtn> </div> <button class="my-2 flex w-fit items-center rounded-full bg-black px-3 py-1 text-base !text-white" name="Activate model" on:click|stopPropagation={() => { settings.instantSet({ activeModel: $page.params.model, }); goto(`${base}/`); }} > <CarbonChat class="mr-1.5 text-sm" /> New chat </button> <div class="relative flex w-full flex-col gap-2"> <div class="flex w-full flex-row content-between"> <h3 class="mb-1.5 text-lg font-semibold text-gray-800">System Prompt</h3> {#if hasCustomPreprompt} <button class="ml-auto underline decoration-gray-300 hover:decoration-gray-700" on:click|stopPropagation={() => ($settings.customPrompts[$page.params.model] = model.preprompt)} > Reset </button> {/if} </div> <textarea aria-label="Custom system prompt" rows="10" class="w-full resize-none rounded-md border-2 bg-gray-100 p-2" bind:value={$settings.customPrompts[$page.params.model]} /> {#if model.tokenizer && $settings.customPrompts[$page.params.model]} <TokensCounter classNames="absolute bottom-2 right-2" prompt={$settings.customPrompts[$page.params.model]} modelTokenizer={model.tokenizer} truncate={model?.parameters?.truncate} /> {/if} </div> </div>
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/conversations/+page.server.ts
import { base } from "$app/paths"; import { authCondition } from "$lib/server/auth"; import { collections } from "$lib/server/database"; import { redirect } from "@sveltejs/kit"; export const actions = { async delete({ locals }) { // double check we have a user to delete conversations for if (locals.user?._id || locals.sessionId) { await collections.conversations.deleteMany({ ...authCondition(locals), }); } redirect(303, `${base}/`); }, };
0
hf_public_repos/chat-ui/src/routes/admin/stats
hf_public_repos/chat-ui/src/routes/admin/stats/compute/+server.ts
import { json } from "@sveltejs/kit"; import { logger } from "$lib/server/logger"; import { computeAllStats } from "$lib/jobs/refresh-conversation-stats"; // Triger like this: // curl -X POST "http://localhost:5173/chat/admin/stats/compute" -H "Authorization: Bearer <ADMIN_API_SECRET>" export async function POST() { computeAllStats().catch((e) => logger.error(e)); return json( { message: "Stats job started", }, { status: 202 } ); }
0
hf_public_repos/chat-ui/src/routes/admin
hf_public_repos/chat-ui/src/routes/admin/export/+server.ts
import { env } from "$env/dynamic/private"; import { collections } from "$lib/server/database"; import type { Message } from "$lib/types/Message"; import { error } from "@sveltejs/kit"; import { pathToFileURL } from "node:url"; import { unlink } from "node:fs/promises"; import { uploadFile } from "@huggingface/hub"; import parquet from "parquetjs"; import { z } from "zod"; import { logger } from "$lib/server/logger.js"; // Triger like this: // curl -X POST "http://localhost:5173/chat/admin/export" -H "Authorization: Bearer <ADMIN_API_SECRET>" -H "Content-Type: application/json" -d '{"model": "OpenAssistant/oasst-sft-6-llama-30b-xor"}' export async function POST({ request }) { if (!env.PARQUET_EXPORT_DATASET || !env.PARQUET_EXPORT_HF_TOKEN) { error(500, "Parquet export is not configured."); } const { model } = z .object({ model: z.string(), }) .parse(await request.json()); const schema = new parquet.ParquetSchema({ title: { type: "UTF8" }, created_at: { type: "TIMESTAMP_MILLIS" }, updated_at: { type: "TIMESTAMP_MILLIS" }, messages: { repeated: true, fields: { from: { type: "UTF8" }, content: { type: "UTF8" }, score: { type: "INT_8", optional: true }, }, }, }); const fileName = `/tmp/conversations-${new Date().toJSON().slice(0, 10)}-${Date.now()}.parquet`; const writer = await parquet.ParquetWriter.openFile(schema, fileName); let count = 0; logger.info("Exporting conversations for model", model); for await (const conversation of collections.settings.aggregate<{ title: string; created_at: Date; updated_at: Date; messages: Message[]; }>([ { $match: { shareConversationsWithModelAuthors: true, sessionId: { $exists: true }, userId: { $exists: false }, }, }, { $lookup: { from: "conversations", localField: "sessionId", foreignField: "sessionId", as: "conversations", pipeline: [{ $match: { model, userId: { $exists: false } } }], }, }, { $unwind: "$conversations" }, { $project: { title: "$conversations.title", created_at: "$conversations.createdAt", updated_at: "$conversations.updatedAt", messages: "$conversations.messages", }, }, ])) { await writer.appendRow({ title: conversation.title, created_at: conversation.created_at, updated_at: conversation.updated_at, messages: conversation.messages.map((message: Message) => ({ from: message.from, content: message.content, ...(message.score ? { score: message.score } : undefined), })), }); ++count; if (count % 1_000 === 0) { logger.info("Exported", count, "conversations"); } } logger.info("exporting convos with userId"); for await (const conversation of collections.settings.aggregate<{ title: string; created_at: Date; updated_at: Date; messages: Message[]; }>([ { $match: { shareConversationsWithModelAuthors: true, userId: { $exists: true } } }, { $lookup: { from: "conversations", localField: "userId", foreignField: "userId", as: "conversations", pipeline: [{ $match: { model } }], }, }, { $unwind: "$conversations" }, { $project: { title: "$conversations.title", created_at: "$conversations.createdAt", updated_at: "$conversations.updatedAt", messages: "$conversations.messages", }, }, ])) { await writer.appendRow({ title: conversation.title, created_at: conversation.created_at, updated_at: conversation.updated_at, messages: conversation.messages.map((message: Message) => ({ from: message.from, content: message.content, ...(message.score ? { score: message.score } : undefined), })), }); ++count; if (count % 1_000 === 0) { logger.info("Exported", count, "conversations"); } } await writer.close(); logger.info("Uploading", fileName, "to Hugging Face Hub"); await uploadFile({ file: pathToFileURL(fileName) as URL, credentials: { accessToken: env.PARQUET_EXPORT_HF_TOKEN }, repo: { type: "dataset", name: env.PARQUET_EXPORT_DATASET, }, }); logger.info("Upload done"); await unlink(fileName); return new Response(); }
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/tools/ToolInputComponent.svelte
<script lang="ts"> export let type: string; export let value: string | boolean | number; export let disabled: boolean = false; let innerValue: string | boolean | number = (() => { if (type === "bool") { return Boolean(value) || false; } else if (type === "int" || type === "float") { return Number(value) || 0; } else { return value || ""; } })(); let previousValue: string | boolean | number = innerValue; $: value = typeof innerValue === "string" ? innerValue : innerValue.toString(); </script> {#if type === "str" && typeof innerValue === "string"} <input type="text" class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" bind:value={innerValue} {disabled} /> {:else if type === "int" && typeof innerValue === "number"} <input type="number" step="1" class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" {disabled} on:input={(e) => { const value = e.currentTarget.value; if (value === "" || isNaN(parseInt(value))) { innerValue = previousValue; e.currentTarget.value = previousValue.toString(); return; } else { innerValue = parseFloat(value); previousValue = innerValue; } }} value={innerValue} /> {:else if type === "float" && typeof innerValue === "number"} <input type="number" step="0.001" class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" {disabled} on:input={(e) => { const value = e.currentTarget.value; if (value === "" || isNaN(parseFloat(value))) { innerValue = previousValue; e.currentTarget.value = previousValue.toString(); return; } else { innerValue = parseFloat(value); previousValue = innerValue; } }} value={innerValue} /> {:else if type === "bool" && typeof innerValue === "boolean"} <input type="checkbox" class="peer my-auto mr-4 size-6 rounded-lg border-2 border-gray-200 bg-gray-100 p-1" bind:checked={innerValue} /> <!-- Literal['bigvgan_24khz_100band', 'bigvgan_base_24khz_100band', 'bigvgan_22khz_80band', 'bigvgan_base_22khz_80band', 'bigvgan_v2_22khz_80band_256x', 'bigvgan_v2_22khz_80band_fmax8k_256x', 'bigvgan_v2_24khz_100band_256x', 'bigvgan_v2_44khz_128band_256x', 'bigvgan_v2_44khz_128band_512x'] --> {:else if type.startsWith("Literal[") && typeof innerValue === "string"} {@const options = type .slice(8, -1) .split(",") .map((option) => option.trim().replaceAll("'", ""))} <select class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" bind:value={innerValue} {disabled} > {#each options as option} <option value={option}>{option}</option> {/each} </select> {:else} <span class="font-mono text-red-800">{innerValue}-{typeof innerValue}</span> {/if}
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/tools/+layout.ts
import { base } from "$app/paths"; import { redirect } from "@sveltejs/kit"; export async function load({ parent }) { const { enableCommunityTools } = await parent(); if (enableCommunityTools) { return {}; } redirect(302, `${base}/`); }
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/tools/+layout.svelte
<script lang="ts"> import { env as envPublic } from "$env/dynamic/public"; import { isHuggingChat } from "$lib/utils/isHuggingChat"; import { base } from "$app/paths"; import { page } from "$app/stores"; </script> <svelte:head> {#if isHuggingChat} <title>HuggingChat - Tools</title> <meta property="og:title" content="HuggingChat - Tools" /> <meta property="og:type" content="link" /> <meta property="og:description" content="Browse HuggingChat tools made by the community." /> <meta property="og:image" content="{envPublic.PUBLIC_ORIGIN || $page.url.origin}{base}/{envPublic.PUBLIC_APP_ASSETS}/tools-thumbnail.png" /> <meta property="og:url" content={$page.url.href} /> {/if} </svelte:head> <slot />
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/tools/+page.svelte
<script lang="ts"> import type { PageData } from "./$types"; import { isHuggingChat } from "$lib/utils/isHuggingChat"; import { goto } from "$app/navigation"; import { base } from "$app/paths"; import { page } from "$app/stores"; import CarbonAdd from "~icons/carbon/add"; import CarbonHelpFilled from "~icons/carbon/help-filled"; import CarbonClose from "~icons/carbon/close"; import CarbonArrowUpRight from "~icons/carbon/arrow-up-right"; import CarbonEarthAmerica from "~icons/carbon/earth-americas-filled"; import CarbonSearch from "~icons/carbon/search"; import Pagination from "$lib/components/Pagination.svelte"; import { getHref } from "$lib/utils/getHref"; import { debounce } from "$lib/utils/debounce"; import { isDesktop } from "$lib/utils/isDesktop"; import { SortKey } from "$lib/types/Assistant"; import ToolLogo from "$lib/components/ToolLogo.svelte"; import { ReviewStatus } from "$lib/types/Review"; import { useSettingsStore } from "$lib/stores/settings"; export let data: PageData; $: tools = data.tools.filter((t) => activeOnly ? data.settings.tools.some((toolId) => toolId === t._id.toString()) : true ); $: toolsCreator = $page.url.searchParams.get("user"); $: createdByMe = data.user?.username && data.user.username === toolsCreator; $: activeOnly = $page.url.searchParams.get("active") === "true"; const settings = useSettingsStore(); $: currentModelSupportTools = data.models.find((m) => m.id === $settings.activeModel)?.tools ?? false; const SEARCH_DEBOUNCE_DELAY = 400; let filterInputEl: HTMLInputElement; let filterValue = data.query; let isFilterInPorgress = false; let sortValue = data.sort as SortKey; let showUnfeatured = data.showUnfeatured; const resetFilter = () => { filterValue = ""; isFilterInPorgress = false; }; const filterOnName = debounce(async (value: string) => { filterValue = value; if (isFilterInPorgress) { return; } isFilterInPorgress = true; const newUrl = getHref($page.url, { newKeys: { q: value }, existingKeys: { behaviour: "delete", keys: ["p"] }, }); await goto(newUrl); if (isDesktop(window)) { setTimeout(() => filterInputEl.focus(), 0); } isFilterInPorgress = false; // there was a new filter query before server returned response if (filterValue !== value) { filterOnName(filterValue); } }, SEARCH_DEBOUNCE_DELAY); const sortTools = () => { const newUrl = getHref($page.url, { newKeys: { sort: sortValue }, existingKeys: { behaviour: "delete", keys: ["p"] }, }); goto(newUrl); }; const toggleShowUnfeatured = () => { showUnfeatured = !showUnfeatured; const newUrl = getHref($page.url, { newKeys: { showUnfeatured: showUnfeatured ? "true" : undefined }, existingKeys: { behaviour: "delete", keys: [] }, }); goto(newUrl); }; const goToActiveUrl = () => { return getHref($page.url, { newKeys: { active: "true" }, existingKeys: { behaviour: "delete_except", keys: ["active", "sort"] }, }); }; const goToCommunity = () => { return getHref($page.url, { existingKeys: { behaviour: "delete_except", keys: ["sort", "q"] }, }); }; </script> <div class="scrollbar-custom h-full overflow-y-auto py-12 max-sm:pt-8 md:py-24"> <div class="pt-42 mx-auto flex flex-col px-5 xl:w-[60rem] 2xl:w-[64rem]"> <div class="flex items-center"> <h1 class="text-2xl font-bold">Tools</h1> {#if isHuggingChat} <div class="5 ml-1.5 rounded-lg text-xxs uppercase text-gray-500 dark:text-gray-500"> beta </div> <a href="https://huggingface.co/spaces/huggingchat/chat-ui/discussions/357" class="ml-auto dark:text-gray-400 dark:hover:text-gray-300" target="_blank" aria-label="Hub discussion about tools" > <CarbonHelpFilled /> </a> {/if} </div> <h2 class="text-gray-500">Popular tools made by the community</h2> <h3 class="mt-2 w-fit text-purple-700 dark:text-purple-300"> This feature is <span class="rounded-lg bg-purple-100 px-2 py-1 font-semibold dark:bg-purple-800/50" >experimental</span >. Consider <a class="underline hover:text-purple-500" href="https://huggingface.co/spaces/huggingchat/chat-ui/discussions/569" target="_blank">sharing your feedback with us!</a > </h3> <div class="ml-auto mt-6 flex justify-between gap-2 max-sm:flex-col sm:items-center"> {#if data.user?.isAdmin} <label class="mr-auto flex items-center gap-1 text-red-500" title="Admin only feature"> <input type="checkbox" checked={showUnfeatured} on:change={toggleShowUnfeatured} /> Show unfeatured tools </label> {/if} <a href={`${base}/tools/new`} class="flex items-center gap-1 whitespace-nowrap rounded-lg border bg-white py-1 pl-1.5 pr-2.5 shadow-sm hover:bg-gray-50 hover:shadow-none dark:border-gray-600 dark:bg-gray-700 dark:hover:bg-gray-700" > <CarbonAdd />Create new tool </a> </div> <div class="mb-4 mt-7 flex flex-wrap items-center gap-x-2 gap-y-3 text-sm"> {#if toolsCreator && !createdByMe} <div class="flex items-center gap-1.5 rounded-full border border-gray-300 bg-gray-50 px-3 py-1 dark:border-gray-600 dark:bg-gray-700 dark:text-white" > {toolsCreator}'s tools <a href={getHref($page.url, { existingKeys: { behaviour: "delete", keys: ["user", "modelId", "p", "q"] }, })} on:click={resetFilter} class="group" ><CarbonClose class="text-xs group-hover:text-gray-800 dark:group-hover:text-gray-300" /></a > </div> {#if isHuggingChat} <a href="https://hf.co/{toolsCreator}" target="_blank" class="ml-auto flex items-center text-xs text-gray-500 underline hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-300" ><CarbonArrowUpRight class="mr-1 flex-none text-[0.58rem]" target="_blank" />View {toolsCreator} on HF</a > {/if} {:else} <a href={goToActiveUrl()} class="flex items-center gap-1.5 rounded-full border px-3 py-1 {activeOnly ? 'border-gray-300 bg-gray-50 dark:border-gray-600 dark:bg-gray-700 dark:text-white' : 'border-transparent text-gray-400 hover:text-gray-800 dark:hover:text-gray-300'}" > <CarbonEarthAmerica class="text-xs" /> Active ({$page.data.settings?.tools?.length}) </a> <a href={goToCommunity()} class="flex items-center gap-1.5 rounded-full border px-3 py-1 {!activeOnly && !toolsCreator ? 'border-gray-300 bg-gray-50 dark:border-gray-600 dark:bg-gray-700 dark:text-white' : 'border-transparent text-gray-400 hover:text-gray-800 dark:hover:text-gray-300'}" > <CarbonEarthAmerica class="text-xs" /> Community </a> {#if data.user?.username} <a href={getHref($page.url, { newKeys: { user: data.user.username }, existingKeys: { behaviour: "delete", keys: ["modelId", "p", "q", "active"] }, })} on:click={resetFilter} class="flex items-center gap-1.5 truncate rounded-full border px-3 py-1 {toolsCreator && createdByMe ? 'border-gray-300 bg-gray-50 dark:border-gray-600 dark:bg-gray-700 dark:text-white' : 'border-transparent text-gray-400 hover:text-gray-800 dark:hover:text-gray-300'}" >{data.user.username} </a> {/if} {/if} <div class="relative ml-auto flex h-[30px] w-40 items-center rounded-full border px-2 has-[:focus]:border-gray-400 dark:border-gray-600 sm:w-64" > <CarbonSearch class="pointer-events-none absolute left-2 text-xs text-gray-400" /> <input class="h-[30px] w-full bg-transparent pl-5 focus:outline-none" placeholder="Filter by name" value={filterValue} on:input={(e) => filterOnName(e.currentTarget.value)} bind:this={filterInputEl} maxlength="150" type="search" aria-label="Filter tools by name" /> </div> <select bind:value={sortValue} on:change={sortTools} class="rounded-lg border border-gray-300 bg-gray-50 px-2 py-1 text-sm text-gray-900 focus:border-blue-700 focus:ring-blue-700 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400" aria-label="Sort tools" > <option value={SortKey.TRENDING}>{SortKey.TRENDING}</option> <option value={SortKey.POPULAR}>{SortKey.POPULAR}</option> </select> </div> {#if !currentModelSupportTools} <div class="mx-auto text-center text-sm text-purple-700 dark:text-purple-300"> You are currently not using a model that supports tools. Activate one <a href="{base}/models" class="underline">here</a>. </div> {/if} <div class="mt-4 grid grid-cols-1 gap-3 sm:gap-5 lg:grid-cols-2"> {#each tools as tool} {@const isActive = ($page.data.settings?.tools ?? []).includes(tool._id.toString())} {@const isOfficial = !tool.createdByName} <div on:click={() => goto(`${base}/tools/${tool._id.toString()}`)} on:keydown={(e) => e.key === "Enter" && goto(`${base}/tools/${tool._id.toString()}`)} role="button" tabindex="0" class="relative flex flex-row items-center gap-4 overflow-hidden text-balance rounded-xl border bg-gray-50/50 px-4 text-center shadow hover:bg-gray-50 hover:shadow-inner dark:bg-gray-950/20 dark:hover:bg-gray-950/40 max-sm:px-4 sm:h-24 {!( tool.review === ReviewStatus.APPROVED ) && !isOfficial ? ' border-red-500/30' : 'dark:border-gray-800/70'}" class:!border-blue-600={isActive} > <ToolLogo color={tool.color} icon={tool.icon} /> <div class="flex h-full w-full flex-col items-start py-2 text-left"> <span class="font-bold"> <span class="w-full overflow-clip"> {tool.displayName} </span> {#if isActive} <span class="mx-1.5 inline-flex items-center rounded-full bg-blue-600 px-2 py-0.5 text-xs font-semibold text-white" >Active</span > {/if} </span> <span class="line-clamp-1 font-mono text-xs text-gray-400"> {tool.baseUrl ?? "Internal tool"} </span> <p class=" line-clamp-1 w-full text-sm text-gray-600 dark:text-gray-300"> {tool.description} </p> {#if !isOfficial} <p class="mt-auto text-xs text-gray-400 dark:text-gray-500"> Added by <a class="hover:underline" href="{base}/tools?user={tool.createdByName}" on:click|stopPropagation > {tool.createdByName} </a> <span class="text-gray-300">•</span> {#if tool.useCount === 1} 1 run {:else} {tool.useCount} runs {/if} </p> {:else} <p class="mt-auto text-xs text-purple-700 dark:text-purple-400"> HuggingChat official tool </p> {/if} </div> </div> {:else} {#if activeOnly} You don't have any active tools. {:else} No tools found {/if} {/each} </div> <Pagination classNames="w-full flex justify-center mt-14 mb-4" numItemsPerPage={data.numItemsPerPage} numTotalItems={data.numTotalItems} /> </div> </div>
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/tools/ToolEdit.svelte
<script lang="ts"> import { ToolOutputComponents, type CommunityToolEditable, type ToolInput, } from "$lib/types/Tool"; import { createEventDispatcher, onMount } from "svelte"; import { browser } from "$app/environment"; import ToolLogo from "$lib/components/ToolLogo.svelte"; import { colors, icons } from "$lib/utils/tools"; import { applyAction, enhance } from "$app/forms"; import { getGradioApi } from "$lib/utils/getGradioApi"; import { useSettingsStore } from "$lib/stores/settings"; import { goto } from "$app/navigation"; import { base } from "$app/paths"; import ToolInputComponent from "./ToolInputComponent.svelte"; import CarbonInformation from "~icons/carbon/information"; type ActionData = { error?: boolean; errors?: { field: string | number; message: string; }[]; } | null; export let tool: CommunityToolEditable | undefined = undefined; export let readonly = false; export let form: ActionData; function getError(field: string, returnForm: ActionData) { return returnForm?.errors?.find((error) => error.field === field)?.message ?? ""; } let APIloading = false; let formLoading = false; const dispatch = createEventDispatcher<{ close: void }>(); onMount(async () => { await updateConfig(); }); let spaceUrl = tool?.baseUrl ?? ""; let editableTool: CommunityToolEditable = tool ?? { displayName: "", description: "", // random color & icon for new tools color: colors[Math.floor(Math.random() * colors.length)], icon: icons[Math.floor(Math.random() * icons.length)], baseUrl: "", endpoint: "", name: "", inputs: [], outputComponent: null, outputComponentIdx: 0, showOutput: true, }; $: editableTool.baseUrl && (spaceUrl = editableTool.baseUrl); async function updateConfig() { if (!browser || !editableTool.baseUrl || !editableTool.endpoint) { return; } form = { error: false, errors: [] }; APIloading = true; const api = await getGradioApi(editableTool.baseUrl); const newInputs = api.named_endpoints[editableTool.endpoint].parameters.map((param, idx) => { if (tool?.inputs[idx]?.name === param.parameter_name) { // if the tool has the same name, we use the tool's type return { ...tool?.inputs[idx], } satisfies ToolInput; } const type = parseValidInputType(param.python_type.type); if (param.parameter_has_default && param.python_type.type !== "filepath") { // optional if it has a default return { name: param.parameter_name, description: param.description, paramType: "optional" as const, default: param.parameter_default, ...(type === "file" ? { mimeTypes: "*/*", type } : { type }), }; } else { // required if it doesn't have a default return { name: param.parameter_name, description: param.description, paramType: "required" as const, ...(type === "file" ? { mimeTypes: "*/*", type } : { type }), }; } }); editableTool.inputs = newInputs; // outout components const parsedOutputComponent = ToolOutputComponents.safeParse( api.named_endpoints[editableTool.endpoint].returns?.[0]?.component ?? null ); if (parsedOutputComponent.success) { editableTool.outputComponent = "0;" + parsedOutputComponent.data; } else { form = { error: true, errors: [ { field: "outputComponent", message: `Invalid output component. Type ${ api.named_endpoints[editableTool.endpoint].returns?.[0]?.component } is not yet supported. Feel free to report this issue so we can add support for it.`, }, ], }; editableTool.outputComponent = null; } APIloading = false; } async function onEndpointChange(e: Event) { const target = e.target as HTMLInputElement; editableTool.endpoint = target.value; editableTool.name = target.value.replace(/\//g, ""); await updateConfig(); } function parseValidInputType(type: string) { switch (type) { case "str": case "int": case "float": case "bool": return type; case "filepath": return "file" as const; default: return "str"; } } const settings = useSettingsStore(); $: formSubmittable = editableTool.name && editableTool.baseUrl && editableTool.outputComponent; </script> <form method="POST" class="relative flex h-full flex-col overflow-y-auto p-4 md:p-8" use:enhance={async ({ formData }) => { formLoading = true; formData.append("tool", JSON.stringify(editableTool)); return async ({ result }) => { if (result.type === "success" && result.data && typeof result.data.toolId === "string") { $settings.tools = [...($settings.tools ?? []), result.data.toolId]; await goto(`${base}/tools/${result.data.toolId}`).then(() => { formLoading = false; }); } else { await applyAction(result).then(() => { formLoading = false; }); } }; }} > {#if tool} <h2 class="text-xl font-semibold"> {readonly ? "View" : "Edit"} Tool: {tool.displayName} </h2> {#if !readonly} <p class="mb-6 text-sm text-gray-500"> Modifying an existing tool will propagate the changes to all users. </p> {/if} {:else} <h2 class="text-xl font-semibold">Create new tool</h2> <p class="mb-6 text-sm text-gray-500"> Create and share your own tools. All tools are <span class="rounded-full border px-2 py-0.5 leading-none">public</span > </p> {/if} <div class="grid h-full w-full flex-1 grid-cols-2 gap-6 text-sm max-sm:grid-cols-1"> <div class="col-span-1 flex flex-col gap-4"> <div class="flex flex-col gap-4"> <label> <div class="mb-1 font-semibold">Tool Display Name</div> <input type="text" name="displayName" disabled={readonly} class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" placeholder="Image generator" bind:value={editableTool.displayName} /> <p class="text-xs text-red-500">{getError("displayName", form)}</p> </label> <div class="flex flex-row gap-4"> <div> {#key editableTool.color + editableTool.icon} <ToolLogo color={editableTool.color} icon={editableTool.icon} /> {/key} </div> <label class="flex-grow"> <div class="mb-1 font-semibold">Icon</div> <select name="icon" disabled={readonly} class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" bind:value={editableTool.icon} > {#each icons as icon} <option value={icon}>{icon}</option> {/each} <p class="text-xs text-red-500">{getError("icon", form)}</p> </select> </label> <label class="flex-grow"> <div class="mb-1 font-semibold">Color scheme</div> <select name="color" disabled={readonly} class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" bind:value={editableTool.color} > {#each colors as color} <option value={color}>{color}</option> {/each} <p class="text-xs text-red-500">{getError("color", form)}</p> </select> </label> </div> <label> <div class=" font-semibold">Tool Description</div> <p class="mb-1 text-sm text-gray-500"> This description will be passed to the model when picking tools. Describe what your tool does and when it is appropriate to use. </p> <textarea name="description" disabled={readonly} class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" placeholder="This tool lets you generate images using SDXL." bind:value={editableTool.description} /> <p class="text-xs text-red-500">{getError("description", form)}</p> </label> <label> <div class="mb-1 font-semibold">Hugging Face Space URL</div> <p class="mb-1 text-sm text-gray-500"> Specify the Hugging Face Space where your tool is hosted. <a href="https://huggingface.co/spaces" target="_blank" class="underline">See trending spaces here</a >. </p> <input type="text" name="spaceUrl" disabled={readonly} class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" placeholder="ByteDance/Hyper-SDXL-1Step-T2I" bind:value={editableTool.baseUrl} /> <p class="text-xs text-red-500">{getError("spaceUrl", form)}</p> </label> <p class="text-justify text-gray-800"> Tools allows models that support them to use external application directly via function calling. Tools must use Hugging Face Gradio Spaces as we detect the input and output types automatically from the <a class="underline" href="https://www.gradio.app/guides/sharing-your-app#api-page">Gradio API</a >. For GPU intensive tool consider using a ZeroGPU Space. </p> </div> </div> <div class="col-span-1 flex flex-col gap-4"> <div class="flex flex-col gap-2"> <h3 class="mb-1 font-semibold">Functions</h3> {#if editableTool.baseUrl} <p class="text-sm text-gray-500">Choose functions that can be called in your tool.</p> {:else} <p class="text-sm text-gray-500">Start by specifying a Hugging Face Space URL.</p> {/if} {#if editableTool.baseUrl} {#await getGradioApi(spaceUrl)} <p class="text-sm text-gray-500">Loading...</p> {:then api} <div class="flex flex-row flex-wrap gap-4"> {#each Object.keys(api["named_endpoints"] ?? {}) as name} <label class="rounded-lg bg-gray-200 p-2"> <input type="radio" disabled={readonly} on:input={onEndpointChange} bind:group={editableTool.endpoint} value={name} name="endpoint" /> <span class="font-mono text-gray-800" class:font-semibold={editableTool.endpoint === name}>{name}</span > </label> {/each} </div> {#if editableTool.endpoint && api["named_endpoints"][editableTool.endpoint] && !APIloading} {@const endpoint = api["named_endpoints"][editableTool.endpoint]} <div class="flex flex-col gap-2"> <div class="flex flex-col gap-2 rounded-lg border border-gray-200 p-2"> <div class="flex items-center gap-1 border-b border-gray-200 p-1 pb-2"> <span class="flex-grow font-mono text-smd font-semibold" >{editableTool.endpoint}</span > <label class="ml-auto"> <span class="group relative flex w-max items-center justify-center text-sm font-semibold text-gray-700" > AI Function Name <CarbonInformation class="m-1 align-middle text-xs text-purple-500" /> <div class="pointer-events-none absolute -top-16 right-0 w-max rounded-md bg-gray-100 p-2 opacity-0 transition-opacity group-hover:opacity-100 dark:bg-gray-800" > <p class="max-w-sm text-sm font-normal text-gray-800 dark:text-gray-200"> This is the function name that will be used when prompting the model. Make sure it describes your tool well, is short and unique. </p> </div> </span> <input class="h-fit rounded-lg border-2 border-gray-200 bg-gray-100 p-1" type="text" name="name" disabled={readonly} bind:value={editableTool.name} /> </label> </div> <div> <h3 class="text-lg font-semibold">Arguments</h3> <p class="mb-2 text-sm text-gray-500"> Choose parameters that can be passed to your tool. </p> </div> <p class="text-xs text-red-500"> {getError(`inputs`, form)} </p> {#each editableTool.inputs as input, inputIdx} {@const parameter = endpoint.parameters.find( (parameter) => parameter.parameter_name === input.name )} <div class="flex items-center gap-1"> <div class="inline w-full"> <span class="font-mono text-sm">{input.name}</span> <span class="inline-block max-w-lg truncate rounded-lg bg-orange-50 p-1 text-sm text-orange-800" >{parameter?.python_type.type}</span > {#if parameter?.description} <p class="text-sm text-gray-500"> {parameter.description} </p> {/if} <div class="flex w-fit justify-start gap-2"> <label class="ml-auto"> <input type="radio" name="{input.name}-parameter-type" value="required" disabled={readonly} bind:group={editableTool.inputs[inputIdx].paramType} /> <span class="text-sm text-gray-500">Required</span> </label> <label class="ml-auto"> <input type="radio" name="{input.name}-parameter-type" value="optional" disabled={readonly || parameter?.python_type.type === "filepath"} bind:group={editableTool.inputs[inputIdx].paramType} /> <span class="text-sm text-gray-500">Optional</span> </label> <label class="ml-auto"> <input type="radio" name="{input.name}-parameter-type" value="fixed" disabled={readonly || parameter?.python_type.type === "filepath"} bind:group={editableTool.inputs[inputIdx].paramType} /> <span class="text-sm text-gray-500">Fixed</span> </label> </div> </div> </div> <!-- for required we need a description, for optional we need a default value and for fixed we need a value --> {#if input.paramType === "required" || input.paramType === "optional"} <label class="flex flex-row gap-2"> <div class="mb-1 font-semibold"> Description <p class="text-xs font-normal text-gray-500"> Will be passed in the model prompt, make it as clear and concise as possible </p> </div> <textarea name="{input.name}-description" class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" placeholder="This is the description of the input." bind:value={input.description} disabled={readonly} /> </label> {/if} {#if input.paramType === "optional" || input.paramType === "fixed"} {@const isOptional = input.paramType === "optional"} <div class="flex flex-row gap-2"> <div class="mb-1 flex-grow font-semibold"> {isOptional ? "Default value" : "Value"} <p class="text-xs font-normal text-gray-500"> {#if isOptional} The tool will use this value by default but the model can specify a different one. {:else} The tool will use this value and it cannot be changed. {/if} </p> </div> {#if input.paramType === "optional"} <ToolInputComponent type={parameter?.python_type.type ?? "str"} disabled={readonly} bind:value={input.default} /> {:else} <ToolInputComponent type={parameter?.python_type.type ?? "str"} disabled={readonly} bind:value={input.value} /> {/if} </div> {/if} {#if input.type === "file"} <label class="flex flex-row gap-2"> <div class="mb-1 font-semibold"> MIME types <p class="text-xs font-normal text-gray-500"> This input is a file. Specify the MIME types that are allowed to be passed to the tool. </p> </div> <select name="{input.name}-mimeTypes" class="h-fit w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2" bind:value={input.mimeTypes} disabled={readonly} > <option value="image/*">image/*</option> <option value="audio/*">audio/*</option> <option value="video/*">video/*</option> <option value="application/pdf">application/pdf</option> <option value="text/csv">text/csv</option> <option value="*/*">*/*</option> </select></label > {/if} <!-- divider --> <div class="flex w-full flex-row flex-nowrap gap-2 border-b border-gray-200 pt-2" /> {/each} <div class="flex flex-col gap-4"> <div> <h3 class="text-lg font-semibold">Output options</h3> <p class="mb-2 text-sm text-gray-500"> Choose what value your tool will return and how </p> </div> <label class="flex flex-col gap-2" for="showOutput"> <div class="mb-1 font-semibold"> Output component <p class="text-xs font-normal text-gray-500"> Pick the gradio output component whose output will be used in the tool. </p> </div> {#if editableTool.outputComponent} {#if api.named_endpoints[editableTool.endpoint].returns.length > 1} <div class="flex flex-row gap-4"> {#each api.named_endpoints[editableTool.endpoint].returns as { component }, idx} <label class="text-gray-800"> <input type="radio" disabled={readonly || !ToolOutputComponents.safeParse(component).success} bind:group={editableTool.outputComponent} value={idx + ";" + component.toLowerCase()} name="outputComponent" /> <span class="font-mono" class:text-gray-400={!ToolOutputComponents.safeParse(component) .success} class:font-semibold={editableTool?.outputComponent?.split( ";" )[1] === component}>{component.toLowerCase()}-{idx}</span > </label> {/each} </div> {:else} <div> <input disabled checked type="radio" /> <span class="font-mono text-gray-800" >{editableTool.outputComponent.split(";")[1]}</span > </div> {/if} {/if} <p class="text-xs text-red-500"> {getError("outputComponent", form)} </p> </label> <label class="flex flex-row gap-2" for="showOutput"> <div class="mb-1 font-semibold"> Show output to user directly <p class="text-xs font-normal text-gray-500"> Some tools return long context that should not be shown to the user directly. </p> </div> <input type="checkbox" name="showOutput" bind:checked={editableTool.showOutput} class="peer rounded-lg border-2 border-gray-200 bg-gray-100 p-1" /> <p class="text-xs text-red-500"> {getError("showOutput", form)} </p> </label> </div> </div> </div> {:else if APIloading} <p class="text-sm text-gray-500">Loading API...</p> {:else if !api["named_endpoints"]} <p class="font-medium text-red-800"> No endpoints found in this space. Try another one. </p> {/if} {:catch error} <p class="text-sm text-gray-500">{error}</p> {/await} {/if} </div> <div class="relative bottom-0 mb-4 mt-auto flex w-full flex-row justify-end gap-2"> <button type="button" class="mt-4 w-fit rounded-full bg-gray-200 px-4 py-2 font-semibold text-gray-700" on:click={() => dispatch("close")} > Cancel </button> {#if !readonly} <button type="submit" disabled={formLoading || !formSubmittable} class="mt-4 w-fit rounded-full bg-black px-4 py-2 font-semibold" class:text-white={!formLoading && formSubmittable} class:text-gray-300={formLoading || !formSubmittable} class:bg-gray-400={formLoading || !formSubmittable} > {formLoading ? "Saving..." : "Save"} </button> {/if} </div> </div> </div> </form>
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/tools/+page.server.ts
import { env } from "$env/dynamic/private"; import { authCondition } from "$lib/server/auth.js"; import { Database, collections } from "$lib/server/database.js"; import { toolFromConfigs } from "$lib/server/tools/index.js"; import { SortKey } from "$lib/types/Assistant.js"; import { ReviewStatus } from "$lib/types/Review"; import type { CommunityToolDB } from "$lib/types/Tool.js"; import type { User } from "$lib/types/User.js"; import { generateQueryTokens, generateSearchTokens } from "$lib/utils/searchTokens.js"; import { error } from "@sveltejs/kit"; import { ObjectId, type Filter } from "mongodb"; const NUM_PER_PAGE = 16; export const load = async ({ url, locals }) => { if (env.COMMUNITY_TOOLS !== "true") { error(403, "Community tools are not enabled"); } const username = url.searchParams.get("user"); const query = url.searchParams.get("q")?.trim() ?? null; const pageIndex = parseInt(url.searchParams.get("p") ?? "0"); const sort = url.searchParams.get("sort")?.trim() ?? SortKey.TRENDING; const createdByCurrentUser = locals.user?.username && locals.user.username === username; const activeOnly = url.searchParams.get("active") === "true"; const showUnfeatured = url.searchParams.get("showUnfeatured") === "true"; let user: Pick<User, "_id"> | null = null; if (username) { user = await collections.users.findOne<Pick<User, "_id">>( { username }, { projection: { _id: 1 } } ); if (!user) { error(404, `User "${username}" doesn't exist`); } } const settings = await collections.settings.findOne(authCondition(locals)); if (!settings && activeOnly) { error(404, "No user settings found"); } const queryTokens = !!query && generateQueryTokens(query); const filter: Filter<CommunityToolDB> = { ...(!createdByCurrentUser && !activeOnly && !(locals.user?.isAdmin && showUnfeatured) && { review: ReviewStatus.APPROVED }), ...(user && { createdById: user._id }), ...(queryTokens && { searchTokens: { $all: queryTokens } }), ...(activeOnly && { _id: { $in: (settings?.tools ?? []).map((key) => { return new ObjectId(key); }), }, }), }; const communityTools = await Database.getInstance() .getCollections() .tools.find(filter) .skip(NUM_PER_PAGE * pageIndex) .sort({ ...(sort === SortKey.TRENDING && { last24HoursUseCount: -1 }), useCount: -1, }) .limit(NUM_PER_PAGE) .toArray(); const configTools = toolFromConfigs .filter((tool) => !tool?.isHidden) .filter((tool) => { if (queryTokens) { return generateSearchTokens(tool.displayName).some((token) => queryTokens.some((queryToken) => queryToken.test(token)) ); } return true; }); const tools = [...(pageIndex == 0 && !username ? configTools : []), ...communityTools]; const numTotalItems = (await Database.getInstance().getCollections().tools.countDocuments(filter)) + toolFromConfigs.length; return { tools: JSON.parse(JSON.stringify(tools)) as CommunityToolDB[], numTotalItems, numItemsPerPage: NUM_PER_PAGE, query, sort, showUnfeatured, }; };
0
hf_public_repos/chat-ui/src/routes/tools
hf_public_repos/chat-ui/src/routes/tools/[toolId]/+page.svelte
<script lang="ts"> import { afterNavigate, goto } from "$app/navigation"; import { base } from "$app/paths"; import { page } from "$app/stores"; import Modal from "$lib/components/Modal.svelte"; import ToolLogo from "$lib/components/ToolLogo.svelte"; import { env as envPublic } from "$env/dynamic/public"; import { useSettingsStore } from "$lib/stores/settings"; import { ReviewStatus } from "$lib/types/Review"; import ReportModal from "../../settings/(nav)/assistants/[assistantId]/ReportModal.svelte"; import { applyAction, enhance } from "$app/forms"; import CopyToClipBoardBtn from "$lib/components/CopyToClipBoardBtn.svelte"; import CarbonPen from "~icons/carbon/pen"; import CarbonTrash from "~icons/carbon/trash-can"; import CarbonCopy from "~icons/carbon/copy-file"; import CarbonFlag from "~icons/carbon/flag"; import CarbonLink from "~icons/carbon/link"; import CarbonStar from "~icons/carbon/star"; import CarbonLock from "~icons/carbon/locked"; export let data; const settings = useSettingsStore(); let previousPage: string = base; afterNavigate(({ from }) => { if (!from?.url.pathname.includes("tools/")) { previousPage = from?.url.toString() || previousPage; } }); const prefix = envPublic.PUBLIC_SHARE_PREFIX || `${envPublic.PUBLIC_ORIGIN || $page.url.origin}${base}`; $: shareUrl = `${prefix}/tools/${data.tool?._id}`; $: isActive = $settings.tools?.includes(data.tool?._id.toString()); let displayReportModal = false; $: currentModelSupportTools = data.models.find((m) => m.id === $settings.activeModel)?.tools ?? false; </script> {#if displayReportModal} <ReportModal on:close={() => (displayReportModal = false)} /> {/if} <Modal on:close={() => goto(previousPage)} width="min-w-xl"> <div class="w-full min-w-64 p-8"> <div class="flex h-full flex-col gap-2"> <div class="flex flex-col sm:flex-row sm:gap-6"> <div class="mb-4 flex justify-center sm:mb-0"> <ToolLogo color={data.tool.color} icon={data.tool.icon} size="lg" /> </div> <div class="flex-1"> <div class="flex flex-wrap items-center gap-2"> <h1 class="break-words text-xl font-semibold"> {data.tool.displayName} </h1> <span class="inline rounded-full border px-2 py-0.5 text-sm leading-none text-gray-500" >public</span > </div> {#if data.tool?.baseUrl} {#if data.tool.baseUrl.startsWith("https://")} <p class="mb-2 break-words font-mono text-gray-500"> {data.tool.baseUrl} </p> {:else} <a href="https://huggingface.co/spaces/{data.tool.baseUrl}" target="_blank" class="mb-2 break-words font-mono text-gray-500 hover:underline" > {data.tool.baseUrl} </a> {/if} {/if} {#if data.tool.type === "community"} <p class="text-sm text-gray-500"> Added by <a class="underline" href="{base}/tools?user={data.tool?.createdByName}"> {data.tool?.createdByName} </a> <span class="text-gray-300">•</span> {#if data.tool.useCount === 1} 1 run {:else} {data.tool.useCount} runs {/if} </p> {/if} <div class="flex flex-wrap items-center gap-x-4 gap-y-2 whitespace-nowrap text-sm text-gray-500 hover:*:text-gray-800 max-sm:justify-center" > <div class="w-full sm:w-auto"> {#if currentModelSupportTools} <button class="{isActive ? 'bg-gray-100 text-gray-800' : 'bg-black !text-white'} mx-auto my-2 flex w-min items-center justify-center rounded-full px-3 py-1 text-base" name="Activate model" on:click|stopPropagation={() => { if (isActive) { settings.instantSet({ tools: ($settings?.tools ?? []).filter((t) => t !== data.tool._id), }); } else { settings.instantSet({ tools: [...($settings?.tools ?? []), data.tool._id], }); } }} > {isActive ? "Deactivate" : "Activate"} </button> {:else} <button disabled class="mx-auto my-2 flex w-min items-center justify-center rounded-full bg-gray-200 px-3 py-1 text-base text-gray-500" > Activate </button> {/if} </div> {#if data.tool?.createdByMe} <a href="{base}/tools/{data.tool?._id}/edit" class="underline" ><CarbonPen class="mr-1.5 inline text-xs" />Edit </a> <form method="POST" action="?/delete" use:enhance={async () => { return async ({ result }) => { if (result.type === "success") { $settings.tools = ($settings?.tools ?? []).filter((t) => t !== data.tool._id); goto(`${base}/tools`, { invalidateAll: true }); } else { await applyAction(result); } }; }} > <button type="submit" class="flex items-center underline" on:click={(event) => { if (!confirm("Are you sure you want to delete this tool?")) { event.preventDefault(); } }} > <CarbonTrash class="mr-1.5 inline text-xs" />Delete </button> </form> {:else if !!data.tool?.baseUrl} <a href="{base}/tools/{data.tool?._id}/edit" class="underline"> <CarbonPen class="mr-1.5 inline text-xs" />View spec </a> <form method="POST" action="?/edit" use:enhance class="hidden"> <button type="submit" class="underline"> <CarbonCopy class="mr-1.5 inline text-xs" />Duplicate</button > </form> {#if !data.tool?.reported} <button type="button" on:click={() => { displayReportModal = true; }} class="underline" > <CarbonFlag class="mr-1.5 inline text-xs" />Report </button> {:else} <button type="button" disabled class="text-gray-700"> <CarbonFlag class="mr-1.5 inline text-xs" />Reported</button > {/if} {/if} {#if data?.user?.isAdmin} <span class="rounded-full border px-2 py-0.5 text-sm leading-none text-gray-500" >{data.tool?.review?.toLocaleUpperCase()}</span > {#if !data.tool?.createdByMe} <form method="POST" action="?/delete" use:enhance> <button type="submit" class="flex items-center text-red-600 underline" on:click={(event) => { if (!confirm("Are you sure you want to delete this tool?")) { event.preventDefault(); } }} > <CarbonTrash class="mr-1.5 inline text-xs" />Delete </button> </form> {/if} {#if data.tool?.review === ReviewStatus.PRIVATE} <form method="POST" action="?/approve" use:enhance> <button type="submit" class="flex items-center text-green-600 underline"> <CarbonStar class="mr-1.5 inline text-xs" />Force feature</button > </form> {/if} {#if data.tool?.review === ReviewStatus.PENDING} <form method="POST" action="?/approve" use:enhance> <button type="submit" class="flex items-center text-green-600 underline"> <CarbonStar class="mr-1.5 inline text-xs" />Approve</button > </form> <form method="POST" action="?/deny" use:enhance> <button type="submit" class="flex items-center text-red-600"> <span class="mr-1.5 font-light no-underline">X</span> <span class="underline">Deny</span> </button> </form> {/if} {#if data.tool?.review === ReviewStatus.APPROVED || data.tool?.review === ReviewStatus.DENIED} <form method="POST" action="?/unrequest" use:enhance> <button type="submit" class="flex items-center text-red-600 underline"> <CarbonLock class="mr-1.5 inline text-xs " />Reset review</button > </form> {/if} {/if} {#if data.tool?.createdByMe && data.tool?.review === ReviewStatus.PRIVATE} <form method="POST" action="?/request" use:enhance={async ({ cancel }) => { const confirmed = confirm( "Are you sure you want to request this tool to be featured? Make sure you have tried the tool and that it works as expected. We will review your request once submitted." ); if (!confirmed) { cancel(); } }} > <button type="submit" class="flex items-center underline"> <CarbonStar class="mr-1.5 inline text-xs" />Request to be featured</button > </form> {/if} </div> </div> </div> {#if !currentModelSupportTools} <span class="relative text-sm text-gray-500"> You are currently not using a model that supports tools. Activate one <a href="{base}/models" class="underline">here</a>. </span> {:else} <p class="text-sm max-sm:hidden"> Tools are applications that the model can choose to call while you are chatting with it. </p> {/if} {#if data.tool.description} <div> <h2 class="text-lg font-semibold">Description</h2> <p class="pb-2">{data.tool.description}</p> </div> {/if} <div> <h2 class="text-lg font-semibold">Direct URL</h2> <p class="pb-2 text-sm text-gray-500">Share this link with people to use your tool.</p> <div class="flex flex-row items-center gap-2 rounded-lg border-2 border-gray-200 bg-gray-100 py-2 pl-3 pr-1.5" > <div class="relative flex-1 overflow-hidden"> <input disabled class="w-full truncate bg-inherit pr-16" value={shareUrl} /> <div class="absolute right-0 top-1/2 -translate-y-1/2"> <CopyToClipBoardBtn value={shareUrl} classNames="!border-none !shadow-none !py-0 !px-1 !rounded-md" > <div class="flex items-center gap-1.5 text-gray-500 hover:underline"> <CarbonLink />Copy </div> </CopyToClipBoardBtn> </div> </div> </div> </div> </div> </div></Modal >
0
hf_public_repos/chat-ui/src/routes/tools
hf_public_repos/chat-ui/src/routes/tools/[toolId]/+page.server.ts
import { base } from "$app/paths"; import { env } from "$env/dynamic/private"; import { env as envPublic } from "$env/dynamic/public"; import { collections } from "$lib/server/database"; import { sendSlack } from "$lib/server/sendSlack"; import { ReviewStatus } from "$lib/types/Review"; import type { Tool } from "$lib/types/Tool"; import { fail, redirect, type Actions } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; import { z } from "zod"; async function toolOnlyIfAuthor(locals: App.Locals, toolId?: string) { const tool = await collections.tools.findOne({ _id: new ObjectId(toolId) }); if (!tool) { throw Error("Tool not found"); } if ( tool.createdById.toString() !== (locals.user?._id ?? locals.sessionId).toString() && !locals.user?.isAdmin ) { throw Error("You are not the creator of this tool"); } return tool; } export const actions: Actions = { delete: async ({ params, locals }) => { let tool; try { tool = await toolOnlyIfAuthor(locals, params.toolId); } catch (e) { return fail(400, { error: true, message: (e as Error).message }); } await collections.tools.deleteOne({ _id: tool._id }); // Remove the tool from all users' settings await collections.settings.updateMany( { tools: { $in: [tool._id.toString()] }, }, { $pull: { tools: tool._id.toString() }, } ); // Remove the tool from all assistants await collections.assistants.updateMany( { tools: { $in: [tool._id.toString()] }, }, { $pull: { tools: tool._id.toString() }, } ); redirect(302, `${base}/tools`); }, report: async ({ request, params, locals, url }) => { // is there already a report from this user for this model ? const report = await collections.reports.findOne({ createdBy: locals.user?._id ?? locals.sessionId, object: "tool", contentId: new ObjectId(params.toolId), }); if (report) { return fail(400, { error: true, message: "Already reported" }); } const formData = await request.formData(); const result = z.string().min(1).max(128).safeParse(formData?.get("reportReason")); if (!result.success) { return fail(400, { error: true, message: "Invalid report reason" }); } const { acknowledged } = await collections.reports.insertOne({ _id: new ObjectId(), contentId: new ObjectId(params.toolId), object: "tool", createdBy: locals.user?._id ?? locals.sessionId, createdAt: new Date(), updatedAt: new Date(), reason: result.data, }); if (!acknowledged) { return fail(500, { error: true, message: "Failed to report tool" }); } if (env.WEBHOOK_URL_REPORT_ASSISTANT) { const prefixUrl = envPublic.PUBLIC_SHARE_PREFIX || `${envPublic.PUBLIC_ORIGIN || url.origin}${base}`; const toolUrl = `${prefixUrl}/tools/${params.toolId}`; const tool = await collections.tools.findOne<Pick<Tool, "displayName">>( { _id: new ObjectId(params.toolId) }, { projection: { displayName: 1 } } ); const username = locals.user?.username; await sendSlack( `🔴 Tool <${toolUrl}|${tool?.displayName}> reported by ${ username ? `<http://hf.co/${username}|${username}>` : "non-logged in user" }.\n\n> ${result.data}` ); } return { from: "report", ok: true, message: "Tool reported" }; }, deny: async ({ params, locals, url }) => { return await setReviewStatus({ toolId: params.toolId, locals, status: ReviewStatus.DENIED, url, }); }, approve: async ({ params, locals, url }) => { return await setReviewStatus({ toolId: params.toolId, locals, status: ReviewStatus.APPROVED, url, }); }, request: async ({ params, locals, url }) => { return await setReviewStatus({ toolId: params.toolId, locals, status: ReviewStatus.PENDING, url, }); }, unrequest: async ({ params, locals, url }) => { return await setReviewStatus({ toolId: params.toolId, locals, status: ReviewStatus.PRIVATE, url, }); }, }; async function setReviewStatus({ locals, toolId, status, url, }: { locals: App.Locals; toolId?: string; status: ReviewStatus; url: URL; }) { if (!toolId) { return fail(400, { error: true, message: "Tool ID is required" }); } const tool = await collections.tools.findOne({ _id: new ObjectId(toolId), }); if (!tool) { return fail(404, { error: true, message: "Tool not found" }); } if ( !locals.user || (!locals.user.isAdmin && tool.createdById.toString() !== locals.user._id.toString()) ) { return fail(403, { error: true, message: "Permission denied" }); } // only admins can set the status to APPROVED or DENIED // if the status is already APPROVED or DENIED, only admins can change it if ( (status === ReviewStatus.APPROVED || status === ReviewStatus.DENIED || tool.review === ReviewStatus.APPROVED || tool.review === ReviewStatus.DENIED) && !locals.user?.isAdmin ) { return fail(403, { error: true, message: "Permission denied" }); } const result = await collections.tools.updateOne({ _id: tool._id }, { $set: { review: status } }); if (result.modifiedCount === 0) { return fail(500, { error: true, message: "Failed to update review status" }); } if (status === ReviewStatus.PENDING) { const prefixUrl = envPublic.PUBLIC_SHARE_PREFIX || `${envPublic.PUBLIC_ORIGIN || url.origin}${base}`; const toolUrl = `${prefixUrl}/tools/${toolId}`; const username = locals.user?.username; await sendSlack( `🟢 Tool <${toolUrl}|${tool?.displayName}> requested to be featured by ${ username ? `<http://hf.co/${username}|${username}>` : "non-logged in user" }.` ); } return { from: "setReviewStatus", ok: true, message: "Review status updated" }; }
0
hf_public_repos/chat-ui/src/routes/tools
hf_public_repos/chat-ui/src/routes/tools/[toolId]/+layout.server.ts
import { base } from "$app/paths"; import { collections } from "$lib/server/database.js"; import { toolFromConfigs } from "$lib/server/tools/index.js"; import { ReviewStatus } from "$lib/types/Review.js"; import { redirect } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; export const load = async ({ params, locals }) => { const tool = await collections.tools.findOne({ _id: new ObjectId(params.toolId) }); if (!tool) { const tool = toolFromConfigs.find((el) => el._id.toString() === params.toolId); if (!tool) { redirect(302, `${base}/tools`); } return { tool: { ...tool, _id: tool._id.toString(), call: undefined, createdById: null, createdByName: null, createdByMe: false, reported: false, review: ReviewStatus.APPROVED, }, }; } const reported = await collections.reports.findOne({ contentId: tool._id, object: "tool", }); return { tool: { ...tool, _id: tool._id.toString(), call: undefined, createdById: tool.createdById.toString(), createdByMe: tool.createdById.toString() === (locals.user?._id ?? locals.sessionId).toString(), reported: !!reported, }, }; };
0
hf_public_repos/chat-ui/src/routes/tools/[toolId]
hf_public_repos/chat-ui/src/routes/tools/[toolId]/edit/+page.svelte
<script lang="ts"> import Modal from "$lib/components/Modal.svelte"; import ToolEdit from "../../ToolEdit.svelte"; export let data; export let form; </script> <Modal on:close={() => window.history.back()} width="h-[95dvh] w-[90dvw] overflow-hidden rounded-2xl bg-white shadow-2xl outline-none sm:h-[85dvh] xl:w-[1200px] 2xl:h-[75dvh]" > <ToolEdit bind:form tool={data.tool} readonly={!data.tool.createdByMe} on:close={() => { window.history.back(); }} /> </Modal>
0
hf_public_repos/chat-ui/src/routes/tools/[toolId]
hf_public_repos/chat-ui/src/routes/tools/[toolId]/edit/+page.server.ts
import { base } from "$app/paths"; import { requiresUser } from "$lib/server/auth.js"; import { collections } from "$lib/server/database.js"; import { editableToolSchema } from "$lib/server/tools/index.js"; import { generateSearchTokens } from "$lib/utils/searchTokens.js"; import { error, fail, redirect } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; export const actions = { default: async ({ request, params, locals }) => { const tool = await collections.tools.findOne({ _id: new ObjectId(params.toolId), }); if (!tool) { throw Error("Tool not found"); } if (tool.createdById.toString() !== (locals.user?._id ?? locals.sessionId).toString()) { throw Error("You are not the creator of this tool"); } // can only create tools when logged in, IF login is setup if (!locals.user && requiresUser) { const errors = [{ field: "description", message: "Must be logged in. Unauthorized" }]; return fail(400, { error: true, errors }); } const body = await request.formData(); const toolStringified = body.get("tool"); if (!toolStringified || typeof toolStringified !== "string") { error(400, "Tool is required"); } const parse = editableToolSchema.safeParse(JSON.parse(toolStringified)); if (!parse.success) { // Loop through the errors array and create a custom errors array const errors = parse.error.errors.map((error) => { return { field: error.path[0], message: error.message, }; }); return fail(400, { error: true, errors }); } // modify the tool await collections.tools.updateOne( { _id: tool._id }, { $set: { ...parse.data, updatedAt: new Date(), searchTokens: generateSearchTokens(parse.data.displayName), }, } ); redirect(302, `${base}/tools/${tool._id.toString()}`); }, };
0
hf_public_repos/chat-ui/src/routes/tools
hf_public_repos/chat-ui/src/routes/tools/new/+page.svelte
<script lang="ts"> import Modal from "$lib/components/Modal.svelte"; import ToolEdit from "../ToolEdit.svelte"; export let form; </script> <Modal on:close={() => window.history.back()} width="h-[95dvh] w-[90dvw] overflow-hidden rounded-2xl bg-white shadow-2xl outline-none sm:h-[85dvh] xl:w-[1200px] 2xl:h-[75dvh]" > <ToolEdit bind:form on:close={() => window.history.back()} /> </Modal>
0
hf_public_repos/chat-ui/src/routes/tools
hf_public_repos/chat-ui/src/routes/tools/new/+page.server.ts
import { env } from "$env/dynamic/private"; import { authCondition, requiresUser } from "$lib/server/auth.js"; import { collections } from "$lib/server/database.js"; import { editableToolSchema } from "$lib/server/tools/index.js"; import { usageLimits } from "$lib/server/usageLimits.js"; import { ReviewStatus } from "$lib/types/Review"; import { generateSearchTokens } from "$lib/utils/searchTokens.js"; import { error, fail } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; export const actions = { default: async ({ request, locals }) => { if (env.COMMUNITY_TOOLS !== "true") { error(403, "Community tools are not enabled"); } const body = await request.formData(); const toolStringified = body.get("tool"); if (!toolStringified || typeof toolStringified !== "string") { error(400, "Tool is required"); } const parse = editableToolSchema.safeParse(JSON.parse(toolStringified)); if (!parse.success) { // Loop through the errors array and create a custom errors array const errors = parse.error.errors.map((error) => { return { field: error.path[0], message: error.message, }; }); return fail(400, { error: true, errors }); } // can only create tools when logged in, IF login is setup if (!locals.user && requiresUser) { const errors = [{ field: "description", message: "Must be logged in. Unauthorized" }]; return fail(400, { error: true, errors }); } const toolCounts = await collections.tools.countDocuments({ createdById: locals.user?._id }); if (usageLimits?.tools && toolCounts > usageLimits.tools) { const errors = [ { field: "description", message: "You have reached the maximum number of tools. Delete some to continue.", }, ]; return fail(400, { error: true, errors }); } if (!locals.user || !authCondition(locals)) { error(401, "Unauthorized"); } const { insertedId } = await collections.tools.insertOne({ ...parse.data, type: "community" as const, _id: new ObjectId(), createdById: locals.user?._id, createdByName: locals.user?.username, createdAt: new Date(), updatedAt: new Date(), last24HoursUseCount: 0, useCount: 0, review: ReviewStatus.PRIVATE, searchTokens: generateSearchTokens(parse.data.displayName), }); return { toolId: insertedId.toString() }; }, };
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/models/+page.svelte
<script lang="ts"> import type { PageData } from "./$types"; import { env as envPublic } from "$env/dynamic/public"; import { isHuggingChat } from "$lib/utils/isHuggingChat"; import { base } from "$app/paths"; import { page } from "$app/stores"; import CarbonHelpFilled from "~icons/carbon/help-filled"; import CarbonTools from "~icons/carbon/tools"; import CarbonImage from "~icons/carbon/image"; import { useSettingsStore } from "$lib/stores/settings"; export let data: PageData; const settings = useSettingsStore(); </script> <svelte:head> {#if isHuggingChat} <title>HuggingChat - Models</title> <meta property="og:title" content="HuggingChat - Models" /> <meta property="og:type" content="link" /> <meta property="og:description" content="Browse HuggingChat available models" /> <meta property="og:url" content={$page.url.href} /> {/if} </svelte:head> <div class="scrollbar-custom h-full overflow-y-auto py-12 max-sm:pt-8 md:py-24"> <div class="pt-42 mx-auto flex flex-col px-5 xl:w-[60rem] 2xl:w-[64rem]"> <div class="flex items-center"> <h1 class="text-2xl font-bold">Models</h1> {#if isHuggingChat} <a href="https://huggingface.co/spaces/huggingchat/chat-ui/discussions/372" class="ml-auto dark:text-gray-400 dark:hover:text-gray-300" target="_blank" aria-label="Hub discussion about models" > <CarbonHelpFilled /> </a> {/if} </div> <h2 class="text-gray-500">All models available on {envPublic.PUBLIC_APP_NAME}</h2> <div class="mt-8 grid grid-cols-1 gap-3 sm:gap-5 xl:grid-cols-2"> {#each data.models.filter((el) => !el.unlisted) as model, index (model.id)} <div aria-label="Model card" role="region" class="relative flex flex-col gap-2 overflow-hidden rounded-xl border bg-gray-50/50 px-6 py-5 shadow hover:bg-gray-50 hover:shadow-inner dark:border-gray-800/70 dark:bg-gray-950/20 dark:hover:bg-gray-950/40" class:active-model={model.id === $settings.activeModel} > <a href="{base}/models/{model.id}" class="absolute inset-0 z-10" aria-label="View details for {model.displayName}" /> <div class="flex items-center justify-between gap-1"> {#if model.logoUrl} <img class="overflown aspect-square size-6 rounded border dark:border-gray-700" src={model.logoUrl} alt="{model.displayName} logo" /> {:else} <div class="size-6 rounded border border-transparent bg-gray-300 dark:bg-gray-800" aria-hidden="true" /> {/if} {#if model.tools} <span title="This model supports tools." class="ml-auto grid size-[21px] place-items-center rounded-lg border border-purple-300 dark:border-purple-700" aria-label="Model supports tools" role="img" > <CarbonTools class="text-xxs text-purple-700 dark:text-purple-500" /> </span> {/if} {#if model.multimodal} <span title="This model is multimodal and supports image inputs natively." class="ml-auto flex size-[21px] items-center justify-center rounded-lg border border-blue-700 dark:border-blue-500" aria-label="Model is multimodal" role="img" > <CarbonImage class="text-xxs text-blue-700 dark:text-blue-500" /> </span> {/if} {#if model.id === $settings.activeModel} <span class="rounded-full border border-blue-500 bg-blue-500/5 px-2 py-0.5 text-xs text-blue-500 dark:border-blue-500 dark:bg-blue-500/10" > Active </span> {:else if index === 0} <span class="rounded-full border border-gray-300 px-2 py-0.5 text-xs text-gray-500 dark:border-gray-500 dark:text-gray-400" > Default </span> {/if} </div> <span class="flex items-center gap-2 font-semibold"> {model.displayName} </span> <span class="whitespace-pre-wrap text-sm text-gray-500 dark:text-gray-400"> {model.description || "-"} </span> </div> {/each} </div> </div> </div> <style lang="postcss"> .active-model { @apply border-blue-500 bg-blue-500/5 hover:bg-blue-500/10; } </style>
0
hf_public_repos/chat-ui/src/routes/models
hf_public_repos/chat-ui/src/routes/models/[...model]/+page.svelte
<script lang="ts"> import { page } from "$app/stores"; import { base } from "$app/paths"; import { goto } from "$app/navigation"; import { onMount } from "svelte"; import { env as envPublic } from "$env/dynamic/public"; import ChatWindow from "$lib/components/chat/ChatWindow.svelte"; import { findCurrentModel } from "$lib/utils/models"; import { useSettingsStore } from "$lib/stores/settings"; import { ERROR_MESSAGES, error } from "$lib/stores/errors"; import { pendingMessage } from "$lib/stores/pendingMessage"; export let data; let loading = false; let files: File[] = []; const settings = useSettingsStore(); const modelId = $page.params.model; async function createConversation(message: string) { try { loading = true; const res = await fetch(`${base}/conversation`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ model: modelId, preprompt: $settings.customPrompts[modelId], }), }); if (!res.ok) { error.set("Error while creating conversation, try again."); console.error("Error while creating conversation: " + (await res.text())); return; } const { conversationId } = await res.json(); // Ugly hack to use a store as temp storage, feel free to improve ^^ pendingMessage.set({ content: message, files, }); // invalidateAll to update list of conversations await goto(`${base}/conversation/${conversationId}`, { invalidateAll: true }); } catch (err) { error.set(ERROR_MESSAGES.default); console.error(err); } finally { loading = false; } } onMount(async () => { const query = $page.url.searchParams.get("q"); if (query) createConversation(query); settings.instantSet({ activeModel: modelId }); }); </script> <svelte:head> <meta property="og:title" content={modelId + " - " + envPublic.PUBLIC_APP_NAME} /> <meta property="og:type" content="link" /> <meta property="og:description" content={`Use ${modelId} with ${envPublic.PUBLIC_APP_NAME}`} /> <meta property="og:image" content="{envPublic.PUBLIC_ORIGIN || $page.url.origin}{base}/models/{modelId}/thumbnail.png" /> <meta property="og:url" content={$page.url.href} /> <meta name="twitter:card" content="summary_large_image" /> </svelte:head> <ChatWindow on:message={(ev) => createConversation(ev.detail)} {loading} currentModel={findCurrentModel([...data.models, ...data.oldModels], modelId)} models={data.models} bind:files />
0
hf_public_repos/chat-ui/src/routes/models
hf_public_repos/chat-ui/src/routes/models/[...model]/+page.server.ts
import { base } from "$app/paths"; import { authCondition } from "$lib/server/auth.js"; import { collections } from "$lib/server/database"; import { models } from "$lib/server/models"; import { redirect } from "@sveltejs/kit"; export async function load({ params, locals, parent }) { const model = models.find(({ id }) => id === params.model); const data = await parent(); if (!model || model.unlisted) { redirect(302, `${base}/`); } if (locals.user?._id ?? locals.sessionId) { await collections.settings.updateOne( authCondition(locals), { $set: { activeModel: model.id, updatedAt: new Date(), }, $setOnInsert: { createdAt: new Date(), }, }, { upsert: true, } ); } return { settings: { ...data.settings, activeModel: model.id, }, }; }
0
hf_public_repos/chat-ui/src/routes/models/[...model]
hf_public_repos/chat-ui/src/routes/models/[...model]/thumbnail.png/+server.ts
import ModelThumbnail from "./ModelThumbnail.svelte"; import { redirect, type RequestHandler } from "@sveltejs/kit"; import type { SvelteComponent } from "svelte"; import { Resvg } from "@resvg/resvg-js"; import satori from "satori"; import { html } from "satori-html"; import InterRegular from "$lib/server/fonts/Inter-Regular.ttf"; import InterBold from "$lib/server/fonts/Inter-Bold.ttf"; import { base } from "$app/paths"; import { models } from "$lib/server/models"; export const GET: RequestHandler = (async ({ params }) => { const model = models.find(({ id }) => id === params.model); if (!model || model.unlisted) { redirect(302, `${base}/`); } const renderedComponent = (ModelThumbnail as unknown as SvelteComponent).render({ name: model.name, logoUrl: model.logoUrl, }); const reactLike = html( "<style>" + renderedComponent.css.code + "</style>" + renderedComponent.html ); const svg = await satori(reactLike, { width: 1200, height: 648, fonts: [ { name: "Inter", data: InterRegular as unknown as ArrayBuffer, weight: 500, }, { name: "Inter", data: InterBold as unknown as ArrayBuffer, weight: 700, }, ], }); const png = new Resvg(svg, { fitTo: { mode: "original" }, }) .render() .asPng(); return new Response(png, { headers: { "Content-Type": "image/png", }, }); }) satisfies RequestHandler;
0
hf_public_repos/chat-ui/src/routes/models/[...model]
hf_public_repos/chat-ui/src/routes/models/[...model]/thumbnail.png/ModelThumbnail.svelte
<script lang="ts"> import { env as envPublic } from "$env/dynamic/public"; import { isHuggingChat } from "$lib/utils/isHuggingChat"; export let name: string; export let logoUrl: string | undefined; import logo from "../../../../../static/huggingchat/logo.svg?raw"; </script> <div class=" flex h-[648px] w-full flex-col items-center bg-white"> <div class="flex flex-1 flex-col items-center justify-center"> {#if logoUrl} <img class="h-48 w-48" src={logoUrl} alt="avatar" /> {/if} <h1 class="m-0 text-5xl font-bold text-black"> {name} </h1> </div> <div class="flex h-[200px] w-full flex-col items-center justify-center rounded-b-none bg-{envPublic.PUBLIC_APP_COLOR}-500/10 pb-10 pt-10 text-4xl text-gray-500" style="border-radius: 100% 100% 0 0;" > Try it now {#if isHuggingChat} on {/if} {#if isHuggingChat} <div class="flex flex-row pt-3 text-5xl font-bold text-black"> <div class="mr-5 flex items-center justify-center" id="logo"> <!-- eslint-disable-next-line --> {@html logo} </div> <span>HuggingChat</span> </div> {/if} </div> </div>
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/login/+page.server.ts
import { redirect } from "@sveltejs/kit"; import { getOIDCAuthorizationUrl } from "$lib/server/auth"; import { base } from "$app/paths"; import { env } from "$env/dynamic/private"; export const actions = { async default({ url, locals, request }) { const referer = request.headers.get("referer"); let redirectURI = `${(referer ? new URL(referer) : url).origin}${base}/login/callback`; // TODO: Handle errors if provider is not responding if (url.searchParams.has("callback")) { const callback = url.searchParams.get("callback") || redirectURI; if (env.ALTERNATIVE_REDIRECT_URLS.includes(callback)) { redirectURI = callback; } } const authorizationUrl = await getOIDCAuthorizationUrl( { redirectURI }, { sessionId: locals.sessionId } ); redirect(303, authorizationUrl); }, };
0
hf_public_repos/chat-ui/src/routes/login
hf_public_repos/chat-ui/src/routes/login/callback/updateUser.ts
import { refreshSessionCookie } from "$lib/server/auth"; import { collections } from "$lib/server/database"; import { ObjectId } from "mongodb"; import { DEFAULT_SETTINGS } from "$lib/types/Settings"; import { z } from "zod"; import type { UserinfoResponse } from "openid-client"; import { error, type Cookies } from "@sveltejs/kit"; import crypto from "crypto"; import { sha256 } from "$lib/utils/sha256"; import { addWeeks } from "date-fns"; import { OIDConfig } from "$lib/server/auth"; import { env } from "$env/dynamic/private"; import { logger } from "$lib/server/logger"; export async function updateUser(params: { userData: UserinfoResponse; locals: App.Locals; cookies: Cookies; userAgent?: string; ip?: string; }) { const { userData, locals, cookies, userAgent, ip } = params; // Microsoft Entra v1 tokens do not provide preferred_username, instead the username is provided in the upn // claim. See https://learn.microsoft.com/en-us/entra/identity-platform/access-token-claims-reference if (!userData.preferred_username && userData.upn) { userData.preferred_username = userData.upn as string; } const { preferred_username: username, name, email, picture: avatarUrl, sub: hfUserId, orgs, } = z .object({ preferred_username: z.string().optional(), name: z.string(), picture: z.string().optional(), sub: z.string(), email: z.string().email().optional(), orgs: z .array( z.object({ sub: z.string(), name: z.string(), picture: z.string(), preferred_username: z.string(), isEnterprise: z.boolean(), }) ) .optional(), }) .setKey(OIDConfig.NAME_CLAIM, z.string()) .refine((data) => data.preferred_username || data.email, { message: "Either preferred_username or email must be provided by the provider.", }) .transform((data) => ({ ...data, name: data[OIDConfig.NAME_CLAIM], })) .parse(userData) as { preferred_username?: string; email?: string; picture?: string; sub: string; name: string; orgs?: Array<{ sub: string; name: string; picture: string; preferred_username: string; isEnterprise: boolean; }>; } & Record<string, string>; // Dynamically access user data based on NAME_CLAIM from environment // This approach allows us to adapt to different OIDC providers flexibly. logger.info( { login_username: username, login_name: name, login_email: email, login_orgs: orgs?.map((el) => el.sub), }, "user login" ); // if using huggingface as auth provider, check orgs for earl access and amin rights const isAdmin = (env.HF_ORG_ADMIN && orgs?.some((org) => org.sub === env.HF_ORG_ADMIN)) || false; const isEarlyAccess = (env.HF_ORG_EARLY_ACCESS && orgs?.some((org) => org.sub === env.HF_ORG_EARLY_ACCESS)) || false; logger.debug( { isAdmin, isEarlyAccess, hfUserId, }, `Updating user ${hfUserId}` ); // check if user already exists const existingUser = await collections.users.findOne({ hfUserId }); let userId = existingUser?._id; // update session cookie on login const previousSessionId = locals.sessionId; const secretSessionId = crypto.randomUUID(); const sessionId = await sha256(secretSessionId); if (await collections.sessions.findOne({ sessionId })) { error(500, "Session ID collision"); } locals.sessionId = sessionId; if (existingUser) { // update existing user if any await collections.users.updateOne( { _id: existingUser._id }, { $set: { username, name, avatarUrl, isAdmin, isEarlyAccess } } ); // remove previous session if it exists and add new one await collections.sessions.deleteOne({ sessionId: previousSessionId }); await collections.sessions.insertOne({ _id: new ObjectId(), sessionId: locals.sessionId, userId: existingUser._id, createdAt: new Date(), updatedAt: new Date(), userAgent, ip, expiresAt: addWeeks(new Date(), 2), }); } else { // user doesn't exist yet, create a new one const { insertedId } = await collections.users.insertOne({ _id: new ObjectId(), createdAt: new Date(), updatedAt: new Date(), username, name, email, avatarUrl, hfUserId, isAdmin, isEarlyAccess, }); userId = insertedId; await collections.sessions.insertOne({ _id: new ObjectId(), sessionId: locals.sessionId, userId, createdAt: new Date(), updatedAt: new Date(), userAgent, ip, expiresAt: addWeeks(new Date(), 2), }); // move pre-existing settings to new user const { matchedCount } = await collections.settings.updateOne( { sessionId: previousSessionId }, { $set: { userId, updatedAt: new Date() }, $unset: { sessionId: "" }, } ); if (!matchedCount) { // if no settings found for user, create default settings await collections.settings.insertOne({ userId, ethicsModalAcceptedAt: new Date(), updatedAt: new Date(), createdAt: new Date(), ...DEFAULT_SETTINGS, }); } } // refresh session cookie refreshSessionCookie(cookies, secretSessionId); // migrate pre-existing conversations await collections.conversations.updateMany( { sessionId: previousSessionId }, { $set: { userId }, $unset: { sessionId: "" }, } ); }
0
hf_public_repos/chat-ui/src/routes/login
hf_public_repos/chat-ui/src/routes/login/callback/updateUser.spec.ts
import { assert, it, describe, afterEach, vi, expect } from "vitest"; import type { Cookies } from "@sveltejs/kit"; import { collections } from "$lib/server/database"; import { updateUser } from "./updateUser"; import { ObjectId } from "mongodb"; import { DEFAULT_SETTINGS } from "$lib/types/Settings"; import { defaultModel } from "$lib/server/models"; import { findUser } from "$lib/server/auth"; import { defaultEmbeddingModel } from "$lib/server/embeddingModels"; const userData = { preferred_username: "new-username", name: "name", picture: "https://example.com/avatar.png", sub: "1234567890", }; Object.freeze(userData); const locals = { userId: "1234567890", sessionId: "1234567890", }; // @ts-expect-error SvelteKit cookies dumb mock const cookiesMock: Cookies = { set: vi.fn(), }; const insertRandomUser = async () => { const res = await collections.users.insertOne({ _id: new ObjectId(), createdAt: new Date(), updatedAt: new Date(), username: "base-username", name: userData.name, avatarUrl: userData.picture, hfUserId: userData.sub, }); return res.insertedId; }; const insertRandomConversations = async (count: number) => { const res = await collections.conversations.insertMany( new Array(count).fill(0).map(() => ({ _id: new ObjectId(), title: "random title", messages: [], model: defaultModel.id, embeddingModel: defaultEmbeddingModel.id, createdAt: new Date(), updatedAt: new Date(), sessionId: locals.sessionId, })) ); return res.insertedIds; }; describe("login", () => { it("should update user if existing", async () => { await insertRandomUser(); await updateUser({ userData, locals, cookies: cookiesMock }); const existingUser = await collections.users.findOne({ hfUserId: userData.sub }); assert.equal(existingUser?.name, userData.name); expect(cookiesMock.set).toBeCalledTimes(1); }); it("should migrate pre-existing conversations for new user", async () => { const insertedId = await insertRandomUser(); await insertRandomConversations(2); await updateUser({ userData, locals, cookies: cookiesMock }); const conversationCount = await collections.conversations.countDocuments({ userId: insertedId, sessionId: { $exists: false }, }); assert.equal(conversationCount, 2); await collections.conversations.deleteMany({ userId: insertedId }); }); it("should create default settings for new user", async () => { await updateUser({ userData, locals, cookies: cookiesMock }); const user = await findUser(locals.sessionId); assert.exists(user); const settings = await collections.settings.findOne({ userId: user?._id }); expect(settings).toMatchObject({ userId: user?._id, updatedAt: expect.any(Date), createdAt: expect.any(Date), ethicsModalAcceptedAt: expect.any(Date), ...DEFAULT_SETTINGS, }); await collections.settings.deleteOne({ userId: user?._id }); }); it("should migrate pre-existing settings for pre-existing user", async () => { const { insertedId } = await collections.settings.insertOne({ sessionId: locals.sessionId, ethicsModalAcceptedAt: new Date(), updatedAt: new Date(), createdAt: new Date(), ...DEFAULT_SETTINGS, shareConversationsWithModelAuthors: false, }); await updateUser({ userData, locals, cookies: cookiesMock }); const settings = await collections.settings.findOne({ _id: insertedId, sessionId: { $exists: false }, }); assert.exists(settings); const user = await collections.users.findOne({ hfUserId: userData.sub }); expect(settings).toMatchObject({ userId: user?._id, updatedAt: expect.any(Date), createdAt: expect.any(Date), ethicsModalAcceptedAt: expect.any(Date), ...DEFAULT_SETTINGS, shareConversationsWithModelAuthors: false, }); await collections.settings.deleteOne({ userId: user?._id }); }); }); afterEach(async () => { await collections.users.deleteMany({ hfUserId: userData.sub }); await collections.sessions.deleteMany({}); locals.userId = "1234567890"; locals.sessionId = "1234567890"; vi.clearAllMocks(); });
0
hf_public_repos/chat-ui/src/routes/login
hf_public_repos/chat-ui/src/routes/login/callback/+page.server.ts
import { redirect, error } from "@sveltejs/kit"; import { getOIDCUserData, validateAndParseCsrfToken } from "$lib/server/auth"; import { z } from "zod"; import { base } from "$app/paths"; import { updateUser } from "./updateUser"; import { env } from "$env/dynamic/private"; import JSON5 from "json5"; const allowedUserEmails = z .array(z.string().email()) .optional() .default([]) .parse(JSON5.parse(env.ALLOWED_USER_EMAILS)); export async function load({ url, locals, cookies, request, getClientAddress }) { const { error: errorName, error_description: errorDescription } = z .object({ error: z.string().optional(), error_description: z.string().optional(), }) .parse(Object.fromEntries(url.searchParams.entries())); if (errorName) { error(400, errorName + (errorDescription ? ": " + errorDescription : "")); } const { code, state, iss } = z .object({ code: z.string(), state: z.string(), iss: z.string().optional(), }) .parse(Object.fromEntries(url.searchParams.entries())); const csrfToken = Buffer.from(state, "base64").toString("utf-8"); const validatedToken = await validateAndParseCsrfToken(csrfToken, locals.sessionId); if (!validatedToken) { error(403, "Invalid or expired CSRF token"); } const { userData } = await getOIDCUserData( { redirectURI: validatedToken.redirectUrl }, code, iss ); // Filter by allowed user emails if (allowedUserEmails.length > 0) { if (!userData.email) { error(403, "User not allowed: email not returned"); } const emailVerified = userData.email_verified ?? true; if (!emailVerified) { error(403, "User not allowed: email not verified"); } if (!allowedUserEmails.includes(userData.email)) { error(403, "User not allowed"); } } await updateUser({ userData, locals, cookies, userAgent: request.headers.get("user-agent") ?? undefined, ip: getClientAddress(), }); redirect(302, `${base}/`); }
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/conversation/+server.ts
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"; import { defaultEmbeddingModel } from "$lib/server/embeddingModels"; import { v4 } from "uuid"; import { authCondition } from "$lib/server/auth"; import { usageLimits } from "$lib/server/usageLimits"; import { MetricsServer } from "$lib/server/metrics"; export const POST: RequestHandler = async ({ locals, request }) => { const body = await request.text(); let title = ""; const parsedBody = z .object({ fromShare: z.string().optional(), model: validateModel(models), assistantId: z.string().optional(), preprompt: z.string().optional(), }) .safeParse(JSON.parse(body)); if (!parsedBody.success) { error(400, "Invalid request"); } const values = parsedBody.data; const convCount = await collections.conversations.countDocuments(authCondition(locals)); if (usageLimits?.conversations && convCount > usageLimits?.conversations) { error(429, "You have reached the maximum number of conversations. Delete some to continue."); } const model = models.find((m) => (m.id || m.name) === values.model); if (!model) { error(400, "Invalid model"); } let messages: Message[] = [ { id: v4(), from: "system", content: values.preprompt ?? "", createdAt: new Date(), updatedAt: new Date(), children: [], ancestors: [], }, ]; let rootMessageId: Message["id"] = messages[0].id; let embeddingModel: string; if (values.fromShare) { const conversation = await collections.sharedConversations.findOne({ _id: values.fromShare, }); if (!conversation) { error(404, "Conversation not found"); } title = conversation.title; messages = conversation.messages; rootMessageId = conversation.rootMessageId ?? rootMessageId; values.model = conversation.model; values.preprompt = conversation.preprompt; values.assistantId = conversation.assistantId?.toString(); embeddingModel = conversation.embeddingModel; } embeddingModel ??= model.embeddingModel ?? defaultEmbeddingModel.name; if (model.unlisted) { error(400, "Can't start a conversation with an unlisted model"); } // get preprompt from assistant if it exists const assistant = await collections.assistants.findOne({ _id: new ObjectId(values.assistantId), }); if (assistant) { values.preprompt = assistant.preprompt; } else { values.preprompt ??= model?.preprompt ?? ""; } if (messages && messages.length > 0 && messages[0].from === "system") { messages[0].content = values.preprompt; } const res = await collections.conversations.insertOne({ _id: new ObjectId(), title: title || "New Chat", rootMessageId, messages, model: values.model, preprompt: values.preprompt, assistantId: values.assistantId ? new ObjectId(values.assistantId) : undefined, createdAt: new Date(), updatedAt: new Date(), userAgent: request.headers.get("User-Agent") ?? undefined, embeddingModel, ...(locals.user ? { userId: locals.user._id } : { sessionId: locals.sessionId }), ...(values.fromShare ? { meta: { fromShareId: values.fromShare } } : {}), }); MetricsServer.getMetrics().model.conversationsTotal.inc({ model: values.model }); return new Response( JSON.stringify({ conversationId: res.insertedId.toString(), }), { headers: { "Content-Type": "application/json" } } ); }; export const GET: RequestHandler = async () => { redirect(302, `${base}/`); };
0
hf_public_repos/chat-ui/src/routes/conversation
hf_public_repos/chat-ui/src/routes/conversation/[id]/+server.ts
import { env } from "$env/dynamic/private"; import { startOfHour } from "date-fns"; import { authCondition, requiresUser } from "$lib/server/auth"; import { collections } from "$lib/server/database"; import { models, validModelIdSchema } from "$lib/server/models"; import { ERROR_MESSAGES } from "$lib/stores/errors"; import type { Message } from "$lib/types/Message"; import { error } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; import { z } from "zod"; import { MessageReasoningUpdateType, MessageUpdateStatus, MessageUpdateType, type MessageUpdate, } from "$lib/types/MessageUpdate"; import { uploadFile } from "$lib/server/files/uploadFile"; import { convertLegacyConversation } from "$lib/utils/tree/convertLegacyConversation"; import { isMessageId } from "$lib/utils/tree/isMessageId"; import { buildSubtree } from "$lib/utils/tree/buildSubtree.js"; import { addChildren } from "$lib/utils/tree/addChildren.js"; import { addSibling } from "$lib/utils/tree/addSibling.js"; import { usageLimits } from "$lib/server/usageLimits"; import { MetricsServer } from "$lib/server/metrics"; import { textGeneration } from "$lib/server/textGeneration"; import type { TextGenerationContext } from "$lib/server/textGeneration/types"; import { logger } from "$lib/server/logger.js"; export async function POST({ request, locals, params, getClientAddress }) { const id = z.string().parse(params.id); const convId = new ObjectId(id); const promptedAt = new Date(); const userId = locals.user?._id ?? locals.sessionId; // check user if (!userId) { error(401, "Unauthorized"); } // check if the user has access to the conversation const convBeforeCheck = await collections.conversations.findOne({ _id: convId, ...authCondition(locals), }); if (convBeforeCheck && !convBeforeCheck.rootMessageId) { const res = await collections.conversations.updateOne( { _id: convId, }, { $set: { ...convBeforeCheck, ...convertLegacyConversation(convBeforeCheck), }, } ); if (!res.acknowledged) { error(500, "Failed to convert conversation"); } } const conv = await collections.conversations.findOne({ _id: convId, ...authCondition(locals), }); if (!conv) { error(404, "Conversation not found"); } // register the event for ratelimiting await collections.messageEvents.insertOne({ userId, createdAt: new Date(), ip: getClientAddress(), }); const messagesBeforeLogin = env.MESSAGES_BEFORE_LOGIN ? parseInt(env.MESSAGES_BEFORE_LOGIN) : 0; // guest mode check if (!locals.user?._id && requiresUser && messagesBeforeLogin) { const totalMessages = ( await collections.conversations .aggregate([ { $match: { ...authCondition(locals), "messages.from": "assistant" } }, { $project: { messages: 1 } }, { $limit: messagesBeforeLogin + 1 }, { $unwind: "$messages" }, { $match: { "messages.from": "assistant" } }, { $count: "messages" }, ]) .toArray() )[0]?.messages ?? 0; if (totalMessages > messagesBeforeLogin) { error(429, "Exceeded number of messages before login"); } } if (usageLimits?.messagesPerMinute) { // check if the user is rate limited const nEvents = Math.max( await collections.messageEvents.countDocuments({ userId, createdAt: { $gte: new Date(Date.now() - 60_000) }, }), await collections.messageEvents.countDocuments({ ip: getClientAddress(), createdAt: { $gte: new Date(Date.now() - 60_000) }, }) ); if (nEvents > usageLimits.messagesPerMinute) { error(429, ERROR_MESSAGES.rateLimited); } } if (usageLimits?.messages && conv.messages.length > usageLimits.messages) { error( 429, `This conversation has more than ${usageLimits.messages} messages. Start a new one to continue` ); } // fetch the model const model = models.find((m) => m.id === conv.model); if (!model) { error(410, "Model not available anymore"); } // finally parse the content of the request const form = await request.formData(); const json = form.get("data"); if (!json || typeof json !== "string") { error(400, "Invalid request"); } const { inputs: newPrompt, id: messageId, is_retry: isRetry, is_continue: isContinue, web_search: webSearch, tools: toolsPreferences, } = z .object({ id: z.string().uuid().refine(isMessageId).optional(), // parent message id to append to for a normal message, or the message id for a retry/continue inputs: z.optional( z .string() .min(1) .transform((s) => s.replace(/\r\n/g, "\n")) ), is_retry: z.optional(z.boolean()), is_continue: z.optional(z.boolean()), web_search: z.optional(z.boolean()), tools: z.array(z.string()).optional(), files: z.optional( z.array( z.object({ type: z.literal("base64").or(z.literal("hash")), name: z.string(), value: z.string(), mime: z.string(), }) ) ), }) .parse(JSON.parse(json)); const inputFiles = await Promise.all( form .getAll("files") .filter((entry): entry is File => entry instanceof File && entry.size > 0) .map(async (file) => { const [type, ...name] = file.name.split(";"); return { type: z.literal("base64").or(z.literal("hash")).parse(type), value: await file.text(), mime: file.type, name: name.join(";"), }; }) ); if (usageLimits?.messageLength && (newPrompt?.length ?? 0) > usageLimits.messageLength) { error(400, "Message too long."); } // each file is either: // base64 string requiring upload to the server // hash pointing to an existing file const hashFiles = inputFiles?.filter((file) => file.type === "hash") ?? []; const b64Files = inputFiles ?.filter((file) => file.type !== "hash") .map((file) => { const blob = Buffer.from(file.value, "base64"); return new File([blob], file.name, { type: file.mime }); }) ?? []; // check sizes // todo: make configurable if (b64Files.some((file) => file.size > 10 * 1024 * 1024)) { error(413, "File too large, should be <10MB"); } const uploadedFiles = await Promise.all(b64Files.map((file) => uploadFile(file, conv))).then( (files) => [...files, ...hashFiles] ); // we will append tokens to the content of this message let messageToWriteToId: Message["id"] | undefined = undefined; // used for building the prompt, subtree of the conversation that goes from the latest message to the root let messagesForPrompt: Message[] = []; if (isContinue && messageId) { // if it's the last message and we continue then we build the prompt up to the last message // we will strip the end tokens afterwards when the prompt is built if ((conv.messages.find((msg) => msg.id === messageId)?.children?.length ?? 0) > 0) { error(400, "Can only continue the last message"); } messageToWriteToId = messageId; messagesForPrompt = buildSubtree(conv, messageId); } else if (isRetry && messageId) { // two cases, if we're retrying a user message with a newPrompt set, // it means we're editing a user message // if we're retrying on an assistant message, newPrompt cannot be set // it means we're retrying the last assistant message for a new answer const messageToRetry = conv.messages.find((message) => message.id === messageId); if (!messageToRetry) { error(404, "Message not found"); } if (messageToRetry.from === "user" && newPrompt) { // add a sibling to this message from the user, with the alternative prompt // add a children to that sibling, where we can write to const newUserMessageId = addSibling( conv, { from: "user", content: newPrompt, files: uploadedFiles, createdAt: new Date(), updatedAt: new Date(), }, messageId ); messageToWriteToId = addChildren( conv, { from: "assistant", content: "", createdAt: new Date(), updatedAt: new Date(), }, newUserMessageId ); messagesForPrompt = buildSubtree(conv, newUserMessageId); } else if (messageToRetry.from === "assistant") { // we're retrying an assistant message, to generate a new answer // just add a sibling to the assistant answer where we can write to messageToWriteToId = addSibling( conv, { from: "assistant", content: "", createdAt: new Date(), updatedAt: new Date() }, messageId ); messagesForPrompt = buildSubtree(conv, messageId); messagesForPrompt.pop(); // don't need the latest assistant message in the prompt since we're retrying it } } else { // just a normal linear conversation, so we add the user message // and the blank assistant message back to back const newUserMessageId = addChildren( conv, { from: "user", content: newPrompt ?? "", files: uploadedFiles, createdAt: new Date(), updatedAt: new Date(), }, messageId ); messageToWriteToId = addChildren( conv, { from: "assistant", content: "", createdAt: new Date(), updatedAt: new Date(), }, newUserMessageId ); // build the prompt from the user message messagesForPrompt = buildSubtree(conv, newUserMessageId); } const messageToWriteTo = conv.messages.find((message) => message.id === messageToWriteToId); if (!messageToWriteTo) { error(500, "Failed to create message"); } if (messagesForPrompt.length === 0) { error(500, "Failed to create prompt"); } // update the conversation with the new messages await collections.conversations.updateOne( { _id: convId }, { $set: { messages: conv.messages, title: conv.title, updatedAt: new Date() } } ); let doneStreaming = false; let lastTokenTimestamp: undefined | Date = undefined; // we now build the stream const stream = new ReadableStream({ async start(controller) { messageToWriteTo.updates ??= []; async function update(event: MessageUpdate) { if (!messageToWriteTo || !conv) { throw Error("No message or conversation to write events to"); } // Add token to content or skip if empty if (event.type === MessageUpdateType.Stream) { if (event.token === "") return; messageToWriteTo.content += event.token; // add to token total MetricsServer.getMetrics().model.tokenCountTotal.inc({ model: model?.id }); // if this is the first token, add to time to first token if (!lastTokenTimestamp) { MetricsServer.getMetrics().model.timeToFirstToken.observe( { model: model?.id }, Date.now() - promptedAt.getTime() ); lastTokenTimestamp = new Date(); } // add to time per token MetricsServer.getMetrics().model.timePerOutputToken.observe( { model: model?.id }, Date.now() - (lastTokenTimestamp ?? promptedAt).getTime() ); lastTokenTimestamp = new Date(); } else if ( event.type === MessageUpdateType.Reasoning && event.subtype === MessageReasoningUpdateType.Stream ) { messageToWriteTo.reasoning ??= ""; messageToWriteTo.reasoning += event.token; } // Set the title else if (event.type === MessageUpdateType.Title) { conv.title = event.title; await collections.conversations.updateOne( { _id: convId }, { $set: { title: conv?.title, updatedAt: new Date() } } ); } // Set the final text and the interrupted flag else if (event.type === MessageUpdateType.FinalAnswer) { messageToWriteTo.interrupted = event.interrupted; messageToWriteTo.content = initialMessageContent + event.text; // add to latency MetricsServer.getMetrics().model.latency.observe( { model: model?.id }, Date.now() - promptedAt.getTime() ); } // Add file else if (event.type === MessageUpdateType.File) { messageToWriteTo.files = [ ...(messageToWriteTo.files ?? []), { type: "hash", name: event.name, value: event.sha, mime: event.mime }, ]; } // Append to the persistent message updates if it's not a stream update if ( event.type !== MessageUpdateType.Stream && !( event.type === MessageUpdateType.Status && event.status === MessageUpdateStatus.KeepAlive ) && !( event.type === MessageUpdateType.Reasoning && event.subtype === MessageReasoningUpdateType.Stream ) ) { messageToWriteTo?.updates?.push(event); } // Avoid remote keylogging attack executed by watching packet lengths // by padding the text with null chars to a fixed length // https://cdn.arstechnica.net/wp-content/uploads/2024/03/LLM-Side-Channel.pdf if (event.type === MessageUpdateType.Stream) { event = { ...event, token: event.token.padEnd(16, "\0") }; } // Send the update to the client controller.enqueue(JSON.stringify(event) + "\n"); // Send 4096 of spaces to make sure the browser doesn't blocking buffer that holding the response if (event.type === MessageUpdateType.FinalAnswer) { controller.enqueue(" ".repeat(4096)); } } await collections.conversations.updateOne( { _id: convId }, { $set: { title: conv.title, updatedAt: new Date() } } ); messageToWriteTo.updatedAt = new Date(); let hasError = false; const initialMessageContent = messageToWriteTo.content; try { const ctx: TextGenerationContext = { model, endpoint: await model.getEndpoint(), conv, messages: messagesForPrompt, assistant: undefined, isContinue: isContinue ?? false, webSearch: webSearch ?? false, toolsPreference: toolsPreferences ?? [], promptedAt, ip: getClientAddress(), username: locals.user?.username, }; // run the text generation and send updates to the client for await (const event of textGeneration(ctx)) await update(event); } catch (e) { hasError = true; await update({ type: MessageUpdateType.Status, status: MessageUpdateStatus.Error, message: (e as Error).message, }); logger.error(e); } finally { // check if no output was generated if (!hasError && messageToWriteTo.content === initialMessageContent) { await update({ type: MessageUpdateType.Status, status: MessageUpdateStatus.Error, message: "No output was generated. Something went wrong.", }); } } await collections.conversations.updateOne( { _id: convId }, { $set: { messages: conv.messages, title: conv?.title, updatedAt: new Date() } } ); // used to detect if cancel() is called bc of interrupt or just because the connection closes doneStreaming = true; controller.close(); }, async cancel() { if (doneStreaming) return; await collections.conversations.updateOne( { _id: convId }, { $set: { messages: conv.messages, title: conv.title, updatedAt: new Date() } } ); }, }); if (conv.assistantId) { await collections.assistantStats.updateOne( { assistantId: conv.assistantId, "date.at": startOfHour(new Date()), "date.span": "hour" }, { $inc: { count: 1 } }, { upsert: true } ); } const metrics = MetricsServer.getMetrics(); metrics.model.messagesTotal.inc({ model: model?.id }); // Todo: maybe we should wait for the message to be saved before ending the response - in case of errors return new Response(stream, { headers: { "Content-Type": "text/event-stream", }, }); } export async function DELETE({ locals, params }) { const convId = new ObjectId(params.id); const conv = await collections.conversations.findOne({ _id: convId, ...authCondition(locals), }); if (!conv) { error(404, "Conversation not found"); } await collections.conversations.deleteOne({ _id: conv._id }); return new Response(); } export async function PATCH({ request, locals, params }) { const values = z .object({ title: z.string().trim().min(1).max(100).optional(), model: validModelIdSchema.optional(), }) .parse(await request.json()); const convId = new ObjectId(params.id); const conv = await collections.conversations.findOne({ _id: convId, ...authCondition(locals), }); if (!conv) { error(404, "Conversation not found"); } await collections.conversations.updateOne( { _id: convId, }, { $set: values, } ); return new Response(); }
0
hf_public_repos/chat-ui/src/routes/conversation
hf_public_repos/chat-ui/src/routes/conversation/[id]/+page.svelte
<script lang="ts"> import ChatWindow from "$lib/components/chat/ChatWindow.svelte"; import { pendingMessage } from "$lib/stores/pendingMessage"; import { isAborted } from "$lib/stores/isAborted"; import { onMount } from "svelte"; import { page } from "$app/stores"; import { goto, invalidateAll } from "$app/navigation"; import { base } from "$app/paths"; import { shareConversation } from "$lib/shareConversation"; import { ERROR_MESSAGES, error } from "$lib/stores/errors"; import { findCurrentModel } from "$lib/utils/models"; import { webSearchParameters } from "$lib/stores/webSearchParameters"; import type { Message } from "$lib/types/Message"; import { MessageReasoningUpdateType, MessageUpdateStatus, MessageUpdateType, } from "$lib/types/MessageUpdate"; import titleUpdate from "$lib/stores/titleUpdate"; import file2base64 from "$lib/utils/file2base64"; import { addChildren } from "$lib/utils/tree/addChildren"; import { addSibling } from "$lib/utils/tree/addSibling"; import { fetchMessageUpdates } from "$lib/utils/messageUpdates"; import { createConvTreeStore } from "$lib/stores/convTree"; import type { v4 } from "uuid"; import { useSettingsStore } from "$lib/stores/settings.js"; export let data; $: ({ messages } = data); let loading = false; let pending = false; $: activeModel = findCurrentModel([...data.models, ...data.oldModels], data.model); let files: File[] = []; async function convFromShared() { try { loading = true; const res = await fetch(`${base}/conversation`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ fromShare: $page.params.id, model: data.model, }), }); if (!res.ok) { error.set(await res.text()); console.error("Error while creating conversation: " + (await res.text())); return; } const { conversationId } = await res.json(); return conversationId; } catch (err) { error.set(ERROR_MESSAGES.default); console.error(String(err)); throw err; } } // this function is used to send new message to the backends async function writeMessage({ prompt, messageId = $convTreeStore.leaf ?? undefined, isRetry = false, isContinue = false, }: { prompt?: string; messageId?: ReturnType<typeof v4>; isRetry?: boolean; isContinue?: boolean; }): Promise<void> { try { $isAborted = false; loading = true; pending = true; const base64Files = await Promise.all( (files ?? []).map((file) => file2base64(file).then((value) => ({ type: "base64" as const, value, mime: file.type, name: file.name, })) ) ); let messageToWriteToId: Message["id"] | undefined = undefined; // used for building the prompt, subtree of the conversation that goes from the latest message to the root if (isContinue && messageId) { if ((messages.find((msg) => msg.id === messageId)?.children?.length ?? 0) > 0) { $error = "Can only continue the last message"; } else { messageToWriteToId = messageId; } } else if (isRetry && messageId) { // two cases, if we're retrying a user message with a newPrompt set, // it means we're editing a user message // if we're retrying on an assistant message, newPrompt cannot be set // it means we're retrying the last assistant message for a new answer const messageToRetry = messages.find((message) => message.id === messageId); if (!messageToRetry) { $error = "Message not found"; } if (messageToRetry?.from === "user" && prompt) { // add a sibling to this message from the user, with the alternative prompt // add a children to that sibling, where we can write to const newUserMessageId = addSibling( { messages, rootMessageId: data.rootMessageId, }, { from: "user", content: prompt, files: messageToRetry.files, }, messageId ); messageToWriteToId = addChildren( { messages, rootMessageId: data.rootMessageId, }, { from: "assistant", content: "" }, newUserMessageId ); } else if (messageToRetry?.from === "assistant") { // we're retrying an assistant message, to generate a new answer // just add a sibling to the assistant answer where we can write to messageToWriteToId = addSibling( { messages, rootMessageId: data.rootMessageId, }, { from: "assistant", content: "" }, messageId ); } } else { // just a normal linear conversation, so we add the user message // and the blank assistant message back to back const newUserMessageId = addChildren( { messages, rootMessageId: data.rootMessageId, }, { from: "user", content: prompt ?? "", files: base64Files, createdAt: new Date(), updatedAt: new Date(), }, messageId ); if (!data.rootMessageId) { data.rootMessageId = newUserMessageId; } messageToWriteToId = addChildren( { messages, rootMessageId: data.rootMessageId, }, { from: "assistant", content: "", createdAt: new Date(), updatedAt: new Date(), }, newUserMessageId ); } messages = [...messages]; const userMessage = messages.find((message) => message.id === messageId); const messageToWriteTo = messages.find((message) => message.id === messageToWriteToId); if (!messageToWriteTo) { throw new Error("Message to write to not found"); } // disable websearch if assistant is present const hasAssistant = !!$page.data.assistant; const messageUpdatesAbortController = new AbortController(); const messageUpdatesIterator = await fetchMessageUpdates( $page.params.id, { base, inputs: prompt, messageId, isRetry, isContinue, webSearch: !hasAssistant && !activeModel.tools && $webSearchParameters.useSearch, tools: $settings.tools, // preference for tools files: isRetry ? userMessage?.files : base64Files, }, messageUpdatesAbortController.signal ).catch((err) => { error.set(err.message); }); if (messageUpdatesIterator === undefined) return; files = []; for await (const update of messageUpdatesIterator) { if ($isAborted) { messageUpdatesAbortController.abort(); return; } // Remove null characters added due to remote keylogging prevention // See server code for more details if (update.type === MessageUpdateType.Stream) { update.token = update.token.replaceAll("\0", ""); } messageToWriteTo.updates = [...(messageToWriteTo.updates ?? []), update]; if (update.type === MessageUpdateType.Stream && !$settings.disableStream) { messageToWriteTo.content += update.token; pending = false; messages = [...messages]; } else if ( update.type === MessageUpdateType.WebSearch || update.type === MessageUpdateType.Tool ) { messages = [...messages]; } else if ( update.type === MessageUpdateType.Status && update.status === MessageUpdateStatus.Error ) { $error = update.message ?? "An error has occurred"; } else if (update.type === MessageUpdateType.Title) { const convInData = data.conversations.find(({ id }) => id === $page.params.id); if (convInData) { convInData.title = update.title; $titleUpdate = { title: update.title, convId: $page.params.id, }; } } else if (update.type === MessageUpdateType.File) { messageToWriteTo.files = [ ...(messageToWriteTo.files ?? []), { type: "hash", value: update.sha, mime: update.mime, name: update.name }, ]; messages = [...messages]; } else if (update.type === MessageUpdateType.Reasoning) { if (!messageToWriteTo.reasoning) { messageToWriteTo.reasoning = ""; } if (update.subtype === MessageReasoningUpdateType.Stream) { messageToWriteTo.reasoning += update.token; } else { messageToWriteTo.updates = [...(messageToWriteTo.updates ?? []), update]; } messages = [...messages]; } } } catch (err) { if (err instanceof Error && err.message.includes("overloaded")) { $error = "Too much traffic, please try again."; } else if (err instanceof Error && err.message.includes("429")) { $error = ERROR_MESSAGES.rateLimited; } else if (err instanceof Error) { $error = err.message; } else { $error = ERROR_MESSAGES.default; } console.error(err); } finally { loading = false; pending = false; await invalidateAll(); } } async function voteMessage(score: Message["score"], messageId: string) { let conversationId = $page.params.id; let oldScore: Message["score"] | undefined; // optimistic update to avoid waiting for the server messages = messages.map((message) => { if (message.id === messageId) { oldScore = message.score; return { ...message, score }; } return message; }); try { await fetch(`${base}/conversation/${conversationId}/message/${messageId}/vote`, { method: "POST", body: JSON.stringify({ score }), }); } catch { // revert score on any error messages = messages.map((message) => { return message.id !== messageId ? message : { ...message, score: oldScore }; }); } } onMount(async () => { // only used in case of creating new conversations (from the parent POST endpoint) if ($pendingMessage) { files = $pendingMessage.files; await writeMessage({ prompt: $pendingMessage.content }); $pendingMessage = undefined; } }); async function onMessage(event: CustomEvent<string>) { if (!data.shared) { await writeMessage({ prompt: event.detail }); } else { await convFromShared() .then(async (convId) => { await goto(`${base}/conversation/${convId}`, { invalidateAll: true }); }) .then(async () => await writeMessage({ prompt: event.detail })) .finally(() => (loading = false)); } } async function onRetry(event: CustomEvent<{ id: Message["id"]; content?: string }>) { if (!data.shared) { await writeMessage({ prompt: event.detail.content, messageId: event.detail.id, isRetry: true, }); } else { await convFromShared() .then(async (convId) => { await goto(`${base}/conversation/${convId}`, { invalidateAll: true }); }) .then( async () => await writeMessage({ prompt: event.detail.content, messageId: event.detail.id, isRetry: true, }) ) .finally(() => (loading = false)); } } async function onContinue(event: CustomEvent<{ id: Message["id"] }>) { if (!data.shared) { await writeMessage({ messageId: event.detail.id, isContinue: true }); } else { await convFromShared() .then(async (convId) => { await goto(`${base}/conversation/${convId}`, { invalidateAll: true }); }) .then( async () => await writeMessage({ messageId: event.detail.id, isContinue: true, }) ) .finally(() => (loading = false)); } } $: $page.params.id, (($isAborted = true), (loading = false), ($convTreeStore.editing = null)); $: title = data.conversations.find((conv) => conv.id === $page.params.id)?.title ?? data.title; const convTreeStore = createConvTreeStore(); const settings = useSettingsStore(); </script> <svelte:head> {#await title then title} <title>{title}</title> {/await} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css" integrity="sha384-GvrOXuhMATgEsSwCs4smul74iXGOixntILdUW9XmUC6+HX0sLNAK3q71HotJqlAn" crossorigin="anonymous" /> </svelte:head> <ChatWindow {loading} {pending} {messages} shared={data.shared} preprompt={data.preprompt} bind:files on:message={onMessage} on:retry={onRetry} on:continue={onContinue} on:vote={(event) => voteMessage(event.detail.score, event.detail.id)} on:share={() => shareConversation($page.params.id, data.title)} on:stop={() => (($isAborted = true), (loading = false))} models={data.models} currentModel={findCurrentModel([...data.models, ...data.oldModels], data.model)} assistant={data.assistant} />
0
hf_public_repos/chat-ui/src/routes/conversation
hf_public_repos/chat-ui/src/routes/conversation/[id]/+page.server.ts
import { collections } from "$lib/server/database"; import { ObjectId } from "mongodb"; import { error } from "@sveltejs/kit"; import { authCondition } from "$lib/server/auth"; import { UrlDependency } from "$lib/types/UrlDependency"; import { convertLegacyConversation } from "$lib/utils/tree/convertLegacyConversation.js"; export const load = async ({ params, depends, locals }) => { let conversation; let shared = false; // if the conver if (params.id.length === 7) { // shared link of length 7 conversation = await collections.sharedConversations.findOne({ _id: params.id, }); shared = true; if (!conversation) { error(404, "Conversation not found"); } } else { // todo: add validation on params.id conversation = await collections.conversations.findOne({ _id: new ObjectId(params.id), ...authCondition(locals), }); depends(UrlDependency.Conversation); if (!conversation) { const conversationExists = (await collections.conversations.countDocuments({ _id: new ObjectId(params.id), })) !== 0; if (conversationExists) { error( 403, "You don't have access to this conversation. If someone gave you this link, ask them to use the 'share' feature instead." ); } error(404, "Conversation not found."); } } const convertedConv = { ...conversation, ...convertLegacyConversation(conversation) }; return { messages: convertedConv.messages, title: convertedConv.title, model: convertedConv.model, preprompt: convertedConv.preprompt, rootMessageId: convertedConv.rootMessageId, assistant: convertedConv.assistantId ? JSON.parse( JSON.stringify( await collections.assistants.findOne({ _id: new ObjectId(convertedConv.assistantId), }) ) ) : null, shared, }; }; export const actions = { deleteBranch: async ({ request, locals, params }) => { const data = await request.formData(); const messageId = data.get("messageId"); if (!messageId || typeof messageId !== "string") { error(400, "Invalid message id"); } const conversation = await collections.conversations.findOne({ ...authCondition(locals), _id: new ObjectId(params.id), }); if (!conversation) { error(404, "Conversation not found"); } const filteredMessages = conversation.messages .filter( (message) => // not the message AND the message is not in ancestors !(message.id === messageId) && message.ancestors && !message.ancestors.includes(messageId) ) .map((message) => { // remove the message from children if it's there if (message.children && message.children.includes(messageId)) { message.children = message.children.filter((child) => child !== messageId); } return message; }); await collections.conversations.updateOne( { _id: conversation._id, ...authCondition(locals) }, { $set: { messages: filteredMessages } } ); return { from: "deleteBranch", ok: true }; }, };
0
hf_public_repos/chat-ui/src/routes/conversation/[id]
hf_public_repos/chat-ui/src/routes/conversation/[id]/share/+server.ts
import { authCondition } from "$lib/server/auth"; import { collections } from "$lib/server/database"; import type { SharedConversation } from "$lib/types/SharedConversation"; import { getShareUrl } from "$lib/utils/getShareUrl"; import { hashConv } from "$lib/utils/hashConv"; import { error } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; import { nanoid } from "nanoid"; export async function POST({ params, url, locals }) { const conversation = await collections.conversations.findOne({ _id: new ObjectId(params.id), ...authCondition(locals), }); if (!conversation) { error(404, "Conversation not found"); } const hash = await hashConv(conversation); const existingShare = await collections.sharedConversations.findOne({ hash }); if (existingShare) { return new Response( JSON.stringify({ url: getShareUrl(url, existingShare._id), }), { headers: { "Content-Type": "application/json" } } ); } const shared: SharedConversation = { _id: nanoid(7), hash, createdAt: new Date(), updatedAt: new Date(), rootMessageId: conversation.rootMessageId, messages: conversation.messages, title: conversation.title, model: conversation.model, embeddingModel: conversation.embeddingModel, preprompt: conversation.preprompt, assistantId: conversation.assistantId, }; await collections.sharedConversations.insertOne(shared); // copy files from `${conversation._id}-` to `${shared._id}-` const files = await collections.bucket .find({ filename: { $regex: `${conversation._id}-` } }) .toArray(); await Promise.all( files.map(async (file) => { const newFilename = file.filename.replace(`${conversation._id}-`, `${shared._id}-`); // copy files from `${conversation._id}-` to `${shared._id}-` by downloading and reuploaidng const downloadStream = collections.bucket.openDownloadStream(file._id); const uploadStream = collections.bucket.openUploadStream(newFilename, { metadata: { ...file.metadata, conversation: shared._id.toString() }, }); downloadStream.pipe(uploadStream); }) ); return new Response( JSON.stringify({ url: getShareUrl(url, shared._id), }), { headers: { "Content-Type": "application/json" } } ); }
0
hf_public_repos/chat-ui/src/routes/conversation/[id]
hf_public_repos/chat-ui/src/routes/conversation/[id]/stop-generating/+server.ts
import { authCondition } from "$lib/server/auth"; import { collections } from "$lib/server/database"; import { error } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; /** * Ideally, we'd be able to detect the client-side abort, see https://github.com/huggingface/chat-ui/pull/88#issuecomment-1523173850 */ export async function POST({ params, locals }) { const conversationId = new ObjectId(params.id); const conversation = await collections.conversations.findOne({ _id: conversationId, ...authCondition(locals), }); if (!conversation) { error(404, "Conversation not found"); } await collections.abortedGenerations.updateOne( { conversationId }, { $set: { updatedAt: new Date() }, $setOnInsert: { createdAt: new Date() } }, { upsert: true } ); return new Response(); }
0
hf_public_repos/chat-ui/src/routes/conversation/[id]/message/[messageId]
hf_public_repos/chat-ui/src/routes/conversation/[id]/message/[messageId]/vote/+server.ts
import { authCondition } from "$lib/server/auth"; import { collections } from "$lib/server/database"; import { MetricsServer } from "$lib/server/metrics.js"; import { error } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; import { z } from "zod"; export async function POST({ params, request, locals }) { const { score } = z .object({ score: z.number().int().min(-1).max(1), }) .parse(await request.json()); const conversationId = new ObjectId(params.id); const messageId = params.messageId; // aggregate votes per model in order to detect model performance degradation const model = await collections.conversations .findOne( { _id: conversationId, ...authCondition(locals), }, { projection: { model: 1 } } ) .then((c) => c?.model); if (model) { if (score === 1) { MetricsServer.getMetrics().model.votesPositive.inc({ model }); } else { MetricsServer.getMetrics().model.votesNegative.inc({ model }); } } const document = await collections.conversations.updateOne( { _id: conversationId, ...authCondition(locals), "messages.id": messageId, }, { ...(score !== 0 ? { $set: { "messages.$.score": score, }, } : { $unset: { "messages.$.score": "" } }), } ); if (!document.matchedCount) { error(404, "Message not found"); } return new Response(); }
0
hf_public_repos/chat-ui/src/routes/conversation/[id]/message/[messageId]
hf_public_repos/chat-ui/src/routes/conversation/[id]/message/[messageId]/prompt/+server.ts
import { buildPrompt } from "$lib/buildPrompt"; import { authCondition } from "$lib/server/auth"; import { collections } from "$lib/server/database"; import { models } from "$lib/server/models"; import { buildSubtree } from "$lib/utils/tree/buildSubtree"; import { isMessageId } from "$lib/utils/tree/isMessageId"; import { error } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; export async function GET({ params, locals }) { const conv = params.id.length === 7 ? await collections.sharedConversations.findOne({ _id: params.id, }) : await collections.conversations.findOne({ _id: new ObjectId(params.id), ...authCondition(locals), }); if (conv === null) { error(404, "Conversation not found"); } const messageId = params.messageId; const messageIndex = conv.messages.findIndex((msg) => msg.id === messageId); if (!isMessageId(messageId) || messageIndex === -1) { error(404, "Message not found"); } const model = models.find((m) => m.id === conv.model); if (!model) { error(404, "Conversation model not found"); } const messagesUpTo = buildSubtree(conv, messageId); const prompt = await buildPrompt({ preprompt: conv.preprompt, messages: messagesUpTo, model, }); const userMessage = conv.messages[messageIndex]; const assistantMessage = conv.messages[messageIndex + 1]; return new Response( JSON.stringify( { note: "This is a preview of the prompt that will be sent to the model when retrying the message. It may differ from what was sent in the past if the parameters have been updated since", prompt, model: model.name, parameters: { ...model.parameters, return_full_text: false, }, userMessage, ...(assistantMessage ? { assistantMessage } : {}), }, null, 2 ), { headers: { "Content-Type": "application/json" } } ); }
0
hf_public_repos/chat-ui/src/routes/conversation/[id]/output
hf_public_repos/chat-ui/src/routes/conversation/[id]/output/[sha256]/+server.ts
import { authCondition } from "$lib/server/auth"; import { collections } from "$lib/server/database"; import { error } from "@sveltejs/kit"; import { ObjectId } from "mongodb"; import { z } from "zod"; import type { RequestHandler } from "./$types"; import { downloadFile } from "$lib/server/files/downloadFile"; import mimeTypes from "mime-types"; export const GET: RequestHandler = async ({ locals, params }) => { const sha256 = z.string().parse(params.sha256); const userId = locals.user?._id ?? locals.sessionId; // check user if (!userId) { error(401, "Unauthorized"); } if (params.id.length !== 7) { const convId = new ObjectId(z.string().parse(params.id)); // check if the user has access to the conversation const conv = await collections.conversations.findOne({ _id: convId, ...authCondition(locals), }); if (!conv) { error(404, "Conversation not found"); } } else { // look for the conversation in shared conversations const conv = await collections.sharedConversations.findOne({ _id: params.id, }); if (!conv) { error(404, "Conversation not found"); } } const { value, mime } = await downloadFile(sha256, params.id); const b64Value = Buffer.from(value, "base64"); return new Response(b64Value, { headers: { "Content-Type": mime ?? "application/octet-stream", "Content-Security-Policy": "default-src 'none'; script-src 'none'; style-src 'none'; sandbox;", "Content-Disposition": `attachment; filename="${sha256.slice(0, 8)}.${ mime ? mimeTypes.extension(mime) || "bin" : "bin" }"`, "Content-Length": b64Value.length.toString(), "Accept-Range": "bytes", }, }); };
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/privacy/+page.svelte
<script lang="ts"> import { marked } from "marked"; import privacy from "../../../PRIVACY.md?raw"; </script> <div class="overflow-auto p-6"> <div class="prose mx-auto px-4 pb-24 pt-6 dark:prose-invert md:pt-12"> <!-- eslint-disable-next-line svelte/no-at-html-tags --> {@html marked(privacy, { gfm: true })} </div> </div>
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/logout/+page.server.ts
import { dev } from "$app/environment"; import { base } from "$app/paths"; import { env } from "$env/dynamic/private"; import { collections } from "$lib/server/database"; import { redirect } from "@sveltejs/kit"; export const actions = { async default({ cookies, locals }) { await collections.sessions.deleteOne({ sessionId: locals.sessionId }); cookies.delete(env.COOKIE_NAME, { path: "/", // So that it works inside the space's iframe sameSite: dev || env.ALLOW_INSECURE_COOKIES === "true" ? "lax" : "none", secure: !dev && !(env.ALLOW_INSECURE_COOKIES === "true"), httpOnly: true, }); redirect(303, `${base}/`); }, };
0
hf_public_repos/chat-ui/src/routes
hf_public_repos/chat-ui/src/routes/healthcheck/+server.ts
export async function GET() { return new Response("OK", { status: 200 }); }
0
hf_public_repos/chat-ui/src
hf_public_repos/chat-ui/src/lib/buildPrompt.ts
import type { EndpointParameters } from "./server/endpoints/endpoints"; import type { BackendModel } from "./server/models"; import type { Tool, ToolResult } from "./types/Tool"; type buildPromptOptions = Pick<EndpointParameters, "messages" | "preprompt" | "continueMessage"> & { model: BackendModel; tools?: Tool[]; toolResults?: ToolResult[]; }; export async function buildPrompt({ messages, model, preprompt, continueMessage, tools, toolResults, }: buildPromptOptions): Promise<string> { const filteredMessages = messages; if (filteredMessages[0].from === "system" && preprompt) { filteredMessages[0].content = preprompt; } let prompt = model .chatPromptRender({ messages: filteredMessages, preprompt, tools, toolResults, continueMessage, }) // Not super precise, but it's truncated in the model's backend anyway .split(" ") .slice(-(model.parameters?.truncate ?? 0)) .join(" "); if (continueMessage && model.parameters?.stop) { let trimmedPrompt = prompt.trimEnd(); let hasRemovedStop = true; while (hasRemovedStop) { hasRemovedStop = false; for (const stopToken of model.parameters.stop) { if (trimmedPrompt.endsWith(stopToken)) { trimmedPrompt = trimmedPrompt.slice(0, -stopToken.length); hasRemovedStop = true; break; } } trimmedPrompt = trimmedPrompt.trimEnd(); } prompt = trimmedPrompt; } return prompt; }
0
hf_public_repos/chat-ui/src
hf_public_repos/chat-ui/src/lib/switchTheme.ts
export function switchTheme() { const { classList } = document.querySelector("html") as HTMLElement; const metaTheme = document.querySelector('meta[name="theme-color"]') as HTMLMetaElement; if (classList.contains("dark")) { classList.remove("dark"); metaTheme.setAttribute("content", "rgb(249, 250, 251)"); localStorage.theme = "light"; } else { classList.add("dark"); metaTheme.setAttribute("content", "rgb(26, 36, 50)"); localStorage.theme = "dark"; } }
0
hf_public_repos/chat-ui/src
hf_public_repos/chat-ui/src/lib/shareConversation.ts
import { base } from "$app/paths"; import { ERROR_MESSAGES, error } from "$lib/stores/errors"; import { share } from "./utils/share"; import { page } from "$app/stores"; import { get } from "svelte/store"; import { getShareUrl } from "./utils/getShareUrl"; export async function shareConversation(id: string, title: string) { try { if (id.length === 7) { const url = get(page).url; await share(getShareUrl(url, id), title, true); } else { const res = await fetch(`${base}/conversation/${id}/share`, { method: "POST", headers: { "Content-Type": "application/json", }, }); if (!res.ok) { error.set("Error while sharing conversation, try again."); console.error("Error while sharing conversation: " + (await res.text())); return; } const { url } = await res.json(); await share(url, title, true); } } catch (err) { error.set(ERROR_MESSAGES.default); console.error(err); } }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Conversation.ts
import type { ObjectId } from "mongodb"; import type { Message } from "./Message"; import type { Timestamps } from "./Timestamps"; import type { User } from "./User"; import type { Assistant } from "./Assistant"; export interface Conversation extends Timestamps { _id: ObjectId; sessionId?: string; userId?: User["_id"]; model: string; embeddingModel: string; title: string; rootMessageId?: Message["id"]; messages: Message[]; meta?: { fromShareId?: string; }; preprompt?: string; assistantId?: Assistant["_id"]; userAgent?: string; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/WebSearch.ts
import type { ObjectId } from "mongodb"; import type { Conversation } from "./Conversation"; import type { Timestamps } from "./Timestamps"; import type { HeaderElement } from "$lib/server/websearch/markdown/types"; export interface WebSearch extends Timestamps { _id?: ObjectId; convId?: Conversation["_id"]; prompt: string; searchQuery: string; results: WebSearchSource[]; contextSources: WebSearchUsedSource[]; } export interface WebSearchSource { title?: string; link: string; } export interface WebSearchScrapedSource extends WebSearchSource { page: WebSearchPage; } export interface WebSearchPage { title: string; siteName?: string; author?: string; description?: string; createdAt?: string; modifiedAt?: string; markdownTree: HeaderElement; } export interface WebSearchUsedSource extends WebSearchScrapedSource { context: string; } export type WebSearchMessageSources = { type: "sources"; sources: WebSearchSource[]; }; // eslint-disable-next-line no-shadow export enum WebSearchProvider { GOOGLE = "Google", YOU = "You.com", SEARXNG = "SearXNG", BING = "Bing", }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Report.ts
import type { ObjectId } from "mongodb"; import type { User } from "./User"; import type { Assistant } from "./Assistant"; import type { Timestamps } from "./Timestamps"; export interface Report extends Timestamps { _id: ObjectId; createdBy: User["_id"] | string; object: "assistant" | "tool"; contentId: Assistant["_id"]; reason?: string; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Tool.ts
import type { ObjectId } from "mongodb"; import type { User } from "./User"; import type { Timestamps } from "./Timestamps"; import type { BackendToolContext } from "$lib/server/tools"; import type { MessageUpdate } from "./MessageUpdate"; import { z } from "zod"; import type { ReviewStatus } from "./Review"; export const ToolColor = z.union([ z.literal("purple"), z.literal("blue"), z.literal("green"), z.literal("yellow"), z.literal("red"), ]); export const ToolIcon = z.union([ z.literal("wikis"), z.literal("tools"), z.literal("camera"), z.literal("code"), z.literal("email"), z.literal("cloud"), z.literal("terminal"), z.literal("game"), z.literal("chat"), z.literal("speaker"), z.literal("video"), ]); export const ToolOutputComponents = z .string() .toLowerCase() .pipe( z.union([ z.literal("textbox"), z.literal("markdown"), z.literal("image"), z.literal("gallery"), z.literal("number"), z.literal("audio"), z.literal("video"), z.literal("file"), z.literal("json"), ]) ); export type ToolOutputComponents = z.infer<typeof ToolOutputComponents>; export type ToolLogoColor = z.infer<typeof ToolColor>; export type ToolLogoIcon = z.infer<typeof ToolIcon>; export type ToolIOType = "str" | "int" | "float" | "bool" | "file"; export type ToolInputRequired = { paramType: "required"; name: string; description?: string; }; export type ToolInputOptional = { paramType: "optional"; name: string; description?: string; default: string | number | boolean; }; export type ToolInputFixed = { paramType: "fixed"; name: string; value: string | number | boolean; }; type ToolInputBase = ToolInputRequired | ToolInputOptional | ToolInputFixed; export type ToolInputFile = ToolInputBase & { type: "file"; mimeTypes: string; }; export type ToolInputSimple = ToolInputBase & { type: Exclude<ToolIOType, "file">; }; export type ToolInput = ToolInputFile | ToolInputSimple; export interface BaseTool { _id: ObjectId; name: string; // name that will be shown to the AI baseUrl?: string; // namespace for the tool endpoint: string | null; // endpoint to call in gradio, if null we expect to override this function in code outputComponent: string | null; // Gradio component type to use for the output outputComponentIdx: number | null; // index of the output component inputs: Array<ToolInput>; showOutput: boolean; // show output in chat or not call: BackendCall; // for displaying in the UI displayName: string; color: ToolLogoColor; icon: ToolLogoIcon; description: string; } export interface ConfigTool extends BaseTool { type: "config"; isOnByDefault?: true; isLocked?: true; isHidden?: true; } export interface CommunityTool extends BaseTool, Timestamps { type: "community"; createdById: User["_id"] | string; // user id or session createdByName?: User["username"]; // used to compute popular & trending useCount: number; last24HoursUseCount: number; review: ReviewStatus; searchTokens: string[]; } // no call function in db export type CommunityToolDB = Omit<CommunityTool, "call">; export type CommunityToolEditable = Omit< CommunityToolDB, | "_id" | "useCount" | "last24HoursUseCount" | "createdById" | "createdByName" | "review" | "searchTokens" | "type" | "createdAt" | "updatedAt" >; export type Tool = ConfigTool | CommunityTool; export type ToolFront = Pick<Tool, "type" | "name" | "displayName" | "description"> & { _id: string; isOnByDefault: boolean; isLocked: boolean; mimeTypes: string[]; timeToUseMS?: number; }; export enum ToolResultStatus { Success = "success", Error = "error", } export interface ToolResultSuccess { status: ToolResultStatus.Success; call: ToolCall; outputs: Record<string, unknown>[]; display?: boolean; } export interface ToolResultError { status: ToolResultStatus.Error; call: ToolCall; message: string; display?: boolean; } export type ToolResult = ToolResultSuccess | ToolResultError; export interface ToolCall { name: string; parameters: Record<string, string | number | boolean>; } export type BackendCall = ( params: Record<string, string | number | boolean>, context: BackendToolContext, uuid: string ) => AsyncGenerator<MessageUpdate, Omit<ToolResultSuccess, "status" | "call" | "type">, undefined>;
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/SharedConversation.ts
import type { Conversation } from "./Conversation"; export type SharedConversation = Pick< Conversation, | "model" | "embeddingModel" | "title" | "rootMessageId" | "messages" | "preprompt" | "assistantId" | "createdAt" | "updatedAt" > & { _id: string; hash: string; };
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Message.ts
import type { MessageUpdate } from "./MessageUpdate"; import type { Timestamps } from "./Timestamps"; import type { WebSearch } from "./WebSearch"; import type { v4 } from "uuid"; export type Message = Partial<Timestamps> & { from: "user" | "assistant" | "system"; id: ReturnType<typeof v4>; content: string; updates?: MessageUpdate[]; webSearchId?: WebSearch["_id"]; // legacy version webSearch?: WebSearch; reasoning?: string; score?: -1 | 0 | 1; /** * Either contains the base64 encoded image data * or the hash of the file stored on the server **/ files?: MessageFile[]; interrupted?: boolean; // needed for conversation trees ancestors?: Message["id"][]; // goes one level deep children?: Message["id"][]; // the index of the current child in the children array of the message if the message has more than one child currentChildIndex?: number; }; export type MessageFile = { type: "hash" | "base64"; name: string; value: string; mime: string; };
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Timestamps.ts
export interface Timestamps { createdAt: Date; updatedAt: Date; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Model.ts
import type { BackendModel } from "$lib/server/models"; export type Model = Pick< BackendModel, | "id" | "name" | "displayName" | "websiteUrl" | "datasetName" | "promptExamples" | "parameters" | "description" | "logoUrl" | "modelUrl" | "tokenizer" | "datasetUrl" | "preprompt" | "multimodal" | "multimodalAcceptedMimetypes" | "unlisted" | "tools" | "hasInferenceAPI" >;
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Semaphore.ts
import type { Timestamps } from "./Timestamps"; export interface Semaphore extends Timestamps { key: string; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/ConvSidebar.ts
export interface ConvSidebar { id: string; title: string; updatedAt: Date; model?: string; assistantId?: string; avatarUrl?: string; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Review.ts
export enum ReviewStatus { PRIVATE = "PRIVATE", PENDING = "PENDING", APPROVED = "APPROVED", DENIED = "DENIED", }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/MigrationResult.ts
import type { ObjectId } from "mongodb"; export interface MigrationResult { _id: ObjectId; name: string; status: "success" | "failure" | "ongoing"; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/MessageUpdate.ts
import type { WebSearchSource } from "$lib/types/WebSearch"; import type { ToolCall, ToolResult } from "$lib/types/Tool"; export type MessageUpdate = | MessageStatusUpdate | MessageTitleUpdate | MessageToolUpdate | MessageWebSearchUpdate | MessageStreamUpdate | MessageFileUpdate | MessageFinalAnswerUpdate | MessageReasoningUpdate; export enum MessageUpdateType { Status = "status", Title = "title", Tool = "tool", WebSearch = "webSearch", Stream = "stream", File = "file", FinalAnswer = "finalAnswer", Reasoning = "reasoning", } // Status export enum MessageUpdateStatus { Started = "started", Error = "error", Finished = "finished", KeepAlive = "keepAlive", } export interface MessageStatusUpdate { type: MessageUpdateType.Status; status: MessageUpdateStatus; message?: string; } // Web search export enum MessageWebSearchUpdateType { Update = "update", Error = "error", Sources = "sources", Finished = "finished", } export interface BaseMessageWebSearchUpdate<TSubType extends MessageWebSearchUpdateType> { type: MessageUpdateType.WebSearch; subtype: TSubType; } export interface MessageWebSearchErrorUpdate extends BaseMessageWebSearchUpdate<MessageWebSearchUpdateType.Error> { message: string; args?: string[]; } export interface MessageWebSearchGeneralUpdate extends BaseMessageWebSearchUpdate<MessageWebSearchUpdateType.Update> { message: string; args?: string[]; } export interface MessageWebSearchSourcesUpdate extends BaseMessageWebSearchUpdate<MessageWebSearchUpdateType.Sources> { message: string; sources: WebSearchSource[]; } export type MessageWebSearchFinishedUpdate = BaseMessageWebSearchUpdate<MessageWebSearchUpdateType.Finished>; export type MessageWebSearchUpdate = | MessageWebSearchErrorUpdate | MessageWebSearchGeneralUpdate | MessageWebSearchSourcesUpdate | MessageWebSearchFinishedUpdate; // Tool export enum MessageToolUpdateType { /** A request to call a tool alongside it's parameters */ Call = "call", /** The result of a tool call */ Result = "result", /** Error while running tool */ Error = "error", /** ETA update */ ETA = "eta", } interface MessageToolBaseUpdate<TSubType extends MessageToolUpdateType> { type: MessageUpdateType.Tool; subtype: TSubType; uuid: string; } export interface MessageToolCallUpdate extends MessageToolBaseUpdate<MessageToolUpdateType.Call> { call: ToolCall; } export interface MessageToolResultUpdate extends MessageToolBaseUpdate<MessageToolUpdateType.Result> { result: ToolResult; } export interface MessageToolErrorUpdate extends MessageToolBaseUpdate<MessageToolUpdateType.Error> { message: string; } export interface MessageToolETAUpdate extends MessageToolBaseUpdate<MessageToolUpdateType.ETA> { eta: number; } export type MessageToolUpdate = | MessageToolCallUpdate | MessageToolResultUpdate | MessageToolErrorUpdate | MessageToolETAUpdate; // Everything else export interface MessageTitleUpdate { type: MessageUpdateType.Title; title: string; } export interface MessageStreamUpdate { type: MessageUpdateType.Stream; token: string; } export enum MessageReasoningUpdateType { Stream = "stream", Status = "status", } export type MessageReasoningUpdate = MessageReasoningStreamUpdate | MessageReasoningStatusUpdate; export interface MessageReasoningStreamUpdate { type: MessageUpdateType.Reasoning; subtype: MessageReasoningUpdateType.Stream; token: string; } export interface MessageReasoningStatusUpdate { type: MessageUpdateType.Reasoning; subtype: MessageReasoningUpdateType.Status; status: string; } export interface MessageFileUpdate { type: MessageUpdateType.File; name: string; sha: string; mime: string; } export interface MessageFinalAnswerUpdate { type: MessageUpdateType.FinalAnswer; text: string; interrupted: boolean; webSources?: { uri: string; title: string }[]; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/ConversationStats.ts
import type { Timestamps } from "./Timestamps"; export interface ConversationStats extends Timestamps { date: { at: Date; span: "day" | "week" | "month"; field: "updatedAt" | "createdAt"; }; type: "conversation" | "message"; /** _id => number of conversations/messages in the month */ distinct: "sessionId" | "userId" | "userOrSessionId" | "_id"; count: number; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/TokenCache.ts
import type { Timestamps } from "./Timestamps"; export interface TokenCache extends Timestamps { tokenHash: string; // sha256 of the bearer token userId: string; // the matching hf user id }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/AbortedGeneration.ts
// Ideally shouldn't be needed, see https://github.com/huggingface/chat-ui/pull/88#issuecomment-1523173850 import type { Conversation } from "./Conversation"; import type { Timestamps } from "./Timestamps"; export interface AbortedGeneration extends Timestamps { conversationId: Conversation["_id"]; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/MessageEvent.ts
import type { Session } from "./Session"; import type { Timestamps } from "./Timestamps"; import type { User } from "./User"; export interface MessageEvent extends Pick<Timestamps, "createdAt"> { userId: User["_id"] | Session["sessionId"]; ip?: string; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/UrlDependency.ts
/* eslint-disable no-shadow */ export enum UrlDependency { ConversationList = "conversation:list", Conversation = "conversation", }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Assistant.ts
import type { ObjectId } from "mongodb"; import type { User } from "./User"; import type { Timestamps } from "./Timestamps"; import type { ReviewStatus } from "./Review"; export interface Assistant extends Timestamps { _id: ObjectId; createdById: User["_id"] | string; // user id or session createdByName?: User["username"]; avatar?: string; name: string; description?: string; modelId: string; exampleInputs: string[]; preprompt: string; userCount?: number; review: ReviewStatus; rag?: { allowAllDomains: boolean; allowedDomains: string[]; allowedLinks: string[]; }; generateSettings?: { temperature?: number; top_p?: number; repetition_penalty?: number; top_k?: number; }; dynamicPrompt?: boolean; searchTokens: string[]; last24HoursCount: number; tools?: string[]; } // eslint-disable-next-line no-shadow export enum SortKey { POPULAR = "popular", TRENDING = "trending", }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Settings.ts
import { defaultModel } from "$lib/server/models"; import type { Assistant } from "./Assistant"; import type { Timestamps } from "./Timestamps"; import type { User } from "./User"; export interface Settings extends Timestamps { userId?: User["_id"]; sessionId?: string; /** * Note: Only conversations with this settings explicitly set to true should be shared. * * This setting is explicitly set to true when users accept the ethics modal. * */ shareConversationsWithModelAuthors: boolean; ethicsModalAcceptedAt: Date | null; activeModel: string; hideEmojiOnSidebar?: boolean; // model name and system prompts customPrompts?: Record<string, string>; assistants?: Assistant["_id"][]; tools?: string[]; disableStream: boolean; directPaste: boolean; } export type SettingsEditable = Omit<Settings, "ethicsModalAcceptedAt" | "createdAt" | "updatedAt">; // TODO: move this to a constant file along with other constants export const DEFAULT_SETTINGS = { shareConversationsWithModelAuthors: true, activeModel: defaultModel.id, hideEmojiOnSidebar: false, customPrompts: {}, assistants: [], tools: [], disableStream: false, directPaste: false, } satisfies SettingsEditable;
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/User.ts
import type { ObjectId } from "mongodb"; import type { Timestamps } from "./Timestamps"; export interface User extends Timestamps { _id: ObjectId; username?: string; name: string; email?: string; avatarUrl: string | undefined; hfUserId: string; isAdmin?: boolean; isEarlyAccess?: boolean; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/AssistantStats.ts
import type { Timestamps } from "./Timestamps"; import type { Assistant } from "./Assistant"; export interface AssistantStats extends Timestamps { assistantId: Assistant["_id"]; date: { at: Date; span: "hour"; }; count: number; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Template.ts
import type { Message } from "./Message"; import type { Tool, ToolResult } from "./Tool"; export type ChatTemplateInput = { messages: Pick<Message, "from" | "content" | "files">[]; preprompt?: string; tools?: Tool[]; toolResults?: ToolResult[]; continueMessage?: boolean; };
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/types/Session.ts
import type { ObjectId } from "bson"; import type { Timestamps } from "./Timestamps"; import type { User } from "./User"; export interface Session extends Timestamps { _id: ObjectId; sessionId: string; userId: User["_id"]; userAgent?: string; ip?: string; expiresAt: Date; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/stores/titleUpdate.ts
import { writable } from "svelte/store"; export interface TitleUpdate { convId: string; title: string; } export default writable<TitleUpdate | null>(null);
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/stores/webSearchParameters.ts
import { writable } from "svelte/store"; export interface WebSearchParameters { useSearch: boolean; nItems: number; } export const webSearchParameters = writable<WebSearchParameters>({ useSearch: false, nItems: 5, });
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/stores/errors.ts
import { writable } from "svelte/store"; export const ERROR_MESSAGES = { default: "Oops, something went wrong.", authOnly: "You have to be logged in.", rateLimited: "You are sending too many messages. Try again later.", }; export const error = writable<string | null>(null);
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/stores/isAborted.ts
import { writable } from "svelte/store"; export const isAborted = writable<boolean>(false);
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/stores/settings.ts
import { browser } from "$app/environment"; import { invalidate } from "$app/navigation"; import { base } from "$app/paths"; import { UrlDependency } from "$lib/types/UrlDependency"; import type { ObjectId } from "mongodb"; import { getContext, setContext } from "svelte"; import { type Writable, writable, get } from "svelte/store"; type SettingsStore = { shareConversationsWithModelAuthors: boolean; hideEmojiOnSidebar: boolean; ethicsModalAccepted: boolean; ethicsModalAcceptedAt: Date | null; activeModel: string; customPrompts: Record<string, string>; recentlySaved: boolean; assistants: Array<ObjectId | string>; tools?: Array<string>; disableStream: boolean; directPaste: boolean; }; type SettingsStoreWritable = Writable<SettingsStore> & { instantSet: (settings: Partial<SettingsStore>) => Promise<void>; }; export function useSettingsStore() { return getContext<SettingsStoreWritable>("settings"); } export function createSettingsStore(initialValue: Omit<SettingsStore, "recentlySaved">) { const baseStore = writable({ ...initialValue, recentlySaved: false }); let timeoutId: NodeJS.Timeout; async function setSettings(settings: Partial<SettingsStore>) { baseStore.update((s) => ({ ...s, ...settings, })); clearTimeout(timeoutId); if (browser) { timeoutId = setTimeout(async () => { await fetch(`${base}/settings`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ ...get(baseStore), ...settings, }), }); invalidate(UrlDependency.ConversationList); // set savedRecently to true for 3s baseStore.update((s) => ({ ...s, recentlySaved: true, })); setTimeout(() => { baseStore.update((s) => ({ ...s, recentlySaved: false, })); }, 3000); invalidate(UrlDependency.ConversationList); }, 300); // debounce server calls by 300ms } } async function instantSet(settings: Partial<SettingsStore>) { baseStore.update((s) => ({ ...s, ...settings, })); if (browser) { await fetch(`${base}/settings`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ ...get(baseStore), ...settings, }), }); invalidate(UrlDependency.ConversationList); } } const newStore = { subscribe: baseStore.subscribe, set: setSettings, instantSet, update: (fn: (s: SettingsStore) => SettingsStore) => { setSettings(fn(get(baseStore))); }, } satisfies SettingsStoreWritable; setContext("settings", newStore); return newStore; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/stores/pendingMessage.ts
import { writable } from "svelte/store"; export const pendingMessage = writable< | { content: string; files: File[]; } | undefined >();
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/stores/convTree.ts
import type { Message } from "$lib/types/Message"; import { getContext, setContext } from "svelte"; import { writable, type Writable } from "svelte/store"; // used to store the id of the message that is the currently displayed leaf of the conversation tree // (that is the last message in the current branch of the conversation tree) interface ConvTreeStore { leaf: Message["id"] | null; editing: Message["id"] | null; } export function useConvTreeStore() { return getContext<Writable<ConvTreeStore>>("convTreeStore"); } export function createConvTreeStore() { const convTreeStore = writable<ConvTreeStore>({ leaf: null, editing: null, }); setContext("convTreeStore", convTreeStore); return convTreeStore; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/migrations/migrations.spec.ts
import { afterEach, assert, describe, expect, it } from "vitest"; import { migrations } from "./routines"; import { acquireLock, isDBLocked, refreshLock, releaseLock } from "./lock"; import { collections } from "$lib/server/database"; const LOCK_KEY = "migrations.test"; describe("migrations", () => { it("should not have duplicates guid", async () => { const guids = migrations.map((m) => m._id.toString()); const uniqueGuids = [...new Set(guids)]; expect(uniqueGuids.length).toBe(guids.length); }); it("should acquire only one lock on DB", async () => { const results = await Promise.all(new Array(1000).fill(0).map(() => acquireLock(LOCK_KEY))); const locks = results.filter((r) => r); const semaphores = await collections.semaphores.find({}).toArray(); expect(locks.length).toBe(1); expect(semaphores).toBeDefined(); expect(semaphores.length).toBe(1); expect(semaphores?.[0].key).toBe(LOCK_KEY); }); it("should read the lock correctly", async () => { const lockId = await acquireLock(LOCK_KEY); assert(lockId); expect(await isDBLocked(LOCK_KEY)).toBe(true); expect(!!(await acquireLock(LOCK_KEY))).toBe(false); await releaseLock(LOCK_KEY, lockId); expect(await isDBLocked(LOCK_KEY)).toBe(false); }); it("should refresh the lock", async () => { const lockId = await acquireLock(LOCK_KEY); assert(lockId); // get the updatedAt time const updatedAtInitially = (await collections.semaphores.findOne({}))?.updatedAt; await refreshLock(LOCK_KEY, lockId); const updatedAtAfterRefresh = (await collections.semaphores.findOne({}))?.updatedAt; expect(updatedAtInitially).toBeDefined(); expect(updatedAtAfterRefresh).toBeDefined(); expect(updatedAtInitially).not.toBe(updatedAtAfterRefresh); }); }); afterEach(async () => { await collections.semaphores.deleteMany({}); await collections.migrationResults.deleteMany({}); });
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/migrations/lock.ts
import { collections } from "$lib/server/database"; import { ObjectId } from "mongodb"; /** * Returns the lock id if the lock was acquired, false otherwise */ export async function acquireLock(key: string): Promise<ObjectId | false> { try { const id = new ObjectId(); const insert = await collections.semaphores.insertOne({ _id: id, key, createdAt: new Date(), updatedAt: new Date(), }); return insert.acknowledged ? id : false; // true if the document was inserted } catch (e) { // unique index violation, so there must already be a lock return false; } } export async function releaseLock(key: string, lockId: ObjectId) { await collections.semaphores.deleteOne({ _id: lockId, key, }); } export async function isDBLocked(key: string): Promise<boolean> { const res = await collections.semaphores.countDocuments({ key, }); return res > 0; } export async function refreshLock(key: string, lockId: ObjectId): Promise<boolean> { const result = await collections.semaphores.updateOne( { _id: lockId, key, }, { $set: { updatedAt: new Date(), }, } ); return result.matchedCount > 0; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/migrations/migrations.ts
import { Database } from "$lib/server/database"; import { migrations } from "./routines"; import { acquireLock, releaseLock, isDBLocked, refreshLock } from "./lock"; import { isHuggingChat } from "$lib/utils/isHuggingChat"; import { logger } from "$lib/server/logger"; const LOCK_KEY = "migrations"; export async function checkAndRunMigrations() { // make sure all GUIDs are unique if (new Set(migrations.map((m) => m._id.toString())).size !== migrations.length) { throw new Error("Duplicate migration GUIDs found."); } // check if all migrations have already been run const migrationResults = await Database.getInstance() .getCollections() .migrationResults.find() .toArray(); logger.info("[MIGRATIONS] Begin check..."); // connect to the database const connectedClient = await Database.getInstance().getClient().connect(); const lockId = await acquireLock(LOCK_KEY); if (!lockId) { // another instance already has the lock, so we exit early logger.info( "[MIGRATIONS] Another instance already has the lock. Waiting for DB to be unlocked." ); // Todo: is this necessary? Can we just return? // block until the lock is released while (await isDBLocked(LOCK_KEY)) { await new Promise((resolve) => setTimeout(resolve, 1000)); } return; } // once here, we have the lock // make sure to refresh it regularly while it's running const refreshInterval = setInterval(async () => { await refreshLock(LOCK_KEY, lockId); }, 1000 * 10); // iterate over all migrations for (const migration of migrations) { // check if the migration has already been applied const shouldRun = migration.runEveryTime || !migrationResults.find((m) => m._id.toString() === migration._id.toString()); // check if the migration has already been applied if (!shouldRun) { logger.info(`[MIGRATIONS] "${migration.name}" already applied. Skipping...`); } else { // check the modifiers to see if some cases match if ( (migration.runForHuggingChat === "only" && !isHuggingChat) || (migration.runForHuggingChat === "never" && isHuggingChat) ) { logger.info( `[MIGRATIONS] "${migration.name}" should not be applied for this run. Skipping...` ); continue; } // otherwise all is good and we can run the migration logger.info( `[MIGRATIONS] "${migration.name}" ${ migration.runEveryTime ? "should run every time" : "not applied yet" }. Applying...` ); await Database.getInstance() .getCollections() .migrationResults.updateOne( { _id: migration._id }, { $set: { name: migration.name, status: "ongoing", }, }, { upsert: true } ); const session = connectedClient.startSession(); let result = false; try { await session.withTransaction(async () => { result = await migration.up(Database.getInstance()); }); } catch (e) { logger.info(`[MIGRATIONS] "${migration.name}" failed!`); logger.error(e); } finally { await session.endSession(); } await Database.getInstance() .getCollections() .migrationResults.updateOne( { _id: migration._id }, { $set: { name: migration.name, status: result ? "success" : "failure", }, }, { upsert: true } ); } } logger.info("[MIGRATIONS] All migrations applied. Releasing lock"); clearInterval(refreshInterval); await releaseLock(LOCK_KEY, lockId); }
0
hf_public_repos/chat-ui/src/lib/migrations
hf_public_repos/chat-ui/src/lib/migrations/routines/09-delete-empty-conversations.ts
import type { Migration } from "."; import { collections } from "$lib/server/database"; import { Collection, FindCursor, ObjectId } from "mongodb"; import { logger } from "$lib/server/logger"; import type { Conversation } from "$lib/types/Conversation"; const BATCH_SIZE = 1000; const DELETE_THRESHOLD_MS = 60 * 60 * 1000; async function deleteBatch(conversations: Collection<Conversation>, ids: ObjectId[]) { if (ids.length === 0) return 0; const deleteResult = await conversations.deleteMany({ _id: { $in: ids } }); return deleteResult.deletedCount; } async function processCursor<T>( cursor: FindCursor<T>, processBatchFn: (batch: T[]) => Promise<void> ) { let batch = []; while (await cursor.hasNext()) { const doc = await cursor.next(); if (doc) { batch.push(doc); } if (batch.length >= BATCH_SIZE) { await processBatchFn(batch); batch = []; } } if (batch.length > 0) { await processBatchFn(batch); } } export async function deleteConversations( collections: typeof import("$lib/server/database").collections ) { let deleteCount = 0; const { conversations, sessions } = collections; // First criteria: Delete conversations with no user/assistant messages older than 1 hour const emptyConvCursor = conversations .find({ "messages.from": { $not: { $in: ["user", "assistant"] } }, createdAt: { $lt: new Date(Date.now() - DELETE_THRESHOLD_MS) }, }) .batchSize(BATCH_SIZE); await processCursor(emptyConvCursor, async (batch) => { const ids = batch.map((doc) => doc._id); deleteCount += await deleteBatch(conversations, ids); }); // Second criteria: Process conversations without users in batches and check sessions const noUserCursor = conversations.find({ userId: { $exists: false } }).batchSize(BATCH_SIZE); await processCursor(noUserCursor, async (batch) => { const sessionIds = [ ...new Set(batch.map((conv) => conv.sessionId).filter((id): id is string => !!id)), ]; const existingSessions = await sessions.find({ sessionId: { $in: sessionIds } }).toArray(); const validSessionIds = new Set(existingSessions.map((s) => s.sessionId)); const invalidConvs = batch.filter( (conv) => !conv.sessionId || !validSessionIds.has(conv.sessionId) ); const idsToDelete = invalidConvs.map((conv) => conv._id); deleteCount += await deleteBatch(conversations, idsToDelete); }); logger.info(`[MIGRATIONS] Deleted ${deleteCount} conversations in total.`); return deleteCount; } const deleteEmptyConversations: Migration = { _id: new ObjectId("000000000000000000000009"), name: "Delete conversations with no user or assistant messages or valid sessions", up: async () => { await deleteConversations(collections); return true; }, runEveryTime: true, runForHuggingChat: "only", }; export default deleteEmptyConversations;
0
hf_public_repos/chat-ui/src/lib/migrations
hf_public_repos/chat-ui/src/lib/migrations/routines/09-delete-empty-conversations.spec.ts
import type { Session } from "$lib/types/Session"; import type { User } from "$lib/types/User"; import type { Conversation } from "$lib/types/Conversation"; import { ObjectId } from "mongodb"; import { deleteConversations } from "./09-delete-empty-conversations"; import { afterAll, afterEach, beforeAll, describe, expect, test } from "vitest"; import { collections } from "$lib/server/database"; type Message = Conversation["messages"][number]; const userData = { _id: new ObjectId(), createdAt: new Date(), updatedAt: new Date(), username: "new-username", name: "name", avatarUrl: "https://example.com/avatar.png", hfUserId: "9999999999", } satisfies User; Object.freeze(userData); const sessionForUser = { _id: new ObjectId(), createdAt: new Date(), updatedAt: new Date(), userId: userData._id, sessionId: "session-id-9999999999", expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24), } satisfies Session; Object.freeze(sessionForUser); const userMessage = { from: "user", id: "user-message-id", content: "Hello, how are you?", } satisfies Message; const assistantMessage = { from: "assistant", id: "assistant-message-id", content: "I'm fine, thank you!", } satisfies Message; const systemMessage = { from: "system", id: "system-message-id", content: "This is a system message", } satisfies Message; const conversationBase = { _id: new ObjectId(), createdAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), updatedAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), model: "model-id", embeddingModel: "embedding-model-id", title: "title", messages: [], } satisfies Conversation; describe.sequential("Deleting discarded conversations", async () => { test("a conversation with no messages should get deleted", async () => { await collections.conversations.insertOne({ ...conversationBase, sessionId: sessionForUser.sessionId, }); const result = await deleteConversations(collections); expect(result).toBe(1); }); test("a conversation with no messages that is less than 1 hour old should not get deleted", async () => { await collections.conversations.insertOne({ ...conversationBase, sessionId: sessionForUser.sessionId, createdAt: new Date(Date.now() - 30 * 60 * 1000), }); const result = await deleteConversations(collections); expect(result).toBe(0); }); test("a conversation with only system messages should get deleted", async () => { await collections.conversations.insertOne({ ...conversationBase, sessionId: sessionForUser.sessionId, messages: [systemMessage], }); const result = await deleteConversations(collections); expect(result).toBe(1); }); test("a conversation with a user message should not get deleted", async () => { await collections.conversations.insertOne({ ...conversationBase, sessionId: sessionForUser.sessionId, messages: [userMessage], }); const result = await deleteConversations(collections); expect(result).toBe(0); }); test("a conversation with an assistant message should not get deleted", async () => { await collections.conversations.insertOne({ ...conversationBase, sessionId: sessionForUser.sessionId, messages: [assistantMessage], }); const result = await deleteConversations(collections); expect(result).toBe(0); }); test("a conversation with a mix of messages should not get deleted", async () => { await collections.conversations.insertOne({ ...conversationBase, sessionId: sessionForUser.sessionId, messages: [systemMessage, userMessage, assistantMessage, userMessage, assistantMessage], }); const result = await deleteConversations(collections); expect(result).toBe(0); }); test("a conversation with a userId and no sessionId should not get deleted", async () => { await collections.conversations.insertOne({ ...conversationBase, messages: [userMessage, assistantMessage], userId: userData._id, }); const result = await deleteConversations(collections); expect(result).toBe(0); }); test("a conversation with no userId or sessionId should get deleted", async () => { await collections.conversations.insertOne({ ...conversationBase, messages: [userMessage, assistantMessage], }); const result = await deleteConversations(collections); expect(result).toBe(1); }); test("a conversation with a sessionId that exists should not get deleted", async () => { await collections.conversations.insertOne({ ...conversationBase, messages: [userMessage, assistantMessage], sessionId: sessionForUser.sessionId, }); const result = await deleteConversations(collections); expect(result).toBe(0); }); test("a conversation with a userId and a sessionId that doesn't exist should NOT get deleted", async () => { await collections.conversations.insertOne({ ...conversationBase, userId: userData._id, messages: [userMessage, assistantMessage], sessionId: new ObjectId().toString(), }); const result = await deleteConversations(collections); expect(result).toBe(0); }); test("a conversation with only a sessionId that doesn't exist, should get deleted", async () => { await collections.conversations.insertOne({ ...conversationBase, messages: [userMessage, assistantMessage], sessionId: new ObjectId().toString(), }); const result = await deleteConversations(collections); expect(result).toBe(1); }); test("many conversations should get deleted", async () => { const conversations = Array.from({ length: 10010 }, () => ({ ...conversationBase, _id: new ObjectId(), })); await collections.conversations.insertMany(conversations); const result = await deleteConversations(collections); expect(result).toBe(10010); }); }); beforeAll(async () => { await collections.users.insertOne(userData); await collections.sessions.insertOne(sessionForUser); }); afterAll(async () => { await collections.users.deleteOne({ _id: userData._id, }); await collections.sessions.deleteOne({ _id: sessionForUser._id, }); await collections.conversations.deleteMany({}); }); afterEach(async () => { await collections.conversations.deleteMany({ _id: { $in: [conversationBase._id] }, }); });
0
hf_public_repos/chat-ui/src/lib/migrations
hf_public_repos/chat-ui/src/lib/migrations/routines/03-add-tools-in-settings.ts
import type { Migration } from "."; import { collections } from "$lib/server/database"; import { ObjectId } from "mongodb"; import { logger } from "$lib/server/logger"; const addToolsToSettings: Migration = { _id: new ObjectId("5c9c4c4c4c4c4c4c4c4c4c4c"), name: "Add empty 'tools' record in settings", up: async () => { const { settings } = collections; // Find all assistants whose modelId is not in modelIds, and update it to use defaultModelId await settings.updateMany( { tools: { $exists: false }, }, { $set: { tools: [] } } ); settings .createIndex({ tools: 1 }) .catch((e) => logger.error(e, "Error creating index during tools migration")); return true; }, runEveryTime: false, }; export default addToolsToSettings;
0
hf_public_repos/chat-ui/src/lib/migrations
hf_public_repos/chat-ui/src/lib/migrations/routines/08-update-featured-to-review.ts
import type { Migration } from "."; import { collections } from "$lib/server/database"; import { ObjectId } from "mongodb"; import { ReviewStatus } from "$lib/types/Review"; const updateFeaturedToReview: Migration = { _id: new ObjectId("000000000000000000000008"), name: "Update featured to review", up: async () => { const { assistants, tools } = collections; // Update assistants await assistants.updateMany({ featured: true }, { $set: { review: ReviewStatus.APPROVED } }); await assistants.updateMany( { featured: { $ne: true } }, { $set: { review: ReviewStatus.PRIVATE } } ); await assistants.updateMany({}, { $unset: { featured: "" } }); // Update tools await tools.updateMany({ featured: true }, { $set: { review: ReviewStatus.APPROVED } }); await tools.updateMany({ featured: { $ne: true } }, { $set: { review: ReviewStatus.PRIVATE } }); await tools.updateMany({}, { $unset: { featured: "" } }); return true; }, runEveryTime: false, }; export default updateFeaturedToReview;
0
hf_public_repos/chat-ui/src/lib/migrations
hf_public_repos/chat-ui/src/lib/migrations/routines/06-trim-message-updates.ts
import type { Migration } from "."; import { collections } from "$lib/server/database"; import { ObjectId, type WithId } from "mongodb"; import type { Conversation } from "$lib/types/Conversation"; import { MessageUpdateType, MessageWebSearchUpdateType, type MessageUpdate, } from "$lib/types/MessageUpdate"; import type { Message } from "$lib/types/Message"; import { logger } from "$lib/server/logger"; // ----------- /** Converts the old message update to the new schema */ function convertMessageUpdate(message: Message, update: MessageUpdate): MessageUpdate | null { try { // trim final websearch update, and sources update if (update.type === "webSearch") { if (update.subtype === MessageWebSearchUpdateType.Sources) { return { type: MessageUpdateType.WebSearch, subtype: MessageWebSearchUpdateType.Sources, message: update.message, sources: update.sources.map(({ link, title }) => ({ link, title })), }; } else if (update.subtype === MessageWebSearchUpdateType.Finished) { return { type: MessageUpdateType.WebSearch, subtype: MessageWebSearchUpdateType.Finished, }; } } return update; } catch (error) { logger.error(error, "Error converting message update during migration. Skipping it.."); return null; } } const trimMessageUpdates: Migration = { _id: new ObjectId("000000000000000000000006"), name: "Trim message updates to reduce stored size", up: async () => { const allConversations = collections.conversations.find({}); let conversation: WithId<Pick<Conversation, "messages">> | null = null; while ((conversation = await allConversations.tryNext())) { const messages = conversation.messages.map((message) => { // Convert all of the existing updates to the new schema const updates = message.updates ?.map((update) => convertMessageUpdate(message, update)) .filter((update): update is MessageUpdate => Boolean(update)); return { ...message, updates }; }); // Set the new messages array await collections.conversations.updateOne({ _id: conversation._id }, { $set: { messages } }); } return true; }, runEveryTime: false, }; export default trimMessageUpdates;
0
hf_public_repos/chat-ui/src/lib/migrations
hf_public_repos/chat-ui/src/lib/migrations/routines/04-update-message-updates.ts
import type { Migration } from "."; import { collections } from "$lib/server/database"; import { ObjectId, type WithId } from "mongodb"; import type { Conversation } from "$lib/types/Conversation"; import type { WebSearchSource } from "$lib/types/WebSearch"; import { MessageUpdateStatus, MessageUpdateType, MessageWebSearchUpdateType, type MessageUpdate, type MessageWebSearchFinishedUpdate, } from "$lib/types/MessageUpdate"; import type { Message } from "$lib/types/Message"; import { isMessageWebSearchSourcesUpdate } from "$lib/utils/messageUpdates"; // ----------- // Copy of the previous message update types export type FinalAnswer = { type: "finalAnswer"; text: string; }; export type TextStreamUpdate = { type: "stream"; token: string; }; type WebSearchUpdate = { type: "webSearch"; messageType: "update" | "error" | "sources"; message: string; args?: string[]; sources?: WebSearchSource[]; }; type StatusUpdate = { type: "status"; status: "started" | "pending" | "finished" | "error" | "title"; message?: string; }; type ErrorUpdate = { type: "error"; message: string; name: string; }; type FileUpdate = { type: "file"; sha: string; }; type OldMessageUpdate = | FinalAnswer | TextStreamUpdate | WebSearchUpdate | StatusUpdate | ErrorUpdate | FileUpdate; /** Converts the old message update to the new schema */ function convertMessageUpdate(message: Message, update: OldMessageUpdate): MessageUpdate | null { try { // Text and files if (update.type === "finalAnswer") { return { type: MessageUpdateType.FinalAnswer, text: update.text, interrupted: message.interrupted ?? false, }; } else if (update.type === "stream") { return { type: MessageUpdateType.Stream, token: update.token, }; } else if (update.type === "file") { return { type: MessageUpdateType.File, name: "Unknown", sha: update.sha, // assume jpeg but could be any image. should be harmless mime: "image/jpeg", }; } // Status else if (update.type === "status") { if (update.status === "title") { return { type: MessageUpdateType.Title, title: update.message ?? "New Chat", }; } if (update.status === "pending") return null; const status = update.status === "started" ? MessageUpdateStatus.Started : update.status === "finished" ? MessageUpdateStatus.Finished : MessageUpdateStatus.Error; return { type: MessageUpdateType.Status, status, message: update.message, }; } else if (update.type === "error") { // Treat it as an error status update return { type: MessageUpdateType.Status, status: MessageUpdateStatus.Error, message: update.message, }; } // Web Search else if (update.type === "webSearch") { if (update.messageType === "update") { return { type: MessageUpdateType.WebSearch, subtype: MessageWebSearchUpdateType.Update, message: update.message, args: update.args, }; } else if (update.messageType === "error") { return { type: MessageUpdateType.WebSearch, subtype: MessageWebSearchUpdateType.Error, message: update.message, args: update.args, }; } else if (update.messageType === "sources") { return { type: MessageUpdateType.WebSearch, subtype: MessageWebSearchUpdateType.Sources, message: update.message, sources: update.sources ?? [], }; } } console.warn("Unknown message update during migration:", update); return null; } catch (error) { console.error("Error converting message update during migration. Skipping it... Error:", error); return null; } } const updateMessageUpdates: Migration = { _id: new ObjectId("5f9f7f7f7f7f7f7f7f7f7f7f"), name: "Convert message updates to the new schema", up: async () => { const allConversations = collections.conversations.find({}); let conversation: WithId<Pick<Conversation, "messages">> | null = null; while ((conversation = await allConversations.tryNext())) { const messages = conversation.messages.map((message) => { // Convert all of the existing updates to the new schema const updates = message.updates ?.map((update) => convertMessageUpdate(message, update as OldMessageUpdate)) .filter((update): update is MessageUpdate => Boolean(update)); // Add the new web search finished update if the sources update exists and webSearch is defined const webSearchSourcesUpdateIndex = updates?.findIndex(isMessageWebSearchSourcesUpdate); if ( message.webSearch && updates && webSearchSourcesUpdateIndex && webSearchSourcesUpdateIndex !== -1 ) { const webSearchFinishedUpdate: MessageWebSearchFinishedUpdate = { type: MessageUpdateType.WebSearch, subtype: MessageWebSearchUpdateType.Finished, }; updates.splice(webSearchSourcesUpdateIndex + 1, 0, webSearchFinishedUpdate); } return { ...message, updates }; }); // Set the new messages array await collections.conversations.updateOne({ _id: conversation._id }, { $set: { messages } }); } return true; }, runEveryTime: false, }; export default updateMessageUpdates;
0
hf_public_repos/chat-ui/src/lib/migrations
hf_public_repos/chat-ui/src/lib/migrations/routines/05-update-message-files.ts
import { ObjectId, type WithId } from "mongodb"; import { collections } from "$lib/server/database"; import type { Migration } from "."; import type { Conversation } from "$lib/types/Conversation"; import type { MessageFile } from "$lib/types/Message"; const updateMessageFiles: Migration = { _id: new ObjectId("5f9f5f5f5f5f5f5f5f5f5f5f"), name: "Convert message files to the new schema", up: async () => { const allConversations = collections.conversations.find({}, { projection: { messages: 1 } }); let conversation: WithId<Pick<Conversation, "messages">> | null = null; while ((conversation = await allConversations.tryNext())) { const messages = conversation.messages.map((message) => { const files = (message.files as string[] | undefined)?.map<MessageFile>((file) => { // File is already in the new format if (typeof file !== "string") return file; // File was a hash pointing to a file in the bucket if (file.length === 64) { return { type: "hash", name: "unknown.jpg", value: file, mime: "image/jpeg", }; } // File was a base64 string else { return { type: "base64", name: "unknown.jpg", value: file, mime: "image/jpeg", }; } }); return { ...message, files, }; }); // Set the new messages array await collections.conversations.updateOne({ _id: conversation._id }, { $set: { messages } }); } return true; }, runEveryTime: false, }; export default updateMessageFiles;
0
hf_public_repos/chat-ui/src/lib/migrations
hf_public_repos/chat-ui/src/lib/migrations/routines/index.ts
import type { ObjectId } from "mongodb"; import updateSearchAssistant from "./01-update-search-assistants"; import updateAssistantsModels from "./02-update-assistants-models"; import type { Database } from "$lib/server/database"; import addToolsToSettings from "./03-add-tools-in-settings"; import updateMessageUpdates from "./04-update-message-updates"; import updateMessageFiles from "./05-update-message-files"; import trimMessageUpdates from "./06-trim-message-updates"; import resetTools from "./07-reset-tools-in-settings"; import updateFeaturedToReview from "./08-update-featured-to-review"; import deleteEmptyConversations from "./09-delete-empty-conversations"; export interface Migration { _id: ObjectId; name: string; up: (client: Database) => Promise<boolean>; down?: (client: Database) => Promise<boolean>; runForFreshInstall?: "only" | "never"; // leave unspecified to run for both runForHuggingChat?: "only" | "never"; // leave unspecified to run for both runEveryTime?: boolean; } export const migrations: Migration[] = [ updateSearchAssistant, updateAssistantsModels, addToolsToSettings, updateMessageUpdates, updateMessageFiles, trimMessageUpdates, resetTools, updateFeaturedToReview, deleteEmptyConversations, ];
0
hf_public_repos/chat-ui/src/lib/migrations
hf_public_repos/chat-ui/src/lib/migrations/routines/07-reset-tools-in-settings.ts
import type { Migration } from "."; import { collections } from "$lib/server/database"; import { ObjectId } from "mongodb"; const resetTools: Migration = { _id: new ObjectId("000000000000000000000007"), name: "Reset tools to empty", up: async () => { const { settings } = collections; await settings.updateMany({}, { $set: { tools: [] } }); return true; }, runEveryTime: false, }; export default resetTools;
0
hf_public_repos/chat-ui/src/lib/migrations
hf_public_repos/chat-ui/src/lib/migrations/routines/02-update-assistants-models.ts
import type { Migration } from "."; import { collections } from "$lib/server/database"; import { ObjectId } from "mongodb"; const updateAssistantsModels: Migration = { _id: new ObjectId("5f9f3f3f3f3f3f3f3f3f3f3f"), name: "Update deprecated models in assistants with the default model", up: async () => { const models = (await import("$lib/server/models")).models; const oldModels = (await import("$lib/server/models")).oldModels; const { assistants } = collections; const modelIds = models.map((el) => el.id); const defaultModelId = models[0].id; // Find all assistants whose modelId is not in modelIds, and update it const bulkOps = await assistants .find({ modelId: { $nin: modelIds } }) .map((assistant) => { // has an old model let newModelId = defaultModelId; const oldModel = oldModels.find((m) => m.id === assistant.modelId); if (oldModel && oldModel.transferTo && !!models.find((m) => m.id === oldModel.transferTo)) { newModelId = oldModel.transferTo; } return { updateOne: { filter: { _id: assistant._id }, update: { $set: { modelId: newModelId } }, }, }; }) .toArray(); if (bulkOps.length > 0) { await assistants.bulkWrite(bulkOps); } return true; }, runEveryTime: true, runForHuggingChat: "only", }; export default updateAssistantsModels;
0
hf_public_repos/chat-ui/src/lib/migrations
hf_public_repos/chat-ui/src/lib/migrations/routines/01-update-search-assistants.ts
import type { Migration } from "."; import { collections } from "$lib/server/database"; import { ObjectId, type AnyBulkWriteOperation } from "mongodb"; import type { Assistant } from "$lib/types/Assistant"; import { generateSearchTokens } from "$lib/utils/searchTokens"; const migration: Migration = { _id: new ObjectId("5f9f3e3e3e3e3e3e3e3e3e3e"), name: "Update search assistants", up: async () => { const { assistants } = collections; let ops: AnyBulkWriteOperation<Assistant>[] = []; for await (const assistant of assistants .find() .project<Pick<Assistant, "_id" | "name">>({ _id: 1, name: 1 })) { ops.push({ updateOne: { filter: { _id: assistant._id, }, update: { $set: { searchTokens: generateSearchTokens(assistant.name), }, }, }, }); if (ops.length >= 1000) { process.stdout.write("."); await assistants.bulkWrite(ops, { ordered: false }); ops = []; } } if (ops.length) { await assistants.bulkWrite(ops, { ordered: false }); } return true; }, down: async () => { const { assistants } = collections; await assistants.updateMany({}, { $unset: { searchTokens: "" } }); return true; }, }; export default migration;
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/constants/publicSepToken.ts
export const PUBLIC_SEP_TOKEN = "</s>";
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/utils/tools.ts
import type { Tool } from "$lib/types/Tool"; /** * Checks if a tool's name equals a value. Replaces all hyphens with underscores before comparison * since some models return underscores even when hyphens are used in the request. **/ export function toolHasName(name: string, tool: Pick<Tool, "name">): boolean { return tool.name.replaceAll("-", "_") === name.replaceAll("-", "_"); } export const colors = ["purple", "blue", "green", "yellow", "red"] as const; export const icons = [ "wikis", "tools", "camera", "code", "email", "cloud", "terminal", "game", "chat", "speaker", "video", ] as const;
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/utils/deepestChild.ts
export function deepestChild(el: HTMLElement): HTMLElement { if (el.lastElementChild && el.lastElementChild.nodeType !== Node.TEXT_NODE) { return deepestChild(el.lastElementChild as HTMLElement); } return el; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/utils/file2base64.ts
const file2base64 = (file: File): Promise<string> => { return new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { const dataUrl = reader.result as string; const base64 = dataUrl.split(",")[1]; resolve(base64); }; reader.onerror = (error) => reject(error); }); }; export default file2base64;
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/utils/sha256.ts
export async function sha256(input: string): Promise<string> { const utf8 = new TextEncoder().encode(input); const hashBuffer = await crypto.subtle.digest("SHA-256", utf8); const hashArray = Array.from(new Uint8Array(hashBuffer)); const hashHex = hashArray.map((bytes) => bytes.toString(16).padStart(2, "0")).join(""); return hashHex; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/utils/share.ts
import { browser } from "$app/environment"; import { isDesktop } from "./isDesktop"; export async function share(url: string, title: string, appendLeafId: boolean = false) { if (!browser) return; // Retrieve the leafId from localStorage const leafId = localStorage.getItem("leafId"); if (appendLeafId && leafId) { // Use URL and URLSearchParams to add the leafId parameter const shareUrl = new URL(url); shareUrl.searchParams.append("leafId", leafId); url = shareUrl.toString(); } if (navigator.share && !isDesktop(window)) { navigator.share({ url, title }); } else { // this is really ugly // but on chrome the clipboard write doesn't work if the window isn't focused // and after we use confirm() to ask the user if they want to share, the window is no longer focused // for a few ms until the confirm dialog closes. tried await tick(), tried window.focus(), didnt work // bug doesnt occur in firefox, if you can find a better fix for it please do await new Promise((resolve) => setTimeout(resolve, 250)); await navigator.clipboard.writeText(url); } }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/utils/getShareUrl.ts
import { base } from "$app/paths"; import { env as envPublic } from "$env/dynamic/public"; export function getShareUrl(url: URL, shareId: string): string { return `${ envPublic.PUBLIC_SHARE_PREFIX || `${envPublic.PUBLIC_ORIGIN || url.origin}${base}` }/r/${shareId}`; }
0
hf_public_repos/chat-ui/src/lib
hf_public_repos/chat-ui/src/lib/utils/randomUuid.ts
type UUID = ReturnType<typeof crypto.randomUUID>; export function randomUUID(): UUID { // Only on old safari / ios if (!("randomUUID" in crypto)) { return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => ( Number(c) ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (Number(c) / 4))) ).toString(16) ) as UUID; } return crypto.randomUUID(); }