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/lib
|
hf_public_repos/chat-ui/src/lib/utils/getGradioApi.ts
|
import { base } from "$app/paths";
import type { Client } from "@gradio/client";
export type ApiReturnType = Awaited<ReturnType<typeof Client.prototype.view_api>>;
export async function getGradioApi(space: string) {
const api: ApiReturnType = await fetch(`${base}/api/spaces-config?space=${space}`).then(
async (res) => {
if (!res.ok) {
throw new Error(await res.text());
}
return res.json();
}
);
return api;
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/isUrl.ts
|
export function isURL(url: string) {
try {
new URL(url);
return true;
} catch (e) {
return false;
}
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/sum.ts
|
export function sum(nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/getReturnFromGenerator.ts
|
export async function getReturnFromGenerator<T, R>(generator: AsyncGenerator<T, R>): Promise<R> {
let result: IteratorResult<T, R>;
do {
result = await generator.next();
} while (!result.done); // Keep calling `next()` until `done` is true
return result.value; // Return the final value
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/hashConv.ts
|
import type { Conversation } from "$lib/types/Conversation";
import { sha256 } from "./sha256";
export async function hashConv(conv: Conversation) {
// messages contains the conversation message but only the immutable part
const messages = conv.messages.map((message) => {
return (({ from, id, content, webSearchId }) => ({ from, id, content, webSearchId }))(message);
});
const hash = await sha256(JSON.stringify(messages));
return hash;
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/parseStringToList.ts
|
export function parseStringToList(links: unknown): string[] {
if (typeof links !== "string") {
throw new Error("Expected a string");
}
return links
.split(",")
.map((link) => link.trim())
.filter((link) => link.length > 0);
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/models.ts
|
import type { Model } from "$lib/types/Model";
export const findCurrentModel = (models: Model[], id?: string): Model =>
models.find((m) => m.id === id) ?? models[0];
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/template.ts
|
import type { Message } from "$lib/types/Message";
import Handlebars from "handlebars";
Handlebars.registerHelper("ifUser", function (this: Pick<Message, "from" | "content">, options) {
if (this.from == "user") return options.fn(this);
});
Handlebars.registerHelper(
"ifAssistant",
function (this: Pick<Message, "from" | "content">, options) {
if (this.from == "assistant") return options.fn(this);
}
);
export function compileTemplate<T>(input: string, model: { preprompt: string }) {
const template = Handlebars.compile<T>(input, {
knownHelpers: { ifUser: true, ifAssistant: true },
knownHelpersOnly: true,
noEscape: true,
strict: true,
preventIndent: true,
});
return function render(inputs: T, options?: RuntimeOptions) {
return template({ ...model, ...inputs }, options);
};
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/mergeAsyncGenerators.ts
|
type Gen<T, TReturn> = AsyncGenerator<T, TReturn, undefined>;
type GenPromiseMap<T, TReturn> = Map<
Gen<T, TReturn>,
Promise<{ gen: Gen<T, TReturn> } & IteratorResult<T, TReturn>>
>;
/** Merges multiple async generators into a single async generator that yields values from all of them in parallel. */
export async function* mergeAsyncGenerators<T, TReturn>(
generators: Gen<T, TReturn>[]
): Gen<T, TReturn[]> {
const promises: GenPromiseMap<T, TReturn> = new Map();
const results: Map<Gen<T, TReturn>, TReturn> = new Map();
for (const gen of generators) {
promises.set(
gen,
gen.next().then((result) => ({ gen, ...result }))
);
}
while (promises.size) {
const { gen, value, done } = await Promise.race(promises.values());
if (done) {
results.set(gen, value as TReturn);
promises.delete(gen);
} else {
promises.set(
gen,
gen.next().then((result) => ({ gen, ...result }))
);
yield value as T;
}
}
const orderedResults = generators.map((gen) => results.get(gen) as TReturn);
return orderedResults;
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/timeout.ts
|
export const timeout = <T>(prom: Promise<T>, time: number): Promise<T> => {
let timer: NodeJS.Timeout;
return Promise.race([
prom,
new Promise<T>((_, reject) => {
timer = setTimeout(() => reject(new Error(`Timeout after ${time / 1000} seconds`)), time);
}),
]).finally(() => clearTimeout(timer));
};
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/searchTokens.ts
|
const PUNCTUATION_REGEX = /\p{P}/gu;
function removeDiacritics(s: string, form: "NFD" | "NFKD" = "NFD"): string {
return s.normalize(form).replace(/[\u0300-\u036f]/g, "");
}
export function generateSearchTokens(value: string): string[] {
const fullTitleToken = removeDiacritics(value)
.replace(PUNCTUATION_REGEX, "")
.replaceAll(/\s+/g, "")
.toLowerCase();
return [
...new Set([
...removeDiacritics(value)
.split(/\s+/)
.map((word) => word.replace(PUNCTUATION_REGEX, "").toLowerCase())
.filter((word) => word.length),
...(fullTitleToken.length ? [fullTitleToken] : []),
]),
];
}
function escapeForRegExp(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
export function generateQueryTokens(query: string): RegExp[] {
return removeDiacritics(query)
.split(/\s+/)
.map((word) => word.replace(PUNCTUATION_REGEX, "").toLowerCase())
.filter((word) => word.length)
.map((token) => new RegExp(`^${escapeForRegExp(token)}`));
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/isDesktop.ts
|
// Approximate width from which we disable autofocus
const TABLET_VIEWPORT_WIDTH = 768;
export function isDesktop(window: Window) {
const { innerWidth } = window;
return innerWidth > TABLET_VIEWPORT_WIDTH;
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/getTokenizer.ts
|
import type { Model } from "$lib/types/Model";
import { AutoTokenizer, PreTrainedTokenizer } from "@huggingface/transformers";
export async function getTokenizer(_modelTokenizer: Exclude<Model["tokenizer"], undefined>) {
if (typeof _modelTokenizer === "string") {
// return auto tokenizer
return await AutoTokenizer.from_pretrained(_modelTokenizer);
} else {
// construct & return pretrained tokenizer
const { tokenizerUrl, tokenizerConfigUrl } = _modelTokenizer satisfies {
tokenizerUrl: string;
tokenizerConfigUrl: string;
};
const tokenizerJSON = await (await fetch(tokenizerUrl)).json();
const tokenizerConfig = await (await fetch(tokenizerConfigUrl)).json();
return new PreTrainedTokenizer(tokenizerJSON, tokenizerConfig);
}
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/messageUpdates.ts
|
import type { MessageFile } from "$lib/types/Message";
import {
type MessageUpdate,
type MessageStreamUpdate,
type MessageToolCallUpdate,
MessageToolUpdateType,
MessageUpdateType,
type MessageToolUpdate,
type MessageWebSearchUpdate,
type MessageWebSearchGeneralUpdate,
type MessageWebSearchSourcesUpdate,
type MessageWebSearchErrorUpdate,
MessageWebSearchUpdateType,
type MessageToolErrorUpdate,
type MessageToolResultUpdate,
} from "$lib/types/MessageUpdate";
import { env as envPublic } from "$env/dynamic/public";
export const isMessageWebSearchUpdate = (update: MessageUpdate): update is MessageWebSearchUpdate =>
update.type === MessageUpdateType.WebSearch;
export const isMessageWebSearchGeneralUpdate = (
update: MessageUpdate
): update is MessageWebSearchGeneralUpdate =>
isMessageWebSearchUpdate(update) && update.subtype === MessageWebSearchUpdateType.Update;
export const isMessageWebSearchSourcesUpdate = (
update: MessageUpdate
): update is MessageWebSearchSourcesUpdate =>
isMessageWebSearchUpdate(update) && update.subtype === MessageWebSearchUpdateType.Sources;
export const isMessageWebSearchErrorUpdate = (
update: MessageUpdate
): update is MessageWebSearchErrorUpdate =>
isMessageWebSearchUpdate(update) && update.subtype === MessageWebSearchUpdateType.Error;
export const isMessageToolUpdate = (update: MessageUpdate): update is MessageToolUpdate =>
update.type === MessageUpdateType.Tool;
export const isMessageToolCallUpdate = (update: MessageUpdate): update is MessageToolCallUpdate =>
isMessageToolUpdate(update) && update.subtype === MessageToolUpdateType.Call;
export const isMessageToolResultUpdate = (
update: MessageUpdate
): update is MessageToolResultUpdate =>
isMessageToolUpdate(update) && update.subtype === MessageToolUpdateType.Result;
export const isMessageToolErrorUpdate = (update: MessageUpdate): update is MessageToolErrorUpdate =>
isMessageToolUpdate(update) && update.subtype === MessageToolUpdateType.Error;
type MessageUpdateRequestOptions = {
base: string;
inputs?: string;
messageId?: string;
isRetry: boolean;
isContinue: boolean;
webSearch: boolean;
tools?: Array<string>;
files?: MessageFile[];
};
export async function fetchMessageUpdates(
conversationId: string,
opts: MessageUpdateRequestOptions,
abortSignal: AbortSignal
): Promise<AsyncGenerator<MessageUpdate>> {
const abortController = new AbortController();
abortSignal.addEventListener("abort", () => abortController.abort());
const form = new FormData();
const optsJSON = JSON.stringify({
inputs: opts.inputs,
id: opts.messageId,
is_retry: opts.isRetry,
is_continue: opts.isContinue,
web_search: opts.webSearch,
tools: opts.tools,
});
opts.files?.forEach((file) => {
const name = file.type + ";" + file.name;
form.append("files", new File([file.value], name, { type: file.mime }));
});
form.append("data", optsJSON);
const response = await fetch(`${opts.base}/conversation/${conversationId}`, {
method: "POST",
body: form,
signal: abortController.signal,
});
if (!response.ok) {
const errorMessage = await response
.json()
.then((obj) => obj.message)
.catch(() => `Request failed with status code ${response.status}: ${response.statusText}`);
throw Error(errorMessage);
}
if (!response.body) {
throw Error("Body not defined");
}
if (!(envPublic.PUBLIC_SMOOTH_UPDATES === "true")) {
return endpointStreamToIterator(response, abortController);
}
return smoothAsyncIterator(
streamMessageUpdatesToFullWords(endpointStreamToIterator(response, abortController))
);
}
async function* endpointStreamToIterator(
response: Response,
abortController: AbortController
): AsyncGenerator<MessageUpdate> {
const reader = response.body?.pipeThrough(new TextDecoderStream()).getReader();
if (!reader) throw Error("Response for endpoint had no body");
// Handle any cases where we must abort
reader.closed.then(() => abortController.abort());
// Handle logic for aborting
abortController.signal.addEventListener("abort", () => reader.cancel());
// ex) If the last response is => {"type": "stream", "token":
// It should be => {"type": "stream", "token": "Hello"} = prev_input_chunk + "Hello"}
let prevChunk = "";
while (!abortController.signal.aborted) {
const { done, value } = await reader.read();
if (done) {
abortController.abort();
break;
}
if (!value) continue;
const { messageUpdates, remainingText } = parseMessageUpdates(prevChunk + value);
prevChunk = remainingText;
for (const messageUpdate of messageUpdates) yield messageUpdate;
}
}
function parseMessageUpdates(value: string): {
messageUpdates: MessageUpdate[];
remainingText: string;
} {
const inputs = value.split("\n");
const messageUpdates: MessageUpdate[] = [];
for (const input of inputs) {
try {
messageUpdates.push(JSON.parse(input) as MessageUpdate);
} catch (error) {
// in case of parsing error, we return what we were able to parse
if (error instanceof SyntaxError) {
return {
messageUpdates,
remainingText: inputs.at(-1) ?? "",
};
}
}
}
return { messageUpdates, remainingText: "" };
}
/**
* Emits all the message updates immediately that aren't "stream" type
* Emits a concatenated "stream" type message update once it detects a full word
* Example: "what" " don" "'t" => "what" " don't"
* Only supports latin languages, ignores others
*/
async function* streamMessageUpdatesToFullWords(
iterator: AsyncGenerator<MessageUpdate>
): AsyncGenerator<MessageUpdate> {
let bufferedStreamUpdates: MessageStreamUpdate[] = [];
const endAlphanumeric = /[a-zA-Z0-9À-ž'`]+$/;
const beginnningAlphanumeric = /^[a-zA-Z0-9À-ž'`]+/;
for await (const messageUpdate of iterator) {
if (messageUpdate.type !== "stream") {
yield messageUpdate;
continue;
}
bufferedStreamUpdates.push(messageUpdate);
let lastIndexEmitted = 0;
for (let i = 1; i < bufferedStreamUpdates.length; i++) {
const prevEndsAlphanumeric = endAlphanumeric.test(bufferedStreamUpdates[i - 1].token);
const currBeginsAlphanumeric = beginnningAlphanumeric.test(bufferedStreamUpdates[i].token);
const shouldCombine = prevEndsAlphanumeric && currBeginsAlphanumeric;
const combinedTooMany = i - lastIndexEmitted >= 5;
if (shouldCombine && !combinedTooMany) continue;
// Combine tokens together and emit
yield {
type: MessageUpdateType.Stream,
token: bufferedStreamUpdates
.slice(lastIndexEmitted, i)
.map((_) => _.token)
.join(""),
};
lastIndexEmitted = i;
}
bufferedStreamUpdates = bufferedStreamUpdates.slice(lastIndexEmitted);
}
for (const messageUpdate of bufferedStreamUpdates) yield messageUpdate;
}
/**
* Attempts to smooth out the time between values emitted by an async iterator
* by waiting for the average time between values to emit the next value
*/
async function* smoothAsyncIterator<T>(iterator: AsyncGenerator<T>): AsyncGenerator<T> {
const eventTarget = new EventTarget();
let done = false;
const valuesBuffer: T[] = [];
const valueTimesMS: number[] = [];
const next = async () => {
const obj = await iterator.next();
if (obj.done) {
done = true;
} else {
valuesBuffer.push(obj.value);
valueTimesMS.push(performance.now());
next();
}
eventTarget.dispatchEvent(new Event("next"));
};
next();
let timeOfLastEmitMS = performance.now();
while (!done || valuesBuffer.length > 0) {
// Only consider the last X times between tokens
const sampledTimesMS = valueTimesMS.slice(-30);
// Get the total time spent in abnormal periods
const anomalyThresholdMS = 2000;
const anomalyDurationMS = sampledTimesMS
.map((time, i, times) => time - times[i - 1])
.slice(1)
.filter((time) => time > anomalyThresholdMS)
.reduce((a, b) => a + b, 0);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const totalTimeMSBetweenValues = sampledTimesMS.at(-1)! - sampledTimesMS[0];
const timeMSBetweenValues = totalTimeMSBetweenValues - anomalyDurationMS;
const averageTimeMSBetweenValues = Math.min(
200,
timeMSBetweenValues / (sampledTimesMS.length - 1)
);
const timeSinceLastEmitMS = performance.now() - timeOfLastEmitMS;
// Emit after waiting duration or cancel if "next" event is emitted
const gotNext = await Promise.race([
sleep(Math.max(5, averageTimeMSBetweenValues - timeSinceLastEmitMS)),
waitForEvent(eventTarget, "next"),
]);
// Go to next iteration so we can re-calculate when to emit
if (gotNext) continue;
// Nothing in buffer to emit
if (valuesBuffer.length === 0) continue;
// Emit
timeOfLastEmitMS = performance.now();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
yield valuesBuffer.shift()!;
}
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const waitForEvent = (eventTarget: EventTarget, eventName: string) =>
new Promise<boolean>((resolve) =>
eventTarget.addEventListener(eventName, () => resolve(true), { once: true })
);
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/getHref.ts
|
export function getHref(
url: URL | string,
modifications: {
newKeys?: Record<string, string | undefined | null>;
existingKeys?: { behaviour: "delete_except" | "delete"; keys: string[] };
}
) {
const newUrl = new URL(url);
const { newKeys, existingKeys } = modifications;
// exsiting keys logic
if (existingKeys) {
const { behaviour, keys } = existingKeys;
if (behaviour === "delete") {
for (const key of keys) {
newUrl.searchParams.delete(key);
}
} else {
// delete_except
const keysToPreserve = keys;
for (const key of [...newUrl.searchParams.keys()]) {
if (!keysToPreserve.includes(key)) {
newUrl.searchParams.delete(key);
}
}
}
}
// new keys logic
if (newKeys) {
for (const [key, val] of Object.entries(newKeys)) {
if (val) {
newUrl.searchParams.set(key, val);
} else {
newUrl.searchParams.delete(key);
}
}
}
return newUrl.toString();
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/chunk.ts
|
/**
* Chunk array into arrays of length at most `chunkSize`
*
* @param chunkSize must be greater than or equal to 1
*/
export function chunk<T extends unknown[] | string>(arr: T, chunkSize: number): T[] {
if (isNaN(chunkSize) || chunkSize < 1) {
throw new RangeError("Invalid chunk size: " + chunkSize);
}
if (!arr.length) {
return [];
}
/// Small optimization to not chunk buffers unless needed
if (arr.length <= chunkSize) {
return [arr];
}
return range(Math.ceil(arr.length / chunkSize)).map((i) => {
return arr.slice(i * chunkSize, (i + 1) * chunkSize);
}) as T[];
}
function range(n: number, b?: number): number[] {
return b
? Array(b - n)
.fill(0)
.map((_, i) => n + i)
: Array(n)
.fill(0)
.map((_, i) => i);
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/debounce.ts
|
/**
* A debounce function that works in both browser and Nodejs.
* For pure Nodejs work, prefer the `Debouncer` class.
*/
export function debounce<T extends unknown[]>(
callback: (...rest: T) => unknown,
limit: number
): (...rest: T) => void {
let timer: ReturnType<typeof setTimeout>;
return function (...rest) {
clearTimeout(timer);
timer = setTimeout(() => {
callback(...rest);
}, limit);
};
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/isHuggingChat.ts
|
import { env as envPublic } from "$env/dynamic/public";
export const isHuggingChat = envPublic.PUBLIC_APP_ASSETS === "huggingchat";
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/cookiesAreEnabled.ts
|
import { browser } from "$app/environment";
export function cookiesAreEnabled(): boolean {
if (!browser) return false;
if (navigator.cookieEnabled) return navigator.cookieEnabled;
// Create cookie
document.cookie = "cookietest=1";
const ret = document.cookie.indexOf("cookietest=") != -1;
// Delete cookie
document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
return ret;
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/formatUserCount.ts
|
export function formatUserCount(userCount: number): string {
const userCountRanges: { min: number; max: number; label: string }[] = [
{ min: 0, max: 1, label: "1" },
{ min: 2, max: 9, label: "1-10" },
{ min: 10, max: 49, label: "10+" },
{ min: 50, max: 99, label: "50+" },
{ min: 100, max: 299, label: "100+" },
{ min: 300, max: 499, label: "300+" },
{ min: 500, max: 999, label: "500+" },
{ min: 1_000, max: 2_999, label: "1k+" },
{ min: 3_000, max: 4_999, label: "3k+" },
{ min: 5_000, max: 9_999, label: "5k+" },
{ min: 10_000, max: 19_999, label: "10k+" },
{ min: 20_000, max: 29_999, label: "20k+" },
{ min: 30_000, max: 39_999, label: "30k+" },
{ min: 40_000, max: 49_999, label: "40k+" },
{ min: 50_000, max: 59_999, label: "50k+" },
{ min: 60_000, max: 69_999, label: "60k+" },
{ min: 70_000, max: 79_999, label: "70k+" },
{ min: 80_000, max: 89_999, label: "80k+" },
{ min: 90_000, max: 99_999, label: "90k+" },
{ min: 100_000, max: 109_999, label: "100k+" },
{ min: 110_000, max: 119_999, label: "110k+" },
{ min: 120_000, max: 129_999, label: "120k+" },
{ min: 130_000, max: 139_999, label: "130k+" },
{ min: 140_000, max: 149_999, label: "140k+" },
{ min: 150_000, max: 199_999, label: "150k+" },
{ min: 200_000, max: 299_999, label: "200k+" },
{ min: 300_000, max: 499_999, label: "300k+" },
{ min: 500_000, max: 749_999, label: "500k+" },
{ min: 750_000, max: 999_999, label: "750k+" },
{ min: 1_000_000, max: Infinity, label: "1M+" },
];
const range = userCountRanges.find(({ min, max }) => userCount >= min && userCount <= max);
return range?.label ?? "";
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/utils/stringifyError.ts
|
/** Takes an unknown error and attempts to convert it to a string */
export function stringifyError(error: unknown): string {
if (error instanceof Error) return error.message;
if (typeof error === "string") return error;
if (typeof error === "object" && error !== null) {
// try a few common properties
if ("message" in error && typeof error.message === "string") return error.message;
if ("body" in error && typeof error.body === "string") return error.body;
if ("name" in error && typeof error.name === "string") return error.name;
}
return "Unknown error";
}
|
0
|
hf_public_repos/chat-ui/src/lib/utils
|
hf_public_repos/chat-ui/src/lib/utils/tree/treeHelpers.spec.ts
|
import { collections } from "$lib/server/database";
import { ObjectId } from "mongodb";
import { describe, expect, it } from "vitest";
// function used to insert conversations used for testing
export const insertLegacyConversation = async () => {
const res = await collections.conversations.insertOne({
_id: new ObjectId(),
createdAt: new Date(),
updatedAt: new Date(),
title: "legacy conversation",
model: "",
embeddingModel: "",
messages: [
{
id: "1-1-1-1-1",
from: "user",
content: "Hello, world! I am a user",
},
{
id: "1-1-1-1-2",
from: "assistant",
content: "Hello, world! I am an assistant.",
},
{
id: "1-1-1-1-3",
from: "user",
content: "Hello, world! I am a user.",
},
{
id: "1-1-1-1-4",
from: "assistant",
content: "Hello, world! I am an assistant.",
},
],
});
return res.insertedId;
};
export const insertLinearBranchConversation = async () => {
const res = await collections.conversations.insertOne({
_id: new ObjectId(),
createdAt: new Date(),
updatedAt: new Date(),
title: "linear branch conversation",
model: "",
embeddingModel: "",
rootMessageId: "1-1-1-1-1",
messages: [
{
id: "1-1-1-1-1",
from: "user",
content: "Hello, world! I am a user",
ancestors: [],
children: ["1-1-1-1-2"],
},
{
id: "1-1-1-1-2",
from: "assistant",
content: "Hello, world! I am an assistant.",
ancestors: ["1-1-1-1-1"],
children: ["1-1-1-1-3"],
},
{
id: "1-1-1-1-3",
from: "user",
content: "Hello, world! I am a user.",
ancestors: ["1-1-1-1-1", "1-1-1-1-2"],
children: ["1-1-1-1-4"],
},
{
id: "1-1-1-1-4",
from: "assistant",
content: "Hello, world! I am an assistant.",
ancestors: ["1-1-1-1-1", "1-1-1-1-2", "1-1-1-1-3"],
children: [],
},
],
});
return res.insertedId;
};
export const insertSideBranchesConversation = async () => {
const res = await collections.conversations.insertOne({
_id: new ObjectId(),
createdAt: new Date(),
updatedAt: new Date(),
title: "side branches conversation",
model: "",
embeddingModel: "",
rootMessageId: "1-1-1-1-1",
messages: [
{
id: "1-1-1-1-1",
from: "user",
content: "Hello, world, root message!",
ancestors: [],
children: ["1-1-1-1-2", "1-1-1-1-5"],
},
{
id: "1-1-1-1-2",
from: "assistant",
content: "Hello, response to root message!",
ancestors: ["1-1-1-1-1"],
children: ["1-1-1-1-3"],
},
{
id: "1-1-1-1-3",
from: "user",
content: "Hello, follow up question!",
ancestors: ["1-1-1-1-1", "1-1-1-1-2"],
children: ["1-1-1-1-4"],
},
{
id: "1-1-1-1-4",
from: "assistant",
content: "Hello, response from follow up question!",
ancestors: ["1-1-1-1-1", "1-1-1-1-2", "1-1-1-1-3"],
children: [],
},
{
id: "1-1-1-1-5",
from: "assistant",
content: "Hello, alternative assistant answer!",
ancestors: ["1-1-1-1-1"],
children: ["1-1-1-1-6", "1-1-1-1-7"],
},
{
id: "1-1-1-1-6",
from: "user",
content: "Hello, follow up question to alternative answer!",
ancestors: ["1-1-1-1-1", "1-1-1-1-5"],
children: [],
},
{
id: "1-1-1-1-7",
from: "user",
content: "Hello, alternative follow up question to alternative answer!",
ancestors: ["1-1-1-1-1", "1-1-1-1-5"],
children: [],
},
],
});
return res.insertedId;
};
describe("inserting conversations", () => {
it("should insert a legacy conversation", async () => {
const id = await insertLegacyConversation();
expect(id).toBeDefined();
});
it("should insert a linear branch conversation", async () => {
const id = await insertLinearBranchConversation();
expect(id).toBeDefined();
});
it("should insert a side branches conversation", async () => {
const id = await insertSideBranchesConversation();
expect(id).toBeDefined();
});
});
|
0
|
hf_public_repos/chat-ui/src/lib/utils
|
hf_public_repos/chat-ui/src/lib/utils/tree/addSibling.spec.ts
|
import { collections } from "$lib/server/database";
import { ObjectId } from "mongodb";
import { describe, expect, it } from "vitest";
import { insertLegacyConversation, insertSideBranchesConversation } from "./treeHelpers.spec";
import type { Message } from "$lib/types/Message";
import { addSibling } from "./addSibling";
const newMessage: Omit<Message, "id"> = {
content: "new message",
from: "user",
};
Object.freeze(newMessage);
describe("addSibling", async () => {
it("should fail on empty conversations", () => {
const conv = {
_id: new ObjectId(),
rootMessageId: undefined,
messages: [],
};
expect(() => addSibling(conv, newMessage, "not-a-real-id-test")).toThrow(
"Cannot add a sibling to an empty conversation"
);
});
it("should fail on legacy conversations", async () => {
const convId = await insertLegacyConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
expect(() => addSibling(conv, newMessage, conv.messages[0].id)).toThrow(
"Cannot add a sibling to a legacy conversation"
);
});
it("should fail if the sibling message doesn't exist", async () => {
const convId = await insertSideBranchesConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
expect(() => addSibling(conv, newMessage, "not-a-real-id-test")).toThrow(
"The sibling message doesn't exist"
);
});
// TODO: This behaviour should be fixed, we do not need to fail on the root message.
it("should fail if the sibling message is the root message", async () => {
const convId = await insertSideBranchesConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
if (!conv.rootMessageId) throw new Error("Root message not found");
expect(() => addSibling(conv, newMessage, conv.rootMessageId as Message["id"])).toThrow(
"The sibling message is the root message, therefore we can't add a sibling"
);
});
it("should add a sibling to a message", async () => {
const convId = await insertSideBranchesConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
// add sibling and check children count for parnets
const nChildren = conv.messages[1].children?.length;
const siblingId = addSibling(conv, newMessage, conv.messages[2].id);
const nChildrenNew = conv.messages[1].children?.length;
if (!nChildren) throw new Error("No children found");
expect(nChildrenNew).toBe(nChildren + 1);
// make sure siblings have the same ancestors
const sibling = conv.messages.find((m) => m.id === siblingId);
expect(sibling?.ancestors).toEqual(conv.messages[2].ancestors);
});
});
|
0
|
hf_public_repos/chat-ui/src/lib/utils
|
hf_public_repos/chat-ui/src/lib/utils/tree/convertLegacyConversation.ts
|
import type { Conversation } from "$lib/types/Conversation";
import type { Message } from "$lib/types/Message";
import { v4 } from "uuid";
export function convertLegacyConversation(
conv: Pick<Conversation, "messages" | "rootMessageId" | "preprompt">
): Pick<Conversation, "messages" | "rootMessageId" | "preprompt"> {
if (conv.rootMessageId) return conv; // not a legacy conversation
if (conv.messages.length === 0) return conv; // empty conversation
const messages = [
{
from: "system",
content: conv.preprompt ?? "",
createdAt: new Date(),
updatedAt: new Date(),
id: v4(),
} satisfies Message,
...conv.messages,
];
const rootMessageId = messages[0].id;
const newMessages = messages.map((message, index) => {
return {
...message,
ancestors: messages.slice(0, index).map((m) => m.id),
children: index < messages.length - 1 ? [messages[index + 1].id] : [],
};
});
return {
...conv,
rootMessageId,
messages: newMessages,
};
}
|
0
|
hf_public_repos/chat-ui/src/lib/utils
|
hf_public_repos/chat-ui/src/lib/utils/tree/buildSubtree.ts
|
import type { Conversation } from "$lib/types/Conversation";
import type { Message } from "$lib/types/Message";
export function buildSubtree(
conv: Pick<Conversation, "messages" | "rootMessageId">,
id: Message["id"]
): Message[] {
if (!conv.rootMessageId) {
if (conv.messages.length === 0) return [];
// legacy conversation slice up to id
const index = conv.messages.findIndex((m) => m.id === id);
if (index === -1) throw new Error("Message not found");
return conv.messages.slice(0, index + 1);
} else {
// find the message with the right id then create the ancestor tree
const message = conv.messages.find((m) => m.id === id);
if (!message) throw new Error("Message not found");
return [
...(message.ancestors?.map((ancestorId) => {
const ancestor = conv.messages.find((m) => m.id === ancestorId);
if (!ancestor) throw new Error("Ancestor not found");
return ancestor;
}) ?? []),
message,
];
}
}
|
0
|
hf_public_repos/chat-ui/src/lib/utils
|
hf_public_repos/chat-ui/src/lib/utils/tree/addChildren.ts
|
import type { Conversation } from "$lib/types/Conversation";
import type { Message } from "$lib/types/Message";
import { v4 } from "uuid";
export function addChildren(
conv: Pick<Conversation, "messages" | "rootMessageId">,
message: Omit<Message, "id">,
parentId?: Message["id"]
): Message["id"] {
// if this is the first message we just push it
if (conv.messages.length === 0) {
const messageId = v4();
conv.rootMessageId = messageId;
conv.messages.push({
...message,
ancestors: [],
id: messageId,
});
return messageId;
}
if (!parentId) {
throw new Error("You need to specify a parentId if this is not the first message");
}
const messageId = v4();
if (!conv.rootMessageId) {
// if there is no parentId we just push the message
if (!!parentId && parentId !== conv.messages[conv.messages.length - 1].id) {
throw new Error("This is a legacy conversation, you can only append to the last message");
}
conv.messages.push({ ...message, id: messageId });
return messageId;
}
const ancestors = [...(conv.messages.find((m) => m.id === parentId)?.ancestors ?? []), parentId];
conv.messages.push({
...message,
ancestors,
id: messageId,
children: [],
});
const parent = conv.messages.find((m) => m.id === parentId);
if (parent) {
if (parent.children) {
parent.children.push(messageId);
} else parent.children = [messageId];
}
return messageId;
}
|
0
|
hf_public_repos/chat-ui/src/lib/utils
|
hf_public_repos/chat-ui/src/lib/utils/tree/isMessageId.ts
|
import type { Message } from "$lib/types/Message";
export function isMessageId(id: string): id is Message["id"] {
return id.split("-").length === 5;
}
|
0
|
hf_public_repos/chat-ui/src/lib/utils
|
hf_public_repos/chat-ui/src/lib/utils/tree/convertLegacyConversation.spec.ts
|
import { collections } from "$lib/server/database";
import { ObjectId } from "mongodb";
import { describe, expect, it } from "vitest";
import { convertLegacyConversation } from "./convertLegacyConversation";
import { insertLegacyConversation } from "./treeHelpers.spec";
describe("convertLegacyConversation", () => {
it("should convert a legacy conversation", async () => {
const convId = await insertLegacyConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
const newConv = convertLegacyConversation(conv);
expect(newConv.rootMessageId).toBe(newConv.messages[0].id);
expect(newConv.messages[0].ancestors).toEqual([]);
expect(newConv.messages[1].ancestors).toEqual([newConv.messages[0].id]);
expect(newConv.messages[0].children).toEqual([newConv.messages[1].id]);
});
it("should work on empty conversations", async () => {
const conv = {
_id: new ObjectId(),
rootMessageId: undefined,
messages: [],
};
const newConv = convertLegacyConversation(conv);
expect(newConv.rootMessageId).toBe(undefined);
expect(newConv.messages).toEqual([]);
});
});
|
0
|
hf_public_repos/chat-ui/src/lib/utils
|
hf_public_repos/chat-ui/src/lib/utils/tree/isMessageId.spec.ts
|
import { describe, expect, it } from "vitest";
import { isMessageId } from "./isMessageId";
import { v4 } from "uuid";
describe("isMessageId", () => {
it("should return true for a valid message id", () => {
expect(isMessageId(v4())).toBe(true);
});
it("should return false for an invalid message id", () => {
expect(isMessageId("1-2-3-4")).toBe(false);
});
it("should return false for an empty string", () => {
expect(isMessageId("")).toBe(false);
});
});
|
0
|
hf_public_repos/chat-ui/src/lib/utils
|
hf_public_repos/chat-ui/src/lib/utils/tree/addSibling.ts
|
import type { Conversation } from "$lib/types/Conversation";
import type { Message } from "$lib/types/Message";
import { v4 } from "uuid";
export function addSibling(
conv: Pick<Conversation, "messages" | "rootMessageId">,
message: Omit<Message, "id">,
siblingId: Message["id"]
): Message["id"] {
if (conv.messages.length === 0) {
throw new Error("Cannot add a sibling to an empty conversation");
}
if (!conv.rootMessageId) {
throw new Error("Cannot add a sibling to a legacy conversation");
}
const sibling = conv.messages.find((m) => m.id === siblingId);
if (!sibling) {
throw new Error("The sibling message doesn't exist");
}
if (!sibling.ancestors || sibling.ancestors?.length === 0) {
throw new Error("The sibling message is the root message, therefore we can't add a sibling");
}
const messageId = v4();
conv.messages.push({
...message,
id: messageId,
ancestors: sibling.ancestors,
children: [],
});
const nearestAncestorId = sibling.ancestors[sibling.ancestors.length - 1];
const nearestAncestor = conv.messages.find((m) => m.id === nearestAncestorId);
if (nearestAncestor) {
if (nearestAncestor.children) {
nearestAncestor.children.push(messageId);
} else nearestAncestor.children = [messageId];
}
return messageId;
}
|
0
|
hf_public_repos/chat-ui/src/lib/utils
|
hf_public_repos/chat-ui/src/lib/utils/tree/buildSubtree.spec.ts
|
import { collections } from "$lib/server/database";
import { ObjectId } from "mongodb";
import { describe, expect, it } from "vitest";
import {
insertLegacyConversation,
insertLinearBranchConversation,
insertSideBranchesConversation,
} from "./treeHelpers.spec";
import { buildSubtree } from "./buildSubtree";
describe("buildSubtree", () => {
it("a subtree in a legacy conversation should be just a slice", async () => {
const convId = await insertLegacyConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
// check middle
const id = conv.messages[2].id;
const subtree = buildSubtree(conv, id);
expect(subtree).toEqual(conv.messages.slice(0, 3));
// check zero
const id2 = conv.messages[0].id;
const subtree2 = buildSubtree(conv, id2);
expect(subtree2).toEqual(conv.messages.slice(0, 1));
//check full length
const id3 = conv.messages[conv.messages.length - 1].id;
const subtree3 = buildSubtree(conv, id3);
expect(subtree3).toEqual(conv.messages);
});
it("a subtree in a linear branch conversation should be the ancestors and the message", async () => {
const convId = await insertLinearBranchConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
// check middle
const id = conv.messages[1].id;
const subtree = buildSubtree(conv, id);
expect(subtree).toEqual([conv.messages[0], conv.messages[1]]);
// check zero
const id2 = conv.messages[0].id;
const subtree2 = buildSubtree(conv, id2);
expect(subtree2).toEqual([conv.messages[0]]);
//check full length
const id3 = conv.messages[conv.messages.length - 1].id;
const subtree3 = buildSubtree(conv, id3);
expect(subtree3).toEqual(conv.messages);
});
it("should throw an error if the message is not found", async () => {
const convId = await insertLinearBranchConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
const id = "not-a-real-id-test";
expect(() => buildSubtree(conv, id)).toThrow("Message not found");
});
it("should throw an error if the ancestor is not found", async () => {
const convId = await insertLinearBranchConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
const id = "1-1-1-1-2";
conv.messages[1].ancestors = ["not-a-real-id-test"];
expect(() => buildSubtree(conv, id)).toThrow("Ancestor not found");
});
it("should work on empty conversations", () => {
const conv = {
_id: new ObjectId(),
rootMessageId: undefined,
messages: [],
};
const subtree = buildSubtree(conv, "not-a-real-id-test");
expect(subtree).toEqual([]);
});
it("should work for conversation with subtrees", async () => {
const convId = await insertSideBranchesConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
const subtree = buildSubtree(conv, "1-1-1-1-2");
expect(subtree).toEqual([conv.messages[0], conv.messages[1]]);
const subtree2 = buildSubtree(conv, "1-1-1-1-4");
expect(subtree2).toEqual([
conv.messages[0],
conv.messages[1],
conv.messages[2],
conv.messages[3],
]);
const subtree3 = buildSubtree(conv, "1-1-1-1-6");
expect(subtree3).toEqual([conv.messages[0], conv.messages[4], conv.messages[5]]);
const subtree4 = buildSubtree(conv, "1-1-1-1-7");
expect(subtree4).toEqual([conv.messages[0], conv.messages[4], conv.messages[6]]);
});
});
|
0
|
hf_public_repos/chat-ui/src/lib/utils
|
hf_public_repos/chat-ui/src/lib/utils/tree/addChildren.spec.ts
|
import { collections } from "$lib/server/database";
import { ObjectId } from "mongodb";
import { describe, expect, it } from "vitest";
import { insertLegacyConversation, insertSideBranchesConversation } from "./treeHelpers.spec";
import { addChildren } from "./addChildren";
import type { Message } from "$lib/types/Message";
const newMessage: Omit<Message, "id"> = {
content: "new message",
from: "user",
};
Object.freeze(newMessage);
describe("addChildren", async () => {
it("should let you append on legacy conversations", async () => {
const convId = await insertLegacyConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
const convLength = conv.messages.length;
addChildren(conv, newMessage, conv.messages[conv.messages.length - 1].id);
expect(conv.messages.length).toEqual(convLength + 1);
});
it("should not let you create branches on legacy conversations", async () => {
const convId = await insertLegacyConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
expect(() => addChildren(conv, newMessage, conv.messages[0].id)).toThrow();
});
it("should not let you create a message that already exists", async () => {
const convId = await insertLegacyConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
const messageThatAlreadyExists: Message = {
id: conv.messages[0].id,
content: "new message",
from: "user",
};
expect(() => addChildren(conv, messageThatAlreadyExists, conv.messages[0].id)).toThrow();
});
it("should let you create branches on conversations with subtrees", async () => {
const convId = await insertSideBranchesConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
const nChildren = conv.messages[0].children?.length;
if (!nChildren) throw new Error("No children found");
addChildren(conv, newMessage, conv.messages[0].id);
expect(conv.messages[0].children?.length).toEqual(nChildren + 1);
});
it("should let you create a new leaf", async () => {
const convId = await insertSideBranchesConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
const parentId = conv.messages[conv.messages.length - 1].id;
const nChildren = conv.messages[conv.messages.length - 1].children?.length;
if (nChildren === undefined) throw new Error("No children found");
expect(nChildren).toEqual(0);
addChildren(conv, newMessage, parentId);
expect(conv.messages[conv.messages.length - 2].children?.length).toEqual(nChildren + 1);
});
it("should let you append to an empty conversation without specifying a parentId", async () => {
const conv = {
_id: new ObjectId(),
rootMessageId: undefined,
messages: [] as Message[],
};
addChildren(conv, newMessage);
expect(conv.messages.length).toEqual(1);
expect(conv.rootMessageId).toEqual(conv.messages[0].id);
});
it("should throw if you don't specify a parentId in a conversation with messages", async () => {
const convId = await insertLegacyConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
expect(() => addChildren(conv, newMessage)).toThrow();
});
it("should return the id of the new message", async () => {
const convId = await insertLegacyConversation();
const conv = await collections.conversations.findOne({ _id: new ObjectId(convId) });
if (!conv) throw new Error("Conversation not found");
expect(addChildren(conv, newMessage, conv.messages[conv.messages.length - 1].id)).toEqual(
conv.messages[conv.messages.length - 1].id
);
});
});
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/jobs/refresh-assistants-counts.ts
|
import { Database } from "$lib/server/database";
import { acquireLock, refreshLock } from "$lib/migrations/lock";
import type { ObjectId } from "mongodb";
import { subDays } from "date-fns";
import { logger } from "$lib/server/logger";
const LOCK_KEY = "assistants.count";
let hasLock = false;
let lockId: ObjectId | null = null;
async function refreshAssistantsCountsHelper() {
if (!hasLock) {
return;
}
try {
await Database.getInstance()
.getClient()
.withSession((session) =>
session.withTransaction(async () => {
await Database.getInstance()
.getCollections()
.assistants.aggregate([
{ $project: { _id: 1 } },
{ $set: { last24HoursCount: 0 } },
{
$unionWith: {
coll: "assistants.stats",
pipeline: [
{
$match: { "date.at": { $gte: subDays(new Date(), 1) }, "date.span": "hour" },
},
{
$group: {
_id: "$assistantId",
last24HoursCount: { $sum: "$count" },
},
},
],
},
},
{
$group: {
_id: "$_id",
last24HoursCount: { $sum: "$last24HoursCount" },
},
},
{
$merge: {
into: "assistants",
on: "_id",
whenMatched: "merge",
whenNotMatched: "discard",
},
},
])
.next();
})
);
} catch (e) {
logger.error(e, "Refresh assistants counter failed!");
}
}
async function maintainLock() {
if (hasLock && lockId) {
hasLock = await refreshLock(LOCK_KEY, lockId);
if (!hasLock) {
lockId = null;
}
} else if (!hasLock) {
lockId = (await acquireLock(LOCK_KEY)) || null;
hasLock = !!lockId;
}
setTimeout(maintainLock, 10_000);
}
export function refreshAssistantsCounts() {
const ONE_HOUR_MS = 3_600_000;
maintainLock().then(() => {
refreshAssistantsCountsHelper();
setInterval(refreshAssistantsCountsHelper, ONE_HOUR_MS);
});
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/jobs/refresh-conversation-stats.ts
|
import type { ConversationStats } from "$lib/types/ConversationStats";
import { CONVERSATION_STATS_COLLECTION, collections } from "$lib/server/database";
import { logger } from "$lib/server/logger";
import type { ObjectId } from "mongodb";
import { acquireLock, refreshLock } from "$lib/migrations/lock";
export async function computeAllStats() {
for (const span of ["day", "week", "month"] as const) {
computeStats({ dateField: "updatedAt", type: "conversation", span }).catch((e) =>
logger.error(e)
);
computeStats({ dateField: "createdAt", type: "conversation", span }).catch((e) =>
logger.error(e)
);
computeStats({ dateField: "createdAt", type: "message", span }).catch((e) => logger.error(e));
}
}
async function computeStats(params: {
dateField: ConversationStats["date"]["field"];
span: ConversationStats["date"]["span"];
type: ConversationStats["type"];
}) {
const lastComputed = await collections.conversationStats.findOne(
{ "date.field": params.dateField, "date.span": params.span, type: params.type },
{ sort: { "date.at": -1 } }
);
// If the last computed week is at the beginning of the last computed month, we need to include some days from the previous month
// In those cases we need to compute the stats from before the last month as everything is one aggregation
const minDate = lastComputed ? lastComputed.date.at : new Date(0);
logger.info(
{ minDate, dateField: params.dateField, span: params.span, type: params.type },
"Computing conversation stats"
);
const dateField = params.type === "message" ? "messages." + params.dateField : params.dateField;
const pipeline = [
{
$match: {
[dateField]: { $gte: minDate },
},
},
{
$project: {
[dateField]: 1,
sessionId: 1,
userId: 1,
},
},
...(params.type === "message"
? [
{
$unwind: "$messages",
},
{
$match: {
[dateField]: { $gte: minDate },
},
},
]
: []),
{
$sort: {
[dateField]: 1,
},
},
{
$facet: {
userId: [
{
$match: {
userId: { $exists: true },
},
},
{
$group: {
_id: {
at: { $dateTrunc: { date: `$${dateField}`, unit: params.span } },
userId: "$userId",
},
},
},
{
$group: {
_id: "$_id.at",
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
date: {
at: "$_id",
field: params.dateField,
span: params.span,
},
distinct: "userId",
count: 1,
},
},
],
sessionId: [
{
$match: {
sessionId: { $exists: true },
},
},
{
$group: {
_id: {
at: { $dateTrunc: { date: `$${dateField}`, unit: params.span } },
sessionId: "$sessionId",
},
},
},
{
$group: {
_id: "$_id.at",
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
date: {
at: "$_id",
field: params.dateField,
span: params.span,
},
distinct: "sessionId",
count: 1,
},
},
],
userOrSessionId: [
{
$group: {
_id: {
at: { $dateTrunc: { date: `$${dateField}`, unit: params.span } },
userOrSessionId: { $ifNull: ["$userId", "$sessionId"] },
},
},
},
{
$group: {
_id: "$_id.at",
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
date: {
at: "$_id",
field: params.dateField,
span: params.span,
},
distinct: "userOrSessionId",
count: 1,
},
},
],
_id: [
{
$group: {
_id: { $dateTrunc: { date: `$${dateField}`, unit: params.span } },
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
date: {
at: "$_id",
field: params.dateField,
span: params.span,
},
distinct: "_id",
count: 1,
},
},
],
},
},
{
$project: {
stats: {
$concatArrays: ["$userId", "$sessionId", "$userOrSessionId", "$_id"],
},
},
},
{
$unwind: "$stats",
},
{
$replaceRoot: {
newRoot: "$stats",
},
},
{
$set: {
type: params.type,
},
},
{
$merge: {
into: CONVERSATION_STATS_COLLECTION,
on: ["date.at", "type", "date.span", "date.field", "distinct"],
whenMatched: "replace",
whenNotMatched: "insert",
},
},
];
await collections.conversations.aggregate(pipeline, { allowDiskUse: true }).next();
logger.info(
{ minDate, dateField: params.dateField, span: params.span, type: params.type },
"Computed conversation stats"
);
}
const LOCK_KEY = "conversation.stats";
let hasLock = false;
let lockId: ObjectId | null = null;
async function maintainLock() {
if (hasLock && lockId) {
hasLock = await refreshLock(LOCK_KEY, lockId);
if (!hasLock) {
lockId = null;
}
} else if (!hasLock) {
lockId = (await acquireLock(LOCK_KEY)) || null;
hasLock = !!lockId;
}
setTimeout(maintainLock, 10_000);
}
export function refreshConversationStats() {
const ONE_HOUR_MS = 3_600_000;
maintainLock().then(() => {
computeAllStats();
setInterval(computeAllStats, 12 * ONE_HOUR_MS);
});
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/NavConversationItem.svelte
|
<script lang="ts">
import { base } from "$app/paths";
import { page } from "$app/stores";
import { createEventDispatcher } from "svelte";
import CarbonCheckmark from "~icons/carbon/checkmark";
import CarbonTrashCan from "~icons/carbon/trash-can";
import CarbonClose from "~icons/carbon/close";
import CarbonEdit from "~icons/carbon/edit";
import type { ConvSidebar } from "$lib/types/ConvSidebar";
export let conv: ConvSidebar;
let confirmDelete = false;
const dispatch = createEventDispatcher<{
deleteConversation: string;
editConversationTitle: { id: string; title: string };
}>();
</script>
<a
data-sveltekit-noscroll
on:mouseleave={() => {
confirmDelete = false;
}}
href="{base}/conversation/{conv.id}"
class="group flex h-10 flex-none items-center gap-1.5 rounded-lg pl-2.5 pr-2 text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700 sm:h-[2.35rem] {conv.id ===
$page.params.id
? 'bg-gray-100 dark:bg-gray-700'
: ''}"
>
<div class="flex flex-1 items-center truncate">
{#if confirmDelete}
<span class="mr-1 font-semibold"> Delete </span>
{/if}
{#if conv.avatarUrl}
<img
src="{base}{conv.avatarUrl}"
alt="Assistant avatar"
class="mr-1.5 inline size-4 flex-none rounded-full object-cover"
/>
{conv.title.replace(/\p{Emoji}/gu, "")}
{:else if conv.assistantId}
<div
class="mr-1.5 flex size-4 flex-none items-center justify-center rounded-full bg-gray-300 text-xs font-bold uppercase text-gray-500"
/>
{conv.title.replace(/\p{Emoji}/gu, "")}
{:else}
{conv.title}
{/if}
</div>
{#if confirmDelete}
<button
type="button"
class="flex h-5 w-5 items-center justify-center rounded md:hidden md:group-hover:flex"
title="Cancel delete action"
on:click|preventDefault={() => (confirmDelete = false)}
>
<CarbonClose class="text-xs text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" />
</button>
<button
type="button"
class="flex h-5 w-5 items-center justify-center rounded md:hidden md:group-hover:flex"
title="Confirm delete action"
on:click|preventDefault={() => {
confirmDelete = false;
dispatch("deleteConversation", conv.id);
}}
>
<CarbonCheckmark class="text-xs text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" />
</button>
{:else}
<button
type="button"
class="flex h-5 w-5 items-center justify-center rounded md:hidden md:group-hover:flex"
title="Edit conversation title"
on:click|preventDefault={() => {
const newTitle = prompt("Edit this conversation title:", conv.title);
if (!newTitle) return;
dispatch("editConversationTitle", { id: conv.id, title: newTitle });
}}
>
<CarbonEdit class="text-xs text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" />
</button>
<button
type="button"
class="flex h-5 w-5 items-center justify-center rounded md:hidden md:group-hover:flex"
title="Delete conversation"
on:click|preventDefault={(event) => {
if (event.shiftKey) {
dispatch("deleteConversation", conv.id);
} else {
confirmDelete = true;
}
}}
>
<CarbonTrashCan class="text-xs text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" />
</button>
{/if}
</a>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/NavMenu.svelte
|
<script lang="ts">
import { base } from "$app/paths";
import Logo from "$lib/components/icons/Logo.svelte";
import { switchTheme } from "$lib/switchTheme";
import { isAborted } from "$lib/stores/isAborted";
import { env as envPublic } from "$env/dynamic/public";
import NavConversationItem from "./NavConversationItem.svelte";
import type { LayoutData } from "../../routes/$types";
import type { ConvSidebar } from "$lib/types/ConvSidebar";
import type { Model } from "$lib/types/Model";
import { page } from "$app/stores";
export let conversations: ConvSidebar[];
export let canLogin: boolean;
export let user: LayoutData["user"];
function handleNewChatClick() {
isAborted.set(true);
}
const dateRanges = [
new Date().setDate(new Date().getDate() - 1),
new Date().setDate(new Date().getDate() - 7),
new Date().setMonth(new Date().getMonth() - 1),
];
$: groupedConversations = {
today: conversations.filter(({ updatedAt }) => updatedAt.getTime() > dateRanges[0]),
week: conversations.filter(
({ updatedAt }) => updatedAt.getTime() > dateRanges[1] && updatedAt.getTime() < dateRanges[0]
),
month: conversations.filter(
({ updatedAt }) => updatedAt.getTime() > dateRanges[2] && updatedAt.getTime() < dateRanges[1]
),
older: conversations.filter(({ updatedAt }) => updatedAt.getTime() < dateRanges[2]),
};
const titles: { [key: string]: string } = {
today: "Today",
week: "This week",
month: "This month",
older: "Older",
} as const;
const nModels: number = $page.data.models.filter((el: Model) => !el.unlisted).length;
</script>
<div class="sticky top-0 flex flex-none items-center justify-between px-1.5 py-3.5 max-sm:pt-0">
<a
class="flex items-center rounded-xl text-lg font-semibold"
href="{envPublic.PUBLIC_ORIGIN}{base}/"
>
<Logo classNames="mr-1" />
{envPublic.PUBLIC_APP_NAME}
</a>
<a
href={`${base}/`}
on:click={handleNewChatClick}
class="flex rounded-lg border bg-white px-2 py-0.5 text-center shadow-sm hover:shadow-none dark:border-gray-600 dark:bg-gray-700 sm:text-smd"
>
New Chat
</a>
</div>
<div
class="scrollbar-custom flex flex-col gap-1 overflow-y-auto rounded-r-xl from-gray-50 px-3 pb-3 pt-2 text-[.9rem] dark:from-gray-800/30 max-sm:bg-gradient-to-t md:bg-gradient-to-l"
>
{#await groupedConversations}
{#if $page.data.nConversations > 0}
<div class="overflow-y-hidden">
<div class="flex animate-pulse flex-col gap-4">
<div class="h-4 w-24 rounded bg-gray-200 dark:bg-gray-700" />
{#each Array(100) as _}
<div class="ml-2 h-5 w-4/5 gap-5 rounded bg-gray-200 dark:bg-gray-700" />
{/each}
</div>
</div>
{/if}
{:then groupedConversations}
<div class="flex flex-col gap-1">
{#each Object.entries(groupedConversations) as [group, convs]}
{#if convs.length}
<h4 class="mb-1.5 mt-4 pl-0.5 text-sm text-gray-400 first:mt-0 dark:text-gray-500">
{titles[group]}
</h4>
{#each convs as conv}
<NavConversationItem on:editConversationTitle on:deleteConversation {conv} />
{/each}
{/if}
{/each}
</div>
{/await}
</div>
<div
class="mt-0.5 flex flex-col gap-1 rounded-r-xl p-3 text-sm md:bg-gradient-to-l md:from-gray-50 md:dark:from-gray-800/30"
>
{#if user?.username || user?.email}
<form
action="{base}/logout"
method="post"
class="group flex items-center gap-1.5 rounded-lg pl-2.5 pr-2 hover:bg-gray-100 dark:hover:bg-gray-700"
>
<span
class="flex h-9 flex-none shrink items-center gap-1.5 truncate pr-2 text-gray-500 dark:text-gray-400"
>{user?.username || user?.email}</span
>
{#if !user.logoutDisabled}
<button
type="submit"
class="ml-auto h-6 flex-none items-center gap-1.5 rounded-md border bg-white px-2 text-gray-700 shadow-sm group-hover:flex hover:shadow-none dark:border-gray-600 dark:bg-gray-600 dark:text-gray-400 dark:hover:text-gray-300 md:hidden"
>
Sign Out
</button>
{/if}
</form>
{/if}
{#if canLogin}
<form action="{base}/login" method="POST" target="_parent">
<button
type="submit"
class="flex h-9 w-full flex-none items-center gap-1.5 rounded-lg pl-2.5 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
>
Login
</button>
</form>
{/if}
<button
on:click={switchTheme}
type="button"
class="flex h-9 flex-none items-center gap-1.5 rounded-lg pl-2.5 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
>
Theme
</button>
{#if nModels > 1}
<a
href="{base}/models"
class="flex h-9 flex-none items-center gap-1.5 rounded-lg pl-2.5 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
>
Models
<span
class="ml-auto rounded-full border border-gray-300 px-2 py-0.5 text-xs text-gray-500 dark:border-gray-500 dark:text-gray-400"
>{nModels}</span
>
</a>
{/if}
{#if $page.data.enableAssistants}
<a
href="{base}/assistants"
class="flex h-9 flex-none items-center gap-1.5 rounded-lg pl-2.5 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
>
Assistants
</a>
{/if}
{#if $page.data.enableCommunityTools}
<a
href="{base}/tools"
class="flex h-9 flex-none items-center gap-1.5 rounded-lg pl-2.5 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
>
Tools
<span
class="ml-auto rounded-full border border-purple-300 px-2 py-0.5 text-xs text-purple-500 dark:border-purple-500 dark:text-purple-400"
>New</span
>
</a>
{/if}
<a
href="{base}/settings"
class="flex h-9 flex-none items-center gap-1.5 rounded-lg pl-2.5 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
>
Settings
</a>
{#if envPublic.PUBLIC_APP_NAME === "HuggingChat"}
<a
href="{base}/privacy"
class="flex h-9 flex-none items-center gap-1.5 rounded-lg pl-2.5 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
>
About & Privacy
</a>
{/if}
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/ScrollToBottomBtn.svelte
|
<script lang="ts">
import { fade } from "svelte/transition";
import { onDestroy } from "svelte";
import IconChevron from "./icons/IconChevron.svelte";
export let scrollNode: HTMLElement;
export { className as class };
let visible = false;
let className = "";
let observer: ResizeObserver | null = null;
$: if (scrollNode) {
destroy();
if (window.ResizeObserver) {
observer = new ResizeObserver(() => {
updateVisibility();
});
observer.observe(scrollNode);
}
scrollNode.addEventListener("scroll", updateVisibility);
}
function updateVisibility() {
if (!scrollNode) return;
visible =
Math.ceil(scrollNode.scrollTop) + 200 < scrollNode.scrollHeight - scrollNode.clientHeight;
}
function destroy() {
observer?.disconnect();
scrollNode?.removeEventListener("scroll", updateVisibility);
}
onDestroy(destroy);
</script>
{#if visible}
<button
transition:fade={{ duration: 150 }}
on:click={() => scrollNode.scrollTo({ top: scrollNode.scrollHeight, behavior: "smooth" })}
class="btn absolute flex h-[41px] w-[41px] rounded-full border bg-white shadow-md transition-all hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-700 dark:shadow-gray-950 dark:hover:bg-gray-600 {className}"
><IconChevron classNames="mt-[2px]" /></button
>
{/if}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/ToolLogo.svelte
|
<script lang="ts">
import CarbonWikis from "~icons/carbon/wikis";
import CarbonTools from "~icons/carbon/tools";
import CarbonCamera from "~icons/carbon/camera";
import CarbonCode from "~icons/carbon/code";
import CarbonEmail from "~icons/carbon/email";
import CarbonCloud from "~icons/carbon/cloud-upload";
import CarbonTerminal from "~icons/carbon/terminal";
import CarbonGame from "~icons/carbon/game-console";
import CarbonChat from "~icons/carbon/chat-bot";
import CarbonSpeaker from "~icons/carbon/volume-up";
import CarbonVideo from "~icons/carbon/video";
export let color: string;
export let icon: string;
export let size: "sm" | "md" | "lg" = "md";
$: gradientColor = (() => {
switch (color) {
case "purple":
return "#653789";
case "blue":
return "#375889";
case "green":
return "#37894E";
case "yellow":
return "#897C37";
case "red":
return "#893737";
default:
return "#FFF";
}
})();
let iconEl = CarbonWikis;
switch (icon) {
case "wikis":
iconEl = CarbonWikis;
break;
case "tools":
iconEl = CarbonTools;
break;
case "camera":
iconEl = CarbonCamera;
break;
case "code":
iconEl = CarbonCode;
break;
case "email":
iconEl = CarbonEmail;
break;
case "cloud":
iconEl = CarbonCloud;
break;
case "terminal":
iconEl = CarbonTerminal;
break;
case "game":
iconEl = CarbonGame;
break;
case "chat":
iconEl = CarbonChat;
break;
case "speaker":
iconEl = CarbonSpeaker;
break;
case "video":
iconEl = CarbonVideo;
break;
}
$: sizeClass = (() => {
switch (size) {
case "sm":
return "size-8";
case "md":
return "size-14";
case "lg":
return "size-24";
}
})();
</script>
<div class="flex {sizeClass} relative items-center justify-center">
<svg xmlns="http://www.w3.org/2000/svg" class="absolute {sizeClass} h-full" viewBox="0 0 52 58">
<defs>
<linearGradient id="gradient-{gradientColor}" gradientTransform="rotate(90)">
<stop offset="0%" stop-color="#0E1523" />
<stop offset="100%" stop-color={gradientColor} />
</linearGradient>
<mask id="mask">
<path
d="M22.3043 1.2486C23.4279 0.603043 24.7025 0.263184 26 0.263184C27.2975 0.263184 28.5721 0.603043 29.6957 1.2486L48.3043 11.9373C49.4279 12.5828 50.361 13.5113 51.0097 14.6294C51.6584 15.7475 52 17.0158 52 18.3069V39.6902C52 40.9813 51.6584 42.2496 51.0097 43.3677C50.361 44.4858 49.4279 45.4143 48.3043 46.0598L29.6957 56.7514C28.5721 57.397 27.2975 57.7369 26 57.7369C24.7025 57.7369 23.4279 57.397 22.3043 56.7514L3.6957 46.0598C2.57209 45.4143 1.63904 44.4858 0.990308 43.3677C0.341578 42.2496 3.34785e-05 40.9813 5.18628e-07 39.6902V18.3099C-0.000485629 17.0183 0.340813 15.7494 0.989568 14.6307C1.63832 13.512 2.57166 12.5831 3.6957 11.9373L22.3043 1.2486Z"
fill="white"
/>
</mask>
</defs>
<rect width="100%" height="100%" fill="url(#gradient-{gradientColor})" mask="url(#mask)" />
</svg>
<svelte:component this={iconEl} class="relative {sizeClass} scale-50 text-clip text-gray-200" />
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/ToolBadge.svelte
|
<script lang="ts">
import ToolLogo from "./ToolLogo.svelte";
import { base } from "$app/paths";
import { browser } from "$app/environment";
export let toolId: string;
</script>
<div
class="relative flex items-center justify-center space-x-2 rounded border border-gray-300 bg-gray-200 px-2 py-1"
>
{#if browser}
{#await fetch(`${base}/api/tools/${toolId}`).then((res) => res.json()) then value}
<ToolLogo color={value.color} icon={value.icon} size="sm" />
<div class="flex flex-col items-center justify-center py-1">
<a
href={`${base}/tools/${value._id}`}
target="_blank"
class="line-clamp-1 truncate font-semibold text-blue-600 hover:underline"
>{value.displayName}</a
>
{#if value.createdByName}
<p class="text-center text-xs text-gray-500">
Created by
<a class="underline" href="{base}/tools?user={value.createdByName}" target="_blank"
>{value.createdByName}</a
>
</p>
{:else}
<p class="text-center text-xs text-gray-500">Official HuggingChat tool</p>
{/if}
</div>
{/await}
{/if}
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/AssistantToolPicker.svelte
|
<script lang="ts">
import { base } from "$app/paths";
import type { ToolLogoColor, ToolLogoIcon } from "$lib/types/Tool";
import { debounce } from "$lib/utils/debounce";
import { onMount } from "svelte";
import ToolLogo from "./ToolLogo.svelte";
import CarbonClose from "~icons/carbon/close";
interface ToolSuggestion {
_id: string;
displayName: string;
createdByName: string;
color: ToolLogoColor;
icon: ToolLogoIcon;
}
export let toolIds: string[] = [];
let selectedValues: ToolSuggestion[] = [];
onMount(async () => {
selectedValues = await Promise.all(
toolIds.map(async (id) => await fetch(`${base}/api/tools/${id}`).then((res) => res.json()))
);
await fetchSuggestions("");
});
let inputValue = "";
let maxValues = 3;
let suggestions: ToolSuggestion[] = [];
async function fetchSuggestions(query: string) {
suggestions = (await fetch(`${base}/api/tools/search?q=${query}`).then((res) =>
res.json()
)) satisfies ToolSuggestion[];
}
const debouncedFetch = debounce((query: string) => fetchSuggestions(query), 300);
function addValue(value: ToolSuggestion) {
if (selectedValues.length < maxValues && !selectedValues.includes(value)) {
selectedValues = [...selectedValues, value];
toolIds = [...toolIds, value._id];
inputValue = "";
suggestions = [];
}
}
function removeValue(id: ToolSuggestion["_id"]) {
selectedValues = selectedValues.filter((v) => v._id !== id);
toolIds = selectedValues.map((value) => value._id);
}
</script>
{#if selectedValues.length > 0}
<div class="flex flex-wrap items-center justify-center gap-2">
{#each selectedValues as value}
<div
class="flex items-center justify-center space-x-2 rounded border border-gray-300 bg-gray-200 px-2 py-1"
>
<ToolLogo color={value.color} icon={value.icon} size="sm" />
<div class="flex flex-col items-center justify-center py-1">
<a
href={`${base}/tools/${value._id}`}
target="_blank"
class="line-clamp-1 truncate font-semibold text-blue-600 hover:underline"
>{value.displayName}</a
>
{#if value.createdByName}
<p class="text-center text-xs text-gray-500">
Created by
<a class="underline" href="{base}/tools?user={value.createdByName}" target="_blank"
>{value.createdByName}</a
>
</p>
{:else}
<p class="text-center text-xs text-gray-500">Official HuggingChat tool</p>
{/if}
</div>
<button
on:click|stopPropagation|preventDefault={() => removeValue(value._id)}
class="text-lg text-gray-600"
>
<CarbonClose />
</button>
</div>
{/each}
</div>
{/if}
{#if selectedValues.length < maxValues}
<div class="group relative block">
<input
type="text"
bind:value={inputValue}
on:input={(ev) => {
inputValue = ev.currentTarget.value;
debouncedFetch(inputValue);
}}
disabled={selectedValues.length >= maxValues}
class="w-full rounded border border-gray-200 bg-gray-100 px-3 py-2"
class:opacity-50={selectedValues.length >= maxValues}
class:bg-gray-100={selectedValues.length >= maxValues}
placeholder="Type to search tools..."
/>
{#if suggestions.length > 0}
<div
class="invisible absolute z-10 mt-1 w-full rounded border border-gray-300 bg-white shadow-lg group-focus-within:visible"
>
{#if inputValue === ""}
<p class="px-3 py-2 text-left text-xs text-gray-500">
Start typing to search for tools...
</p>
{:else}
{#each suggestions as suggestion}
<button
on:click|stopPropagation|preventDefault={() => addValue(suggestion)}
class="w-full cursor-pointer px-3 py-2 text-left hover:bg-blue-500 hover:text-white"
>
{suggestion.displayName}
{#if suggestion.createdByName}
<span class="text-xs text-gray-500"> by {suggestion.createdByName}</span>
{/if}
</button>
{/each}
{/if}
</div>
{/if}
</div>
{/if}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/ExpandNavigation.svelte
|
<script lang="ts">
export let isCollapsed: boolean;
export let classNames: string;
</script>
<button
on:click
class="{classNames} group flex h-16 w-6 flex-col items-center justify-center -space-y-1 outline-none *:h-3 *:w-1 *:rounded-full *:hover:bg-gray-300 dark:*:hover:bg-gray-600 max-md:hidden {!isCollapsed
? '*:bg-gray-200/70 dark:*:bg-gray-800'
: '*:bg-gray-200 dark:*:bg-gray-700'}"
name="sidebar-toggle"
aria-label="Toggle sidebar navigation"
>
<div class={!isCollapsed ? "group-hover:rotate-[20deg]" : "group-hover:-rotate-[20deg]"} />
<div class={!isCollapsed ? "group-hover:-rotate-[20deg]" : "group-hover:rotate-[20deg]"} />
</button>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/CopyToClipBoardBtn.svelte
|
<script lang="ts">
import { onDestroy } from "svelte";
import IconCopy from "./icons/IconCopy.svelte";
import Tooltip from "./Tooltip.svelte";
export let classNames = "";
export let value: string;
let isSuccess = false;
let timeout: ReturnType<typeof setTimeout>;
const handleClick = async () => {
// writeText() can be unavailable or fail in some cases (iframe, etc) so we try/catch
try {
await navigator.clipboard.writeText(value);
isSuccess = true;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
isSuccess = false;
}, 1000);
} catch (err) {
console.error(err);
}
};
onDestroy(() => {
if (timeout) {
clearTimeout(timeout);
}
});
</script>
<button
class={classNames}
title={"Copy to clipboard"}
type="button"
on:click
on:click={handleClick}
>
<div class="relative">
<slot>
<IconCopy classNames="h-[1.14em] w-[1.14em]" />
</slot>
<Tooltip classNames={isSuccess ? "opacity-100" : "opacity-0"} />
</div>
</button>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/StopGeneratingBtn.svelte
|
<script lang="ts">
import CarbonStopFilledAlt from "~icons/carbon/stop-filled-alt";
export let classNames = "";
</script>
<button
type="button"
on:click
class="btn flex h-8 rounded-lg border bg-white px-3 py-1 shadow-sm transition-all hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-700 dark:hover:bg-gray-600 {classNames}"
>
<CarbonStopFilledAlt class="-ml-1 mr-1 h-[1.25rem] w-[1.1875rem] text-gray-300" /> Stop generating
</button>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/SystemPromptModal.svelte
|
<script lang="ts">
import Modal from "./Modal.svelte";
import CarbonClose from "~icons/carbon/close";
import CarbonBlockchain from "~icons/carbon/blockchain";
export let preprompt: string;
let isOpen = false;
</script>
<button
type="button"
class="mx-auto flex items-center gap-1.5 rounded-full border border-gray-100 bg-gray-50 px-3 py-1 text-xs text-gray-500 hover:bg-gray-100 dark:border-gray-800 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700"
on:click={() => (isOpen = !isOpen)}
on:keydown={(e) => e.key === "Enter" && (isOpen = !isOpen)}
>
<CarbonBlockchain class="text-xxs" /> Using Custom System Prompt
</button>
{#if isOpen}
<Modal on:close={() => (isOpen = false)} width="w-full max-w-2xl">
<div class="flex w-full flex-col gap-5 p-6">
<div class="flex items-start justify-between text-xl font-semibold text-gray-800">
<h2>System Prompt</h2>
<button type="button" class="group" on:click={() => (isOpen = false)}>
<CarbonClose class="mt-auto text-gray-900 group-hover:text-gray-500" />
</button>
</div>
<textarea
disabled
value={preprompt}
class="min-h-[420px] w-full resize-none rounded-lg border bg-gray-50 p-2.5 text-gray-600 max-sm:text-sm"
/>
</div>
</Modal>
{/if}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/RetryBtn.svelte
|
<script lang="ts">
import CarbonRotate360 from "~icons/carbon/rotate-360";
export let classNames = "";
</script>
<button
type="button"
on:click
class="btn flex h-8 rounded-lg border bg-white px-3 py-1 text-gray-500 shadow-sm transition-all hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 {classNames}"
>
<CarbonRotate360 class="mr-2 text-xs " /> Retry
</button>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/ScrollToPreviousBtn.svelte
|
<script lang="ts">
import { fade } from "svelte/transition";
import { onDestroy } from "svelte";
import IconChevron from "./icons/IconChevron.svelte";
export let scrollNode: HTMLElement;
export { className as class };
let visible = false;
let className = "";
let observer: ResizeObserver | null = null;
$: if (scrollNode) {
destroy();
if (window.ResizeObserver) {
observer = new ResizeObserver(() => {
updateVisibility();
});
observer.observe(scrollNode);
}
scrollNode.addEventListener("scroll", updateVisibility);
}
function updateVisibility() {
if (!scrollNode) return;
visible =
Math.ceil(scrollNode.scrollTop) + 200 < scrollNode.scrollHeight - scrollNode.clientHeight &&
scrollNode.scrollTop > 200;
}
function scrollToPrevious() {
if (!scrollNode) return;
const messages = scrollNode.querySelectorAll("[data-message-id]");
const scrollTop = scrollNode.scrollTop;
let previousMessage: Element | null = null;
for (let i = messages.length - 1; i >= 0; i--) {
const messageTop =
messages[i].getBoundingClientRect().top +
scrollTop -
scrollNode.getBoundingClientRect().top;
if (messageTop < scrollTop - 1) {
previousMessage = messages[i];
break;
}
}
if (previousMessage) {
previousMessage.scrollIntoView({ behavior: "smooth", block: "start" });
}
}
function destroy() {
observer?.disconnect();
scrollNode?.removeEventListener("scroll", updateVisibility);
}
onDestroy(destroy);
</script>
{#if visible}
<button
transition:fade={{ duration: 150 }}
on:click={scrollToPrevious}
class="btn absolute flex h-[41px] w-[41px] rounded-full border bg-white shadow-md transition-all hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-700 dark:shadow-gray-950 dark:hover:bg-gray-600 {className}"
>
<IconChevron classNames="rotate-180 mt-[2px]" />
</button>
{/if}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/CodeBlock.svelte
|
<script lang="ts">
import CopyToClipBoardBtn from "./CopyToClipBoardBtn.svelte";
import DOMPurify from "isomorphic-dompurify";
import hljs from "highlight.js";
export let code = "";
export let lang = "";
$: highlightedCode = hljs.highlightAuto(code, hljs.getLanguage(lang)?.aliases).value;
</script>
<div class="group relative my-4 rounded-lg">
<pre
class="scrollbar-custom overflow-auto px-5 scrollbar-thumb-gray-500 hover:scrollbar-thumb-gray-400 dark:scrollbar-thumb-white/10 dark:hover:scrollbar-thumb-white/20"><code
><!-- eslint-disable svelte/no-at-html-tags -->{@html DOMPurify.sanitize(
highlightedCode
)}</code
></pre>
<CopyToClipBoardBtn
classNames="btn rounded-lg border border-gray-200 px-2 py-2 text-sm shadow-sm transition-all hover:border-gray-300 active:shadow-inner dark:border-gray-700 dark:hover:border-gray-500 absolute top-2 right-2 invisible opacity-0 group-hover:visible group-hover:opacity-100 dark:text-gray-700 text-gray-200"
value={code}
/>
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/Portal.svelte
|
<script lang="ts">
import { onMount, onDestroy } from "svelte";
let el: HTMLElement;
onMount(() => {
el.ownerDocument.body.appendChild(el);
});
onDestroy(() => {
if (el?.parentNode) {
el.parentNode.removeChild(el);
}
});
</script>
<div bind:this={el} class="contents" hidden>
<slot />
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/Switch.svelte
|
<script lang="ts">
export let checked: boolean;
export let name: string;
</script>
<input bind:checked type="checkbox" {name} class="peer pointer-events-none absolute opacity-0" />
<div
aria-checked={checked}
aria-roledescription="switch"
aria-label="switch"
role="switch"
tabindex="0"
class="relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full bg-gray-300 p-1 shadow-inner ring-gray-400 transition-all peer-checked:bg-blue-600 peer-focus-visible:ring peer-focus-visible:ring-offset-1 hover:bg-gray-400 dark:bg-gray-600 peer-checked:[&>div]:translate-x-3.5"
>
<div class="h-3.5 w-3.5 rounded-full bg-white shadow-sm transition-all" />
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/Pagination.svelte
|
<script lang="ts">
import { page } from "$app/stores";
import { getHref } from "$lib/utils/getHref";
import PaginationArrow from "./PaginationArrow.svelte";
export let classNames = "";
export let numItemsPerPage: number;
export let numTotalItems: number;
const ELLIPSIS_IDX = -1 as const;
$: numTotalPages = Math.ceil(numTotalItems / numItemsPerPage);
$: pageIndex = parseInt($page.url.searchParams.get("p") ?? "0");
$: pageIndexes = getPageIndexes(pageIndex, numTotalPages);
function getPageIndexes(pageIdx: number, nTotalPages: number) {
let pageIdxs: number[] = [];
const NUM_EXTRA_BUTTONS = 2; // The number of page links to show on either side of the current page link.
const minIdx = 0;
const maxIdx = nTotalPages - 1;
pageIdxs = [pageIdx];
// forward
for (let i = 1; i < NUM_EXTRA_BUTTONS + 1; i++) {
const newPageIdx = pageIdx + i;
if (newPageIdx > maxIdx) {
continue;
}
pageIdxs.push(newPageIdx);
}
if (maxIdx - pageIdxs[pageIdxs.length - 1] > 1) {
pageIdxs.push(...[ELLIPSIS_IDX, maxIdx]);
} else if (maxIdx - pageIdxs[pageIdxs.length - 1] === 1) {
pageIdxs.push(maxIdx);
}
// backward
for (let i = 1; i < NUM_EXTRA_BUTTONS + 1; i++) {
const newPageIdx = pageIdx - i;
if (newPageIdx < minIdx) {
continue;
}
pageIdxs.unshift(newPageIdx);
}
if (pageIdxs[0] - minIdx > 1) {
pageIdxs.unshift(...[minIdx, ELLIPSIS_IDX]);
} else if (pageIdxs[0] - minIdx === 1) {
pageIdxs.unshift(minIdx);
}
return pageIdxs;
}
</script>
{#if numTotalPages > 1}
<nav>
<ul
class="flex select-none items-center justify-between space-x-2 text-gray-700 dark:text-gray-300 sm:justify-center {classNames}"
>
<li>
<PaginationArrow
href={getHref($page.url, { newKeys: { p: (pageIndex - 1).toString() } })}
direction="previous"
isDisabled={pageIndex - 1 < 0}
/>
</li>
{#each pageIndexes as pageIdx}
<li class="hidden sm:block">
<a
class="
rounded-lg px-2.5 py-1
{pageIndex === pageIdx
? 'bg-gray-50 font-semibold ring-1 ring-inset ring-gray-200 dark:bg-gray-800 dark:text-yellow-500 dark:ring-gray-700'
: ''}
"
class:pointer-events-none={pageIdx === ELLIPSIS_IDX || pageIndex === pageIdx}
href={getHref($page.url, { newKeys: { p: pageIdx.toString() } })}
>
{pageIdx === ELLIPSIS_IDX ? "..." : pageIdx + 1}
</a>
</li>
{/each}
<li>
<PaginationArrow
href={getHref($page.url, { newKeys: { p: (pageIndex + 1).toString() } })}
direction="next"
isDisabled={pageIndex + 1 >= numTotalPages}
/>
</li>
</ul>
</nav>
{/if}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/TokensCounter.svelte
|
<script lang="ts">
import type { Model } from "$lib/types/Model";
import { getTokenizer } from "$lib/utils/getTokenizer";
import type { PreTrainedTokenizer } from "@huggingface/transformers";
export let classNames = "";
export let prompt = "";
export let modelTokenizer: Exclude<Model["tokenizer"], undefined>;
export let truncate: number | undefined = undefined;
let tokenizer: PreTrainedTokenizer | undefined = undefined;
async function tokenizeText(_prompt: string) {
if (!tokenizer) {
return;
}
const { input_ids } = await tokenizer(_prompt);
return input_ids.size;
}
$: (async () => {
tokenizer = await getTokenizer(modelTokenizer);
})();
</script>
{#if tokenizer}
{#await tokenizeText(prompt) then nTokens}
{@const exceedLimit = nTokens > (truncate || Infinity)}
<div class={classNames}>
<p
class="peer text-sm {exceedLimit
? 'text-red-500 opacity-100'
: 'opacity-60 hover:opacity-90'}"
>
{nTokens}{truncate ? `/${truncate}` : ""}
</p>
<div
class="invisible absolute -top-6 right-0 whitespace-nowrap rounded bg-black px-1 text-sm text-white peer-hover:visible"
>
Tokens usage
</div>
</div>
{/await}
{/if}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/MobileNav.svelte
|
<script lang="ts">
import { navigating } from "$app/stores";
import { createEventDispatcher } from "svelte";
import { browser } from "$app/environment";
import { base } from "$app/paths";
import { page } from "$app/stores";
import CarbonClose from "~icons/carbon/close";
import CarbonTextAlignJustify from "~icons/carbon/text-align-justify";
import IconNew from "$lib/components/icons/IconNew.svelte";
export let isOpen = false;
export let title: string | undefined;
$: title = title ?? "New Chat";
let closeEl: HTMLButtonElement;
let openEl: HTMLButtonElement;
const dispatch = createEventDispatcher();
$: if ($navigating) {
dispatch("toggle", false);
}
$: if (isOpen && closeEl) {
closeEl.focus();
} else if (!isOpen && browser && document.activeElement === closeEl) {
openEl.focus();
}
</script>
<nav
class="flex h-12 items-center justify-between border-b bg-gray-50 px-3 dark:border-gray-800 dark:bg-gray-800/70 md:hidden"
>
<button
type="button"
class="-ml-3 flex size-12 shrink-0 items-center justify-center text-lg"
on:click={() => dispatch("toggle", true)}
aria-label="Open menu"
bind:this={openEl}><CarbonTextAlignJustify /></button
>
{#await title}
<div class="flex h-full items-center justify-center" />
{:then title}
<span class="truncate px-4">{title ?? ""}</span>
{/await}
<a
class:invisible={!$page.params.id}
href="{base}/"
class="-mr-3 flex size-12 shrink-0 items-center justify-center text-lg"><IconNew /></a
>
</nav>
<nav
class="fixed inset-0 z-30 grid max-h-screen grid-cols-1 grid-rows-[auto,auto,1fr,auto] bg-white dark:bg-gray-900 {isOpen
? 'block'
: 'hidden'}"
>
<div class="flex h-12 items-center px-4">
<button
type="button"
class="-mr-3 ml-auto flex size-12 items-center justify-center text-lg"
on:click={() => dispatch("toggle", false)}
aria-label="Close menu"
bind:this={closeEl}><CarbonClose /></button
>
</div>
<slot />
</nav>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/WebSearchToggle.svelte
|
<script lang="ts">
import { webSearchParameters } from "$lib/stores/webSearchParameters";
import CarbonInformation from "~icons/carbon/information";
import Switch from "./Switch.svelte";
const toggle = () => ($webSearchParameters.useSearch = !$webSearchParameters.useSearch);
</script>
<div
class="flex h-8 cursor-pointer select-none items-center gap-2 rounded-lg border bg-white p-1.5 shadow-sm hover:shadow-none dark:border-gray-800 dark:bg-gray-900"
on:click={toggle}
on:keydown={toggle}
aria-checked={$webSearchParameters.useSearch}
aria-label="Web Search Toggle"
role="switch"
tabindex="0"
>
<Switch name="useSearch" bind:checked={$webSearchParameters.useSearch} />
<label for="useSearch" class="whitespace-nowrap text-sm text-gray-800 dark:text-gray-200">
Search web
</label>
<div class="group relative w-max">
<CarbonInformation class="text-xs text-gray-500" />
<div
class="pointer-events-none absolute -top-20 left-1/2 w-max -translate-x-1/2 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 text-gray-800 dark:text-gray-200">
When enabled, the model will try to complement its answer with information queried from the
web.
</p>
</div>
</div>
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/PaginationArrow.svelte
|
<script lang="ts">
import CarbonCaretLeft from "~icons/carbon/caret-left";
import CarbonCaretRight from "~icons/carbon/caret-right";
export let href: string;
export let direction: "next" | "previous";
export let isDisabled = false;
</script>
<a
class="flex items-center rounded-lg px-2.5 py-1 hover:bg-gray-50 dark:hover:bg-gray-800 {isDisabled
? 'pointer-events-none opacity-50'
: ''}"
{href}
>
{#if direction === "previous"}
<CarbonCaretLeft classNames="mr-1.5" />
Previous
{:else}
Next
<CarbonCaretRight classNames="ml-1.5" />
{/if}
</a>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/DisclaimerModal.svelte
|
<script lang="ts">
import { base } from "$app/paths";
import { page } from "$app/stores";
import { env as envPublic } from "$env/dynamic/public";
import LogoHuggingFaceBorderless from "$lib/components/icons/LogoHuggingFaceBorderless.svelte";
import Modal from "$lib/components/Modal.svelte";
import { useSettingsStore } from "$lib/stores/settings";
import { cookiesAreEnabled } from "$lib/utils/cookiesAreEnabled";
import Logo from "./icons/Logo.svelte";
const settings = useSettingsStore();
</script>
<Modal on:close>
<div
class="from-primary-500/40 via-primary-500/10 to-primary-500/0 flex w-full flex-col items-center gap-6 bg-gradient-to-b px-5 pb-8 pt-9 text-center sm:px-6"
>
<h2 class="flex items-center text-2xl font-semibold text-gray-800">
<Logo classNames="mr-1" />
{envPublic.PUBLIC_APP_NAME}
</h2>
<p class="text-lg font-semibold leading-snug text-gray-800" style="text-wrap: balance;">
{envPublic.PUBLIC_APP_DESCRIPTION}
</p>
<p class="text-sm text-gray-500">
{envPublic.PUBLIC_APP_DISCLAIMER_MESSAGE}
</p>
<div class="flex w-full flex-col items-center gap-2">
<button
class="w-full justify-center rounded-full border-2 border-gray-300 bg-black px-5 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900"
class:bg-white={$page.data.loginEnabled}
class:text-gray-800={$page.data.loginEnabled}
class:hover:bg-slate-100={$page.data.loginEnabled}
on:click|preventDefault|stopPropagation={() => {
if (!cookiesAreEnabled()) {
window.open(window.location.href, "_blank");
}
$settings.ethicsModalAccepted = true;
}}
>
{#if $page.data.loginEnabled}
{#if $page.data.guestMode}
Continue as guest
{:else}
Explore the app
{/if}
{:else}
Start chatting
{/if}
</button>
{#if $page.data.loginEnabled}
<form action="{base}/login" target="_parent" method="POST" class="w-full">
<button
type="submit"
class="flex w-full flex-wrap items-center justify-center whitespace-nowrap rounded-full border-2 border-black bg-black px-5 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900"
>
Sign in
{#if envPublic.PUBLIC_APP_NAME === "HuggingChat"}
<span class="flex items-center">
with <LogoHuggingFaceBorderless classNames="text-xl mr-1 ml-1.5 flex-none" /> Hugging
Face
</span>
{/if}
</button>
</form>
{/if}
</div>
</div>
</Modal>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/AssistantSettings.svelte
|
<script lang="ts">
import type { readAndCompressImage } from "browser-image-resizer";
import type { Model } from "$lib/types/Model";
import type { Assistant } from "$lib/types/Assistant";
import { onMount } from "svelte";
import { applyAction, enhance } from "$app/forms";
import { page } from "$app/stores";
import { base } from "$app/paths";
import CarbonPen from "~icons/carbon/pen";
import CarbonUpload from "~icons/carbon/upload";
import CarbonHelpFilled from "~icons/carbon/help";
import CarbonSettingsAdjust from "~icons/carbon/settings-adjust";
import CarbonTools from "~icons/carbon/tools";
import { useSettingsStore } from "$lib/stores/settings";
import { isHuggingChat } from "$lib/utils/isHuggingChat";
import IconInternet from "./icons/IconInternet.svelte";
import TokensCounter from "./TokensCounter.svelte";
import HoverTooltip from "./HoverTooltip.svelte";
import { findCurrentModel } from "$lib/utils/models";
import AssistantToolPicker from "./AssistantToolPicker.svelte";
type ActionData = {
error: boolean;
errors: {
field: string | number;
message: string;
}[];
} | null;
type AssistantFront = Omit<Assistant, "_id" | "createdById"> & { _id: string };
export let form: ActionData;
export let assistant: AssistantFront | undefined = undefined;
export let models: Model[] = [];
let files: FileList | null = null;
const settings = useSettingsStore();
let modelId = "";
let systemPrompt = assistant?.preprompt ?? "";
let dynamicPrompt = assistant?.dynamicPrompt ?? false;
let showModelSettings = Object.values(assistant?.generateSettings ?? {}).some((v) => !!v);
let compress: typeof readAndCompressImage | null = null;
onMount(async () => {
const module = await import("browser-image-resizer");
compress = module.readAndCompressImage;
modelId = findCurrentModel(models, assistant ? assistant.modelId : $settings.activeModel).id;
});
let inputMessage1 = assistant?.exampleInputs[0] ?? "";
let inputMessage2 = assistant?.exampleInputs[1] ?? "";
let inputMessage3 = assistant?.exampleInputs[2] ?? "";
let inputMessage4 = assistant?.exampleInputs[3] ?? "";
function resetErrors() {
if (form) {
form.errors = [];
form.error = false;
}
}
function onFilesChange(e: Event) {
const inputEl = e.target as HTMLInputElement;
if (inputEl.files?.length && inputEl.files[0].size > 0) {
if (!inputEl.files[0].type.includes("image")) {
inputEl.files = null;
files = null;
form = { error: true, errors: [{ field: "avatar", message: "Only images are allowed" }] };
return;
}
files = inputEl.files;
resetErrors();
deleteExistingAvatar = false;
}
}
function getError(field: string, returnForm: ActionData) {
return returnForm?.errors.find((error) => error.field === field)?.message ?? "";
}
let deleteExistingAvatar = false;
let loading = false;
let ragMode: false | "links" | "domains" | "all" = assistant?.rag?.allowAllDomains
? "all"
: assistant?.rag?.allowedLinks?.length ?? 0 > 0
? "links"
: (assistant?.rag?.allowedDomains?.length ?? 0) > 0
? "domains"
: false;
let tools = assistant?.tools ?? [];
const regex = /{{\s?url=(.+?)\s?}}/g;
$: templateVariables = [...systemPrompt.matchAll(regex)].map((match) => match[1]);
$: selectedModel = models.find((m) => m.id === modelId);
</script>
<form
method="POST"
class="relative flex h-full flex-col overflow-y-auto p-4 md:p-8"
enctype="multipart/form-data"
use:enhance={async ({ formData }) => {
loading = true;
if (files?.[0] && files[0].size > 0 && compress) {
await compress(files[0], {
maxWidth: 500,
maxHeight: 500,
quality: 1,
}).then((resizedImage) => {
formData.set("avatar", resizedImage);
});
}
if (deleteExistingAvatar === true) {
if (assistant?.avatar) {
// if there is an avatar we explicitly removei t
formData.set("avatar", "null");
} else {
// else we just remove it from the input
formData.delete("avatar");
}
} else {
if (files === null) {
formData.delete("avatar");
}
}
formData.delete("ragMode");
if (ragMode === false || !$page.data.enableAssistantsRAG) {
formData.set("ragAllowAll", "false");
formData.set("ragLinkList", "");
formData.set("ragDomainList", "");
} else if (ragMode === "all") {
formData.set("ragAllowAll", "true");
formData.set("ragLinkList", "");
formData.set("ragDomainList", "");
} else if (ragMode === "links") {
formData.set("ragAllowAll", "false");
formData.set("ragDomainList", "");
} else if (ragMode === "domains") {
formData.set("ragAllowAll", "false");
formData.set("ragLinkList", "");
}
formData.set("tools", tools.join(","));
return async ({ result }) => {
loading = false;
await applyAction(result);
};
}}
>
{#if assistant}
<h2 class="text-xl font-semibold">
Edit Assistant: {assistant?.name ?? "assistant"}
</h2>
<p class="mb-6 text-sm text-gray-500">
Modifying an existing assistant will propagate the changes to all users.
</p>
{:else}
<h2 class="text-xl font-semibold">Create new assistant</h2>
<p class="mb-6 text-sm text-gray-500">
Create and share your own AI Assistant. All assistants 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>
<div class="mb-1 block pb-2 text-sm font-semibold">Avatar</div>
<input
type="file"
accept="image/*"
name="avatar"
id="avatar"
class="hidden"
on:change={onFilesChange}
/>
{#if (files && files[0]) || (assistant?.avatar && !deleteExistingAvatar)}
<div class="group relative mx-auto h-12 w-12">
{#if files && files[0]}
<img
src={URL.createObjectURL(files[0])}
alt="avatar"
class="crop mx-auto h-12 w-12 cursor-pointer rounded-full object-cover"
/>
{:else if assistant?.avatar}
<img
src="{base}/settings/assistants/{assistant._id}/avatar.jpg?hash={assistant.avatar}"
alt="avatar"
class="crop mx-auto h-12 w-12 cursor-pointer rounded-full object-cover"
/>
{/if}
<label
for="avatar"
class="invisible absolute bottom-0 h-12 w-12 rounded-full bg-black bg-opacity-50 p-1 group-hover:visible hover:visible"
>
<CarbonPen class="mx-auto my-auto h-full cursor-pointer text-center text-white" />
</label>
</div>
<div class="mx-auto w-max pt-1">
<button
type="button"
on:click|stopPropagation|preventDefault={() => {
files = null;
deleteExistingAvatar = true;
}}
class="mx-auto w-max text-center text-xs text-gray-600 hover:underline"
>
Delete
</button>
</div>
{:else}
<div class="mb-1 flex w-max flex-row gap-4">
<label
for="avatar"
class="btn flex h-8 rounded-lg border bg-white px-3 py-1 text-gray-500 shadow-sm transition-all hover:bg-gray-100"
>
<CarbonUpload class="mr-2 text-xs " /> Upload
</label>
</div>
{/if}
<p class="text-xs text-red-500">{getError("avatar", form)}</p>
</div>
<label>
<div class="mb-1 font-semibold">Name</div>
<input
name="name"
class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2"
placeholder="Assistant Name"
value={assistant?.name ?? ""}
/>
<p class="text-xs text-red-500">{getError("name", form)}</p>
</label>
<label>
<div class="mb-1 font-semibold">Description</div>
<textarea
name="description"
class="h-15 w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2"
placeholder="It knows everything about python"
value={assistant?.description ?? ""}
/>
<p class="text-xs text-red-500">{getError("description", form)}</p>
</label>
<label>
<div class="mb-1 font-semibold">Model</div>
<div class="flex gap-2">
<select
name="modelId"
class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2"
bind:value={modelId}
>
{#each models.filter((model) => !model.unlisted) as model}
<option value={model.id}>{model.displayName}</option>
{/each}
<p class="text-xs text-red-500">{getError("modelId", form)}</p>
</select>
<button
type="button"
class="flex aspect-square items-center gap-2 whitespace-nowrap rounded-lg border px-3 {showModelSettings
? 'border-blue-500/20 bg-blue-50 text-blue-600'
: ''}"
on:click={() => (showModelSettings = !showModelSettings)}
><CarbonSettingsAdjust class="text-xs" /></button
>
</div>
<div
class="mt-2 rounded-lg border border-blue-500/20 bg-blue-500/5 px-2 py-0.5"
class:hidden={!showModelSettings}
>
<p class="text-xs text-red-500">{getError("inputMessage1", form)}</p>
<div class="my-2 grid grid-cols-1 gap-2.5 sm:grid-cols-2 sm:grid-rows-2">
<label for="temperature" class="flex justify-between">
<span class="m-1 ml-0 flex items-center gap-1.5 whitespace-nowrap text-sm">
Temperature
<HoverTooltip
label="Temperature: Controls creativity, higher values allow more variety."
>
<CarbonHelpFilled
class="inline text-xxs text-gray-500 group-hover/tooltip:text-blue-600"
/>
</HoverTooltip>
</span>
<input
type="number"
name="temperature"
min="0.1"
max="2"
step="0.1"
class="w-20 rounded-lg border-2 border-gray-200 bg-gray-100 px-2 py-1"
placeholder={selectedModel?.parameters?.temperature?.toString() ?? "1"}
value={assistant?.generateSettings?.temperature ?? ""}
/>
</label>
<label for="top_p" class="flex justify-between">
<span class="m-1 ml-0 flex items-center gap-1.5 whitespace-nowrap text-sm">
Top P
<HoverTooltip
label="Top P: Sets word choice boundaries, lower values tighten focus."
>
<CarbonHelpFilled
class="inline text-xxs text-gray-500 group-hover/tooltip:text-blue-600"
/>
</HoverTooltip>
</span>
<input
type="number"
name="top_p"
class="w-20 rounded-lg border-2 border-gray-200 bg-gray-100 px-2 py-1"
min="0.05"
max="1"
step="0.05"
placeholder={selectedModel?.parameters?.top_p?.toString() ?? "1"}
value={assistant?.generateSettings?.top_p ?? ""}
/>
</label>
<label for="repetition_penalty" class="flex justify-between">
<span class="m-1 ml-0 flex items-center gap-1.5 whitespace-nowrap text-sm">
Repetition penalty
<HoverTooltip
label="Repetition penalty: Prevents reuse, higher values decrease repetition."
>
<CarbonHelpFilled
class="inline text-xxs text-gray-500 group-hover/tooltip:text-blue-600"
/>
</HoverTooltip>
</span>
<input
type="number"
name="repetition_penalty"
min="0.1"
max="2"
step="0.1"
class="w-20 rounded-lg border-2 border-gray-200 bg-gray-100 px-2 py-1"
placeholder={selectedModel?.parameters?.repetition_penalty?.toString() ?? "1.0"}
value={assistant?.generateSettings?.repetition_penalty ?? ""}
/>
</label>
<label for="top_k" class="flex justify-between">
<span class="m-1 ml-0 flex items-center gap-1.5 whitespace-nowrap text-sm">
Top K <HoverTooltip
label="Top K: Restricts word options, lower values for predictability."
>
<CarbonHelpFilled
class="inline text-xxs text-gray-500 group-hover/tooltip:text-blue-600"
/>
</HoverTooltip>
</span>
<input
type="number"
name="top_k"
min="5"
max="100"
step="5"
class="w-20 rounded-lg border-2 border-gray-200 bg-gray-100 px-2 py-1"
placeholder={selectedModel?.parameters?.top_k?.toString() ?? "50"}
value={assistant?.generateSettings?.top_k ?? ""}
/>
</label>
</div>
</div>
</label>
<label>
<div class="mb-1 font-semibold">User start messages</div>
<div class="grid gap-1.5 text-sm md:grid-cols-2">
<input
name="exampleInput1"
placeholder="Start Message 1"
bind:value={inputMessage1}
class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2"
/>
<input
name="exampleInput2"
placeholder="Start Message 2"
bind:value={inputMessage2}
class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2"
/>
<input
name="exampleInput3"
placeholder="Start Message 3"
bind:value={inputMessage3}
class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2"
/>
<input
name="exampleInput4"
placeholder="Start Message 4"
bind:value={inputMessage4}
class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2"
/>
</div>
<p class="text-xs text-red-500">{getError("inputMessage1", form)}</p>
</label>
{#if selectedModel?.tools}
<div>
<span class="text-smd font-semibold"
>Tools
<CarbonTools class="inline text-xs text-purple-600" />
<span class="ml-1 rounded bg-gray-100 px-1 py-0.5 text-xxs font-normal text-gray-600"
>Experimental</span
>
</span>
<p class="text-xs text-gray-500">
Choose up to 3 community tools that will be used with this assistant.
</p>
</div>
<AssistantToolPicker bind:toolIds={tools} />
{/if}
{#if $page.data.enableAssistantsRAG}
<div class="flex flex-col flex-nowrap pb-4">
<span class="mt-2 text-smd font-semibold"
>Internet access
<IconInternet classNames="inline text-sm text-blue-600" />
{#if isHuggingChat}
<a
href="https://huggingface.co/spaces/huggingchat/chat-ui/discussions/385"
target="_blank"
class="ml-0.5 rounded bg-gray-100 px-1 py-0.5 text-xxs font-normal text-gray-700 underline decoration-gray-400"
>Give feedback</a
>
{/if}
</span>
<label class="mt-1">
<input
checked={!ragMode}
on:change={() => (ragMode = false)}
type="radio"
name="ragMode"
value={false}
/>
<span class="my-2 text-sm" class:font-semibold={!ragMode}> Default </span>
{#if !ragMode}
<span class="block text-xs text-gray-500">
Assistant will not use internet to do information retrieval and will respond faster.
Recommended for most Assistants.
</span>
{/if}
</label>
<label class="mt-1">
<input
checked={ragMode === "all"}
on:change={() => (ragMode = "all")}
type="radio"
name="ragMode"
value={"all"}
/>
<span class="my-2 text-sm" class:font-semibold={ragMode === "all"}> Web search </span>
{#if ragMode === "all"}
<span class="block text-xs text-gray-500">
Assistant will do a web search on each user request to find information.
</span>
{/if}
</label>
<label class="mt-1">
<input
checked={ragMode === "domains"}
on:change={() => (ragMode = "domains")}
type="radio"
name="ragMode"
value={false}
/>
<span class="my-2 text-sm" class:font-semibold={ragMode === "domains"}>
Domains search
</span>
</label>
{#if ragMode === "domains"}
<span class="mb-2 text-xs text-gray-500">
Specify domains and URLs that the application can search, separated by commas.
</span>
<input
name="ragDomainList"
class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2"
placeholder="wikipedia.org,bbc.com"
value={assistant?.rag?.allowedDomains?.join(",") ?? ""}
/>
<p class="text-xs text-red-500">{getError("ragDomainList", form)}</p>
{/if}
<label class="mt-1">
<input
checked={ragMode === "links"}
on:change={() => (ragMode = "links")}
type="radio"
name="ragMode"
value={false}
/>
<span class="my-2 text-sm" class:font-semibold={ragMode === "links"}>
Specific Links
</span>
</label>
{#if ragMode === "links"}
<span class="mb-2 text-xs text-gray-500">
Specify a maximum of 10 direct URLs that the Assistant will access. HTML & Plain Text
only, separated by commas
</span>
<input
name="ragLinkList"
class="w-full rounded-lg border-2 border-gray-200 bg-gray-100 p-2"
placeholder="https://raw.githubusercontent.com/huggingface/chat-ui/main/README.md"
value={assistant?.rag?.allowedLinks.join(",") ?? ""}
/>
<p class="text-xs text-red-500">{getError("ragLinkList", form)}</p>
{/if}
</div>
{/if}
</div>
<div class="relative col-span-1 flex h-full flex-col">
<div class="mb-1 flex justify-between text-sm">
<span class="block font-semibold"> Instructions (System Prompt) </span>
{#if dynamicPrompt && templateVariables.length}
<div class="relative">
<button
type="button"
class="peer rounded bg-blue-500/20 px-1 text-xs text-blue-600 focus:bg-blue-500/30 focus:text-blue-800 sm:text-sm"
>
{templateVariables.length} template variable{templateVariables.length > 1 ? "s" : ""}
</button>
<div
class="invisible absolute right-0 top-6 z-10 rounded-lg border bg-white p-2 text-xs shadow-lg peer-focus:visible hover:visible sm:w-96"
>
Will perform a GET request and inject the response into the prompt. Works better with
plain text, csv or json content.
{#each templateVariables as match}
<a href={match} target="_blank" class="text-gray-500 underline decoration-gray-300"
>{match}</a
>
{/each}
</div>
</div>
{/if}
</div>
<label class="pb-2 text-sm has-[:checked]:font-semibold">
<input type="checkbox" name="dynamicPrompt" bind:checked={dynamicPrompt} />
Dynamic Prompt
<p class="mb-2 text-xs font-normal text-gray-500">
Allow the use of template variables {"{{url=https://example.com/path}}"}
to insert dynamic content into your prompt by making GET requests to specified URLs on each
inference.
</p>
</label>
<div class="relative mb-20 flex h-full flex-col gap-2">
<textarea
name="preprompt"
class="min-h-[8lh] flex-1 rounded-lg border-2 border-gray-200 bg-gray-100 p-2 text-sm"
placeholder="You'll act as..."
bind:value={systemPrompt}
/>
{#if modelId}
{@const model = models.find((_model) => _model.id === modelId)}
{#if model?.tokenizer && systemPrompt}
<TokensCounter
classNames="absolute bottom-4 right-4"
prompt={systemPrompt}
modelTokenizer={model.tokenizer}
truncate={model?.parameters?.truncate}
/>
{/if}
{/if}
<p class="text-xs text-red-500">{getError("preprompt", form)}</p>
</div>
<div class="absolute bottom-6 flex w-full justify-end gap-2 md:right-0 md:w-fit">
<a
href={assistant ? `${base}/settings/assistants/${assistant?._id}` : `${base}/settings`}
class="flex items-center justify-center rounded-full bg-gray-200 px-5 py-2 font-semibold text-gray-600"
>
Cancel
</a>
<button
type="submit"
disabled={loading}
aria-disabled={loading}
class="flex items-center justify-center rounded-full bg-black px-8 py-2 font-semibold"
class:bg-gray-200={loading}
class:text-gray-600={loading}
class:text-white={!loading}
>
{assistant ? "Save" : "Create"}
</button>
</div>
</div>
</div>
</form>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/AnnouncementBanner.svelte
|
<script lang="ts">
export let title = "";
export let classNames = "";
</script>
<div class="flex items-center rounded-xl bg-gray-100 p-1 text-sm dark:bg-gray-800 {classNames}">
<span
class="from-primary-300 text-primary-700 dark:from-primary-900 dark:text-primary-400 mr-2 inline-flex items-center rounded-lg bg-gradient-to-br px-2 py-1 text-xxs font-medium uppercase leading-3"
>New</span
>
{title}
<div class="ml-auto shrink-0">
<slot />
</div>
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/OpenWebSearchResults.svelte
|
<script lang="ts">
import {
MessageWebSearchUpdateType,
type MessageWebSearchUpdate,
} from "$lib/types/MessageUpdate";
import { isMessageWebSearchSourcesUpdate } from "$lib/utils/messageUpdates";
import CarbonError from "~icons/carbon/error-filled";
import EosIconsLoading from "~icons/eos-icons/loading";
import IconInternet from "./icons/IconInternet.svelte";
import CarbonCaretDown from "~icons/carbon/caret-down";
export let webSearchMessages: MessageWebSearchUpdate[] = [];
$: sources = webSearchMessages.find(isMessageWebSearchSourcesUpdate)?.sources;
$: lastMessage = webSearchMessages
.filter((update) => update.subtype !== MessageWebSearchUpdateType.Sources)
.at(-1) as MessageWebSearchUpdate;
$: errored = webSearchMessages.some(
(update) => update.subtype === MessageWebSearchUpdateType.Error
);
$: loading = !sources && !errored;
</script>
<details
class="group flex w-fit max-w-full flex-col rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900"
>
<summary
class="grid min-w-72 cursor-pointer select-none grid-cols-[40px,1fr,24px] items-center gap-2.5 rounded-xl p-2 group-open:rounded-b-none hover:bg-gray-500/10"
>
<div
class="relative grid aspect-square place-content-center overflow-hidden rounded-lg bg-gray-100 dark:bg-gray-800"
>
<svg
class="absolute inset-0 text-gray-300 transition-opacity dark:text-gray-700 {loading
? 'opacity-100'
: 'opacity-0'}"
width="40"
height="40"
viewBox="0 0 38 38"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
class="loading-path"
d="M8 2.5H30C30 2.5 35.5 2.5 35.5 8V30C35.5 30 35.5 35.5 30 35.5H8C8 35.5 2.5 35.5 2.5 30V8C2.5 8 2.5 2.5 8 2.5Z"
stroke="currentColor"
stroke-width="1"
stroke-linecap="round"
id="shape"
/>
</svg>
<IconInternet classNames="relative fill-current text-xl" />
</div>
<dl class="leading-4">
<dd class="text-sm">Web Search</dd>
<dt class="flex items-center gap-1 truncate whitespace-nowrap text-[.82rem] text-gray-400">
{#if sources}
Completed
{:else}
{"message" in lastMessage ? lastMessage.message : "An error occurred"}
{/if}
</dt>
</dl>
<CarbonCaretDown class="size-6 text-gray-400 transition-transform group-open:rotate-180" />
</summary>
<div class="content px-5 pb-5 pt-4">
{#if webSearchMessages.length === 0}
<div class="mx-auto w-fit">
<EosIconsLoading class="mb-3 h-4 w-4" />
</div>
{:else}
<ol>
{#each webSearchMessages as message}
{#if message.subtype === MessageWebSearchUpdateType.Update}
<li class="group border-l pb-6 last:!border-transparent last:pb-0 dark:border-gray-800">
<div class="flex items-start">
<div
class="-ml-1.5 h-3 w-3 flex-none rounded-full bg-gray-200 dark:bg-gray-600 {loading
? 'group-last:animate-pulse group-last:bg-gray-300 group-last:dark:bg-gray-500'
: ''}"
/>
<h3 class="text-md -mt-1.5 pl-2.5 text-gray-800 dark:text-gray-100">
{message.message}
</h3>
</div>
{#if message.args}
<p class="mt-0.5 pl-4 text-gray-500 dark:text-gray-400">
{message.args}
</p>
{/if}
</li>
{:else if message.subtype === MessageWebSearchUpdateType.Error}
<li class="group border-l pb-6 last:!border-transparent last:pb-0 dark:border-gray-800">
<div class="flex items-start">
<CarbonError
class="-ml-1.5 h-3 w-3 flex-none scale-110 text-red-700 dark:text-red-500"
/>
<h3 class="text-md -mt-1.5 pl-2.5 text-red-700 dark:text-red-500">
{message.message}
</h3>
</div>
{#if message.args}
<p class="mt-0.5 pl-4 text-gray-500 dark:text-gray-400">
{message.args}
</p>
{/if}
</li>
{/if}
{/each}
</ol>
{/if}
</div>
</details>
<style>
details summary::-webkit-details-marker {
display: none;
}
.loading-path {
stroke-dasharray: 61.45;
animation: loading 2s linear infinite;
}
@keyframes loading {
to {
stroke-dashoffset: 122.9;
}
}
</style>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/UploadBtn.svelte
|
<script lang="ts">
import CarbonUpload from "~icons/carbon/upload";
export let classNames = "";
export let files: File[];
export let mimeTypes: string[];
/**
* Due to a bug with Svelte, we cannot use bind:files with multiple
* So we use this workaround
**/
const onFileChange = (e: Event) => {
if (!e.target) return;
const target = e.target as HTMLInputElement;
files = [...files, ...(target.files ?? [])];
};
</script>
<button
class="btn relative h-8 rounded-lg border bg-white px-3 py-1 text-sm text-gray-500 shadow-sm hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 {classNames}"
>
<input
class="absolute w-full cursor-pointer opacity-0"
aria-label="Upload file"
type="file"
on:change={onFileChange}
accept={mimeTypes.join(",")}
/>
<CarbonUpload class="mr-2 text-xxs" /> Upload file
</button>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/ModelCardMetadata.svelte
|
<script lang="ts">
import CarbonEarth from "~icons/carbon/earth";
import CarbonArrowUpRight from "~icons/carbon/arrow-up-right";
import BIMeta from "~icons/bi/meta";
import CarbonCode from "~icons/carbon/code";
import type { Model } from "$lib/types/Model";
export let model: Pick<
Model,
"name" | "datasetName" | "websiteUrl" | "modelUrl" | "datasetUrl" | "hasInferenceAPI"
>;
export let variant: "light" | "dark" = "light";
</script>
<div
class="flex items-center gap-5 rounded-xl bg-gray-100 px-3 py-2 text-xs sm:text-sm
{variant === 'dark'
? 'text-gray-600 dark:bg-gray-800 dark:text-gray-300'
: 'text-gray-800 dark:bg-gray-100 dark:text-gray-600'}"
>
<a
href={model.modelUrl || "https://huggingface.co/" + model.name}
target="_blank"
rel="noreferrer"
class="flex items-center hover:underline"
><CarbonArrowUpRight class="mr-1.5 shrink-0 text-xs text-gray-400" />
Model
<div class="max-sm:hidden"> page</div></a
>
{#if model.datasetName || model.datasetUrl}
<a
href={model.datasetUrl || "https://huggingface.co/datasets/" + model.datasetName}
target="_blank"
rel="noreferrer"
class="flex items-center hover:underline"
><CarbonArrowUpRight class="mr-1.5 shrink-0 text-xs text-gray-400" />
Dataset
<div class="max-sm:hidden"> page</div></a
>
{/if}
{#if model.hasInferenceAPI}
<a
href={"https://huggingface.co/playground?modelId=" + model.name}
target="_blank"
rel="noreferrer"
class="flex items-center hover:underline"
><CarbonCode class="mr-1.5 shrink-0 text-xs text-gray-400" />
API
</a>
{/if}
{#if model.websiteUrl}
<a
href={model.websiteUrl}
target="_blank"
class="ml-auto flex items-center hover:underline"
rel="noreferrer"
>
{#if model.name.startsWith("meta-llama/Meta-Llama")}
<BIMeta class="mr-1.5 shrink-0 text-xs text-gray-400" />
Built with Llama
{:else}
<CarbonEarth class="mr-1.5 shrink-0 text-xs text-gray-400" />
Website
{/if}
</a>
{/if}
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/ContinueBtn.svelte
|
<script lang="ts">
import CarbonContinue from "~icons/carbon/continue";
export let classNames = "";
</script>
<button
type="button"
on:click
class="btn flex h-8 rounded-lg border bg-white px-3 py-1 text-gray-500 shadow-sm transition-all hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600 {classNames}"
>
<CarbonContinue class="mr-2 text-xs " /> Continue
</button>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/HoverTooltip.svelte
|
<script lang="ts">
export let label = "";
</script>
<div class="group/tooltip md:relative">
<slot />
<div
class="invisible absolute z-10 w-64 whitespace-normal rounded-md bg-black p-2 text-center text-white group-hover/tooltip:visible group-active/tooltip:visible max-sm:left-1/2 max-sm:-translate-x-1/2"
>
{label}
</div>
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/Modal.svelte
|
<script lang="ts">
import { createEventDispatcher, onDestroy, onMount } from "svelte";
import { cubicOut } from "svelte/easing";
import { fade } from "svelte/transition";
import Portal from "./Portal.svelte";
import { browser } from "$app/environment";
export let width = "max-w-sm";
let backdropEl: HTMLDivElement;
let modalEl: HTMLDivElement;
const dispatch = createEventDispatcher<{ close: void }>();
function handleKeydown(event: KeyboardEvent) {
// close on ESC
if (event.key === "Escape") {
event.preventDefault();
dispatch("close");
}
}
function handleBackdropClick(event: MouseEvent) {
if (window?.getSelection()?.toString()) {
return;
}
if (event.target === backdropEl) {
dispatch("close");
}
}
onMount(() => {
document.getElementById("app")?.setAttribute("inert", "true");
modalEl.focus();
});
onDestroy(() => {
if (!browser) return;
// remove inert attribute if this is the last modal
if (document.querySelectorAll('[role="dialog"]:not(#app *)').length === 1) {
document.getElementById("app")?.removeAttribute("inert");
}
});
</script>
<Portal>
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<div
role="presentation"
tabindex="-1"
bind:this={backdropEl}
on:click|stopPropagation={handleBackdropClick}
transition:fade|local={{ easing: cubicOut, duration: 300 }}
class="fixed inset-0 z-40 flex items-center justify-center bg-black/80 p-8 backdrop-blur-sm dark:bg-black/50"
>
<div
role="dialog"
tabindex="-1"
bind:this={modalEl}
on:keydown={handleKeydown}
class="max-h-[90dvh] overflow-y-auto overflow-x-hidden rounded-2xl bg-white shadow-2xl outline-none sm:-mt-10 {width}"
>
<slot />
</div>
</div>
</Portal>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/LoginModal.svelte
|
<script lang="ts">
import { base } from "$app/paths";
import { page } from "$app/stores";
import { env as envPublic } from "$env/dynamic/public";
import LogoHuggingFaceBorderless from "$lib/components/icons/LogoHuggingFaceBorderless.svelte";
import Modal from "$lib/components/Modal.svelte";
import { useSettingsStore } from "$lib/stores/settings";
import { cookiesAreEnabled } from "$lib/utils/cookiesAreEnabled";
import Logo from "./icons/Logo.svelte";
const settings = useSettingsStore();
</script>
<Modal on:close>
<div
class="from-primary-500/40 via-primary-500/10 to-primary-500/0 flex w-full flex-col items-center gap-6 bg-gradient-to-b px-5 pb-8 pt-9 text-center"
>
<h2 class="flex items-center text-2xl font-semibold text-gray-800">
<Logo classNames="mr-1" />
{envPublic.PUBLIC_APP_NAME}
</h2>
<p class="text-balance text-lg font-semibold leading-snug text-gray-800">
{envPublic.PUBLIC_APP_DESCRIPTION}
</p>
<p class="text-balance rounded-xl border bg-white/80 p-2 text-base text-gray-800">
{envPublic.PUBLIC_APP_GUEST_MESSAGE}
</p>
<form
action="{base}/{$page.data.loginRequired ? 'login' : 'settings'}"
target="_parent"
method="POST"
class="flex w-full flex-col items-center gap-2"
>
{#if $page.data.loginRequired}
<button
type="submit"
class="flex w-full flex-wrap items-center justify-center whitespace-nowrap rounded-full bg-black px-5 py-2 text-center text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900"
>
Sign in
{#if envPublic.PUBLIC_APP_NAME === "HuggingChat"}
<span class="flex items-center">
with <LogoHuggingFaceBorderless classNames="text-xl mr-1 ml-1.5" /> Hugging Face
</span>
{/if}
</button>
{:else}
<button
class="flex w-full items-center justify-center whitespace-nowrap rounded-full border-2 border-black bg-black px-5 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-gray-900"
on:click={(e) => {
if (!cookiesAreEnabled()) {
e.preventDefault();
window.open(window.location.href, "_blank");
}
$settings.ethicsModalAccepted = true;
}}
>
Start chatting
</button>
{/if}
</form>
</div>
</Modal>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/ToolsMenu.svelte
|
<script lang="ts">
import { base } from "$app/paths";
import { page } from "$app/stores";
import { clickOutside } from "$lib/actions/clickOutside";
import { useSettingsStore } from "$lib/stores/settings";
import type { ToolFront } from "$lib/types/Tool";
import { isHuggingChat } from "$lib/utils/isHuggingChat";
import IconTool from "./icons/IconTool.svelte";
import CarbonInformation from "~icons/carbon/information";
import CarbonGlobe from "~icons/carbon/earth-filled";
export let loading = false;
const settings = useSettingsStore();
let detailsEl: HTMLDetailsElement;
// active tools are all the checked tools, either from settings or on by default
$: activeToolCount = $page.data.tools.filter(
(tool: ToolFront) =>
// community tools are always on by default
tool.type === "community" || $settings?.tools?.includes(tool._id)
).length;
async function setAllTools(value: boolean) {
const configToolsIds = $page.data.tools
.filter((t: ToolFront) => t.type === "config")
.map((t: ToolFront) => t._id);
if (value) {
await settings.instantSet({
tools: Array.from(new Set([...configToolsIds, ...($settings?.tools ?? [])])),
});
} else {
await settings.instantSet({
tools: [],
});
}
}
$: allToolsEnabled = activeToolCount === $page.data.tools.length;
$: tools = $page.data.tools;
</script>
<details
class="group relative bottom-0 h-full min-h-8"
bind:this={detailsEl}
use:clickOutside={() => {
if (detailsEl.hasAttribute("open")) {
detailsEl.removeAttribute("open");
}
}}
>
<summary
class="absolute bottom-0 flex h-8
cursor-pointer select-none items-center gap-1 rounded-lg border bg-white px-2 py-1.5 shadow-sm hover:shadow-none dark:border-gray-800 dark:bg-gray-900"
>
<IconTool classNames="dark:text-purple-600" />
Tools
<span class="text-gray-400 dark:text-gray-500"> ({activeToolCount}) </span>
</summary>
<div
class="absolute bottom-10 h-max w-max select-none items-center gap-1 rounded-lg border bg-white p-0.5 shadow-sm dark:border-gray-800 dark:bg-gray-900"
>
<div class="grid grid-cols-2 gap-x-6 gap-y-1 p-3">
<div class="col-span-2 flex items-center gap-1.5 text-sm text-gray-500">
Available tools
{#if isHuggingChat}
<a
href="https://huggingface.co/spaces/huggingchat/chat-ui/discussions/470"
target="_blank"
class="hover:brightness-0 dark:hover:brightness-200"
><CarbonInformation class="text-xs" /></a
>
{/if}
<button
class="ml-auto text-xs underline"
on:click|stopPropagation={() => setAllTools(!allToolsEnabled)}
>
{#if allToolsEnabled}
Disable all
{:else}
Enable all
{/if}
</button>
</div>
{#if $page.data.enableCommunityTools}
<a
href="{base}/tools"
class="col-span-2 my-1 h-fit w-fit items-center justify-center rounded-full bg-purple-500/20 px-2.5 py-1.5 text-sm hover:bg-purple-500/30"
>
<span class="mr-1 rounded-full bg-purple-700 px-1.5 py-1 text-xs font-bold uppercase">
new
</span>
Browse community tools ({$page.data.communityToolCount ?? 0})
</a>
{/if}
{#each tools as tool}
{@const isChecked = $settings?.tools?.includes(tool._id)}
<div class="flex items-center gap-1.5">
{#if tool.type === "community"}
<input
type="checkbox"
id={tool._id}
checked={true}
class="rounded-xs font-semibold accent-purple-500 hover:accent-purple-600"
on:click|stopPropagation|preventDefault={async () => {
await settings.instantSet({
tools: $settings?.tools?.filter((t) => t !== tool._id) ?? [],
});
}}
/>
{:else}
<input
type="checkbox"
id={tool._id}
checked={isChecked}
disabled={loading}
on:click|stopPropagation={async () => {
if (isChecked) {
await settings.instantSet({
tools: ($settings?.tools ?? []).filter((t) => t !== tool._id),
});
} else {
await settings.instantSet({
tools: [...($settings?.tools ?? []), tool._id],
});
}
}}
/>
{/if}
<label class="cursor-pointer" for={tool._id}>{tool.displayName}</label>
{#if tool.type === "community"}
<a href="{base}/tools/{tool._id}" class="text-purple-600 hover:text-purple-700">
<CarbonGlobe />
</a>
{/if}
</div>
{/each}
</div>
</div>
</details>
<style>
details summary::-webkit-details-marker {
display: none;
}
</style>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/Toast.svelte
|
<script lang="ts">
import { fade } from "svelte/transition";
import IconDazzled from "$lib/components/icons/IconDazzled.svelte";
export let message = "";
</script>
<div
transition:fade|global={{ duration: 300 }}
class="pointer-events-none fixed right-0 top-12 z-20 bg-gradient-to-bl from-red-500/20 via-red-500/0 to-red-500/0 pb-36 pl-36 pr-2 pt-2 md:top-0 md:pr-8 md:pt-5"
>
<div
class="pointer-events-auto flex items-center rounded-full bg-white/90 px-3 py-1 shadow-sm dark:bg-gray-900/80"
>
<IconDazzled classNames="text-2xl mr-2" />
<h2 class="font-semibold">{message}</h2>
</div>
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/components/Tooltip.svelte
|
<script lang="ts">
export let classNames = "";
export let label = "Copied";
export let position = "left-1/2 top-full transform -translate-x-1/2 translate-y-2";
</script>
<div
class="
pointer-events-none absolute rounded bg-black px-2 py-1 font-normal leading-tight text-white shadow transition-opacity
{position}
{classNames}
"
>
<div
class="absolute bottom-full left-1/2 h-0 w-0 -translate-x-1/2 transform border-4 border-t-0 border-black"
style="
border-left-color: transparent;
border-right-color: transparent;
"
/>
{label}
</div>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/chat/ModelSwitch.svelte
|
<script lang="ts">
import { invalidateAll } from "$app/navigation";
import { page } from "$app/stores";
import { base } from "$app/paths";
import type { Model } from "$lib/types/Model";
export let models: Model[];
export let currentModel: Model;
let selectedModelId = models.map((m) => m.id).includes(currentModel.id)
? currentModel.id
: models[0].id;
async function handleModelChange() {
if (!$page.params.id) return;
try {
const response = await fetch(`${base}/conversation/${$page.params.id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ model: selectedModelId }),
});
if (!response.ok) {
throw new Error("Failed to update model");
}
await invalidateAll();
} catch (error) {
console.error(error);
}
}
</script>
<div
class="mx-auto mt-0 flex w-fit flex-col items-center justify-center gap-2 rounded-lg border border-gray-200 bg-gray-500/20 p-4 dark:border-gray-800"
>
<span>
This model is no longer available. Switch to a new one to continue this conversation:
</span>
<div class="flex items-center space-x-2">
<select
bind:value={selectedModelId}
class="rounded-md bg-gray-100 px-2 py-1 dark:bg-gray-900 max-sm:max-w-32"
>
{#each models as model}
<option value={model.id}>{model.name}</option>
{/each}
</select>
<button
on:click={handleModelChange}
disabled={selectedModelId === currentModel.id}
class="rounded-md bg-gray-100 px-2 py-1 dark:bg-gray-900"
>
Accept
</button>
</div>
</div>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/chat/AssistantIntroduction.svelte
|
<script lang="ts">
import { createEventDispatcher } from "svelte";
import { base } from "$app/paths";
import { goto } from "$app/navigation";
import type { Model } from "$lib/types/Model";
import type { Assistant } from "$lib/types/Assistant";
import { useSettingsStore } from "$lib/stores/settings";
import { formatUserCount } from "$lib/utils/formatUserCount";
import IconGear from "~icons/bi/gear-fill";
import IconInternet from "../icons/IconInternet.svelte";
import CarbonExport from "~icons/carbon/export";
import CarbonCheckmark from "~icons/carbon/checkmark";
import CarbonRenew from "~icons/carbon/renew";
import CarbonUserMultiple from "~icons/carbon/user-multiple";
import CarbonTools from "~icons/carbon/tools";
import { share } from "$lib/utils/share";
import { env as envPublic } from "$env/dynamic/public";
import { page } from "$app/stores";
export let models: Model[];
export let assistant: Pick<
Assistant,
| "avatar"
| "name"
| "rag"
| "dynamicPrompt"
| "modelId"
| "createdByName"
| "exampleInputs"
| "_id"
| "description"
| "userCount"
| "tools"
>;
const dispatch = createEventDispatcher<{ message: string }>();
$: hasRag =
assistant?.rag?.allowAllDomains ||
(assistant?.rag?.allowedDomains?.length ?? 0) > 0 ||
(assistant?.rag?.allowedLinks?.length ?? 0) > 0 ||
assistant?.dynamicPrompt;
const prefix =
envPublic.PUBLIC_SHARE_PREFIX || `${envPublic.PUBLIC_ORIGIN || $page.url.origin}${base}`;
$: shareUrl = `${prefix}/assistant/${assistant?._id}`;
let isCopied = false;
const settings = useSettingsStore();
</script>
<div class="flex h-full w-full flex-col content-center items-center justify-center pb-52">
<div
class="relative mt-auto rounded-2xl bg-gray-100 text-gray-600 dark:border-gray-800 dark:bg-gray-800/60 dark:text-gray-300"
>
<div
class="mt-3 flex min-w-[80dvw] items-center gap-4 p-4 pr-1 sm:min-w-[440px] md:p-8 xl:gap-8"
>
{#if assistant.avatar}
<img
src={`${base}/settings/assistants/${assistant._id.toString()}/avatar.jpg?hash=${
assistant.avatar
}`}
alt="avatar"
class="size-16 flex-none rounded-full object-cover max-sm:self-start md:size-32"
/>
{:else}
<div
class="flex size-12 flex-none items-center justify-center rounded-full bg-gray-300 object-cover text-xl font-bold uppercase text-gray-500 dark:bg-gray-600 max-sm:self-start sm:text-4xl md:size-32"
>
{assistant?.name[0]}
</div>
{/if}
<div class="flex h-full flex-col gap-2 text-balance">
<p class="-mb-1">Assistant</p>
<p class="text-xl font-bold sm:text-2xl">{assistant.name}</p>
{#if assistant.description}
<p class="line-clamp-6 text-sm text-gray-500 dark:text-gray-400">
{assistant.description}
</p>
{/if}
{#if assistant?.tools?.length}
<div
class="flex h-5 w-fit items-center gap-1 rounded-full bg-purple-500/10 pl-1 pr-2 text-xs"
title="This assistant uses the websearch."
>
<CarbonTools class="text-sm text-purple-600" />
Has tools
</div>
{/if}
{#if hasRag}
<div
class="flex h-5 w-fit items-center gap-1 rounded-full bg-blue-500/10 pl-1 pr-2 text-xs"
title="This assistant uses the websearch."
>
<IconInternet classNames="text-sm text-blue-600" />
Has internet access
</div>
{/if}
{#if assistant.createdByName}
<div class="pt-1 text-sm text-gray-400 dark:text-gray-500">
Created by
<a class="hover:underline" href="{base}/assistants?user={assistant.createdByName}">
{assistant.createdByName}
</a>
{#if assistant.userCount && assistant.userCount > 1}
<span class="mx-1">·</span>
<div
class="inline-flex items-baseline gap-1 text-sm text-gray-400 dark:text-gray-500"
title="Number of users"
>
<CarbonUserMultiple class="text-xxs" />{formatUserCount(assistant.userCount)} users
</div>
{/if}
</div>
{/if}
</div>
</div>
<div class="absolute right-3 top-3 md:right-4 md:top-4">
<div class="flex flex-row items-center gap-1">
<button
class="flex h-7 items-center gap-1.5 rounded-full border bg-white px-2.5 py-1 text-gray-800 shadow-sm hover:shadow-inner dark:border-gray-700 dark:bg-gray-700 dark:text-gray-300/90 dark:hover:bg-gray-800 max-sm:px-1.5 md:text-sm"
on:click={() => {
if (!isCopied) {
share(shareUrl, assistant.name);
isCopied = true;
setTimeout(() => {
isCopied = false;
}, 2000);
}
}}
>
{#if isCopied}
<CarbonCheckmark class="text-xxs text-green-600 max-sm:text-xs" />
<span class="text-green-600 max-sm:hidden"> Link copied </span>
{:else}
<CarbonExport class="text-xxs max-sm:text-xs" />
<span class="max-sm:hidden"> Share </span>
{/if}
</button>
<a
href="{base}/settings/assistants/{assistant._id.toString()}"
class="flex h-7 items-center gap-1.5 rounded-full border bg-white px-2.5 py-1 text-gray-800 shadow-sm hover:shadow-inner dark:border-gray-700 dark:bg-gray-700 dark:text-gray-300/90 dark:hover:bg-gray-800 md:text-sm"
><IconGear class="text-xxs" />Settings</a
>
</div>
</div>
<button
on:click={() => {
settings.instantSet({
activeModel: models[0].name,
});
goto(`${base}/`);
}}
class="absolute -bottom-6 right-2 inline-flex items-center justify-center text-xs text-gray-600 underline hover:brightness-50 dark:text-gray-400 dark:hover:brightness-110"
>
<CarbonRenew class="mr-1.5 text-xxs" /> Reset to default model
</button>
</div>
{#if assistant.exampleInputs}
<div class="mx-auto mt-auto w-full gap-8 sm:-mb-8">
<div class="md:col-span-2 md:mt-6">
<div
class="grid grid-cols-1 gap-3 {assistant.exampleInputs.length > 1
? 'md:grid-cols-2'
: ''}"
>
{#each assistant.exampleInputs as example}
<button
type="button"
class="truncate whitespace-nowrap rounded-xl border bg-gray-50 px-3 py-2 text-left text-smd text-gray-600 hover:bg-gray-100 dark:border-gray-800 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"
on:click={() => dispatch("message", example)}
>
{example}
</button>
{/each}
</div>
</div>
</div>
{/if}
</div>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/chat/ChatIntroduction.svelte
|
<script lang="ts">
import { env as envPublic } from "$env/dynamic/public";
import Logo from "$lib/components/icons/Logo.svelte";
import { createEventDispatcher } from "svelte";
import IconGear from "~icons/bi/gear-fill";
import AnnouncementBanner from "../AnnouncementBanner.svelte";
import type { Model } from "$lib/types/Model";
import ModelCardMetadata from "../ModelCardMetadata.svelte";
import { base } from "$app/paths";
import JSON5 from "json5";
export let currentModel: Model;
const announcementBanners = envPublic.PUBLIC_ANNOUNCEMENT_BANNERS
? JSON5.parse(envPublic.PUBLIC_ANNOUNCEMENT_BANNERS)
: [];
const dispatch = createEventDispatcher<{ message: string }>();
</script>
<div class="my-auto grid gap-8 lg:grid-cols-3">
<div class="lg:col-span-1">
<div>
<div class="mb-3 flex items-center text-2xl font-semibold">
<Logo classNames="mr-1 flex-none" />
{envPublic.PUBLIC_APP_NAME}
<div
class="ml-3 flex h-6 items-center rounded-lg border border-gray-100 bg-gray-50 px-2 text-base text-gray-400 dark:border-gray-700/60 dark:bg-gray-800"
>
v{envPublic.PUBLIC_VERSION}
</div>
</div>
<p class="text-base text-gray-600 dark:text-gray-400">
{envPublic.PUBLIC_APP_DESCRIPTION ||
"Making the community's best AI chat models available to everyone."}
</p>
</div>
</div>
<div class="lg:col-span-2 lg:pl-24">
{#each announcementBanners as banner}
<AnnouncementBanner classNames="mb-4" title={banner.title}>
<a
target="_blank"
href={banner.linkHref}
class="mr-2 flex items-center underline hover:no-underline">{banner.linkTitle}</a
>
</AnnouncementBanner>
{/each}
<div class="overflow-hidden rounded-xl border dark:border-gray-800">
<div class="flex p-3">
<div>
<div class="text-sm text-gray-600 dark:text-gray-400">Current Model</div>
<div class="flex items-center gap-1.5 font-semibold max-sm:text-smd">
{#if currentModel.logoUrl}
<img
class=" overflown aspect-square size-4 rounded border dark:border-gray-700"
src={currentModel.logoUrl}
alt=""
/>
{:else}
<div class="size-4 rounded border border-transparent bg-gray-300 dark:bg-gray-800" />
{/if}
{currentModel.displayName}
</div>
</div>
<a
href="{base}/settings/{currentModel.id}"
aria-label="Settings"
class="btn ml-auto flex h-7 w-7 self-start rounded-full bg-gray-100 p-1 text-xs hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-800 dark:hover:bg-gray-600"
><IconGear /></a
>
</div>
<ModelCardMetadata variant="dark" model={currentModel} />
</div>
</div>
{#if currentModel.promptExamples}
<div class="lg:col-span-3 lg:mt-6">
<p class="mb-3 text-gray-600 dark:text-gray-300">Examples</p>
<div class="grid gap-3 lg:grid-cols-3 lg:gap-5">
{#each currentModel.promptExamples as example}
<button
type="button"
class="rounded-xl border bg-gray-50 p-3 text-gray-600 hover:bg-gray-100 dark:border-gray-800 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700 max-xl:text-sm xl:p-3.5"
on:click={() => dispatch("message", example.prompt)}
>
{example.title}
</button>
{/each}
</div>
</div>{/if}
<div class="h-40 sm:h-24" />
</div>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/chat/UploadedFile.svelte
|
<script lang="ts">
import { createEventDispatcher } from "svelte";
import { page } from "$app/stores";
import type { MessageFile } from "$lib/types/Message";
import CarbonClose from "~icons/carbon/close";
import CarbonDocumentBlank from "~icons/carbon/document-blank";
import CarbonDownload from "~icons/carbon/download";
import CarbonDocument from "~icons/carbon/document";
import Modal from "../Modal.svelte";
import AudioPlayer from "../players/AudioPlayer.svelte";
import EosIconsLoading from "~icons/eos-icons/loading";
import { base } from "$app/paths";
export let file: MessageFile;
export let canClose = true;
$: showModal = false;
$: urlNotTrailing = $page.url.pathname.replace(/\/$/, "");
const dispatch = createEventDispatcher<{ close: void }>();
function truncateMiddle(text: string, maxLength: number): string {
if (text.length <= maxLength) {
return text;
}
const halfLength = Math.floor((maxLength - 1) / 2);
const start = text.substring(0, halfLength);
const end = text.substring(text.length - halfLength);
return `${start}…${end}`;
}
const isImage = (mime: string) =>
mime.startsWith("image/") || mime === "webp" || mime === "jpeg" || mime === "png";
const isAudio = (mime: string) =>
mime.startsWith("audio/") || mime === "mp3" || mime === "wav" || mime === "x-wav";
const isVideo = (mime: string) =>
mime.startsWith("video/") || mime === "mp4" || mime === "x-mpeg";
const isPlainText = (mime: string) =>
mime === "text/plain" ||
mime === "text/csv" ||
mime === "text/markdown" ||
mime === "application/json" ||
mime === "application/xml" ||
mime === "application/vnd.chatui.clipboard";
$: isClickable = isImage(file.mime) || isPlainText(file.mime);
</script>
{#if showModal && isClickable}
<!-- show the image file full screen, click outside to exit -->
<Modal width="sm:max-w-[800px]" on:close={() => (showModal = false)}>
{#if isImage(file.mime)}
{#if file.type === "hash"}
<img
src={urlNotTrailing + "/output/" + file.value}
alt="input from user"
class="aspect-auto"
/>
{:else}
<!-- handle the case where this is a base64 encoded image -->
<img
src={`data:${file.mime};base64,${file.value}`}
alt="input from user"
class="aspect-auto"
/>
{/if}
{:else if isPlainText(file.mime)}
<div class="relative flex h-full w-full flex-col gap-4 p-4">
<h3 class="-mb-4 pt-2 text-xl font-bold">{file.name}</h3>
{#if file.mime === "application/vnd.chatui.clipboard"}
<p class="text-sm text-gray-500">
If you prefer to inject clipboard content directly in the chat, you can disable this
feature in the
<a href={`${base}/settings`} class="underline">settings page</a>.
</p>
{/if}
<button
class="absolute right-4 top-4 text-xl text-gray-500 hover:text-gray-800"
on:click={() => (showModal = false)}
>
<CarbonClose class="text-xl" />
</button>
{#if file.type === "hash"}
{#await fetch(urlNotTrailing + "/output/" + file.value).then((res) => res.text())}
<div class="flex h-full w-full items-center justify-center">
<EosIconsLoading class="text-xl" />
</div>
{:then result}
<pre
class="w-full whitespace-pre-wrap break-words pt-0 text-sm"
class:font-sans={file.mime === "text/plain" ||
file.mime === "application/vnd.chatui.clipboard"}
class:font-mono={file.mime !== "text/plain" &&
file.mime !== "application/vnd.chatui.clipboard"}>{result}</pre>
{/await}
{:else}
<pre
class="w-full whitespace-pre-wrap break-words pt-0 text-sm"
class:font-sans={file.mime === "text/plain" ||
file.mime === "application/vnd.chatui.clipboard"}
class:font-mono={file.mime !== "text/plain" &&
file.mime !== "application/vnd.chatui.clipboard"}>{atob(file.value)}</pre>
{/if}
</div>
{/if}
</Modal>
{/if}
<button on:click={() => (showModal = true)} disabled={!isClickable} class:clickable={isClickable}>
<div class="group relative flex items-center rounded-xl shadow-sm">
{#if isImage(file.mime)}
<div class="size-48 overflow-hidden rounded-xl">
<img
src={file.type === "base64"
? `data:${file.mime};base64,${file.value}`
: urlNotTrailing + "/output/" + file.value}
alt={file.name}
class="h-full w-full bg-gray-200 object-cover dark:bg-gray-800"
/>
</div>
{:else if isAudio(file.mime)}
<AudioPlayer
src={file.type === "base64"
? `data:${file.mime};base64,${file.value}`
: urlNotTrailing + "/output/" + file.value}
name={truncateMiddle(file.name, 28)}
/>
{:else if isVideo(file.mime)}
<div
class="border-1 w-72 overflow-clip rounded-xl border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900"
>
<!-- svelte-ignore a11y-media-has-caption -->
<video
src={file.type === "base64"
? `data:${file.mime};base64,${file.value}`
: urlNotTrailing + "/output/" + file.value}
controls
/>
</div>
{:else if isPlainText(file.mime)}
<div
class="flex h-14 w-72 items-center gap-2 overflow-hidden rounded-xl border border-gray-200 bg-white p-2 dark:border-gray-800 dark:bg-gray-900"
class:hoverable={isClickable}
>
<div
class="grid size-10 flex-none place-items-center rounded-lg bg-gray-100 dark:bg-gray-800"
>
<CarbonDocument class="text-base text-gray-700 dark:text-gray-300" />
</div>
<dl class="flex flex-col items-start truncate leading-tight">
<dd class="text-sm">
{truncateMiddle(file.name, 28)}
</dd>
{#if file.mime === "application/vnd.chatui.clipboard"}
<dt class="text-xs text-gray-400">Clipboard source</dt>
{:else}
<dt class="text-xs text-gray-400">{file.mime}</dt>
{/if}
</dl>
</div>
{:else if file.mime === "octet-stream"}
<div
class="flex h-14 w-72 items-center gap-2 overflow-hidden rounded-xl border border-gray-200 bg-white p-2 dark:border-gray-800 dark:bg-gray-900"
class:hoverable={isClickable}
>
<div
class="grid size-10 flex-none place-items-center rounded-lg bg-gray-100 dark:bg-gray-800"
>
<CarbonDocumentBlank class="text-base text-gray-700 dark:text-gray-300" />
</div>
<dl class="flex flex-grow flex-col truncate leading-tight">
<dd class="text-sm">
{truncateMiddle(file.name, 28)}
</dd>
<dt class="text-xs text-gray-400">File type could not be determined</dt>
</dl>
<a
href={file.type === "base64"
? `data:application/octet-stream;base64,${file.value}`
: urlNotTrailing + "/output/" + file.value}
download={file.name}
class="ml-auto flex-none"
>
<CarbonDownload class="text-base text-gray-700 dark:text-gray-300" />
</a>
</div>
{:else}
<div
class="flex h-14 w-72 items-center gap-2 overflow-hidden rounded-xl border border-gray-200 bg-white p-2 dark:border-gray-800 dark:bg-gray-900"
class:hoverable={isClickable}
>
<div
class="grid size-10 flex-none place-items-center rounded-lg bg-gray-100 dark:bg-gray-800"
>
<CarbonDocumentBlank class="text-base text-gray-700 dark:text-gray-300" />
</div>
<dl class="flex flex-col items-start truncate leading-tight">
<dd class="text-sm">
{truncateMiddle(file.name, 28)}
</dd>
<dt class="text-xs text-gray-400">{file.mime}</dt>
</dl>
</div>
{/if}
<!-- add a button on top that removes the image -->
{#if canClose}
<button
class="absolute -right-2 -top-2 z-10 grid size-6 place-items-center rounded-full border bg-black group-hover:visible dark:border-gray-700"
class:invisible={navigator.maxTouchPoints === 0}
on:click|stopPropagation|preventDefault={() => dispatch("close")}
>
<CarbonClose class=" text-xs text-white" />
</button>
{/if}
</div>
</button>
<style lang="postcss">
.hoverable {
@apply hover:bg-gray-500/10;
}
</style>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/chat/MarkdownRenderer.svelte
|
<script lang="ts">
import type { WebSearchSource } from "$lib/types/WebSearch";
import katex from "katex";
import DOMPurify from "isomorphic-dompurify";
import { Marked } from "marked";
import CodeBlock from "../CodeBlock.svelte";
export let content: string;
export let sources: WebSearchSource[] = [];
function addInlineCitations(md: string, webSearchSources: WebSearchSource[] = []): string {
const linkStyle =
"color: rgb(59, 130, 246); text-decoration: none; hover:text-decoration: underline;";
return md.replace(/\[(\d+)\]/g, (match: string) => {
const indices: number[] = (match.match(/\d+/g) || []).map(Number);
const links: string = indices
.map((index: number) => {
if (index === 0) return false;
const source = webSearchSources[index - 1];
if (source) {
return `<a href="${source.link}" target="_blank" rel="noreferrer" style="${linkStyle}">${index}</a>`;
}
return "";
})
.filter(Boolean)
.join(", ");
return links ? ` <sup>${links}</sup>` : match;
});
}
function escapeHTML(content: string) {
return content.replace(
/[<>&\n]/g,
(x) =>
({
"<": "<",
">": ">",
"&": "&",
}[x] || x)
);
}
function processLatex(parsed: string) {
const delimiters = [
{ left: "$$", right: "$$", display: true },
{ left: "$", right: "$", display: false },
{ left: "( ", right: " )", display: false },
{ left: "[ ", right: " ]", display: true },
];
for (const { left, right, display } of delimiters) {
// Escape special regex characters in the delimiters
const escapedLeft = left.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const escapedRight = right.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Create regex pattern that matches content between delimiters
const pattern = new RegExp(`${escapedLeft}([^]*?)${escapedRight}`, "g");
parsed = parsed.replace(pattern, (match, latex) => {
try {
// Remove the delimiters from the latex content
const cleanLatex = latex.trim();
const rendered = katex.renderToString(cleanLatex, { displayMode: display });
// For display mode, wrap in centered paragraph
if (display) {
return `<p style="width:100%;text-align:center;">${rendered}</p>`;
}
return rendered;
} catch (error) {
console.error("KaTeX error:", error);
return match; // Return original on error
}
});
}
return parsed;
}
const marked = new Marked({
hooks: {
preprocess: (md) => addInlineCitations(escapeHTML(md), sources),
postprocess: (html) => {
return DOMPurify.sanitize(processLatex(html));
},
},
renderer: {
codespan: (code) => `<code>${code.replaceAll("&", "&")}</code>`,
link: (href, title, text) =>
`<a href="${href?.replace(/>$/, "")}" target="_blank" rel="noreferrer">${text}</a>`,
},
gfm: true,
});
DOMPurify.addHook("afterSanitizeAttributes", (node) => {
if (node.tagName === "A") {
node.setAttribute("rel", "noreferrer");
node.setAttribute("target", "_blank");
}
});
</script>
{#each marked.lexer(content) as token}
{#if token.type === "code"}
<CodeBlock lang={token.lang} code={token.text} />
{:else}
{#await marked.parse(token.raw) then parsed}
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html parsed}
{/await}
{/if}
{/each}
<style lang="postcss">
:global(.katex-display) {
overflow: auto hidden;
}
</style>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/chat/FileDropzone.svelte
|
<script lang="ts">
import CarbonImage from "~icons/carbon/image";
// import EosIconsLoading from "~icons/eos-icons/loading";
export let files: File[];
export let mimeTypes: string[] = [];
export let onDrag = false;
export let onDragInner = false;
async function dropHandle(event: DragEvent) {
event.preventDefault();
if (event.dataTransfer && event.dataTransfer.items) {
// Use DataTransferItemList interface to access the file(s)
if (files.length > 0) {
files = [];
}
if (event.dataTransfer.items[0].kind === "file") {
for (let i = 0; i < event.dataTransfer.items.length; i++) {
const file = event.dataTransfer.items[i].getAsFile();
if (file) {
// check if the file matches the mimeTypes
// else abort
if (
!mimeTypes.some((mimeType: string) => {
const [type, subtype] = mimeType.split("/");
const [fileType, fileSubtype] = file.type.split("/");
return (
(type === "*" || type === fileType) &&
(subtype === "*" || subtype === fileSubtype)
);
})
) {
setErrorMsg(`Some file type not supported. Only allowed: ${mimeTypes.join(", ")}`);
files = [];
return;
}
// if file is bigger than 10MB abort
if (file.size > 10 * 1024 * 1024) {
setErrorMsg("Some file is too big. (10MB max)");
files = [];
return;
}
// add the file to the files array
files = [...files, file];
}
}
onDrag = false;
}
}
}
function setErrorMsg(errorMsg: string) {
onDrag = false;
alert(errorMsg);
}
</script>
<div
id="dropzone"
role="form"
on:drop={dropHandle}
on:dragenter={() => (onDragInner = true)}
on:dragleave={() => (onDragInner = false)}
on:dragover|preventDefault
class="relative flex h-28 w-full max-w-4xl flex-col items-center justify-center gap-1 rounded-xl border-2 border-dotted {onDragInner
? 'border-blue-200 !bg-blue-500/10 text-blue-600 *:pointer-events-none dark:border-blue-600 dark:bg-blue-500/20 dark:text-blue-500'
: 'bg-gray-100 text-gray-500 dark:border-gray-500 dark:bg-gray-700 dark:text-gray-400'}"
>
<CarbonImage class="text-xl" />
<p>Drop File to add to chat</p>
</div>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/chat/ChatInput.svelte
|
<script lang="ts">
import { browser } from "$app/environment";
import { createEventDispatcher, onMount } from "svelte";
export let value = "";
export let minRows = 1;
export let maxRows: null | number = null;
export let placeholder = "";
export let disabled = false;
let textareaElement: HTMLTextAreaElement;
let isCompositionOn = false;
const dispatch = createEventDispatcher<{ submit: void }>();
function isVirtualKeyboard(): boolean {
if (!browser) return false;
// Check for touch capability
if (navigator.maxTouchPoints > 0) return true;
// Check for touch events
if ("ontouchstart" in window) return true;
// Fallback to user agent string check
const userAgent = navigator.userAgent.toLowerCase();
return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent);
}
$: minHeight = `${1 + minRows * 1.5}em`;
$: maxHeight = maxRows ? `${1 + maxRows * 1.5}em` : `auto`;
function handleKeydown(event: KeyboardEvent) {
if (event.key === "Enter" && !event.shiftKey && !isCompositionOn) {
event.preventDefault();
if (isVirtualKeyboard()) {
// Insert a newline at the cursor position
const start = textareaElement.selectionStart;
const end = textareaElement.selectionEnd;
value = value.substring(0, start) + "\n" + value.substring(end);
textareaElement.selectionStart = textareaElement.selectionEnd = start + 1;
} else {
if (value.trim() !== "") {
dispatch("submit");
}
}
}
}
onMount(() => {
if (!isVirtualKeyboard()) {
textareaElement.focus();
}
});
</script>
<div class="relative min-w-0 flex-1" on:paste>
<pre
class="scrollbar-custom invisible overflow-x-hidden overflow-y-scroll whitespace-pre-wrap break-words p-3"
aria-hidden="true"
style="min-height: {minHeight}; max-height: {maxHeight}">{(value || " ") + "\n"}</pre>
<textarea
enterkeyhint={!isVirtualKeyboard() ? "enter" : "send"}
tabindex="0"
rows="1"
class="scrollbar-custom absolute top-0 m-0 h-full w-full resize-none scroll-p-3 overflow-x-hidden overflow-y-scroll border-0 bg-transparent p-3 outline-none focus:ring-0 focus-visible:ring-0 max-sm:p-2.5 max-sm:text-[16px]"
class:text-gray-400={disabled}
bind:value
bind:this={textareaElement}
{disabled}
on:keydown={handleKeydown}
on:compositionstart={() => (isCompositionOn = true)}
on:compositionend={() => (isCompositionOn = false)}
on:beforeinput
{placeholder}
/>
</div>
<style>
pre,
textarea {
font-family: inherit;
box-sizing: border-box;
line-height: 1.5;
}
</style>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/chat/ToolUpdate.svelte
|
<script lang="ts">
import { MessageToolUpdateType, type MessageToolUpdate } from "$lib/types/MessageUpdate";
import {
isMessageToolCallUpdate,
isMessageToolErrorUpdate,
isMessageToolResultUpdate,
} from "$lib/utils/messageUpdates";
import CarbonTools from "~icons/carbon/tools";
import { ToolResultStatus, type ToolFront } from "$lib/types/Tool";
import { page } from "$app/stores";
import { onDestroy } from "svelte";
import { browser } from "$app/environment";
export let tool: MessageToolUpdate[];
export let loading: boolean = false;
const toolFnName = tool.find(isMessageToolCallUpdate)?.call.name;
$: toolError = tool.some(isMessageToolErrorUpdate);
$: toolDone = tool.some(isMessageToolResultUpdate);
$: eta = tool.find((el) => el.subtype === MessageToolUpdateType.ETA)?.eta;
const availableTools: ToolFront[] = $page.data.tools;
let loadingBarEl: HTMLDivElement;
let animation: Animation | undefined = undefined;
let isShowingLoadingBar = false;
$: !toolError &&
!toolDone &&
loading &&
loadingBarEl &&
eta &&
(() => {
loadingBarEl.classList.remove("hidden");
isShowingLoadingBar = true;
animation = loadingBarEl.animate([{ width: "0%" }, { width: "calc(100%+1rem)" }], {
duration: eta * 1000,
fill: "forwards",
});
})();
onDestroy(() => {
if (animation) {
animation.cancel();
}
});
// go to 100% quickly if loading is done
$: (!loading || toolDone || toolError) &&
browser &&
loadingBarEl &&
isShowingLoadingBar &&
(() => {
isShowingLoadingBar = false;
loadingBarEl.classList.remove("hidden");
animation?.cancel();
animation = loadingBarEl.animate(
[{ width: loadingBarEl.style.width }, { width: "calc(100%+1rem)" }],
{
duration: 300,
fill: "forwards",
}
);
setTimeout(() => {
loadingBarEl.classList.add("hidden");
}, 300);
})();
</script>
{#if toolFnName && toolFnName !== "websearch"}
<details
class="group/tool my-2.5 w-fit cursor-pointer rounded-lg border border-gray-200 bg-white pl-1 pr-2.5 text-sm shadow-sm transition-all open:mb-3
open:border-purple-500/10 open:bg-purple-600/5 open:shadow-sm dark:border-gray-800 dark:bg-gray-900 open:dark:border-purple-800/40 open:dark:bg-purple-800/10"
>
<summary
class="relative flex select-none list-none items-center gap-1.5 py-1 group-open/tool:text-purple-700 group-open/tool:dark:text-purple-300"
>
<div
bind:this={loadingBarEl}
class="absolute -m-1 hidden h-full w-[calc(100%+1rem)] rounded-lg bg-purple-500/5 transition-all dark:bg-purple-500/10"
/>
<div
class="relative grid size-[22px] place-items-center rounded bg-purple-600/10 dark:bg-purple-600/20"
>
<svg
class="absolute inset-0 text-purple-500/40 transition-opacity"
class:invisible={toolDone || toolError}
width="22"
height="22"
viewBox="0 0 38 38"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
class="loading-path"
d="M8 2.5H30C30 2.5 35.5 2.5 35.5 8V30C35.5 30 35.5 35.5 30 35.5H8C8 35.5 2.5 35.5 2.5 30V8C2.5 8 2.5 2.5 8 2.5Z"
stroke="currentColor"
stroke-width="1"
stroke-linecap="round"
id="shape"
/>
</svg>
<CarbonTools class="text-xs text-purple-700 dark:text-purple-500" />
</div>
<span>
{toolError ? "Error calling" : toolDone ? "Called" : "Calling"} tool
<span class="font-semibold"
>{availableTools.find((tool) => tool.name === toolFnName)?.displayName ??
toolFnName}</span
>
</span>
</summary>
{#each tool as toolUpdate}
{#if toolUpdate.subtype === MessageToolUpdateType.Call}
<div class="mt-1 flex items-center gap-2 opacity-80">
<h3 class="text-sm">Parameters</h3>
<div class="h-px flex-1 bg-gradient-to-r from-gray-500/20" />
</div>
<ul class="py-1 text-sm">
{#each Object.entries(toolUpdate.call.parameters ?? {}) as [k, v]}
{#if v !== null}
<li>
<span class="font-semibold">{k}</span>:
<span>{v}</span>
</li>
{/if}
{/each}
</ul>
{:else if toolUpdate.subtype === MessageToolUpdateType.Error}
<div class="mt-1 flex items-center gap-2 opacity-80">
<h3 class="text-sm">Error</h3>
<div class="h-px flex-1 bg-gradient-to-r from-gray-500/20" />
</div>
<p class="text-sm">{toolUpdate.message}</p>
{:else if isMessageToolResultUpdate(toolUpdate) && toolUpdate.result.status === ToolResultStatus.Success && toolUpdate.result.display}
<div class="mt-1 flex items-center gap-2 opacity-80">
<h3 class="text-sm">Result</h3>
<div class="h-px flex-1 bg-gradient-to-r from-gray-500/20" />
</div>
<ul class="py-1 text-sm">
{#each toolUpdate.result.outputs as output}
{#each Object.entries(output) as [k, v]}
{#if v !== null}
<li>
<span class="font-semibold">{k}</span>:
<span>{v}</span>
</li>
{/if}
{/each}
{/each}
</ul>
{/if}
{/each}
</details>
{/if}
<style>
details summary::-webkit-details-marker {
display: none;
}
.loading-path {
stroke-dasharray: 61.45;
animation: loading 2s linear infinite;
}
</style>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/chat/OpenReasoningResults.svelte
|
<script lang="ts">
import MarkdownRenderer from "./MarkdownRenderer.svelte";
import CarbonCaretDown from "~icons/carbon/caret-down";
export let summary: string;
export let content: string;
export let loading: boolean = false;
</script>
<details
class="group flex w-fit max-w-full flex-col rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900"
>
<summary
class="
grid min-w-72 cursor-pointer select-none grid-cols-[40px,1fr,24px] items-center gap-2.5 rounded-xl p-2 group-open:rounded-b-none hover:bg-gray-500/10"
>
<div
class="relative grid aspect-square place-content-center overflow-hidden rounded-lg bg-gray-100 dark:bg-gray-800"
>
<div class="grid h-dvh place-items-center">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 32 32">
<path
class="stroke-gray-600 dark:stroke-gray-400"
style="stroke-width: 1.9; fill: none; stroke-linecap: round; stroke-linejoin: round;"
d="M16 6v3.33M16 6c0-2.65 3.25-4.3 5.4-2.62 1.2.95 1.6 2.65.95 4.04a3.63 3.63 0 0 1 4.61.16 3.45 3.45 0 0 1 .46 4.37 5.32 5.32 0 0 1 1.87 4.75c-.22 1.66-1.39 3.6-3.07 4.14M16 6c0-2.65-3.25-4.3-5.4-2.62a3.37 3.37 0 0 0-.95 4.04 3.65 3.65 0 0 0-4.6.16 3.37 3.37 0 0 0-.49 4.27 5.57 5.57 0 0 0-1.85 4.85 5.3 5.3 0 0 0 3.07 4.15M16 9.33v17.34m0-17.34c0 2.18 1.82 4 4 4m6.22 7.5c.67 1.3.56 2.91-.27 4.11a4.05 4.05 0 0 1-4.62 1.5c0 1.53-1.05 2.9-2.66 2.9A2.7 2.7 0 0 1 16 26.66m10.22-5.83a4.05 4.05 0 0 0-3.55-2.17m-16.9 2.18a4.05 4.05 0 0 0 .28 4.1c1 1.44 2.92 2.09 4.59 1.5 0 1.52 1.12 2.88 2.7 2.88A2.7 2.7 0 0 0 16 26.67M5.78 20.85a4.04 4.04 0 0 1 3.55-2.18"
/>
{#if loading}
<path
class="animate-pulse stroke-purple-700"
style="stroke-width: 2; fill: none; stroke-linecap: round; stroke-linejoin: round; stroke-dasharray: 50;"
d="M16 6v3.33M16 6c0-2.65 3.25-4.3 5.4-2.62 1.2.95 1.6 2.65.95 4.04a3.63 3.63 0 0 1 4.61.16 3.45 3.45 0 0 1 .46 4.37 5.32 5.32 0 0 1 1.87 4.75c-.22 1.66-1.39 3.6-3.07 4.14M16 6c0-2.65-3.25-4.3-5.4-2.62a3.37 3.37 0 0 0-.95 4.04 3.65 3.65 0 0 0-4.6.16 3.37 3.37 0 0 0-.49 4.27 5.57 5.57 0 0 0-1.85 4.85 5.3 5.3 0 0 0 3.07 4.15M16 9.33v17.34m0-17.34c0 2.18 1.82 4 4 4m6.22 7.5c.67 1.3.56 2.91-.27 4.11a4.05 4.05 0 0 1-4.62 1.5c0 1.53-1.05 2.9-2.66 2.9A2.7 2.7 0 0 1 16 26.66m10.22-5.83a4.05 4.05 0 0 0-3.55-2.17m-16.9 2.18a4.05 4.05 0 0 0 .28 4.1c1 1.44 2.92 2.09 4.59 1.5 0 1.52 1.12 2.88 2.7 2.88A2.7 2.7 0 0 0 16 26.67M5.78 20.85a4.04 4.04 0 0 1 3.55-2.18"
>
<animate
attributeName="stroke-dashoffset"
values="0;500"
dur="12s"
repeatCount="indefinite"
/>
</path>
{/if}
</svg>
</div>
</div>
<dl class="leading-4">
<dd class="text-sm">Reasoning</dd>
<dt
class="flex items-center gap-1 truncate whitespace-nowrap text-[.82rem] text-gray-400"
class:animate-pulse={loading}
>
{summary}
</dt>
</dl>
<CarbonCaretDown class="size-6 text-gray-400 transition-transform group-open:rotate-180" />
</summary>
<div
class="space-y-4 border-t border-gray-200 px-5 pb-2 pt-2 text-sm text-gray-600 dark:border-gray-800 dark:text-gray-400"
>
<MarkdownRenderer {content} />
</div>
</details>
<style>
details summary::-webkit-details-marker {
display: none;
}
</style>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/chat/ChatMessage.svelte
|
<script lang="ts">
import type { Message } from "$lib/types/Message";
import { afterUpdate, createEventDispatcher, tick } from "svelte";
import { deepestChild } from "$lib/utils/deepestChild";
import { page } from "$app/stores";
import CopyToClipBoardBtn from "../CopyToClipBoardBtn.svelte";
import IconLoading from "../icons/IconLoading.svelte";
import CarbonRotate360 from "~icons/carbon/rotate-360";
import CarbonTrashCan from "~icons/carbon/trash-can";
import CarbonDownload from "~icons/carbon/download";
import CarbonThumbsUp from "~icons/carbon/thumbs-up";
import CarbonThumbsDown from "~icons/carbon/thumbs-down";
import CarbonPen from "~icons/carbon/pen";
import CarbonChevronLeft from "~icons/carbon/chevron-left";
import CarbonChevronRight from "~icons/carbon/chevron-right";
import type { Model } from "$lib/types/Model";
import UploadedFile from "./UploadedFile.svelte";
import OpenWebSearchResults from "../OpenWebSearchResults.svelte";
import {
MessageUpdateType,
MessageWebSearchUpdateType,
type MessageToolUpdate,
type MessageWebSearchSourcesUpdate,
type MessageWebSearchUpdate,
type MessageFinalAnswerUpdate,
type MessageReasoningUpdate,
MessageReasoningUpdateType,
} from "$lib/types/MessageUpdate";
import { base } from "$app/paths";
import { useConvTreeStore } from "$lib/stores/convTree";
import ToolUpdate from "./ToolUpdate.svelte";
import { useSettingsStore } from "$lib/stores/settings";
import { enhance } from "$app/forms";
import { browser } from "$app/environment";
import MarkdownRenderer from "./MarkdownRenderer.svelte";
import OpenReasoningResults from "./OpenReasoningResults.svelte";
export let model: Model;
export let id: Message["id"];
export let messages: Message[];
export let loading = false;
export let isAuthor = true;
export let readOnly = false;
export let isTapped = false;
$: message = messages.find((m) => m.id === id) ?? ({} as Message);
$: urlNotTrailing = $page.url.pathname.replace(/\/$/, "");
const dispatch = createEventDispatcher<{
retry: { content?: string; id: Message["id"] };
vote: { score: Message["score"]; id: Message["id"] };
}>();
let contentEl: HTMLElement;
let loadingEl: IconLoading;
let pendingTimeout: ReturnType<typeof setTimeout>;
let isCopied = false;
let initialized = false;
$: emptyLoad =
!message.content && (webSearchIsDone || (searchUpdates && searchUpdates.length === 0));
const settings = useSettingsStore();
afterUpdate(() => {
if ($settings.disableStream) {
return;
}
loadingEl?.$destroy();
clearTimeout(pendingTimeout);
// Add loading animation to the last message if update takes more than 600ms
if (isLast && loading && emptyLoad) {
pendingTimeout = setTimeout(() => {
if (contentEl) {
loadingEl = new IconLoading({
target: deepestChild(contentEl),
props: { classNames: "loading inline ml-2 first:ml-0" },
});
}
}, 600);
}
});
function handleKeyDown(e: KeyboardEvent) {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
editFormEl.requestSubmit();
}
}
$: searchUpdates = (message.updates?.filter(({ type }) => type === MessageUpdateType.WebSearch) ??
[]) as MessageWebSearchUpdate[];
$: reasoningUpdates = (message.updates?.filter(
({ type }) => type === MessageUpdateType.Reasoning
) ?? []) as MessageReasoningUpdate[];
$: messageFinalAnswer = message.updates?.find(
({ type }) => type === MessageUpdateType.FinalAnswer
) as MessageFinalAnswerUpdate;
// filter all updates with type === "tool" then group them by uuid field
$: toolUpdates = message.updates
?.filter(({ type }) => type === "tool")
.reduce((acc, update) => {
if (update.type !== "tool") {
return acc;
}
acc[update.uuid] = acc[update.uuid] ?? [];
acc[update.uuid].push(update);
return acc;
}, {} as Record<string, MessageToolUpdate[]>);
$: downloadLink = urlNotTrailing + `/message/${message.id}/prompt`;
let webSearchIsDone = true;
$: webSearchIsDone = searchUpdates.some(
(update) => update.subtype === MessageWebSearchUpdateType.Finished
);
$: webSearchSources = searchUpdates?.find(
(update): update is MessageWebSearchSourcesUpdate =>
update.subtype === MessageWebSearchUpdateType.Sources
)?.sources;
$: if (isCopied) {
setTimeout(() => {
isCopied = false;
}, 1000);
}
$: editMode = $convTreeStore.editing === message.id;
let editContentEl: HTMLTextAreaElement;
let editFormEl: HTMLFormElement;
$: if (editMode) {
tick();
if (editContentEl) {
editContentEl.value = message.content;
editContentEl?.focus();
}
}
$: isLast = (message && message.children?.length === 0) ?? false;
$: childrenToRender = 0;
$: nChildren = message?.children?.length ?? 0;
$: {
if (initialized) {
childrenToRender = Math.max(0, nChildren - 1);
} else {
childrenToRender = 0;
initialized = true;
}
}
const convTreeStore = useConvTreeStore();
$: if (message.children?.length === 0) {
$convTreeStore.leaf = message.id;
// Check if the code is running in a browser
if (browser) {
// Remember the last message viewed or interacted by the user
localStorage.setItem("leafId", message.id);
}
}
let isRun = false;
$: {
if (message.id && !isRun) {
if (message.currentChildIndex) childrenToRender = message.currentChildIndex;
isRun = true;
}
}
$: if (message.children?.length === 0) $convTreeStore.leaf = message.id;
</script>
{#if message.from === "assistant"}
<div
class="group relative -mb-4 flex items-start justify-start gap-4 pb-4 leading-relaxed"
data-message-id={message.id}
data-message-role="assistant"
role="presentation"
on:click={() => (isTapped = !isTapped)}
on:keydown={() => (isTapped = !isTapped)}
>
{#if $page.data?.assistant?.avatar}
<img
src="{base}/settings/assistants/{$page.data.assistant._id}/avatar.jpg"
alt="Avatar"
class="mt-5 h-3 w-3 flex-none select-none rounded-full shadow-lg"
/>
{:else}
<img
alt=""
src="https://huggingface.co/avatars/2edb18bd0206c16b433841a47f53fa8e.svg"
class="mt-5 h-3 w-3 flex-none select-none rounded-full shadow-lg"
/>
{/if}
<div
class="relative min-h-[calc(2rem+theme(spacing[3.5])*2)] min-w-[60px] break-words rounded-2xl border border-gray-100 bg-gradient-to-br from-gray-50 px-5 py-3.5 text-gray-600 prose-pre:my-2 dark:border-gray-800 dark:from-gray-800/40 dark:text-gray-300"
>
{#if message.files?.length}
<div class="flex h-fit flex-wrap gap-x-5 gap-y-2">
{#each message.files as file}
<UploadedFile {file} canClose={false} />
{/each}
</div>
{/if}
{#if searchUpdates && searchUpdates.length > 0}
<OpenWebSearchResults webSearchMessages={searchUpdates} />
{/if}
{#if reasoningUpdates && reasoningUpdates.length > 0}
{@const summaries = reasoningUpdates
.filter((u) => u.subtype === MessageReasoningUpdateType.Status)
.map((u) => u.status)}
<OpenReasoningResults
summary={summaries[summaries.length - 1] || ""}
content={message.reasoning || ""}
loading={loading && message.content.length === 0}
/>
{/if}
{#if toolUpdates}
{#each Object.values(toolUpdates) as tool}
{#if tool.length}
{#key tool[0].uuid}
<ToolUpdate {tool} {loading} />
{/key}
{/if}
{/each}
{/if}
<div
bind:this={contentEl}
class:mt-2={reasoningUpdates.length > 0 || searchUpdates.length > 0}
>
{#if isLast && loading && $settings.disableStream}
<IconLoading classNames="loading inline ml-2 first:ml-0" />
{/if}
<div
class="prose max-w-none dark:prose-invert max-sm:prose-sm prose-headings:font-semibold prose-h1:text-lg prose-h2:text-base prose-h3:text-base prose-pre:bg-gray-800 dark:prose-pre:bg-gray-900"
>
<MarkdownRenderer content={message.content} sources={webSearchSources} />
</div>
</div>
<!-- Web Search sources -->
{#if webSearchSources?.length}
<div class="mt-4 flex flex-wrap items-center gap-x-2 gap-y-1.5 text-sm">
<div class="text-gray-400">Sources:</div>
{#each webSearchSources as { link, title }}
<a
class="flex items-center gap-2 whitespace-nowrap rounded-lg border bg-white px-2 py-1.5 leading-none hover:border-gray-300 dark:border-gray-800 dark:bg-gray-900 dark:hover:border-gray-700"
href={link}
target="_blank"
>
<img
class="h-3.5 w-3.5 rounded"
src="https://www.google.com/s2/favicons?sz=64&domain_url={new URL(link).hostname ||
'placeholder'}"
alt="{title} favicon"
/>
<div>{new URL(link).hostname.replace(/^www\./, "")}</div>
</a>
{/each}
</div>
{/if}
<!-- Endpoint web sources -->
{#if messageFinalAnswer?.webSources && messageFinalAnswer.webSources.length}
<div class="mt-4 flex flex-wrap items-center gap-x-2 gap-y-1.5 text-sm">
<div class="text-gray-400">Sources:</div>
{#each messageFinalAnswer.webSources as { uri, title }}
<a
class="flex items-center gap-2 whitespace-nowrap rounded-lg border bg-white px-2 py-1.5 leading-none hover:border-gray-300 dark:border-gray-800 dark:bg-gray-900 dark:hover:border-gray-700"
href={uri}
target="_blank"
>
<img
class="h-3.5 w-3.5 rounded"
src="https://www.google.com/s2/favicons?sz=64&domain_url={new URL(uri).hostname ||
'placeholder'}"
alt="{title} favicon"
/>
<div>{title}</div>
</a>
{/each}
</div>
{/if}
</div>
{#if !loading && (message.content || toolUpdates)}
<div
class="absolute -bottom-4 right-0 flex max-md:transition-all md:group-hover:visible md:group-hover:opacity-100
{message.score ? 'visible opacity-100' : 'invisible max-md:-translate-y-4 max-md:opacity-0'}
{isTapped || isCopied ? 'max-md:visible max-md:translate-y-0 max-md:opacity-100' : ''}
"
>
{#if isAuthor}
<button
class="btn rounded-sm p-1 text-sm text-gray-400 hover:text-gray-500 focus:ring-0 dark:text-gray-400 dark:hover:text-gray-300
{message.score && message.score > 0
? 'text-green-500 hover:text-green-500 dark:text-green-400 hover:dark:text-green-400'
: ''}"
title={message.score === 1 ? "Remove +1" : "+1"}
type="button"
on:click={() =>
dispatch("vote", { score: message.score === 1 ? 0 : 1, id: message.id })}
>
<CarbonThumbsUp class="h-[1.14em] w-[1.14em]" />
</button>
<button
class="btn rounded-sm p-1 text-sm text-gray-400 hover:text-gray-500 focus:ring-0 dark:text-gray-400 dark:hover:text-gray-300
{message.score && message.score < 0
? 'text-red-500 hover:text-red-500 dark:text-red-400 hover:dark:text-red-400'
: ''}"
title={message.score === -1 ? "Remove -1" : "-1"}
type="button"
on:click={() =>
dispatch("vote", { score: message.score === -1 ? 0 : -1, id: message.id })}
>
<CarbonThumbsDown class="h-[1.14em] w-[1.14em]" />
</button>
{/if}
<button
class="btn rounded-sm p-1 text-sm text-gray-400 hover:text-gray-500 focus:ring-0 dark:text-gray-400 dark:hover:text-gray-300"
title="Retry"
type="button"
on:click={() => {
dispatch("retry", { id: message.id });
}}
>
<CarbonRotate360 />
</button>
<CopyToClipBoardBtn
on:click={() => {
isCopied = true;
}}
classNames="btn rounded-sm p-1 text-sm text-gray-400 hover:text-gray-500 focus:ring-0 dark:text-gray-400 dark:hover:text-gray-300"
value={message.content}
/>
</div>
{/if}
</div>
<slot name="childrenNav" />
{/if}
{#if message.from === "user"}
<div
class="group relative w-full items-start justify-start gap-4 max-sm:text-sm"
data-message-id={message.id}
data-message-type="user"
role="presentation"
on:click={() => (isTapped = !isTapped)}
on:keydown={() => (isTapped = !isTapped)}
>
<div class="flex w-full flex-col gap-2">
{#if message.files?.length}
<div class="flex w-fit gap-4 px-5">
{#each message.files as file}
<UploadedFile {file} canClose={false} />
{/each}
</div>
{/if}
<div class="flex w-full flex-row flex-nowrap">
{#if !editMode}
<p
class="disabled w-full appearance-none whitespace-break-spaces text-wrap break-words bg-inherit px-5 py-3.5 text-gray-500 dark:text-gray-400"
>
{message.content.trim()}
</p>
{:else}
<form
class="flex w-full flex-col"
bind:this={editFormEl}
on:submit|preventDefault={() => {
dispatch("retry", { content: editContentEl.value, id: message.id });
$convTreeStore.editing = null;
}}
>
<textarea
class="w-full whitespace-break-spaces break-words rounded-xl bg-gray-100 px-5 py-3.5 text-gray-500 *:h-max dark:bg-gray-800 dark:text-gray-400"
rows="5"
bind:this={editContentEl}
value={message.content.trim()}
on:keydown={handleKeyDown}
required
/>
<div class="flex w-full flex-row flex-nowrap items-center justify-center gap-2 pt-2">
<button
type="submit"
class="btn rounded-lg px-3 py-1.5 text-sm
{loading
? 'bg-gray-300 text-gray-400 dark:bg-gray-700 dark:text-gray-600'
: 'bg-gray-200 text-gray-600 hover:text-gray-800 focus:ring-0 dark:bg-gray-800 dark:text-gray-300 dark:hover:text-gray-200'}
"
disabled={loading}
>
Submit
</button>
<button
type="button"
class="btn rounded-sm p-2 text-sm text-gray-400 hover:text-gray-500 focus:ring-0 dark:text-gray-400 dark:hover:text-gray-300"
on:click={() => {
$convTreeStore.editing = null;
}}
>
Cancel
</button>
</div>
</form>
{/if}
{#if !loading && !editMode}
<div
class="
max-md:opacity-0' invisible absolute
right-0 top-3.5 z-10 h-max max-md:-translate-y-4 max-md:transition-all md:bottom-0 md:group-hover:visible md:group-hover:opacity-100 {isTapped ||
isCopied
? 'max-md:visible max-md:translate-y-0 max-md:opacity-100'
: ''}"
>
<div class="mx-auto flex flex-row flex-nowrap gap-2">
{#if downloadLink}
<a
class="rounded-lg border border-gray-100 bg-gray-100 p-1 text-xs text-gray-400 group-hover:block hover:text-gray-500 dark:border-gray-800 dark:bg-gray-800 dark:text-gray-400 dark:hover:text-gray-300 max-sm:!hidden md:hidden"
title="Download prompt and parameters"
type="button"
target="_blank"
href={downloadLink}
>
<CarbonDownload />
</a>
{/if}
{#if !readOnly}
<button
class="cursor-pointer rounded-lg border border-gray-100 bg-gray-100 p-1 text-xs text-gray-400 group-hover:block hover:text-gray-500 dark:border-gray-800 dark:bg-gray-800 dark:text-gray-400 dark:hover:text-gray-300 md:hidden lg:-right-2"
title="Branch"
type="button"
on:click={() => ($convTreeStore.editing = message.id)}
>
<CarbonPen />
</button>
{/if}
</div>
</div>
{/if}
</div>
<slot name="childrenNav" />
</div>
</div>
{/if}
{#if nChildren > 0}
{@const messageId = messages.find((m) => m.id === id)?.children?.[childrenToRender]}
{#key messageId}
<svelte:self
{loading}
{messages}
{isAuthor}
{readOnly}
{model}
id={messageId}
on:retry
on:vote
on:continue
>
<svelte:fragment slot="childrenNav">
{#if nChildren > 1 && $convTreeStore.editing === null}
<div
class="font-white group/navbranch z-0 -mt-1 ml-3.5 mr-auto flex h-6 w-fit select-none flex-row items-center justify-center gap-1 text-sm"
>
<button
class="inline text-lg font-thin text-gray-400 hover:text-gray-800 disabled:pointer-events-none disabled:opacity-25 dark:text-gray-500 dark:hover:text-gray-200"
on:click={() => (childrenToRender = Math.max(0, childrenToRender - 1))}
disabled={childrenToRender === 0 || loading}
>
<CarbonChevronLeft class="text-sm" />
</button>
<span class=" text-gray-400 dark:text-gray-500">
{childrenToRender + 1} / {nChildren}
</span>
<button
class="inline text-lg font-thin text-gray-400 hover:text-gray-800 disabled:pointer-events-none disabled:opacity-25 dark:text-gray-500 dark:hover:text-gray-200"
on:click={() =>
(childrenToRender = Math.min(
message?.children?.length ?? 1 - 1,
childrenToRender + 1
))}
disabled={childrenToRender === nChildren - 1 || loading}
>
<CarbonChevronRight class="text-sm" />
</button>
{#if !loading && message.children}<form
method="POST"
action="?/deleteBranch"
class="hidden group-hover/navbranch:block"
use:enhance={({ cancel }) => {
if (!confirm("Are you sure you want to delete this branch?")) {
cancel();
}
}}
>
<input name="messageId" value={message.children[childrenToRender]} type="hidden" />
<button
class="flex items-center justify-center text-xs text-gray-400 hover:text-gray-800 dark:text-gray-500 dark:hover:text-gray-200"
type="submit"
><CarbonTrashCan />
</button>
</form>
{/if}
</div>
{/if}
</svelte:fragment>
</svelte:self>
{/key}
{/if}
<style>
@keyframes loading {
to {
stroke-dashoffset: 122.9;
}
}
</style>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/chat/ChatWindow.svelte
|
<script lang="ts">
import type { Message, MessageFile } from "$lib/types/Message";
import { createEventDispatcher, onDestroy, tick } from "svelte";
import CarbonSendAltFilled from "~icons/carbon/send-alt-filled";
import CarbonExport from "~icons/carbon/export";
import CarbonStopFilledAlt from "~icons/carbon/stop-filled-alt";
import CarbonCheckmark from "~icons/carbon/checkmark";
import CarbonCaretDown from "~icons/carbon/caret-down";
import EosIconsLoading from "~icons/eos-icons/loading";
import ChatInput from "./ChatInput.svelte";
import StopGeneratingBtn from "../StopGeneratingBtn.svelte";
import type { Model } from "$lib/types/Model";
import WebSearchToggle from "../WebSearchToggle.svelte";
import ToolsMenu from "../ToolsMenu.svelte";
import LoginModal from "../LoginModal.svelte";
import { page } from "$app/stores";
import FileDropzone from "./FileDropzone.svelte";
import RetryBtn from "../RetryBtn.svelte";
import UploadBtn from "../UploadBtn.svelte";
import file2base64 from "$lib/utils/file2base64";
import type { Assistant } from "$lib/types/Assistant";
import { base } from "$app/paths";
import ContinueBtn from "../ContinueBtn.svelte";
import AssistantIntroduction from "./AssistantIntroduction.svelte";
import ChatMessage from "./ChatMessage.svelte";
import ScrollToBottomBtn from "../ScrollToBottomBtn.svelte";
import ScrollToPreviousBtn from "../ScrollToPreviousBtn.svelte";
import { browser } from "$app/environment";
import { snapScrollToBottom } from "$lib/actions/snapScrollToBottom";
import SystemPromptModal from "../SystemPromptModal.svelte";
import ChatIntroduction from "./ChatIntroduction.svelte";
import { useConvTreeStore } from "$lib/stores/convTree";
import UploadedFile from "./UploadedFile.svelte";
import { useSettingsStore } from "$lib/stores/settings";
import type { ToolFront } from "$lib/types/Tool";
import ModelSwitch from "./ModelSwitch.svelte";
import { fly } from "svelte/transition";
import { cubicInOut } from "svelte/easing";
export let messages: Message[] = [];
export let loading = false;
export let pending = false;
export let shared = false;
export let currentModel: Model;
export let models: Model[];
export let assistant: Assistant | undefined = undefined;
export let preprompt: string | undefined = undefined;
export let files: File[] = [];
$: isReadOnly = !models.some((model) => model.id === currentModel.id);
let loginModalOpen = false;
let message: string;
let timeout: ReturnType<typeof setTimeout>;
let isSharedRecently = false;
$: pastedLongContent = false;
$: $page.params.id && (isSharedRecently = false);
const dispatch = createEventDispatcher<{
message: string;
share: void;
stop: void;
retry: { id: Message["id"]; content?: string };
continue: { id: Message["id"] };
}>();
const handleSubmit = () => {
if (loading) return;
dispatch("message", message);
message = "";
};
let lastTarget: EventTarget | null = null;
let onDrag = false;
const onDragEnter = (e: DragEvent) => {
lastTarget = e.target;
onDrag = true;
};
const onDragLeave = (e: DragEvent) => {
if (e.target === lastTarget) {
onDrag = false;
}
};
const onPaste = (e: ClipboardEvent) => {
const textContent = e.clipboardData?.getData("text");
if (!$settings.directPaste && textContent && textContent.length >= 3984) {
e.preventDefault();
pastedLongContent = true;
setTimeout(() => {
pastedLongContent = false;
}, 1000);
const pastedFile = new File([textContent], "Pasted Content", {
type: "application/vnd.chatui.clipboard",
});
files = [...files, pastedFile];
}
if (!e.clipboardData) {
return;
}
// paste of files
const pastedFiles = Array.from(e.clipboardData.files);
if (pastedFiles.length !== 0) {
e.preventDefault();
// filter based on activeMimeTypes, including wildcards
const filteredFiles = pastedFiles.filter((file) => {
return activeMimeTypes.some((mimeType: string) => {
const [type, subtype] = mimeType.split("/");
const [fileType, fileSubtype] = file.type.split("/");
return type === fileType && (subtype === "*" || fileSubtype === subtype);
});
});
files = [...files, ...filteredFiles];
}
};
const convTreeStore = useConvTreeStore();
const updateCurrentIndex = () => {
const url = new URL($page.url);
let leafId = url.searchParams.get("leafId");
// Ensure the function is only run in the browser.
if (!browser) return;
if (leafId) {
// Remove the 'leafId' from the URL to clean up after retrieving it.
url.searchParams.delete("leafId");
history.replaceState(null, "", url.toString());
} else {
// Retrieve the 'leafId' from localStorage if it's not in the URL.
leafId = localStorage.getItem("leafId");
}
// If a 'leafId' exists, find the corresponding message and update indices.
if (leafId) {
let leafMessage = messages.find((m) => m.id == leafId);
if (!leafMessage?.ancestors) return; // Exit if the message has no ancestors.
let ancestors = leafMessage.ancestors;
// Loop through all ancestors to update the current child index.
for (let i = 0; i < ancestors.length; i++) {
let curMessage = messages.find((m) => m.id == ancestors[i]);
if (curMessage?.children) {
for (let j = 0; j < curMessage.children.length; j++) {
// Check if the current message's child matches the next ancestor
// or the leaf itself, and update the currentChildIndex accordingly.
if (i + 1 < ancestors.length) {
if (curMessage.children[j] == ancestors[i + 1]) {
curMessage.currentChildIndex = j;
break;
}
} else {
if (curMessage.children[j] == leafId) {
curMessage.currentChildIndex = j;
break;
}
}
}
}
}
}
};
updateCurrentIndex();
$: lastMessage = browser && (messages.find((m) => m.id == $convTreeStore.leaf) as Message);
$: lastIsError =
lastMessage &&
!loading &&
(lastMessage.from === "user" ||
lastMessage.updates?.findIndex((u) => u.type === "status" && u.status === "error") !== -1);
$: sources = files?.map<Promise<MessageFile>>((file) =>
file2base64(file).then((value) => ({ type: "base64", value, mime: file.type, name: file.name }))
);
function onShare() {
if (!confirm("Are you sure you want to share this conversation? This cannot be undone.")) {
return;
}
dispatch("share");
isSharedRecently = true;
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
isSharedRecently = false;
}, 2000);
}
onDestroy(() => {
if (timeout) {
clearTimeout(timeout);
}
});
let chatContainer: HTMLElement;
async function scrollToBottom() {
await tick();
chatContainer.scrollTop = chatContainer.scrollHeight;
}
// If last message is from user, scroll to bottom
$: if (lastMessage && lastMessage.from === "user") {
scrollToBottom();
}
const settings = useSettingsStore();
// active tools are all the checked tools, either from settings or on by default
$: activeTools = $page.data.tools.filter((tool: ToolFront) => {
if ($page.data?.assistant) {
return $page.data.assistant.tools?.includes(tool._id);
}
return $settings?.tools?.includes(tool._id) ?? tool.isOnByDefault;
});
$: activeMimeTypes = [
...(currentModel.tools ? activeTools.flatMap((tool: ToolFront) => tool.mimeTypes ?? []) : []),
...(currentModel.multimodal ? currentModel.multimodalAcceptedMimetypes ?? ["image/*"] : []),
];
$: isFileUploadEnabled = activeMimeTypes.length > 0;
</script>
<svelte:window
on:dragenter={onDragEnter}
on:dragleave={onDragLeave}
on:dragover|preventDefault
on:drop|preventDefault={() => (onDrag = false)}
/>
<div class="relative min-h-0 min-w-0">
{#if loginModalOpen}
<LoginModal
on:close={() => {
loginModalOpen = false;
}}
/>
{/if}
<div
class="scrollbar-custom h-full overflow-y-auto"
use:snapScrollToBottom={messages.length ? [...messages] : false}
bind:this={chatContainer}
>
<div
class="mx-auto flex h-full max-w-3xl flex-col gap-6 px-5 pt-6 sm:gap-8 xl:max-w-4xl xl:pt-10"
>
{#if $page.data?.assistant && !!messages.length}
<a
class="mx-auto flex items-center gap-1.5 rounded-full border border-gray-100 bg-gray-50 py-1 pl-1 pr-3 text-sm text-gray-800 hover:bg-gray-100 dark:border-gray-800 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700"
href="{base}/settings/assistants/{$page.data.assistant._id}"
>
{#if $page.data?.assistant.avatar}
<img
src="{base}/settings/assistants/{$page.data?.assistant._id.toString()}/avatar.jpg?hash=${$page
.data.assistant.avatar}"
alt="Avatar"
class="size-5 rounded-full object-cover"
/>
{:else}
<div
class="flex size-6 items-center justify-center rounded-full bg-gray-300 font-bold uppercase text-gray-500"
>
{$page.data?.assistant.name[0]}
</div>
{/if}
{$page.data.assistant.name}
</a>
{:else if preprompt && preprompt != currentModel.preprompt}
<SystemPromptModal preprompt={preprompt ?? ""} />
{/if}
{#if messages.length > 0}
<div class="flex h-max flex-col gap-8 pb-52">
<ChatMessage
{loading}
{messages}
id={messages[0].id}
isAuthor={!shared}
readOnly={isReadOnly}
model={currentModel}
on:retry
on:vote
on:continue
/>
{#if isReadOnly}
<ModelSwitch {models} {currentModel} />
{/if}
</div>
{:else if pending}
<ChatMessage
loading={true}
messages={[
{
id: "0-0-0-0-0",
content: "",
from: "assistant",
children: [],
},
]}
id={"0-0-0-0-0"}
isAuthor={!shared}
readOnly={isReadOnly}
model={currentModel}
/>
{:else if !assistant}
<ChatIntroduction
{currentModel}
on:message={(ev) => {
if ($page.data.loginRequired) {
ev.preventDefault();
loginModalOpen = true;
} else {
dispatch("message", ev.detail);
}
}}
/>
{:else}
<AssistantIntroduction
{models}
{assistant}
on:message={(ev) => {
if ($page.data.loginRequired) {
ev.preventDefault();
loginModalOpen = true;
} else {
dispatch("message", ev.detail);
}
}}
/>
{/if}
</div>
<ScrollToPreviousBtn
class="fixed right-4 max-md:bottom-[calc(50%+26px)] md:bottom-48 lg:right-10"
scrollNode={chatContainer}
/>
<ScrollToBottomBtn
class="fixed right-4 max-md:bottom-[calc(50%-26px)] md:bottom-36 lg:right-10"
scrollNode={chatContainer}
/>
</div>
<div
class="dark:via-gray-80 pointer-events-none absolute inset-x-0 bottom-0 z-0 mx-auto flex w-full max-w-3xl flex-col items-center justify-center bg-gradient-to-t from-white via-white/80 to-white/0 px-3.5 py-4 dark:border-gray-800 dark:from-gray-900 dark:to-gray-900/0 max-md:border-t max-md:bg-white max-md:dark:bg-gray-900 sm:px-5 md:py-8 xl:max-w-4xl [&>*]:pointer-events-auto"
>
{#if sources?.length && !loading}
<div
in:fly|local={sources.length === 1 ? { y: -20, easing: cubicInOut } : undefined}
class="flex flex-row flex-wrap justify-center gap-2.5 rounded-xl max-md:pb-3"
>
{#each sources as source, index}
{#await source then src}
<UploadedFile
file={src}
on:close={() => {
files = files.filter((_, i) => i !== index);
}}
/>
{/await}
{/each}
</div>
{/if}
<div class="w-full">
<div class="flex w-full pb-3">
{#if !assistant}
{#if currentModel.tools}
<ToolsMenu {loading} />
{:else if $page.data.settings?.searchEnabled}
<WebSearchToggle />
{/if}
{/if}
{#if loading}
<StopGeneratingBtn classNames="ml-auto" on:click={() => dispatch("stop")} />
{:else if lastIsError}
<RetryBtn
classNames="ml-auto"
on:click={() => {
if (lastMessage && lastMessage.ancestors) {
dispatch("retry", {
id: lastMessage.id,
});
}
}}
/>
{:else}
<div class="ml-auto gap-2">
{#if isFileUploadEnabled}
<UploadBtn bind:files mimeTypes={activeMimeTypes} classNames="ml-auto" />
{/if}
{#if messages && lastMessage && lastMessage.interrupted && !isReadOnly}
<ContinueBtn
on:click={() => {
if (lastMessage && lastMessage.ancestors) {
dispatch("continue", {
id: lastMessage?.id,
});
}
}}
/>
{/if}
</div>
{/if}
</div>
<form
tabindex="-1"
aria-label={isFileUploadEnabled ? "file dropzone" : undefined}
on:submit|preventDefault={handleSubmit}
class="relative flex w-full max-w-4xl flex-1 items-center rounded-xl border bg-gray-100 focus-within:border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:focus-within:border-gray-500
{isReadOnly ? 'opacity-30' : ''}"
>
{#if onDrag && isFileUploadEnabled}
<FileDropzone bind:files bind:onDrag mimeTypes={activeMimeTypes} />
{:else}
<div
class="flex w-full flex-1 rounded-xl border-none bg-transparent"
class:paste-glow={pastedLongContent}
>
{#if lastIsError}
<ChatInput value="Sorry, something went wrong. Please try again." disabled={true} />
{:else}
<ChatInput
placeholder={isReadOnly ? "This conversation is read-only." : "Ask anything"}
bind:value={message}
on:submit={handleSubmit}
on:beforeinput={(ev) => {
if ($page.data.loginRequired) {
ev.preventDefault();
loginModalOpen = true;
}
}}
on:paste={onPaste}
maxRows={6}
disabled={isReadOnly || lastIsError}
/>
{/if}
{#if loading}
<button
class="btn mx-1 my-1 inline-block h-[2.4rem] self-end rounded-lg bg-transparent p-1 px-[0.7rem] text-gray-400 enabled:hover:text-gray-700 disabled:opacity-60 enabled:dark:hover:text-gray-100 dark:disabled:opacity-40 md:hidden"
on:click={() => dispatch("stop")}
>
<CarbonStopFilledAlt />
</button>
<div
class="mx-1 my-1 hidden h-[2.4rem] items-center p-1 px-[0.7rem] text-gray-400 enabled:hover:text-gray-700 disabled:opacity-60 enabled:dark:hover:text-gray-100 dark:disabled:opacity-40 md:flex"
>
<EosIconsLoading />
</div>
{:else}
<button
class="btn mx-1 my-1 h-[2.4rem] self-end rounded-lg bg-transparent p-1 px-[0.7rem] text-gray-400 enabled:hover:text-gray-700 disabled:opacity-60 enabled:dark:hover:text-gray-100 dark:disabled:opacity-40"
disabled={!message || isReadOnly}
type="submit"
aria-label="Send message"
name="submit"
>
<CarbonSendAltFilled />
</button>
{/if}
</div>
{/if}
</form>
<div
class="mt-2 flex justify-between self-stretch px-1 text-xs text-gray-400/90 max-md:mb-2 max-sm:gap-2"
>
<p>
Model:
{#if !assistant}
{#if models.find((m) => m.id === currentModel.id)}
<a
href="{base}/settings/{currentModel.id}"
class="inline-flex items-center hover:underline"
>{currentModel.displayName}<CarbonCaretDown class="text-xxs" /></a
>
{:else}
<span class="inline-flex items-center line-through dark:border-gray-700">
{currentModel.id}
</span>
{/if}
{:else}
{@const model = models.find((m) => m.id === assistant?.modelId)}
{#if model}
<a
href="{base}/settings/assistants/{assistant._id}"
class="inline-flex items-center border-b hover:text-gray-600 dark:border-gray-700 dark:hover:text-gray-300"
>{model?.displayName}<CarbonCaretDown class="text-xxs" /></a
>
{:else}
<span class="inline-flex items-center line-through dark:border-gray-700">
{currentModel.id}
</span>
{/if}
{/if}
<span class="max-sm:hidden">·</span><br class="sm:hidden" /> Generated content may be inaccurate
or false.
</p>
{#if messages.length}
<button
class="flex flex-none items-center hover:text-gray-400 max-sm:rounded-lg max-sm:bg-gray-50 max-sm:px-2.5 dark:max-sm:bg-gray-800"
type="button"
class:hover:underline={!isSharedRecently}
on:click={onShare}
disabled={isSharedRecently}
>
{#if isSharedRecently}
<CarbonCheckmark class="text-[.6rem] sm:mr-1.5 sm:text-green-600" />
<div class="text-green-600 max-sm:hidden">Link copied to clipboard</div>
{:else}
<CarbonExport class="sm:text-primary-500 text-[.6rem] sm:mr-1.5" />
<div class="max-sm:hidden">Share this conversation</div>
{/if}
</button>
{/if}
</div>
</div>
</div>
</div>
<style lang="postcss">
.paste-glow {
animation: glow 1s cubic-bezier(0.4, 0, 0.2, 1) forwards;
will-change: box-shadow;
}
@keyframes glow {
0% {
box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.8);
}
50% {
box-shadow: 0 0 20px 4px rgba(59, 130, 246, 0.6);
}
100% {
box-shadow: 0 0 0 0 rgba(59, 130, 246, 0);
}
}
</style>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/players/AudioPlayer.svelte
|
<script lang="ts">
export let src: string;
export let name: string;
import CarbonPause from "~icons/carbon/pause";
import CarbonPlay from "~icons/carbon/play";
let time = 0;
let duration = 0;
let paused = true;
function format(time: number) {
if (isNaN(time)) return "...";
const minutes = Math.floor(time / 60);
const seconds = Math.floor(time % 60);
return `${minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
}
function seek(e: PointerEvent) {
if (!e.currentTarget) return;
const { left, width } = (e.currentTarget as HTMLElement).getBoundingClientRect();
let p = (e.clientX - left) / width;
if (p < 0) p = 0;
if (p > 1) p = 1;
time = p * duration;
}
</script>
<div
class="flex h-14 w-72 items-center gap-4 rounded-2xl border border-gray-200 bg-white p-2.5 text-gray-600 shadow-sm transition-all dark:border-gray-800 dark:bg-gray-900 dark:text-gray-300"
>
<audio
{src}
bind:currentTime={time}
bind:duration
bind:paused
preload="metadata"
on:ended={() => {
time = 0;
}}
/>
<button
class="mx-auto my-auto aspect-square size-8 rounded-full border border-gray-400 bg-gray-100 dark:border-gray-800 dark:bg-gray-700"
aria-label={paused ? "play" : "pause"}
on:click={() => (paused = !paused)}
>
{#if paused}
<CarbonPlay class="mx-auto my-auto text-gray-600 dark:text-gray-300" />
{:else}
<CarbonPause class="mx-auto my-auto text-gray-600 dark:text-gray-300" />
{/if}
</button>
<div class="overflow-hidden">
<div class="truncate font-medium">{name}</div>
{#if duration !== Infinity}
<div class="flex items-center gap-2">
<span class="text-xs">{format(time)}</span>
<div
class="relative h-2 flex-1 rounded-full bg-gray-200 dark:bg-gray-700"
on:pointerdown={() => {
paused = true;
}}
on:pointerup={seek}
>
<div
class="absolute inset-0 h-full bg-gray-400 dark:bg-gray-600"
style="width: {(time / duration) * 100}%"
/>
</div>
<span class="text-xs">{duration ? format(duration) : "--:--"}</span>
</div>
{/if}
</div>
</div>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/icons/IconTool.svelte
|
<script lang="ts">
export let classNames = "";
</script>
<svg
xmlns="http://www.w3.org/2000/svg"
class={classNames}
width="1em"
height="1em"
fill="none"
viewBox="0 0 15 15"
><path
fill="currentColor"
d="M8.33 6.56c0 .11-.04.22-.1.31a.55.55 0 0 1-.26.2l-.71.23c-.2.07-.38.18-.53.33-.15.15-.26.33-.33.53l-.24.7a.55.55 0 0 1-.83.26.55.55 0 0 1-.19-.27l-.23-.7a1.37 1.37 0 0 0-.85-.85l-.7-.24a.52.52 0 0 1-.27-.2.56.56 0 0 1 .27-.82l.7-.23a1.4 1.4 0 0 0 .86-.86l.23-.7c.03-.1.1-.19.18-.26a.55.55 0 0 1 .63-.02c.1.06.17.15.2.26l.24.72a1.4 1.4 0 0 0 .86.86l.7.24c.11.04.2.1.26.2.07.09.1.2.1.31ZM13.94 10.14c0 .12-.03.24-.1.34a.55.55 0 0 1-.3.21l-.96.32a2.01 2.01 0 0 0-1.27 1.27l-.33.96a.55.55 0 0 1-.2.28c-.1.07-.23.11-.35.11a.56.56 0 0 1-.57-.4l-.32-.96c-.1-.3-.26-.57-.48-.79-.22-.21-.49-.38-.78-.48l-.97-.32a.62.62 0 0 1-.28-.2.61.61 0 0 1-.02-.7c.07-.1.18-.18.3-.22l.96-.32a1.99 1.99 0 0 0 1.29-1.28l.32-.95a.56.56 0 0 1 .53-.4c.12 0 .24.02.34.09.1.07.18.17.23.28l.32.98a1.99 1.99 0 0 0 1.29 1.28l.95.34c.12.04.22.11.29.21.07.1.11.22.11.35ZM11.48 3.84c.06-.09.1-.19.1-.29a.5.5 0 0 0-.1-.29.55.55 0 0 0-.23-.16l-.35-.12a.55.55 0 0 1-.18-.11.55.55 0 0 1-.11-.19l-.12-.36a.54.54 0 0 0-.18-.23A.55.55 0 0 0 10 2c-.1.01-.2.05-.27.1a.55.55 0 0 0-.16.23l-.12.35a.55.55 0 0 1-.11.19.55.55 0 0 1-.19.1l-.34.12a.5.5 0 0 0-.24.17.55.55 0 0 0-.1.29c0 .1.04.2.1.28.06.08.14.14.23.18l.35.11c.07.02.13.06.18.11.05.05.1.11.11.18l.12.35c.04.1.1.19.18.25.09.05.18.08.28.08.1 0 .2-.03.29-.1a.55.55 0 0 0 .16-.22l.13-.35a.47.47 0 0 1 .29-.3l.35-.11c.1-.03.17-.1.23-.17Z"
/></svg
>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/icons/Logo.svelte
|
<script lang="ts">
import { page } from "$app/stores";
import { env as envPublic } from "$env/dynamic/public";
import { base } from "$app/paths";
export let classNames = "";
</script>
{#if envPublic.PUBLIC_APP_ASSETS === "chatui"}
<svg
height="30"
width="30"
viewBox="0 0 30 30"
xmlns="http://www.w3.org/2000/svg"
class={classNames}
>
<path
d="M4.06151 14.1464C4.06151 11.8818 4.9611 9.71004 6.56237 8.10877C8.16364 6.5075 10.3354 5.60791 12.6 5.60791H16.5231C18.6254 5.60791 20.6416 6.44307 22.1282 7.92965C23.6148 9.41624 24.45 11.4325 24.45 13.5348C24.45 15.6372 23.6148 17.6534 22.1282 19.14C20.6416 20.6266 18.6254 21.4618 16.5231 21.4618H7.08459L4.63844 23.8387C4.59547 23.8942 4.53557 23.9343 4.4678 23.9527C4.40004 23.9712 4.32811 23.9671 4.2629 23.941C4.1977 23.9149 4.14276 23.8683 4.10643 23.8082C4.07009 23.7481 4.05432 23.6778 4.06151 23.6079V14.1464Z"
class="fill-primary-500"
/>
</svg>
{:else}
<img
class={classNames}
alt="{envPublic.PUBLIC_APP_NAME} logo"
src="{envPublic.PUBLIC_ORIGIN || $page.url.origin}{base}/{envPublic.PUBLIC_APP_ASSETS}/logo.svg"
/>
{/if}
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/icons/IconNew.svelte
|
<script lang="ts">
export let classNames = "";
</script>
<svg
xmlns="http://www.w3.org/2000/svg"
class={classNames}
width="1em"
height="1em"
fill="none"
viewBox="0 0 32 32"
><path
fill="currentColor"
fill-rule="evenodd"
d="M3.143 20.286h4.286v2.142H3.143A2.143 2.143 0 0 1 1 20.287V3.143A2.143 2.143 0 0 1 3.143 1h17.143a2.143 2.143 0 0 1 2.142 2.143v4.286h-2.142V3.143H3.143v17.143Zm9.643-12.857v3.214H16v2.143h-3.214V16h-2.143v-3.214H7.429v-2.143h3.214V7.429h2.143Zm14.185 2.639 3.533 3.532a1.7 1.7 0 0 1 0 2.4L15.5 31H9.57v-5.928l15-15.004a1.7 1.7 0 0 1 2.4 0Zm-15.257 18.79h2.897l10.116-10.116-2.899-2.897L11.714 25.96v2.897ZM23.346 14.33l2.897 2.897 2.429-2.43-2.897-2.896-2.43 2.429Z"
clip-rule="evenodd"
/></svg
>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/icons/IconInternet.svelte
|
<script lang="ts">
export let classNames = "";
</script>
<svg
class={classNames}
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
focusable="false"
role="img"
width="1em"
height="1em"
fill="currentColor"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 20 20"
>
><path
fill-rule="evenodd"
d="M1.5 10a8.5 8.5 0 1 0 17 0a8.5 8.5 0 0 0-17 0m16 0a7.5 7.5 0 1 1-15 0a7.5 7.5 0 0 1 15 0"
clip-rule="evenodd"
/><path
fill-rule="evenodd"
d="M6.5 10c0 4.396 1.442 8 3.5 8s3.5-3.604 3.5-8s-1.442-8-3.5-8s-3.5 3.604-3.5 8m6 0c0 3.889-1.245 7-2.5 7s-2.5-3.111-2.5-7S8.745 3 10 3s2.5 3.111 2.5 7"
clip-rule="evenodd"
/><path
d="m3.735 5.312l.67-.742c.107.096.221.19.343.281c1.318.988 3.398 1.59 5.665 1.59c1.933 0 3.737-.437 5.055-1.19a5.59 5.59 0 0 0 .857-.597l.65.76c-.298.255-.636.49-1.01.704c-1.477.845-3.452 1.323-5.552 1.323c-2.47 0-4.762-.663-6.265-1.79a5.81 5.81 0 0 1-.413-.34m0 9.389l.67.74c.107-.096.221-.19.343-.28c1.318-.988 3.398-1.59 5.665-1.59c1.933 0 3.737.436 5.055 1.19c.321.184.608.384.857.596l.65-.76a6.583 6.583 0 0 0-1.01-.704c-1.477-.844-3.452-1.322-5.552-1.322c-2.47 0-4.762.663-6.265 1.789c-.146.11-.284.223-.413.34M2 10.5v-1h16v1z"
/></svg
>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/icons/IconChevron.svelte
|
<script lang="ts">
export let classNames = "";
</script>
<svg
width="1em"
height="1em"
viewBox="0 0 15 6"
class={classNames}
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M1.67236 1L7.67236 7L13.6724 1"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/icons/LogoHuggingFaceBorderless.svelte
|
<script lang="ts">
export let classNames = "";
</script>
<svg
class={classNames}
xmlns="http://www.w3.org/2000/svg"
width="1em"
height="1em"
fill="none"
viewBox="0 0 95 88"
>
<path fill="#FFD21E" d="M47.21 76.5a34.75 34.75 0 1 0 0-69.5 34.75 34.75 0 0 0 0 69.5Z" />
<path
fill="#FF9D0B"
d="M81.96 41.75a34.75 34.75 0 1 0-69.5 0 34.75 34.75 0 0 0 69.5 0Zm-73.5 0a38.75 38.75 0 1 1 77.5 0 38.75 38.75 0 0 1-77.5 0Z"
/>
<path
fill="#3A3B45"
d="M58.5 32.3c1.28.44 1.78 3.06 3.07 2.38a5 5 0 1 0-6.76-2.07c.61 1.15 2.55-.72 3.7-.32ZM34.95 32.3c-1.28.44-1.79 3.06-3.07 2.38a5 5 0 1 1 6.76-2.07c-.61 1.15-2.56-.72-3.7-.32ZM46.96 56.29c9.83 0 13-8.76 13-13.26 0-2.34-1.57-1.6-4.09-.36-2.33 1.15-5.46 2.74-8.9 2.74-7.19 0-13-6.88-13-2.38s3.16 13.26 13 13.26Z"
/>
<mask id="a" width="27" height="16" x="33" y="41" maskUnits="userSpaceOnUse">
<path
fill="#fff"
d="M46.96 56.29c9.83 0 13-8.76 13-13.26 0-2.34-1.57-1.6-4.09-.36-2.33 1.15-5.46 2.74-8.9 2.74-7.19 0-13-6.88-13-2.38s3.16 13.26 13 13.26Z"
/>
</mask>
<g mask="url(#a)">
<path
fill="#F94040"
d="M47.21 66.5a8.67 8.67 0 0 0 2.65-16.94c-.84-.26-1.73 2.6-2.65 2.6-.86 0-1.7-2.88-2.48-2.65a8.68 8.68 0 0 0 2.48 16.99Z"
/>
</g>
<path
fill="#FF9D0B"
d="M70.71 37a3.25 3.25 0 1 0 0-6.5 3.25 3.25 0 0 0 0 6.5ZM24.21 37a3.25 3.25 0 1 0 0-6.5 3.25 3.25 0 0 0 0 6.5ZM17.52 48c-1.62 0-3.06.66-4.07 1.87a5.97 5.97 0 0 0-1.33 3.76 7.1 7.1 0 0 0-1.94-.3c-1.55 0-2.95.59-3.94 1.66a5.8 5.8 0 0 0-.8 7 5.3 5.3 0 0 0-1.79 2.82c-.24.9-.48 2.8.8 4.74a5.22 5.22 0 0 0-.37 5.02c1.02 2.32 3.57 4.14 8.52 6.1 3.07 1.22 5.89 2 5.91 2.01a44.33 44.33 0 0 0 10.93 1.6c5.86 0 10.05-1.8 12.46-5.34 3.88-5.69 3.33-10.9-1.7-15.92-2.77-2.78-4.62-6.87-5-7.77-.78-2.66-2.84-5.62-6.25-5.62a5.7 5.7 0 0 0-4.6 2.46c-1-1.26-1.98-2.25-2.86-2.82A7.4 7.4 0 0 0 17.52 48Zm0 4c.51 0 1.14.22 1.82.65 2.14 1.36 6.25 8.43 7.76 11.18.5.92 1.37 1.31 2.14 1.31 1.55 0 2.75-1.53.15-3.48-3.92-2.93-2.55-7.72-.68-8.01.08-.02.17-.02.24-.02 1.7 0 2.45 2.93 2.45 2.93s2.2 5.52 5.98 9.3c3.77 3.77 3.97 6.8 1.22 10.83-1.88 2.75-5.47 3.58-9.16 3.58-3.81 0-7.73-.9-9.92-1.46-.11-.03-13.45-3.8-11.76-7 .28-.54.75-.76 1.34-.76 2.38 0 6.7 3.54 8.57 3.54.41 0 .7-.17.83-.6.79-2.85-12.06-4.05-10.98-8.17.2-.73.71-1.02 1.44-1.02 3.14 0 10.2 5.53 11.68 5.53.11 0 .2-.03.24-.1.74-1.2.33-2.04-4.9-5.2-5.21-3.16-8.88-5.06-6.8-7.33.24-.26.58-.38 1-.38 3.17 0 10.66 6.82 10.66 6.82s2.02 2.1 3.25 2.1c.28 0 .52-.1.68-.38.86-1.46-8.06-8.22-8.56-11.01-.34-1.9.24-2.85 1.31-2.85Z"
/>
<path
fill="#FFD21E"
d="M38.6 76.69c2.75-4.04 2.55-7.07-1.22-10.84-3.78-3.77-5.98-9.3-5.98-9.3s-.82-3.2-2.69-2.9c-1.87.3-3.24 5.08.68 8.01 3.91 2.93-.78 4.92-2.29 2.17-1.5-2.75-5.62-9.82-7.76-11.18-2.13-1.35-3.63-.6-3.13 2.2.5 2.79 9.43 9.55 8.56 11-.87 1.47-3.93-1.71-3.93-1.71s-9.57-8.71-11.66-6.44c-2.08 2.27 1.59 4.17 6.8 7.33 5.23 3.16 5.64 4 4.9 5.2-.75 1.2-12.28-8.53-13.36-4.4-1.08 4.11 11.77 5.3 10.98 8.15-.8 2.85-9.06-5.38-10.74-2.18-1.7 3.21 11.65 6.98 11.76 7.01 4.3 1.12 15.25 3.49 19.08-2.12Z"
/>
<path
fill="#FF9D0B"
d="M77.4 48c1.62 0 3.07.66 4.07 1.87a5.97 5.97 0 0 1 1.33 3.76 7.1 7.1 0 0 1 1.95-.3c1.55 0 2.95.59 3.94 1.66a5.8 5.8 0 0 1 .8 7 5.3 5.3 0 0 1 1.78 2.82c.24.9.48 2.8-.8 4.74a5.22 5.22 0 0 1 .37 5.02c-1.02 2.32-3.57 4.14-8.51 6.1-3.08 1.22-5.9 2-5.92 2.01a44.33 44.33 0 0 1-10.93 1.6c-5.86 0-10.05-1.8-12.46-5.34-3.88-5.69-3.33-10.9 1.7-15.92 2.78-2.78 4.63-6.87 5.01-7.77.78-2.66 2.83-5.62 6.24-5.62a5.7 5.7 0 0 1 4.6 2.46c1-1.26 1.98-2.25 2.87-2.82A7.4 7.4 0 0 1 77.4 48Zm0 4c-.51 0-1.13.22-1.82.65-2.13 1.36-6.25 8.43-7.76 11.18a2.43 2.43 0 0 1-2.14 1.31c-1.54 0-2.75-1.53-.14-3.48 3.91-2.93 2.54-7.72.67-8.01a1.54 1.54 0 0 0-.24-.02c-1.7 0-2.45 2.93-2.45 2.93s-2.2 5.52-5.97 9.3c-3.78 3.77-3.98 6.8-1.22 10.83 1.87 2.75 5.47 3.58 9.15 3.58 3.82 0 7.73-.9 9.93-1.46.1-.03 13.45-3.8 11.76-7-.29-.54-.75-.76-1.34-.76-2.38 0-6.71 3.54-8.57 3.54-.42 0-.71-.17-.83-.6-.8-2.85 12.05-4.05 10.97-8.17-.19-.73-.7-1.02-1.44-1.02-3.14 0-10.2 5.53-11.68 5.53-.1 0-.19-.03-.23-.1-.74-1.2-.34-2.04 4.88-5.2 5.23-3.16 8.9-5.06 6.8-7.33-.23-.26-.57-.38-.98-.38-3.18 0-10.67 6.82-10.67 6.82s-2.02 2.1-3.24 2.1a.74.74 0 0 1-.68-.38c-.87-1.46 8.05-8.22 8.55-11.01.34-1.9-.24-2.85-1.31-2.85Z"
/>
<path
fill="#FFD21E"
d="M56.33 76.69c-2.75-4.04-2.56-7.07 1.22-10.84 3.77-3.77 5.97-9.3 5.97-9.3s.82-3.2 2.7-2.9c1.86.3 3.23 5.08-.68 8.01-3.92 2.93.78 4.92 2.28 2.17 1.51-2.75 5.63-9.82 7.76-11.18 2.13-1.35 3.64-.6 3.13 2.2-.5 2.79-9.42 9.55-8.55 11 .86 1.47 3.92-1.71 3.92-1.71s9.58-8.71 11.66-6.44c2.08 2.27-1.58 4.17-6.8 7.33-5.23 3.16-5.63 4-4.9 5.2.75 1.2 12.28-8.53 13.36-4.4 1.08 4.11-11.76 5.3-10.97 8.15.8 2.85 9.05-5.38 10.74-2.18 1.69 3.21-11.65 6.98-11.76 7.01-4.31 1.12-15.26 3.49-19.08-2.12Z"
/>
</svg>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/icons/IconDazzled.svelte
|
<script lang="ts">
export let classNames = "";
</script>
<svg
xmlns="http://www.w3.org/2000/svg"
width="1em"
height="1em"
class={classNames}
fill="none"
viewBox="0 0 26 23"
>
<path
fill="url(#a)"
d="M.93 10.65A10.17 10.17 0 0 1 11.11.48h4.67a9.45 9.45 0 0 1 0 18.89H4.53L1.62 22.2a.38.38 0 0 1-.69-.28V10.65Z"
/>
<path
fill="#000"
fill-rule="evenodd"
d="M11.52 7.4a1.86 1.86 0 1 1-3.72 0 1.86 1.86 0 0 1 3.72 0Zm7.57 0a1.86 1.86 0 1 1-3.73 0 1.86 1.86 0 0 1 3.73 0ZM8.9 12.9a.55.55 0 0 0-.11.35.76.76 0 0 1-1.51 0c0-.95.67-1.94 1.76-1.94 1.09 0 1.76 1 1.76 1.94H9.3a.55.55 0 0 0-.12-.35c-.06-.07-.1-.08-.13-.08s-.08 0-.14.08Zm4.04 0a.55.55 0 0 0-.12.35h-1.51c0-.95.68-1.94 1.76-1.94 1.1 0 1.77 1 1.77 1.94h-1.51a.55.55 0 0 0-.12-.35c-.06-.07-.11-.08-.14-.08-.02 0-.07 0-.13.08Zm-1.89.79c-.02 0-.07-.01-.13-.08a.55.55 0 0 1-.12-.36h-1.5c0 .95.67 1.95 1.75 1.95 1.1 0 1.77-1 1.77-1.95h-1.51c0 .16-.06.28-.12.36-.06.07-.11.08-.14.08Zm4.04 0c-.03 0-.08-.01-.14-.08a.55.55 0 0 1-.12-.36h-1.5c0 .95.67 1.95 1.76 1.95 1.08 0 1.76-1 1.76-1.95h-1.51c0 .16-.06.28-.12.36-.06.07-.11.08-.13.08Zm1.76-.44c0-.16.05-.28.12-.35.06-.07.1-.08.13-.08s.08 0 .14.08c.06.07.11.2.11.35a.76.76 0 0 0 1.51 0c0-.95-.67-1.94-1.76-1.94-1.09 0-1.76 1-1.76 1.94h1.5Z"
clip-rule="evenodd"
/>
<defs>
<radialGradient
id="a"
cx="0"
cy="0"
r="1"
gradientTransform="matrix(0 31.37 -34.85 0 13.08 -9.02)"
gradientUnits="userSpaceOnUse"
>
<stop stop-color="#FFD21E" />
<stop offset="1" stop-color="red" />
</radialGradient>
</defs>
</svg>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/icons/IconCopy.svelte
|
<script lang="ts">
export let classNames = "";
</script>
<svg
class={classNames}
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
fill="currentColor"
focusable="false"
role="img"
width="1em"
height="1em"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 32 32"
>
<path
d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z"
transform="translate(0)"
/>
<path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)" /><rect
fill="none"
width="32"
height="32"
/>
</svg>
|
0
|
hf_public_repos/chat-ui/src/lib/components
|
hf_public_repos/chat-ui/src/lib/components/icons/IconLoading.svelte
|
<script lang="ts">
export let classNames = "";
</script>
<div class={"inline-flex h-8 flex-none items-center gap-1 " + classNames}>
<div
class="h-1 w-1 flex-none animate-bounce rounded-full bg-gray-500 dark:bg-gray-400"
style="animation-delay: 0.25s;"
/>
<div
class="h-1 w-1 flex-none animate-bounce rounded-full bg-gray-500 dark:bg-gray-400"
style="animation-delay: 0.5s;"
/>
<div
class="h-1 w-1 flex-none animate-bounce rounded-full bg-gray-500 dark:bg-gray-400"
style="animation-delay: 0.75s;"
/>
</div>
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/actions/snapScrollToBottom.ts
|
import { navigating } from "$app/stores";
import { tick } from "svelte";
import { get } from "svelte/store";
const detachedOffset = 10;
/**
* @param node element to snap scroll to bottom
* @param dependency pass in a dependency to update scroll on changes.
*/
export const snapScrollToBottom = (node: HTMLElement, dependency: unknown) => {
let prevScrollValue = node.scrollTop;
let isDetached = false;
const handleScroll = () => {
// if user scrolled up, we detach
if (node.scrollTop < prevScrollValue) {
isDetached = true;
}
// if user scrolled back to within 10px of bottom, we reattach
if (node.scrollTop - (node.scrollHeight - node.clientHeight) >= -detachedOffset) {
isDetached = false;
}
prevScrollValue = node.scrollTop;
};
const updateScroll = async (_options: { force?: boolean } = {}) => {
const defaultOptions = { force: false };
const options = { ...defaultOptions, ..._options };
const { force } = options;
if (!force && isDetached && !get(navigating)) return;
// wait for next tick to ensure that the DOM is updated
await tick();
node.scrollTo({ top: node.scrollHeight });
};
node.addEventListener("scroll", handleScroll);
if (dependency) {
updateScroll({ force: true });
}
return {
update: updateScroll,
destroy: () => {
node.removeEventListener("scroll", handleScroll);
},
};
};
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/actions/clickOutside.ts
|
export function clickOutside(element: HTMLElement, callbackFunction: () => void) {
function onClick(event: MouseEvent) {
if (!element.contains(event.target as Node)) {
callbackFunction();
}
}
document.body.addEventListener("click", onClick);
return {
update(newCallbackFunction: () => void) {
callbackFunction = newCallbackFunction;
},
destroy() {
document.body.removeEventListener("click", onClick);
},
};
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/server/generateFromDefaultEndpoint.ts
|
import { smallModel } from "$lib/server/models";
import { MessageUpdateType, type MessageUpdate } from "$lib/types/MessageUpdate";
import type { EndpointMessage } from "./endpoints/endpoints";
export async function* generateFromDefaultEndpoint({
messages,
preprompt,
generateSettings,
}: {
messages: EndpointMessage[];
preprompt?: string;
generateSettings?: Record<string, unknown>;
}): AsyncGenerator<MessageUpdate, string, undefined> {
const endpoint = await smallModel.getEndpoint();
const tokenStream = await endpoint({ messages, preprompt, generateSettings });
for await (const output of tokenStream) {
// if not generated_text is here it means the generation is not done
if (output.generated_text) {
let generated_text = output.generated_text;
for (const stop of [...(smallModel.parameters?.stop ?? []), "<|endoftext|>"]) {
if (generated_text.endsWith(stop)) {
generated_text = generated_text.slice(0, -stop.length).trimEnd();
}
}
return generated_text;
}
yield {
type: MessageUpdateType.Stream,
token: output.token.text,
};
}
throw new Error("Generation failed");
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/server/isURLLocal.ts
|
import { Address6, Address4 } from "ip-address";
import dns from "node:dns";
const dnsLookup = (hostname: string): Promise<{ address: string; family: number }> => {
return new Promise((resolve, reject) => {
dns.lookup(hostname, (err, address, family) => {
if (err) return reject(err);
resolve({ address, family });
});
});
};
export async function isURLLocal(URL: URL): Promise<boolean> {
const { address, family } = await dnsLookup(URL.hostname);
if (family === 4) {
const addr = new Address4(address);
const localSubnet = new Address4("127.0.0.0/8");
return addr.isInSubnet(localSubnet);
}
if (family === 6) {
const addr = new Address6(address);
return addr.isLoopback() || addr.isInSubnet(new Address6("::1/128")) || addr.isLinkLocal();
}
throw Error("Unknown IP family");
}
export function isURLStringLocal(url: string) {
try {
const urlObj = new URL(url);
return isURLLocal(urlObj);
} catch (e) {
// assume local if URL parsing fails
return true;
}
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/server/sendSlack.ts
|
import { env } from "$env/dynamic/private";
import { logger } from "$lib/server/logger";
export async function sendSlack(text: string) {
if (!env.WEBHOOK_URL_REPORT_ASSISTANT) {
logger.warn("WEBHOOK_URL_REPORT_ASSISTANT is not set, tried to send a slack message.");
return;
}
const res = await fetch(env.WEBHOOK_URL_REPORT_ASSISTANT, {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify({
text,
}),
});
if (!res.ok) {
logger.error(`Webhook message failed. ${res.statusText} ${res.text}`);
}
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/server/database.ts
|
import { env } from "$env/dynamic/private";
import { GridFSBucket, MongoClient } from "mongodb";
import type { Conversation } from "$lib/types/Conversation";
import type { SharedConversation } from "$lib/types/SharedConversation";
import type { AbortedGeneration } from "$lib/types/AbortedGeneration";
import type { Settings } from "$lib/types/Settings";
import type { User } from "$lib/types/User";
import type { MessageEvent } from "$lib/types/MessageEvent";
import type { Session } from "$lib/types/Session";
import type { Assistant } from "$lib/types/Assistant";
import type { Report } from "$lib/types/Report";
import type { ConversationStats } from "$lib/types/ConversationStats";
import type { MigrationResult } from "$lib/types/MigrationResult";
import type { Semaphore } from "$lib/types/Semaphore";
import type { AssistantStats } from "$lib/types/AssistantStats";
import type { CommunityToolDB } from "$lib/types/Tool";
import { logger } from "$lib/server/logger";
import { building } from "$app/environment";
import type { TokenCache } from "$lib/types/TokenCache";
import { onExit } from "./exitHandler";
export const CONVERSATION_STATS_COLLECTION = "conversations.stats";
export class Database {
private client: MongoClient;
private static instance: Database;
private constructor() {
if (!env.MONGODB_URL) {
throw new Error(
"Please specify the MONGODB_URL environment variable inside .env.local. Set it to mongodb://localhost:27017 if you are running MongoDB locally, or to a MongoDB Atlas free instance for example."
);
}
this.client = new MongoClient(env.MONGODB_URL, {
directConnection: env.MONGODB_DIRECT_CONNECTION === "true",
});
this.client.connect().catch((err) => {
logger.error(err, "Connection error");
process.exit(1);
});
this.client.db(env.MONGODB_DB_NAME + (import.meta.env.MODE === "test" ? "-test" : ""));
this.client.on("open", () => this.initDatabase());
// Disconnect DB on exit
onExit(() => this.client.close(true));
}
public static getInstance(): Database {
if (!Database.instance) {
Database.instance = new Database();
}
return Database.instance;
}
/**
* Return mongoClient
*/
public getClient(): MongoClient {
return this.client;
}
/**
* Return map of database's collections
*/
public getCollections() {
const db = this.client.db(
env.MONGODB_DB_NAME + (import.meta.env.MODE === "test" ? "-test" : "")
);
const conversations = db.collection<Conversation>("conversations");
const conversationStats = db.collection<ConversationStats>(CONVERSATION_STATS_COLLECTION);
const assistants = db.collection<Assistant>("assistants");
const assistantStats = db.collection<AssistantStats>("assistants.stats");
const reports = db.collection<Report>("reports");
const sharedConversations = db.collection<SharedConversation>("sharedConversations");
const abortedGenerations = db.collection<AbortedGeneration>("abortedGenerations");
const settings = db.collection<Settings>("settings");
const users = db.collection<User>("users");
const sessions = db.collection<Session>("sessions");
const messageEvents = db.collection<MessageEvent>("messageEvents");
const bucket = new GridFSBucket(db, { bucketName: "files" });
const migrationResults = db.collection<MigrationResult>("migrationResults");
const semaphores = db.collection<Semaphore>("semaphores");
const tokenCaches = db.collection<TokenCache>("tokens");
const tools = db.collection<CommunityToolDB>("tools");
return {
conversations,
conversationStats,
assistants,
assistantStats,
reports,
sharedConversations,
abortedGenerations,
settings,
users,
sessions,
messageEvents,
bucket,
migrationResults,
semaphores,
tokenCaches,
tools,
};
}
/**
* Init database once connected: Index creation
* @private
*/
private initDatabase() {
const {
conversations,
conversationStats,
assistants,
assistantStats,
reports,
sharedConversations,
abortedGenerations,
settings,
users,
sessions,
messageEvents,
semaphores,
tokenCaches,
tools,
} = this.getCollections();
conversations
.createIndex(
{ sessionId: 1, updatedAt: -1 },
{ partialFilterExpression: { sessionId: { $exists: true } } }
)
.catch((e) => logger.error(e));
conversations
.createIndex(
{ userId: 1, updatedAt: -1 },
{ partialFilterExpression: { userId: { $exists: true } } }
)
.catch((e) => logger.error(e));
conversations
.createIndex(
{ "message.id": 1, "message.ancestors": 1 },
{ partialFilterExpression: { userId: { $exists: true } } }
)
.catch((e) => logger.error(e));
// Not strictly necessary, could use _id, but more convenient. Also for stats
// To do stats on conversation messages
conversations
.createIndex({ "messages.createdAt": 1 }, { sparse: true })
.catch((e) => logger.error(e));
// Unique index for stats
conversationStats
.createIndex(
{
type: 1,
"date.field": 1,
"date.span": 1,
"date.at": 1,
distinct: 1,
},
{ unique: true }
)
.catch((e) => logger.error(e));
// Allow easy check of last computed stat for given type/dateField
conversationStats
.createIndex({
type: 1,
"date.field": 1,
"date.at": 1,
})
.catch((e) => logger.error(e));
abortedGenerations
.createIndex({ updatedAt: 1 }, { expireAfterSeconds: 30 })
.catch((e) => logger.error(e));
abortedGenerations
.createIndex({ conversationId: 1 }, { unique: true })
.catch((e) => logger.error(e));
sharedConversations.createIndex({ hash: 1 }, { unique: true }).catch((e) => logger.error(e));
settings
.createIndex({ sessionId: 1 }, { unique: true, sparse: true })
.catch((e) => logger.error(e));
settings
.createIndex({ userId: 1 }, { unique: true, sparse: true })
.catch((e) => logger.error(e));
settings.createIndex({ assistants: 1 }).catch((e) => logger.error(e));
users.createIndex({ hfUserId: 1 }, { unique: true }).catch((e) => logger.error(e));
users
.createIndex({ sessionId: 1 }, { unique: true, sparse: true })
.catch((e) => logger.error(e));
// No unicity because due to renames & outdated info from oauth provider, there may be the same username on different users
users.createIndex({ username: 1 }).catch((e) => logger.error(e));
messageEvents
.createIndex({ createdAt: 1 }, { expireAfterSeconds: 60 })
.catch((e) => logger.error(e));
sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 }).catch((e) => logger.error(e));
sessions.createIndex({ sessionId: 1 }, { unique: true }).catch((e) => logger.error(e));
assistants.createIndex({ createdById: 1, userCount: -1 }).catch((e) => logger.error(e));
assistants.createIndex({ userCount: 1 }).catch((e) => logger.error(e));
assistants.createIndex({ review: 1, userCount: -1 }).catch((e) => logger.error(e));
assistants.createIndex({ modelId: 1, userCount: -1 }).catch((e) => logger.error(e));
assistants.createIndex({ searchTokens: 1 }).catch((e) => logger.error(e));
assistants.createIndex({ last24HoursCount: 1 }).catch((e) => logger.error(e));
assistants
.createIndex({ last24HoursUseCount: -1, useCount: -1, _id: 1 })
.catch((e) => logger.error(e));
assistantStats
// Order of keys is important for the queries
.createIndex({ "date.span": 1, "date.at": 1, assistantId: 1 }, { unique: true })
.catch((e) => logger.error(e));
reports.createIndex({ assistantId: 1 }).catch((e) => logger.error(e));
reports.createIndex({ createdBy: 1, assistantId: 1 }).catch((e) => logger.error(e));
// Unique index for semaphore and migration results
semaphores.createIndex({ key: 1 }, { unique: true }).catch((e) => logger.error(e));
semaphores
.createIndex({ createdAt: 1 }, { expireAfterSeconds: 60 })
.catch((e) => logger.error(e));
tokenCaches
.createIndex({ createdAt: 1 }, { expireAfterSeconds: 5 * 60 })
.catch((e) => logger.error(e));
tokenCaches.createIndex({ tokenHash: 1 }).catch((e) => logger.error(e));
tools.createIndex({ createdById: 1, userCount: -1 }).catch((e) => logger.error(e));
tools.createIndex({ userCount: 1 }).catch((e) => logger.error(e));
tools.createIndex({ last24HoursCount: 1 }).catch((e) => logger.error(e));
conversations
.createIndex({
"messages.from": 1,
createdAt: 1,
})
.catch((e) => logger.error(e));
conversations
.createIndex({
userId: 1,
sessionId: 1,
})
.catch((e) => logger.error(e));
}
}
export const collections = building
? ({} as unknown as ReturnType<typeof Database.prototype.getCollections>)
: Database.getInstance().getCollections();
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/server/auth.ts
|
import {
Issuer,
type BaseClient,
type UserinfoResponse,
type TokenSet,
custom,
} from "openid-client";
import { addHours, addWeeks } from "date-fns";
import { env } from "$env/dynamic/private";
import { sha256 } from "$lib/utils/sha256";
import { z } from "zod";
import { dev } from "$app/environment";
import type { Cookies } from "@sveltejs/kit";
import { collections } from "$lib/server/database";
import JSON5 from "json5";
import { logger } from "$lib/server/logger";
export interface OIDCSettings {
redirectURI: string;
}
export interface OIDCUserInfo {
token: TokenSet;
userData: UserinfoResponse;
}
const stringWithDefault = (value: string) =>
z
.string()
.default(value)
.transform((el) => (el ? el : value));
export const OIDConfig = z
.object({
CLIENT_ID: stringWithDefault(env.OPENID_CLIENT_ID),
CLIENT_SECRET: stringWithDefault(env.OPENID_CLIENT_SECRET),
PROVIDER_URL: stringWithDefault(env.OPENID_PROVIDER_URL),
SCOPES: stringWithDefault(env.OPENID_SCOPES),
NAME_CLAIM: stringWithDefault(env.OPENID_NAME_CLAIM).refine(
(el) => !["preferred_username", "email", "picture", "sub"].includes(el),
{ message: "nameClaim cannot be one of the restricted keys." }
),
TOLERANCE: stringWithDefault(env.OPENID_TOLERANCE),
RESOURCE: stringWithDefault(env.OPENID_RESOURCE),
})
.parse(JSON5.parse(env.OPENID_CONFIG || "{}"));
export const requiresUser = !!OIDConfig.CLIENT_ID && !!OIDConfig.CLIENT_SECRET;
const sameSite = z
.enum(["lax", "none", "strict"])
.default(dev || env.ALLOW_INSECURE_COOKIES === "true" ? "lax" : "none")
.parse(env.COOKIE_SAMESITE === "" ? undefined : env.COOKIE_SAMESITE);
const secure = z
.boolean()
.default(!(dev || env.ALLOW_INSECURE_COOKIES === "true"))
.parse(env.COOKIE_SECURE === "" ? undefined : env.COOKIE_SECURE === "true");
export function refreshSessionCookie(cookies: Cookies, sessionId: string) {
cookies.set(env.COOKIE_NAME, sessionId, {
path: "/",
// So that it works inside the space's iframe
sameSite,
secure,
httpOnly: true,
expires: addWeeks(new Date(), 2),
});
}
export async function findUser(sessionId: string) {
const session = await collections.sessions.findOne({ sessionId });
if (!session) {
return null;
}
return await collections.users.findOne({ _id: session.userId });
}
export const authCondition = (locals: App.Locals) => {
return locals.user
? { userId: locals.user._id }
: { sessionId: locals.sessionId, userId: { $exists: false } };
};
/**
* Generates a CSRF token using the user sessionId. Note that we don't need a secret because sessionId is enough.
*/
export async function generateCsrfToken(sessionId: string, redirectUrl: string): Promise<string> {
const data = {
expiration: addHours(new Date(), 1).getTime(),
redirectUrl,
};
return Buffer.from(
JSON.stringify({
data,
signature: await sha256(JSON.stringify(data) + "##" + sessionId),
})
).toString("base64");
}
async function getOIDCClient(settings: OIDCSettings): Promise<BaseClient> {
const issuer = await Issuer.discover(OIDConfig.PROVIDER_URL);
return new issuer.Client({
client_id: OIDConfig.CLIENT_ID,
client_secret: OIDConfig.CLIENT_SECRET,
redirect_uris: [settings.redirectURI],
response_types: ["code"],
[custom.clock_tolerance]: OIDConfig.TOLERANCE || undefined,
});
}
export async function getOIDCAuthorizationUrl(
settings: OIDCSettings,
params: { sessionId: string }
): Promise<string> {
const client = await getOIDCClient(settings);
const csrfToken = await generateCsrfToken(params.sessionId, settings.redirectURI);
return client.authorizationUrl({
scope: OIDConfig.SCOPES,
state: csrfToken,
resource: OIDConfig.RESOURCE || undefined,
});
}
export async function getOIDCUserData(
settings: OIDCSettings,
code: string,
iss?: string
): Promise<OIDCUserInfo> {
const client = await getOIDCClient(settings);
const token = await client.callback(settings.redirectURI, { code, iss });
const userData = await client.userinfo(token);
return { token, userData };
}
export async function validateAndParseCsrfToken(
token: string,
sessionId: string
): Promise<{
/** This is the redirect url that was passed to the OIDC provider */
redirectUrl: string;
} | null> {
try {
const { data, signature } = z
.object({
data: z.object({
expiration: z.number().int(),
redirectUrl: z.string().url(),
}),
signature: z.string().length(64),
})
.parse(JSON.parse(token));
const reconstructSign = await sha256(JSON.stringify(data) + "##" + sessionId);
if (data.expiration > Date.now() && signature === reconstructSign) {
return { redirectUrl: data.redirectUrl };
}
} catch (e) {
logger.error(e);
}
return null;
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/server/usageLimits.ts
|
import { z } from "zod";
import { env } from "$env/dynamic/private";
import JSON5 from "json5";
// RATE_LIMIT is the legacy way to define messages per minute limit
export const usageLimitsSchema = z
.object({
conversations: z.coerce.number().optional(), // how many conversations
messages: z.coerce.number().optional(), // how many messages in a conversation
assistants: z.coerce.number().optional(), // how many assistants
messageLength: z.coerce.number().optional(), // how long can a message be before we cut it off
messagesPerMinute: z
.preprocess((val) => {
if (val === undefined) {
return env.RATE_LIMIT;
}
return val;
}, z.coerce.number().optional())
.optional(), // how many messages per minute
tools: z.coerce.number().optional(), // how many tools
})
.optional();
export const usageLimits = usageLimitsSchema.parse(JSON5.parse(env.USAGE_LIMITS));
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/server/sentenceSimilarity.ts
|
import { dot } from "@huggingface/transformers";
import type { EmbeddingBackendModel } from "$lib/server/embeddingModels";
import type { Embedding } from "$lib/server/embeddingEndpoints/embeddingEndpoints";
// see here: https://github.com/nmslib/hnswlib/blob/359b2ba87358224963986f709e593d799064ace6/README.md?plain=1#L34
export function innerProduct(embeddingA: Embedding, embeddingB: Embedding) {
return 1.0 - dot(embeddingA, embeddingB);
}
export async function getSentenceSimilarity(
embeddingModel: EmbeddingBackendModel,
query: string,
sentences: string[]
): Promise<{ distance: number; embedding: Embedding; idx: number }[]> {
const inputs = [
`${embeddingModel.preQuery}${query}`,
...sentences.map((sentence) => `${embeddingModel.prePassage}${sentence}`),
];
const embeddingEndpoint = await embeddingModel.getEndpoint();
const output = await embeddingEndpoint({ inputs }).catch((err) => {
throw Error("Failed to generate embeddings for sentence similarity", { cause: err });
});
const queryEmbedding: Embedding = output[0];
const sentencesEmbeddings: Embedding[] = output.slice(1);
return sentencesEmbeddings.map((sentenceEmbedding, idx) => ({
distance: innerProduct(queryEmbedding, sentenceEmbedding),
embedding: sentenceEmbedding,
idx,
}));
}
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/server/models.ts
|
import { env } from "$env/dynamic/private";
import type { ChatTemplateInput } from "$lib/types/Template";
import { compileTemplate } from "$lib/utils/template";
import { z } from "zod";
import endpoints, { endpointSchema, type Endpoint } from "./endpoints/endpoints";
import { endpointTgi } from "./endpoints/tgi/endpointTgi";
import { sum } from "$lib/utils/sum";
import { embeddingModels, validateEmbeddingModelByName } from "./embeddingModels";
import type { PreTrainedTokenizer } from "@huggingface/transformers";
import JSON5 from "json5";
import { getTokenizer } from "$lib/utils/getTokenizer";
import { logger } from "$lib/server/logger";
import { ToolResultStatus, type ToolInput } from "$lib/types/Tool";
import { isHuggingChat } from "$lib/utils/isHuggingChat";
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
const reasoningSchema = z.union([
z.object({
type: z.literal("regex"), // everything is reasoning, extract the answer from the regex
regex: z.string(),
}),
z.object({
type: z.literal("tokens"), // use beginning and end tokens that define the reasoning portion of the answer
beginToken: z.string(),
endToken: z.string(),
}),
z.object({
type: z.literal("summarize"), // everything is reasoning, summarize the answer
}),
]);
const modelConfig = z.object({
/** Used as an identifier in DB */
id: z.string().optional(),
/** Used to link to the model page, and for inference */
name: z.string().default(""),
displayName: z.string().min(1).optional(),
description: z.string().min(1).optional(),
logoUrl: z.string().url().optional(),
websiteUrl: z.string().url().optional(),
modelUrl: z.string().url().optional(),
tokenizer: z
.union([
z.string(),
z.object({
tokenizerUrl: z.string().url(),
tokenizerConfigUrl: z.string().url(),
}),
])
.optional(),
datasetName: z.string().min(1).optional(),
datasetUrl: z.string().url().optional(),
preprompt: z.string().default(""),
prepromptUrl: z.string().url().optional(),
chatPromptTemplate: z.string().optional(),
promptExamples: z
.array(
z.object({
title: z.string().min(1),
prompt: z.string().min(1),
})
)
.optional(),
endpoints: z.array(endpointSchema).optional(),
parameters: z
.object({
temperature: z.number().min(0).max(2).optional(),
truncate: z.number().int().positive().optional(),
max_new_tokens: z.number().int().positive().optional(),
stop: z.array(z.string()).optional(),
top_p: z.number().positive().optional(),
top_k: z.number().positive().optional(),
repetition_penalty: z.number().min(-2).max(2).optional(),
presence_penalty: z.number().min(-2).max(2).optional(),
})
.passthrough()
.optional(),
multimodal: z.boolean().default(false),
multimodalAcceptedMimetypes: z.array(z.string()).optional(),
tools: z.boolean().default(false),
unlisted: z.boolean().default(false),
embeddingModel: validateEmbeddingModelByName(embeddingModels).optional(),
/** Used to enable/disable system prompt usage */
systemRoleSupported: z.boolean().default(true),
reasoning: reasoningSchema.optional(),
});
const modelsRaw = z.array(modelConfig).parse(JSON5.parse(env.MODELS));
async function getChatPromptRender(
m: z.infer<typeof modelConfig>
): Promise<ReturnType<typeof compileTemplate<ChatTemplateInput>>> {
if (m.chatPromptTemplate) {
return compileTemplate<ChatTemplateInput>(m.chatPromptTemplate, m);
}
let tokenizer: PreTrainedTokenizer;
try {
tokenizer = await getTokenizer(m.tokenizer ?? m.id ?? m.name);
} catch (e) {
// if fetching the tokenizer fails but it wasnt manually set, use the default template
if (!m.tokenizer) {
logger.warn(
`No tokenizer found for model ${m.name}, using default template. Consider setting tokenizer manually or making sure the model is available on the hub.`,
m
);
return compileTemplate<ChatTemplateInput>(
"{{#if @root.preprompt}}<|im_start|>system\n{{@root.preprompt}}<|im_end|>\n{{/if}}{{#each messages}}{{#ifUser}}<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n{{/ifUser}}{{#ifAssistant}}{{content}}<|im_end|>\n{{/ifAssistant}}{{/each}}",
m
);
}
logger.error(
e,
`Failed to load tokenizer ${
m.tokenizer ?? m.id ?? m.name
} make sure the model is available on the hub and you have access to any gated models.`
);
process.exit();
}
const renderTemplate = ({
messages,
preprompt,
tools,
toolResults,
continueMessage,
}: ChatTemplateInput) => {
let formattedMessages: { role: string; content: string }[] = messages.map((message) => ({
content: message.content,
role: message.from,
}));
if (!m.systemRoleSupported) {
const firstSystemMessage = formattedMessages.find((msg) => msg.role === "system");
formattedMessages = formattedMessages.filter((msg) => msg.role !== "system");
if (
firstSystemMessage &&
formattedMessages.length > 0 &&
formattedMessages[0].role === "user"
) {
formattedMessages[0].content =
firstSystemMessage.content + "\n" + formattedMessages[0].content;
}
}
if (preprompt && formattedMessages[0].role !== "system") {
formattedMessages = [
{
role: m.systemRoleSupported ? "system" : "user",
content: preprompt,
},
...formattedMessages,
];
}
if (toolResults?.length) {
// todo: should update the command r+ tokenizer to support system messages at any location
// or use the `rag` mode without the citations
const id = m.id ?? m.name;
if (isHuggingChat && id.startsWith("CohereForAI")) {
formattedMessages = [
{
role: m.systemRoleSupported ? "system" : "user",
content:
"\n\n<results>\n" +
toolResults
.flatMap((result, idx) => {
if (result.status === ToolResultStatus.Error) {
return (
`Document: ${idx}\n` + `Tool "${result.call.name}" error\n` + result.message
);
}
return (
`Document: ${idx}\n` +
result.outputs
.flatMap((output) =>
Object.entries(output).map(([title, text]) => `${title}\n${text}`)
)
.join("\n")
);
})
.join("\n\n") +
"\n</results>",
},
...formattedMessages,
];
} else if (isHuggingChat && id.startsWith("meta-llama")) {
const results = toolResults.flatMap((result) => {
if (result.status === ToolResultStatus.Error) {
return [
{
tool_call_id: result.call.name,
output: "Error: " + result.message,
},
];
} else {
return result.outputs.map((output) => ({
tool_call_id: result.call.name,
output: JSON.stringify(output),
}));
}
});
formattedMessages = [
...formattedMessages,
{
role: "python",
content: JSON.stringify(results),
},
];
} else {
formattedMessages = [
...formattedMessages,
{
role: m.systemRoleSupported ? "system" : "user",
content: JSON.stringify(toolResults),
},
];
}
tools = [];
}
const chatTemplate = tools?.length ? "tool_use" : undefined;
const documents = (toolResults ?? []).flatMap((result) => {
if (result.status === ToolResultStatus.Error) {
return [{ title: `Tool "${result.call.name}" error`, text: "\n" + result.message }];
}
return result.outputs.flatMap((output) =>
Object.entries(output).map(([title, text]) => ({
title: `Tool "${result.call.name}" ${title}`,
text: "\n" + text,
}))
);
});
const mappedTools =
tools?.map((tool) => {
const inputs: Record<
string,
{
type: ToolInput["type"];
description: string;
required: boolean;
}
> = {};
for (const value of tool.inputs) {
if (value.paramType !== "fixed") {
inputs[value.name] = {
type: value.type,
description: value.description ?? "",
required: value.paramType === "required",
};
}
}
return {
name: tool.name,
description: tool.description,
parameter_definitions: inputs,
};
}) ?? [];
const output = tokenizer.apply_chat_template(formattedMessages, {
tokenize: false,
add_generation_prompt: !continueMessage,
chat_template: chatTemplate,
tools: mappedTools,
documents,
});
if (typeof output !== "string") {
throw new Error("Failed to apply chat template, the output is not a string");
}
return output;
};
return renderTemplate;
}
const processModel = async (m: z.infer<typeof modelConfig>) => ({
...m,
chatPromptRender: await getChatPromptRender(m),
id: m.id || m.name,
displayName: m.displayName || m.name,
preprompt: m.prepromptUrl ? await fetch(m.prepromptUrl).then((r) => r.text()) : m.preprompt,
parameters: { ...m.parameters, stop_sequences: m.parameters?.stop },
});
const addEndpoint = (m: Awaited<ReturnType<typeof processModel>>) => ({
...m,
getEndpoint: async (): Promise<Endpoint> => {
if (!m.endpoints) {
return endpointTgi({
type: "tgi",
url: `${env.HF_API_ROOT}/${m.name}`,
accessToken: env.HF_TOKEN ?? env.HF_ACCESS_TOKEN,
weight: 1,
model: m,
});
}
const totalWeight = sum(m.endpoints.map((e) => e.weight));
let random = Math.random() * totalWeight;
for (const endpoint of m.endpoints) {
if (random < endpoint.weight) {
const args = { ...endpoint, model: m };
switch (args.type) {
case "tgi":
return endpoints.tgi(args);
case "anthropic":
return endpoints.anthropic(args);
case "anthropic-vertex":
return endpoints.anthropicvertex(args);
case "bedrock":
return endpoints.bedrock(args);
case "aws":
return await endpoints.aws(args);
case "openai":
return await endpoints.openai(args);
case "llamacpp":
return endpoints.llamacpp(args);
case "ollama":
return endpoints.ollama(args);
case "vertex":
return await endpoints.vertex(args);
case "genai":
return await endpoints.genai(args);
case "cloudflare":
return await endpoints.cloudflare(args);
case "cohere":
return await endpoints.cohere(args);
case "langserve":
return await endpoints.langserve(args);
default:
// for legacy reason
return endpoints.tgi(args);
}
}
random -= endpoint.weight;
}
throw new Error(`Failed to select endpoint`);
},
});
const inferenceApiIds = isHuggingChat
? await fetch(
"https://huggingface.co/api/models?pipeline_tag=text-generation&inference=warm&filter=conversational"
)
.then((r) => r.json())
.then((json) => json.map((r: { id: string }) => r.id))
.catch((err) => {
logger.error(err, "Failed to fetch inference API ids");
return [];
})
: [];
export const models = await Promise.all(
modelsRaw.map((e) =>
processModel(e)
.then(addEndpoint)
.then(async (m) => ({
...m,
hasInferenceAPI: inferenceApiIds.includes(m.id ?? m.name),
}))
)
);
export type ProcessedModel = (typeof models)[number];
// super ugly but not sure how to make typescript happier
export const validModelIdSchema = z.enum(models.map((m) => m.id) as [string, ...string[]]);
export const defaultModel = models[0];
// Models that have been deprecated
export const oldModels = env.OLD_MODELS
? z
.array(
z.object({
id: z.string().optional(),
name: z.string().min(1),
displayName: z.string().min(1).optional(),
transferTo: validModelIdSchema.optional(),
})
)
.parse(JSON5.parse(env.OLD_MODELS))
.map((m) => ({ ...m, id: m.id || m.name, displayName: m.displayName || m.name }))
: [];
export const validateModel = (_models: BackendModel[]) => {
// Zod enum function requires 2 parameters
return z.enum([_models[0].id, ..._models.slice(1).map((m) => m.id)]);
};
// if `TASK_MODEL` is string & name of a model in `MODELS`, then we use `MODELS[TASK_MODEL]`, else we try to parse `TASK_MODEL` as a model config itself
export const smallModel = env.TASK_MODEL
? (models.find((m) => m.name === env.TASK_MODEL) ||
(await processModel(modelConfig.parse(JSON5.parse(env.TASK_MODEL))).then((m) =>
addEndpoint(m)
))) ??
defaultModel
: defaultModel;
export type BackendModel = Optional<
typeof defaultModel,
"preprompt" | "parameters" | "multimodal" | "unlisted" | "tools" | "hasInferenceAPI"
>;
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/server/logger.ts
|
import pino from "pino";
import { dev } from "$app/environment";
import { env } from "$env/dynamic/private";
let options: pino.LoggerOptions = {};
if (dev) {
options = {
transport: {
target: "pino-pretty",
options: {
colorize: true,
},
},
};
}
export const logger = pino({ ...options, level: env.LOG_LEVEL ?? "info" });
|
0
|
hf_public_repos/chat-ui/src/lib
|
hf_public_repos/chat-ui/src/lib/server/metrics.ts
|
import { collectDefaultMetrics, Registry, Counter, Summary } from "prom-client";
import express from "express";
import { logger } from "$lib/server/logger";
import { env } from "$env/dynamic/private";
import type { Model } from "$lib/types/Model";
import { onExit } from "./exitHandler";
import { promisify } from "util";
interface Metrics {
model: {
conversationsTotal: Counter<Model["id"]>;
messagesTotal: Counter<Model["id"]>;
tokenCountTotal: Counter<Model["id"]>;
timePerOutputToken: Summary<Model["id"]>;
timeToFirstToken: Summary<Model["id"]>;
latency: Summary<Model["id"]>;
votesPositive: Counter<Model["id"]>;
votesNegative: Counter<Model["id"]>;
};
webSearch: {
requestCount: Counter;
pageFetchCount: Counter;
pageFetchCountError: Counter;
pageFetchDuration: Summary;
embeddingDuration: Summary;
};
tool: {
toolUseCount: Counter<string>;
toolUseCountError: Counter<string>;
toolUseDuration: Summary<string>;
timeToChooseTools: Summary;
};
}
export class MetricsServer {
private static instance: MetricsServer;
private metrics: Metrics;
private constructor() {
const app = express();
const port = Number(env.METRICS_PORT || "5565");
if (isNaN(port) || port < 0 || port > 65535) {
logger.warn(`Invalid value for METRICS_PORT: ${env.METRICS_PORT}`);
}
if (env.METRICS_ENABLED !== "false" && env.METRICS_ENABLED !== "true") {
logger.warn(`Invalid value for METRICS_ENABLED: ${env.METRICS_ENABLED}`);
}
if (env.METRICS_ENABLED === "true") {
const server = app.listen(port, () => {
logger.info(`Metrics server listening on port ${port}`);
});
const closeServer = promisify(server.close);
onExit(async () => {
logger.info("Disconnecting metrics server ...");
await closeServer();
logger.info("Server stopped ...");
});
}
const register = new Registry();
collectDefaultMetrics({ register });
this.metrics = {
model: {
conversationsTotal: new Counter({
name: "model_conversations_total",
help: "Total number of conversations",
labelNames: ["model"],
registers: [register],
}),
messagesTotal: new Counter({
name: "model_messages_total",
help: "Total number of messages",
labelNames: ["model"],
registers: [register],
}),
tokenCountTotal: new Counter({
name: "model_token_count_total",
help: "Total number of tokens",
labelNames: ["model"],
registers: [register],
}),
timePerOutputToken: new Summary({
name: "model_time_per_output_token_ms",
help: "Time per output token in ms",
labelNames: ["model"],
registers: [register],
maxAgeSeconds: 5 * 60,
ageBuckets: 5,
}),
timeToFirstToken: new Summary({
name: "model_time_to_first_token_ms",
help: "Time to first token",
labelNames: ["model"],
registers: [register],
maxAgeSeconds: 5 * 60,
ageBuckets: 5,
}),
latency: new Summary({
name: "model_latency_ms",
help: "Total latency until end of answer",
labelNames: ["model"],
registers: [register],
maxAgeSeconds: 5 * 60,
ageBuckets: 5,
}),
votesPositive: new Counter({
name: "model_votes_positive",
help: "Total number of positive votes on messages generated by the model",
labelNames: ["model"],
registers: [register],
}),
votesNegative: new Counter({
name: "model_votes_negative",
help: "Total number of negative votes on messages generated by the model",
labelNames: ["model"],
registers: [register],
}),
},
webSearch: {
requestCount: new Counter({
name: "web_search_request_count",
help: "Total number of web search requests",
registers: [register],
}),
pageFetchCount: new Counter({
name: "web_search_page_fetch_count",
help: "Total number of web search page fetches",
registers: [register],
}),
pageFetchCountError: new Counter({
name: "web_search_page_fetch_count_error",
help: "Total number of web search page fetch errors",
registers: [register],
}),
pageFetchDuration: new Summary({
name: "web_search_page_fetch_duration_ms",
help: "Web search page fetch duration",
registers: [register],
maxAgeSeconds: 5 * 60,
ageBuckets: 5,
}),
embeddingDuration: new Summary({
name: "web_search_embedding_duration_ms",
help: "Web search embedding duration",
registers: [register],
maxAgeSeconds: 5 * 60,
ageBuckets: 5,
}),
},
tool: {
toolUseCount: new Counter({
name: "tool_use_count",
help: "Total number of tool uses",
labelNames: ["tool"],
registers: [register],
}),
toolUseCountError: new Counter({
name: "tool_use_count_error",
help: "Total number of tool use errors",
labelNames: ["tool"],
registers: [register],
}),
toolUseDuration: new Summary({
name: "tool_use_duration_ms",
help: "Tool use duration",
labelNames: ["tool"],
registers: [register],
maxAgeSeconds: 30 * 60, // longer duration since we use this to give feedback to the user
ageBuckets: 5,
}),
timeToChooseTools: new Summary({
name: "time_to_choose_tools_ms",
help: "Time to choose tools",
labelNames: ["model"],
registers: [register],
maxAgeSeconds: 5 * 60,
ageBuckets: 5,
}),
},
};
app.get("/metrics", (req, res) => {
register.metrics().then((metrics) => {
res.set("Content-Type", "text/plain");
res.send(metrics);
});
});
}
public static getInstance(): MetricsServer {
if (!MetricsServer.instance) {
MetricsServer.instance = new MetricsServer();
}
return MetricsServer.instance;
}
public static getMetrics(): Metrics {
return MetricsServer.getInstance().metrics;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.