Eliott C commited on
Split app structure & create convos (#20)
Browse filesFiles changed (15)
- src/hooks.server.ts+11-8
- src/lib/Types.tsDeleted-28
- src/lib/components/chat/ChatInput.svelte+7-5
- src/lib/components/chat/ChatMessage.svelte+2-2
- src/lib/components/chat/ChatMessages.svelteAdded+23
- src/lib/components/chat/ChatWindow.svelteAdded+65
- src/lib/stores/pendingMessage.tsAdded+3
- src/lib/types/Message.ts+1-1
- src/routes/+page.server.ts → src/routes/+layout.server.tsRenamed+2-2
- src/routes/+layout.svelte+54-1
- src/routes/+page.svelte+26-197
- src/routes/api/conversation/+server.ts+1-1
- src/routes/conversation/+server.tsAdded+23
- src/routes/conversation/[id]/+page.server.tsAdded+21
- src/routes/conversation/[id]/+page.svelteAdded+106
5 unmodified lines6789101112131415161718195 unmodified linesevent.locals.sessionId = token || crypto.randomUUID();// Refresh cookie expiration dateevent.cookies.set('session', event.locals.sessionId, {path: '/',sameSite: 'lax',secure: true,httpOnly: true,expires: addYears(new Date(), 1)});const response = await resolve(event);5 unmodified lines6789101112131415161718192021225 unmodified linesevent.locals.sessionId = token || crypto.randomUUID();// Setting a cookie breaks /api/conversation, maybe due to the proxyif (!event.url.pathname.startsWith('/api')) {// Refresh cookie expiration dateevent.cookies.set('session', event.locals.sessionId, {path: '/',sameSite: 'lax',secure: true,httpOnly: true,expires: addYears(new Date(), 1)});}const response = await resolve(event);
12345678910111213141516171819202122232425262728export type Message = | { from: 'user'; content: string; } | { from: 'bot'; content: string; };
export interface Token { id: number; text: string; logprob: number; special: boolean;}
export interface StreamResponse { /** * Generated token */ token: Token; /** * Complete generated text * Only available when the generation is finished */ generated_text?: string;}1234567891011121314151617181920212223247 unmodified lines323334353637<script lang="ts">import { createEventDispatcher } from 'svelte';export let value = '';export let minRows = 1;export let maxRows: null | number = null;export let placeholder = '';export let autofocus = false;const dispatch = createEventDispatcher();$: minHeight = `${1 + minRows * 1.5}em`;$: maxHeight = maxRows ? `${1 + maxRows * 1.5}em` : `auto`;function handleKeydown(event: KeyboardEvent) {// submit on enterif (event.key === 'Enter' && !event.shiftKey) {dispatch('submit');event.preventDefault();}}</script><div class="relative flex-1 min-w-0">7 unmodified linesrows="1"class="absolute m-0 w-full h-full top-0 resize-none border-0 bg-transparent p-3 focus:ring-0 focus-visible:ring-0 dark:bg-transparent outline-none scrollbar-custom overflow-x-hidden overflow-y-scroll"bind:valueon:keydown={handleKeydown}{placeholder}{autofocus}1234567891011121314151617181920212223247 unmodified lines3233343536373839<script lang="ts">export let value = '';export let minRows = 1;export let maxRows: null | number = null;export let placeholder = '';export let disabled = false;export let autofocus = false;$: minHeight = `${1 + minRows * 1.5}em`;$: maxHeight = maxRows ? `${1 + maxRows * 1.5}em` : `auto`;function handleKeydown(event: KeyboardEvent) {// submit on enterif (event.key === 'Enter' && !event.shiftKey) {event.preventDefault();textareaElement.closest('form')?.requestSubmit();}}let textareaElement: HTMLTextAreaElement;</script><div class="relative flex-1 min-w-0">7 unmodified linesrows="1"class="absolute m-0 w-full h-full top-0 resize-none border-0 bg-transparent p-3 focus:ring-0 focus-visible:ring-0 dark:bg-transparent outline-none scrollbar-custom overflow-x-hidden overflow-y-scroll"bind:valuebind:this={textareaElement}{disabled}on:keydown={handleKeydown}{placeholder}{autofocus}
12345678910<script lang="ts">import type { Message } from '$lib/Types';export let message: Message;</script>{#if message.from === 'bot'}<div class="flex items-start justify-start gap-4 leading-relaxed"><imgalt=""12345678910<script lang="ts">import type { Message } from '$lib/types/Message';export let message: Message;</script>{#if message.from === 'assistant'}<div class="flex items-start justify-start gap-4 leading-relaxed"><imgalt=""
1234567891011121314151617181920212223<script lang="ts"> import type { Message } from '$lib/types/Message'; import { snapScrollToBottom } from '$lib/actions/snapScrollToBottom'; import ScrollToBottomBtn from '$lib/components/ScrollToBottomBtn.svelte'; import ChatIntroduction from './ChatIntroduction.svelte'; import ChatMessage from './ChatMessage.svelte';
export let messages: Message[];
let chatContainer: HTMLElement;</script>
<div class="overflow-y-auto h-full" use:snapScrollToBottom={messages} bind:this={chatContainer}> <div class="max-w-3xl xl:max-w-4xl mx-auto px-5 pt-6 flex flex-col gap-8 h-full"> {#each messages as message} <ChatMessage {message} /> {:else} <ChatIntroduction /> {/each} <div class="h-32 flex-none" /> </div> <ScrollToBottomBtn class="bottom-10 right-12" scrollNode={chatContainer} /></div>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465<script lang="ts"> import type { Message } from '$lib/types/Message'; import { createEventDispatcher } from 'svelte'; import ChatMessages from './ChatMessages.svelte'; import ChatInput from './ChatInput.svelte';
export let messages: Message[] = []; export let disabled: boolean;
let message: string;
const dispatch = createEventDispatcher<{ message: string }>();</script>
<div class="relative h-screen"> <nav class="sm:hidden flex items-center h-12 border-b px-4 justify-between dark:border-gray-800"> <button>[ ]</button> <button>New Chat</button> <button>+</button> </nav> <ChatMessages {messages} /> <div class="flex max-md:border-t dark:border-gray-800 items-center max-md:dark:bg-gray-900 max-md:bg-white bg-gradient-to-t from-white dark:from-gray-900 to-transparent justify-center absolute inset-x-0 max-w-3xl xl:max-w-4xl mx-auto px-5 bottom-0 py-4 md:py-8 w-full" > <form on:submit|preventDefault={() => { dispatch('message', message); message = ''; }} class="w-full relative flex items-center rounded-xl flex-1 max-w-4xl border bg-gray-100 focus-within:border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:focus-within:border-gray-500 transition-all" > <div class="w-full flex flex-1 border-none bg-transparent"> <ChatInput placeholder="Ask anything" bind:value={message} {disabled} autofocus maxRows={10} /> <button class="p-1 px-[0.7rem] self-end my-1 h-[2.4rem] rounded-lg hover:bg-gray-100 enabled:dark:hover:text-gray-400 dark:hover:bg-gray-900 disabled:hover:bg-transparent dark:disabled:hover:bg-transparent disabled:opacity-60 dark:disabled:opacity-40 flex-shrink-0 transition-all mx-1" disabled={!message || disabled} type="submit" > <svg class="text-gray-500 dark:text-gray-300 pointer-events-none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32" ><path d="M30 28.59L22.45 21A11 11 0 1 0 21 22.45L28.59 30zM5 14a9 9 0 1 1 9 9a9 9 0 0 1-9-9z" fill="currentColor" /></svg > </button> </div> </form> </div></div>123import { writable } from 'svelte/store';
export const pendingMessage = writable<string>('');1234export interface Message {from: 'user' | 'assistant';content: 'string';}1234export interface Message {from: 'user' | 'assistant';content: string;}
12345678import type { PageServerLoad } from './$types';import { collections } from '$lib/server/database';import type { Conversation } from '$lib/types/Conversation';export const load: PageServerLoad = async (event) => {const { conversations } = collections;return {12345678import type { LayoutServerLoad } from './$types';import { collections } from '$lib/server/database';import type { Conversation } from '$lib/types/Conversation';export const load: LayoutServerLoad = async (event) => {const { conversations } = collections;return {
12345<script lang="ts">import '../styles.css';</script><slot />12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758<script lang="ts">import '../styles.css';import type { LayoutData } from './$types';export let data: LayoutData;function switchTheme() {const { classList } = document.querySelector('html') as HTMLElement;if (classList.contains('dark')) {classList.remove('dark');localStorage.theme = 'light';} else {classList.add('dark');localStorage.theme = 'dark';}}</script><divclass="grid h-screen w-screen md:grid-cols-[280px,1fr] overflow-hidden text-smd dark:text-gray-300"><navclass="max-md:hidden grid grid-rows-[auto,1fr,auto] grid-cols-1 max-h-screen bg-gradient-to-l from-gray-50 dark:from-gray-800/30 rounded-r-xl"><div class="flex-none sticky top-0 p-3 flex flex-col"><buttonon:click={() => location.reload()}class="border px-12 py-2.5 rounded-lg shadow bg-white dark:bg-gray-700 dark:border-gray-600">New Chat</button></div><div class="flex flex-col overflow-y-auto p-3 -mt-3 gap-2">{#each data.conversations as conv}<ahref="/conversation/{conv.id}"class="truncate py-3 px-3 rounded-lg flex-none text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700">{conv.title}</a>{/each}</div><div class="flex flex-col p-3 gap-2"><buttonon:click={switchTheme}class="text-left flex items-center first-letter:capitalize truncate py-3 px-3 rounded-lg flex-none text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700">Theme</button><ahref="/"class="truncate py-3 px-3 rounded-lg flex-none text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700">Settings</a></div></nav><slot /></div>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207<script lang="ts">import type { Message } from '$lib/Types';import { HfInference } from '@huggingface/inference';import ChatMessage from '$lib/components/chat/ChatMessage.svelte';import ChatIntroduction from '$lib/components/chat/ChatIntroduction.svelte';import ChatInput from '$lib/components/chat/ChatInput.svelte';import {PUBLIC_ASSISTANT_MESSAGE_TOKEN,PUBLIC_SEP_TOKEN,PUBLIC_USER_MESSAGE_TOKEN} from '$env/static/public';import { page } from '$app/stores';import type { PageData } from './$types';export let data: PageData;const userToken = PUBLIC_USER_MESSAGE_TOKEN || '<|prompter|>';const assistantToken = PUBLIC_ASSISTANT_MESSAGE_TOKEN || '<|assistant|>';const sepToken = PUBLIC_SEP_TOKEN || '<|endoftext|>';import { snapScrollToBottom } from '$lib/actions/snapScrollToBottom';import ScrollToBottomBtn from '$lib/components/ScrollToBottomBtn.svelte';const hf = new HfInference();const model = hf.endpoint(`${$page.url.origin}/api/conversation`);let messages: Message[] = [];let message = '';let chatContainer: HTMLElement;function switchTheme() {const { classList } = document.querySelector('html') as HTMLElement;if (classList.contains('dark')) {classList.remove('dark');localStorage.theme = 'light';} else {classList.add('dark');localStorage.theme = 'dark';}}async function getTextGenerationStream(inputs: string) {const response = model.textGenerationStream({inputs,parameters: {// Taken from https://huggingface.co/spaces/huggingface/open-assistant-private-testing/blob/main/app.py#L54// @ts-ignorestop: ['<|endoftext|>'],max_new_tokens: 1024,truncate: 1024,typical_p: 0.2}},{use_cache: false});// Regex to check if the text finishes by "<" but is not a piece of code like "`<img>`"const endOfTextRegex = /(?<!`)<(?!`)/;for await (const data of response) {if (!data) break;try {if (!data.token.special) {if (messages.at(-1)?.from !== 'bot') {// First token has a space at the beginning, trim itmessages = [...messages, { from: 'bot', content: data.token.text.trimStart() }];} else {const isEndOfText = endOfTextRegex.test(data.token.text);messages.at(-1)!.content += isEndOfText? data.token.text.replace('<', ''): data.token.text;messages = messages;if (isEndOfText) break;}}} catch (error) {console.error(error);break;}}}function onWrite() {if (!message) return;messages = [...messages, { from: 'user', content: message }];message = '';const inputs =messages.map((m) =>(m.from === 'user' ? userToken + m.content : assistantToken + m.content) +(m.content.endsWith(sepToken) ? '' : sepToken)).join('') + assistantToken;getTextGenerationStream(inputs);}</script><divclass="grid h-screen w-screen md:grid-cols-[280px,1fr] overflow-hidden text-smd dark:text-gray-300"><navclass="max-md:hidden grid grid-rows-[auto,1fr,auto] grid-cols-1 max-h-screen bg-gradient-to-l from-gray-50 dark:from-gray-800/30 rounded-r-xl"><div class="flex-none sticky top-0 p-3 flex flex-col"><buttonon:click={() => location.reload()}class="border px-12 py-2.5 rounded-lg shadow bg-white dark:bg-gray-700 dark:border-gray-600">New Chat</button></div><div class="flex flex-col overflow-y-auto p-3 -mt-3 gap-2">{#each data.conversations as conv}<ahref="/conversation/{conv.id}"class="truncate py-3 px-3 rounded-lg flex-none text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700">{conv.title}</a>{/each}</div><div class="flex flex-col p-3 gap-2"><buttonon:click={switchTheme}class="text-left flex items-center first-letter:capitalize truncate py-3 px-3 rounded-lg flex-none text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700">Theme</button><ahref="/"class="truncate py-3 px-3 rounded-lg flex-none text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700">Settings</a></div></nav><div class="relative h-screen"><navclass="sm:hidden flex items-center h-12 border-b px-4 justify-between dark:border-gray-800"><button>[ ]</button><button>New Chat</button><button>+</button></nav><div class="overflow-y-auto h-full" use:snapScrollToBottom={messages} bind:this={chatContainer}><div class="max-w-3xl xl:max-w-4xl mx-auto px-5 pt-6 flex flex-col gap-8 h-full">{#each messages as message}<ChatMessage {message} />{:else}<ChatIntroduction />{/each}<div class="h-32 flex-none" /></div><ScrollToBottomBtn class="bottom-10 right-12" scrollNode={chatContainer} /></div><divclass="flex max-md:border-t dark:border-gray-800 items-center max-md:dark:bg-gray-900 max-md:bg-white bg-gradient-to-t from-white dark:from-gray-900 to-transparent justify-center absolute inset-x-0 max-w-3xl xl:max-w-4xl mx-auto px-5 bottom-0 py-4 md:py-8 w-full"><formon:submit={onWrite}class="w-full relative flex items-center rounded-xl flex-1 max-w-4xl border bg-gray-100 focus-within:border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:focus-within:border-gray-500 transition-all"><div class="w-full flex flex-1 border-none bg-transparent"><ChatInputplaceholder="Ask anything"bind:value={message}on:submit={onWrite}autofocusmaxRows={10}/><buttonclass="p-1 px-[0.7rem] self-end my-1 h-[2.4rem] rounded-lg hover:bg-gray-100 enabled:dark:hover:text-gray-400 dark:hover:bg-gray-900 disabled:hover:bg-transparent dark:disabled:hover:bg-transparent disabled:opacity-60 dark:disabled:opacity-40 flex-shrink-0 transition-all mx-1"disabled={!message}type="submit"><svgclass="text-gray-500 dark:text-gray-300 pointer-events-none"xmlns="http://www.w3.org/2000/svg"xmlns:xlink="http://www.w3.org/1999/xlink"aria-hidden="true"focusable="false"role="img"width="1em"height="1em"preserveAspectRatio="xMidYMid meet"viewBox="0 0 32 32"><pathd="M30 28.59L22.45 21A11 11 0 1 0 21 22.45L28.59 30zM5 14a9 9 0 1 1 9 9a9 9 0 0 1-9-9z"fill="currentColor"/></svg></button></div></form></div></div></div>123456789101112131415161718192021222324252627282930313233343536<script lang="ts">import { goto, invalidate, invalidateAll } from '$app/navigation';import ChatWindow from '$lib/components/chat/ChatWindow.svelte';import { pendingMessage } from '$lib/stores/pendingMessage';let loading = false;async function createConversation(message: string) {try {loading = true;const res = await fetch('/conversation', {method: 'POST',headers: {'Content-Type': 'application/json'}});if (!res.ok) {alert('Error while creating conversation: ' + (await res.text()));return;}const { conversationId } = await res.json();// Ugly hack to use a store as temp storage, feel free to improve ^^pendingMessage.set(message);// invalidateAll to update list of conversationsawait goto(`/conversation/${conversationId}`, { invalidateAll: true });} finally {loading = false;}}</script><ChatWindow on:message={(ev) => createConversation(ev.detail)} disabled={loading} />
1234567import { HF_TOKEN } from '$env/static/private';import { PUBLIC_MODEL_ENDPOINT } from '$env/static/public';export async function POST({ request }) {return await fetch(PUBLIC_MODEL_ENDPOINT, {headers: {...request.headers,1234567import { HF_TOKEN } from '$env/static/private';import { PUBLIC_MODEL_ENDPOINT } from '$env/static/public';export async function POST({ request, fetch }) {return await fetch(PUBLIC_MODEL_ENDPOINT, {headers: {...request.headers,
1234567891011121314151617181920212223import type { RequestHandler } from './$types';import { collections } from '$lib/server/database';import { ObjectId } from 'mongodb';
export const POST: RequestHandler = async (input) => { const res = await collections.conversations.insertOne({ _id: new ObjectId(), title: 'Untitled ' + ((await collections.conversations.countDocuments({ sessionId: input.locals.sessionId })) + 1), messages: [], createdAt: new Date(), updatedAt: new Date(), sessionId: input.locals.sessionId });
return new Response( JSON.stringify({ conversationId: res.insertedId.toString() }), { headers: { 'Content-Type': 'application/json' } } );};123456789101112131415161718192021import type { PageServerLoad } from './$types';import { collections } from '$lib/server/database';import type { Conversation } from '$lib/types/Conversation';import { ObjectId } from 'mongodb';import { error } from '@sveltejs/kit';
export const load: PageServerLoad = async (event) => { // todo: add validation on params.id const conversation = await collections.conversations.findOne({ _id: new ObjectId(event.params.id), sessionId: event.locals.sessionId });
if (!conversation) { throw error(404, 'Conversation not found'); }
return { messages: conversation.messages };};123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106<script lang="ts"> import ChatWindow from '$lib/components/chat/ChatWindow.svelte'; import { pendingMessage } from '$lib/stores/pendingMessage'; import { onMount } from 'svelte'; import type { PageData } from './$types'; import { page } from '$app/stores'; import { PUBLIC_ASSISTANT_MESSAGE_TOKEN, PUBLIC_SEP_TOKEN, PUBLIC_USER_MESSAGE_TOKEN } from '$env/static/public'; import { HfInference } from '@huggingface/inference';
export let data: PageData;
$: messages = data.messages;
const userToken = PUBLIC_USER_MESSAGE_TOKEN; const assistantToken = PUBLIC_ASSISTANT_MESSAGE_TOKEN; const sepToken = PUBLIC_SEP_TOKEN;
const hf = new HfInference(); const model = hf.endpoint(`${$page.url.origin}/api/conversation`);
let loading = false;
async function getTextGenerationStream(inputs: string) { const response = model.textGenerationStream( { inputs, parameters: { // Taken from https://huggingface.co/spaces/huggingface/open-assistant-private-testing/blob/main/app.py#L54 // @ts-ignore stop: ['<|endoftext|>'], max_new_tokens: 1024, truncate: 1024, typical_p: 0.2 } }, { use_cache: false } );
// Regex to check if the text finishes by "<" but is not a piece of code like "`<img>`" const endOfTextRegex = /(?<!`)<(?!`)/;
for await (const data of response) { if (!data) break;
if (!data.token.special) { if (messages.at(-1)?.from !== 'assistant') { // First token has a space at the beginning, trim it messages = [...messages, { from: 'assistant', content: data.token.text.trimStart() }]; } else { const isEndOfText = endOfTextRegex.test(data.token.text);
messages.at(-1)!.content += isEndOfText ? data.token.text.replace('<', '') : data.token.text; messages = messages;
if (isEndOfText) break; } } }
// todo: if everything went well, store message + response in DB }
async function writeMessage(message: string) { if (!message.trim()) return;
try { loading = true;
messages = [...messages, { from: 'user', content: message }]; message = ''; const inputs = messages .map( (m) => (m.from === 'user' ? userToken + m.content : assistantToken + m.content) + (m.content.endsWith(sepToken) ? '' : sepToken) ) .join('') + assistantToken;
await getTextGenerationStream(inputs); } finally { loading = false; } }
onMount(async () => { if ($pendingMessage) { const val = $pendingMessage; $pendingMessage = '';
if (messages.length === 0) { writeMessage(val); } } });</script>
<ChatWindow disabled={loading} {messages} on:message={(message) => writeMessage(message.detail)} />src/hooks.server.ts+11-8
src/lib/Types.tsDeleted-28
src/lib/components/chat/ChatInput.svelte+7-5
src/lib/components/chat/ChatMessage.svelte+2-2
src/lib/components/chat/ChatMessages.svelteAdded+23
src/lib/components/chat/ChatWindow.svelteAdded+65
src/lib/stores/pendingMessage.tsAdded+3
src/lib/types/Message.ts+1-1
src/routes/+page.server.ts → src/routes/+layout.server.tsRenamed+2-2
src/routes/+layout.svelte+54-1
src/routes/+page.svelte+26-197
src/routes/api/conversation/+server.ts+1-1
src/routes/conversation/+server.tsAdded+23
src/routes/conversation/[id]/+page.server.tsAdded+21
src/routes/conversation/[id]/+page.svelteAdded+106