Spaces:
Runtime error
Runtime error
Feature: chat with two models simultaneously (#11)
Browse filesFiles changed (5)
6 unmodified lines78910111213146 unmodified linesexport let maxTokens: number;export let messages: ChatCompletionInputMessage[];$: console.log(messages);const npmSnippet = `import { HfInference } from '@huggingface/inference'const hf = new HfInference('your access token')`;6 unmodified lines7891011126 unmodified linesexport let maxTokens: number;export let messages: ChatCompletionInputMessage[];const npmSnippet = `import { HfInference } from '@huggingface/inference'const hf = new HfInference('your access token')`;
1234567891011121314151617184 unmodified lines232425262728292 unmodified lines323334353637383940413 unmodified lines4546474849505113 unmodified lines65666768697071727374757617 unmodified lines949596979899<script lang="ts">import { createEventDispatcher } from 'svelte';import PlaygroundCode from '$lib/components/CodeSnippets.svelte';import PlaygroundMessage from '$lib/components/Message.svelte';export let loading;export let streamingMessage;export let conversations;export let conversation;export let index;export let currentConversation;export let viewCode;export let messages;const dispatch = createEventDispatcher<{ addMessage: void; deleteMessage: number }>();let messageContainer: HTMLDivElement | null = null;4 unmodified lines}$: {if (currentConversation.messages.at(-1)) {scrollToBottom();}}2 unmodified lines<divclass="flex max-h-[calc(100dvh-5.8rem)] flex-col overflow-y-auto overflow-x-hidden @container"class:pointer-events-none={loading}class:animate-pulse={loading && !streamingMessage}bind:this={messageContainer}>{#if conversations.length > 1}<divclass="sticky top-0 flex h-11 flex-none items-center gap-2 whitespace-nowrap rounded-lg border border-gray-200/80 bg-white pl-3 pr-2 text-sm leading-none shadow-sm *:flex-none dark:border-gray-800 dark:bg-gray-800/70 dark:hover:bg-gray-800"class:mr-3={index === 0}3 unmodified lines<div>{conversation.model}</div><buttonclass="ml-auto flex size-6 items-center justify-center rounded bg-gray-50 text-xs hover:bg-gray-100 dark:bg-gray-800 dark:hover:bg-gray-700"on:click={() => (conversations = conversations.filter((_, i) => i !== index))}>✕</button>13 unmodified lines</div>{/if}{#if !viewCode}{#each messages as message, i}<PlaygroundMessageclass="border-b"{message}on:delete={() => dispatch('deleteMessage', i)}autofocus={conversations.length === 1 && !loading && i === messages.length - 1}/>{/each}17 unmodified lines</div></button>{:else}<PlaygroundCode {...currentConversation} {...currentConversation.config} />{/if}</div>1234567891011121314154 unmodified lines202122232425262 unmodified lines293031323334353637383 unmodified lines4243444546474813 unmodified lines62636465666768697071727374757617 unmodified lines949596979899<script lang="ts">import { createEventDispatcher } from 'svelte';import CodeSnippets from '$lib/components/CodeSnippets.svelte';import Message from '$lib/components/Message.svelte';export let loading;export let conversation;export let index;export let viewCode;export let sideBySide = false;const dispatch = createEventDispatcher<{ addMessage: void; deleteMessage: number, deleteConversation: number }>();let messageContainer: HTMLDivElement | null = null;4 unmodified lines}$: {if (conversation.messages.at(-1)) {scrollToBottom();}}2 unmodified lines<divclass="flex max-h-[calc(100dvh-5.8rem)] flex-col overflow-y-auto overflow-x-hidden @container"class:pointer-events-none={loading}class:animate-pulse={loading && !conversation.config.streaming}bind:this={messageContainer}>{#if sideBySide}<divclass="sticky top-0 flex h-11 flex-none items-center gap-2 whitespace-nowrap rounded-lg border border-gray-200/80 bg-white pl-3 pr-2 text-sm leading-none shadow-sm *:flex-none dark:border-gray-800 dark:bg-gray-800/70 dark:hover:bg-gray-800"class:mr-3={index === 0}3 unmodified lines<div>{conversation.model}</div><buttonclass="ml-auto flex size-6 items-center justify-center rounded bg-gray-50 text-xs hover:bg-gray-100 dark:bg-gray-800 dark:hover:bg-gray-700"on:click={() => dispatch('deleteConversation', index)}>✕</button>13 unmodified lines</div>{/if}{#if !viewCode}{#each conversation.messages as message, messageIdx}<Messageclass="border-b"{message}conversationIdx={index}{messageIdx}on:messageValueChangedon:delete={() => dispatch('deleteMessage', messageIdx)}autofocus={!sideBySide && !loading && messageIdx === conversation.messages.length - 1}/>{/each}17 unmodified lines</div></button>{:else}<CodeSnippets {...conversation} {...conversation.config} />{/if}</div>
123456785 unmodified lines141516171819202 unmodified lines232425262728299 unmodified lines394041424344452 unmodified lines484950515253542 unmodified lines575859606162632 unmodified lines66676869707172<script lang="ts">export let temperature = 0.5;export let maxTokens = 2048;export let streaming = true;export let jsonMode = true;</script><div>5 unmodified lines<inputtype="number"class="w-16 rounded border bg-transparent px-1 py-0.5 text-right text-sm dark:border-gray-700"bind:value={temperature}min="0"max="1"step="0.1"2 unmodified lines<inputid="temperature-range"type="range"bind:value={temperature}min="0"max="1"step="0.1"9 unmodified lines<inputtype="number"class="w-20 rounded border bg-transparent px-1 py-0.5 text-right text-sm dark:border-gray-700"bind:value={maxTokens}min="0"max="4096"step="512"2 unmodified lines<inputid="max-tokens-range"type="range"bind:value={maxTokens}min="0"max="4096"step="512"2 unmodified lines</div><div class="mt-2"><label class="flex cursor-pointer items-center justify-between"><input type="checkbox" bind:checked={streaming} class="peer sr-only" /><span class="text-sm font-medium text-gray-900 dark:text-gray-300">Streaming</span><divclass="peer relative h-5 w-9 rounded-full bg-gray-200 after:absolute after:start-[2px] after:top-[2px] after:h-4 after:w-4 after:rounded-full after:border after:border-gray-300 after:bg-white after:transition-all after:content-[''] peer-checked:bg-black peer-checked:after:translate-x-full peer-checked:after:border-white peer-focus:outline-none dark:border-gray-600 dark:bg-gray-700 dark:peer-checked:bg-blue-600"2 unmodified lines</div><div class="mt-2"><label class="flex cursor-pointer items-center justify-between"><input type="checkbox" value="" class="peer sr-only" disabled bind:checked={jsonMode} /><span class="text-sm font-medium text-gray-900 dark:text-gray-300">JSON Mode</span><divclass="peer relative h-5 w-9 rounded-full bg-gray-200 after:absolute after:start-[2px] after:top-[2px] after:h-4 after:w-4 after:rounded-full after:border after:border-gray-300 after:bg-white after:transition-all after:content-[''] peer-checked:bg-black peer-checked:after:translate-x-full peer-checked:after:border-white peer-focus:outline-none dark:border-gray-600 dark:bg-gray-700 dark:peer-checked:bg-blue-600"123456789105 unmodified lines161718192021222 unmodified lines252627282930319 unmodified lines414243444546472 unmodified lines505152535455562 unmodified lines596061626364652 unmodified lines68697071727374<script lang="ts">// export let temperature = 0.5;// export let maxTokens = 2048;// export let streaming = true;// export let jsonMode = true;export let config;</script><div>5 unmodified lines<inputtype="number"class="w-16 rounded border bg-transparent px-1 py-0.5 text-right text-sm dark:border-gray-700"bind:value={config.temperature}min="0"max="1"step="0.1"2 unmodified lines<inputid="temperature-range"type="range"bind:value={config.temperature}min="0"max="1"step="0.1"9 unmodified lines<inputtype="number"class="w-20 rounded border bg-transparent px-1 py-0.5 text-right text-sm dark:border-gray-700"bind:value={config.maxTokens}min="0"max="4096"step="512"2 unmodified lines<inputid="max-tokens-range"type="range"bind:value={config.maxTokens}min="0"max="4096"step="512"2 unmodified lines</div><div class="mt-2"><label class="flex cursor-pointer items-center justify-between"><input type="checkbox" bind:checked={config.streaming} class="peer sr-only" /><span class="text-sm font-medium text-gray-900 dark:text-gray-300">Streaming</span><divclass="peer relative h-5 w-9 rounded-full bg-gray-200 after:absolute after:start-[2px] after:top-[2px] after:h-4 after:w-4 after:rounded-full after:border after:border-gray-300 after:bg-white after:transition-all after:content-[''] peer-checked:bg-black peer-checked:after:translate-x-full peer-checked:after:border-white peer-focus:outline-none dark:border-gray-600 dark:bg-gray-700 dark:peer-checked:bg-blue-600"2 unmodified lines</div><div class="mt-2"><label class="flex cursor-pointer items-center justify-between"><input type="checkbox" value="" class="peer sr-only" disabled bind:checked={config.jsonMode} /><span class="text-sm font-medium text-gray-900 dark:text-gray-300">JSON Mode</span><divclass="peer relative h-5 w-9 rounded-full bg-gray-200 after:absolute after:start-[2px] after:top-[2px] after:h-4 after:w-4 after:rounded-full after:border after:border-gray-300 after:bg-white after:transition-all after:content-[''] peer-checked:bg-black peer-checked:after:translate-x-full peer-checked:after:border-white peer-focus:outline-none dark:border-gray-600 dark:bg-gray-700 dark:peer-checked:bg-blue-600"
2 unmodified lines345678910114 unmodified lines161718192021222 unmodified linesimport { type ChatCompletionInputMessage } from '@huggingface/tasks';export let message: ChatCompletionInputMessage;export let autofocus: boolean = false;const dispatch = createEventDispatcher();</script><div4 unmodified lines</div><textarea{autofocus}bind:value={message.content}placeholder="Enter {message.role} message"class="resize-none rounded bg-transparent px-2 py-2.5 ring-gray-100 [field-sizing:content] hover:resize-y hover:bg-white focus:resize-y focus:bg-white focus:ring group-hover/message:ring @2xl:px-3 dark:ring-gray-600 dark:hover:bg-gray-900 dark:focus:bg-gray-900"rows="1"2 unmodified lines3456789101112134 unmodified lines18192021222324252 unmodified linesimport { type ChatCompletionInputMessage } from '@huggingface/tasks';export let message: ChatCompletionInputMessage;export let conversationIdx: number;export let messageIdx: number;export let autofocus: boolean = false;const dispatch = createEventDispatcher<{ delete: void; messageValueChanged: {conversationIdx: number, messageIdx: number, value: string} }>();</script><div4 unmodified lines</div><textarea{autofocus}value={message.content}on:input={(e) => dispatch("messageValueChanged", {conversationIdx, messageIdx, value: e.target.value})}placeholder="Enter {message.role} message"class="resize-none rounded bg-transparent px-2 py-2.5 ring-gray-100 [field-sizing:content] hover:resize-y hover:bg-white focus:resize-y focus:bg-white focus:ring group-hover/message:ring @2xl:px-3 dark:ring-gray-600 dark:hover:bg-gray-900 dark:focus:bg-gray-900"rows="1"
123454 unmodified lines1011121314151614 unmodified lines3132333435363738394041424344454647485 unmodified lines545556575859606162636465666768697071727374755 unmodified lines8182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218351 unmodified lines23523623723823924024124224324424524624724824998 unmodified lines34834935035135235335422 unmodified lines3773783793803813823834 unmodified lines388389390391392393394395396397398399<script lang="ts">import PlaygroundCode from '$lib/components/CodeSnippets.svelte';import {createHfInference,prepareRequestMessages,4 unmodified linesimport PlaygroundTokenModal from '$lib/components/HFTokenModal.svelte';import PlaygroundModelSelector from '$lib/components/ModelSelector.svelte';import Conversation from '$lib/components/Conversation.svelte';import { onDestroy, onMount } from 'svelte';import { type ModelEntry } from '@huggingface/hub';import { type ChatCompletionInputMessage } from '@huggingface/tasks';14 unmodified linesviewCode = false;}let currentConversation = conversations[0];let systemMessage: ChatCompletionInputMessage = { role: 'system', content: '' };$: messages = currentConversation.messages;let hfToken: string | null = import.meta.env.VITE_HF_TOKEN;let viewCode = false;let showTokenModal = false;let loading = false;let streamingMessage: ChatCompletionInputMessage | null = null;let tokens = 0;let latency = 0;let abortController: AbortController | null = null;let waitForNonStreaming = true;onMount(() => {5 unmodified linescompatibleModels = (await res.json()) as ModelEntry[];compatibleModels.sort((a, b) => a.id.toLowerCase().localeCompare(b.id.toLowerCase()));})();});onDestroy(() => {if (abortController) {abortController.abort();}});function addMessage() {currentConversation.messages = [...currentConversation.messages,{role: currentConversation.messages.at(-1)?.role === 'user' ? 'assistant' : 'user',content: ''}];conversations = conversations;}5 unmodified lines}function deleteMessage(idx: number) {const deletedMsg = deleteAndGetItem<ChatCompletionInputMessage>(currentConversation.messages,idx);// delete messages in user/assistant pairs. otherwise, the chat template will be brokenif (deletedMsg) {const { role } = deletedMsg;const pairIdx = role === 'user' ? idx : idx - 1;deleteAndGetItem<ChatCompletionInputMessage>(currentConversation.messages, pairIdx);}conversations = conversations;}function reset() {currentConversation.messages = [...startMessages];systemMessage.content = '';conversations = conversations;}function abort() {if (streamingMessage && abortController) {abortController.abort();abortController = null;}loading = false;streamingMessage = null;waitForNonStreaming = false;}async function submit() {// last message has to be from userif (currentConversation.messages?.at(-1)?.role !== 'user') {addMessage();return;}if (!hfToken) {showTokenModal = true;return;}(document.activeElement as HTMLElement).blur();loading = true;const startTime = performance.now();try {const hf = createHfInference(hfToken);const requestMessages = prepareRequestMessages(systemMessage, messages);if (currentConversation.config.streaming) {streamingMessage = { role: 'assistant', content: '' };currentConversation.messages = [...currentConversation.messages, streamingMessage];abortController = new AbortController();await handleStreamingResponse(hf,currentConversation.model,requestMessages,currentConversation.config.temperature,currentConversation.config.maxTokens,currentConversation.config.jsonMode,(content) => {if (streamingMessage) {streamingMessage.content = content;currentConversation.messages = [...currentConversation.messages];conversations = conversations;}},abortController);} else {streamingMessage = null;waitForNonStreaming = true;const newMessage = await handleNonStreamingResponse(hf,currentConversation.model,requestMessages,currentConversation.config.temperature,currentConversation.config.maxTokens,currentConversation.config.jsonMode);// check if the user did not abort the requestif (waitForNonStreaming) {currentConversation.messages = [...currentConversation.messages, newMessage];conversations = conversations;}}addMessage();} catch (error) {if (error.name !== 'AbortError') {alert('error: ' + (error as Error).message);}} finally {const endTime = performance.now();latency = Math.round(endTime - startTime);loading = false;streamingMessage = null;abortController = null;}}51 unmodified lines{#each conversations as conversation, index}<Conversation{loading}{streamingMessage}{conversations}{conversation}{index}{currentConversation}{viewCode}{messages}on:addMessage={addMessage}on:deleteMessage={(e) => deleteMessage(e.detail)}/>{/each}</div>98 unmodified lines<divclass="flex flex-1 flex-col gap-6 overflow-y-hidden rounded-xl border border-gray-200/80 bg-gradient-to-b from-white via-white p-3 shadow-sm dark:border-white/5 dark:from-gray-800/40 dark:via-gray-800/40"><PlaygroundModelSelector {compatibleModels} bind:currentModel={currentConversation.model} /><divclass="group relative -mt-4 flex h-[26px] w-full items-center justify-center gap-2 rounded-lg bg-black px-5 text-sm text-white hover:bg-gray-900 focus:outline-none focus:ring-4 focus:ring-gray-300 dark:border-gray-700 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-gray-700">22 unmodified linesid: String(Math.random()),model: e.target.value,config: { temperature: 0.5, maxTokens: 2048, streaming: true, jsonMode: false },messages: startMessages}];}}4 unmodified lines</select></div><PlaygroundOptionsbind:temperature={currentConversation.config.temperature}bind:maxTokens={currentConversation.config.maxTokens}bind:jsonMode={currentConversation.config.jsonMode}bind:streaming={currentConversation.config.streaming}/><div class="mt-auto"><div class="mb-3 flex items-center justify-between gap-2"><label12344 unmodified lines910111213141514 unmodified lines30313233343536373839404142435 unmodified lines49505152535455565758596061626364656667686970717273747576777879808182838485865 unmodified lines929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720851 unmodified lines26026126226326426526626726826927027127227327427527698 unmodified lines37537637737837938038122 unmodified lines4044054064074084094104 unmodified lines415416417418419420421<script lang="ts">import {createHfInference,prepareRequestMessages,4 unmodified linesimport PlaygroundTokenModal from '$lib/components/HFTokenModal.svelte';import PlaygroundModelSelector from '$lib/components/ModelSelector.svelte';import Conversation from '$lib/components/Conversation.svelte';import { onMount } from 'svelte';import { type ModelEntry } from '@huggingface/hub';import { type ChatCompletionInputMessage } from '@huggingface/tasks';14 unmodified linesviewCode = false;}let systemMessage: ChatCompletionInputMessage = { role: 'system', content: '' };let hfToken: string | null = import.meta.env.VITE_HF_TOKEN;let viewCode = false;let showTokenModal = false;let loading = false;let tokens = 0;let latency = 0;let abortControllers: AbortController[] = []let waitForNonStreaming = true;onMount(() => {5 unmodified linescompatibleModels = (await res.json()) as ModelEntry[];compatibleModels.sort((a, b) => a.id.toLowerCase().localeCompare(b.id.toLowerCase()));})();return () => {for(const abortController of abortControllers){abortController.abort();}}});function addMessage() {conversations = conversations.map(conversation => {conversation.messages = [...conversation.messages,{role: conversation.messages.at(-1)?.role === 'user' ? 'assistant' : 'user',content: ''}];return conversation;});}function updateMessage(value: string, conversationIdx: number, messageIdx: number) {const lastMsgIdx = conversations[0].messages.length - 1;const msg = conversations[conversationIdx].messages[messageIdx];msg.content = value;const { role } = msg;if(messageIdx === lastMsgIdx && role === "user"){conversations = conversations.map(conversation => {conversation.messages[messageIdx].content = value;return conversation;});}conversations = conversations;}5 unmodified lines}function deleteMessage(idx: number) {conversations = conversations.map(conversation => {const deletedMsg = deleteAndGetItem<ChatCompletionInputMessage>(conversation.messages,idx);// delete messages in user/assistant pairs. otherwise, the chat template will be brokenif (deletedMsg) {const { role } = deletedMsg;const pairIdx = role === 'user' ? idx : idx - 1;deleteAndGetItem<ChatCompletionInputMessage>(conversation.messages, pairIdx);}return conversation;});}function deleteConversation(idx: number) {deleteAndGetItem(conversations, idx);conversations = conversations;}function reset() {systemMessage.content = '';conversations = conversations.map(conversation => {conversation.messages = [...startMessages];return conversation;});}function abort() {if (abortControllers.length) {for(const abortController of abortControllers){abortController.abort();}abortControllers = [];}loading = false;waitForNonStreaming = false;}async function runInference(conversation: Conversation){const startTime = performance.now();const hf = createHfInference(hfToken);const requestMessages = prepareRequestMessages(systemMessage, conversation.messages);if (conversation.config.streaming) {const streamingMessage = { role: 'assistant', content: '' };conversation.messages = [...conversation.messages, streamingMessage];const abortController = new AbortController();abortControllers.push(abortController)await handleStreamingResponse(hf,conversation.model,requestMessages,conversation.config.temperature,conversation.config.maxTokens,conversation.config.jsonMode,(content) => {if (streamingMessage) {streamingMessage.content = content;conversation.messages = [...conversation.messages];conversations = conversations;}},abortController);} else {waitForNonStreaming = true;const newMessage = await handleNonStreamingResponse(hf,conversation.model,requestMessages,conversation.config.temperature,conversation.config.maxTokens,conversation.config.jsonMode);// check if the user did not abort the requestif (waitForNonStreaming) {conversation.messages = [...conversation.messages, newMessage];conversations = conversations;}}const endTime = performance.now();latency = Math.round(endTime - startTime);}async function submit() {// // last message has to be from user// if (currentConversation.messages?.at(-1)?.role !== 'user') {// addMessage();// return;// }if (!hfToken) {showTokenModal = true;return;}(document.activeElement as HTMLElement).blur();loading = true;try{const promises = conversations.map(conversation => runInference(conversation));await Promise.all(promises);addMessage();}catch (error){if (error.name !== 'AbortError') {alert('error: ' + (error as Error).message);}} finally {loading = false;abortControllers = [];}}51 unmodified lines{#each conversations as conversation, index}<Conversation{loading}{conversation}{index}{viewCode}sideBySide={conversations.length > 1}on:addMessage={addMessage}on:messageValueChanged={(e) => {const {conversationIdx, messageIdx, value} = e.detail;updateMessage(value, conversationIdx, messageIdx);}}on:deleteMessage={(e) => deleteMessage(e.detail)}on:deleteConversation={(e) => deleteConversation(e.detail)}/>{/each}</div>98 unmodified lines<divclass="flex flex-1 flex-col gap-6 overflow-y-hidden rounded-xl border border-gray-200/80 bg-gradient-to-b from-white via-white p-3 shadow-sm dark:border-white/5 dark:from-gray-800/40 dark:via-gray-800/40"><PlaygroundModelSelector {compatibleModels} bind:currentModel={conversations[0].model} /><divclass="group relative -mt-4 flex h-[26px] w-full items-center justify-center gap-2 rounded-lg bg-black px-5 text-sm text-white hover:bg-gray-900 focus:outline-none focus:ring-4 focus:ring-gray-300 dark:border-gray-700 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-gray-700">22 unmodified linesid: String(Math.random()),model: e.target.value,config: { temperature: 0.5, maxTokens: 2048, streaming: true, jsonMode: false },messages: conversations[0].messages}];}}4 unmodified lines</select></div><PlaygroundOptions bind:config={conversations[0].config} /><div class="mt-auto"><div class="mb-3 flex items-center justify-between gap-2"><label
src/lib/components/CodeSnippets.svelte-2
src/lib/components/Conversation.svelte+16-16
src/lib/components/GenerationConfig.svelte+12-10
src/lib/components/Message.svelte+5-2
src/routes/+page.svelte+122-100