Spaces:
Runtime error
Runtime error
same prettier as hub
Browse filesFiles changed (30)
- .prettierrcDeleted-8
- .prettierrc.mjsAdded+11
- postcss.config.js+2-2
- src/app.css+1-1
- src/lib/components/Icons/IconCaret.svelte+2-5
- src/lib/components/Icons/IconCode.svelte+1-1
- src/lib/components/Icons/IconCopyCode.svelte+1-1
- src/lib/components/Icons/IconCross.svelte+1-1
- src/lib/components/Icons/IconDelete.svelte+2-5
- src/lib/components/Icons/IconPlus.svelte+2-7
- src/lib/components/Icons/IconSearch.svelte+2-5
- src/lib/components/Icons/IconShare.svelte+2-9
- src/lib/components/Icons/IconStar.svelte+1-1
- src/lib/components/InferencePlayground/InferencePlayground.svelte+34-39
- src/lib/components/InferencePlayground/InferencePlaygroundCodeSnippets.svelte+52-52
- src/lib/components/InferencePlayground/InferencePlaygroundConversation.svelte+7-7
- src/lib/components/InferencePlayground/InferencePlaygroundGenerationConfig.svelte+11-14
- src/lib/components/InferencePlayground/InferencePlaygroundHFTokenModal.svelte+11-15
- src/lib/components/InferencePlayground/InferencePlaygroundMessage.svelte+3-3
- src/lib/components/InferencePlayground/InferencePlaygroundModelSelector.svelte+9-15
- src/lib/components/InferencePlayground/InferencePlaygroundModelSelectorModal.svelte+20-20
- src/lib/components/InferencePlayground/generationConfigSettings.ts+8-12
- src/lib/components/InferencePlayground/inferencePlaygroundUtils.ts+12-16
- src/lib/types/index.d.ts+3-3
- src/routes/+layout.svelte+1-1
- src/routes/+page.server.ts+9-12
- src/routes/+page.svelte+1-1
- svelte.config.js+4-4
- tailwind.config.ts+5-5
- vite.config.ts+3-3
12345678{ "useTabs": true, "singleQuote": true, "trailingComma": "none", "printWidth": 100, "plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"], "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]}1234567891011export default { arrowParens: "avoid", quoteProps: "consistent", trailingComma: "es5", useTabs: true, tabWidth: 2, printWidth: 120, overrides: [{ files: "*.svelte", options: { parser: "svelte" } }], tailwindConfig: "./tailwind.config.ts", plugins: [import("prettier-plugin-svelte"), import("prettier-plugin-tailwindcss")],};12345456export default { plugins: { tailwindcss: {}, autoprefixer: {} } autoprefixer: {}, },};11234@import 'highlight.js/styles/atom-one-light';@import "highlight.js/styles/atom-one-light";@tailwind base;@tailwind components;@tailwind utilities;1223456 unmodified lines121314151617181516<script lang="ts"> export let classNames = ''; export let classNames = "";</script>
<svg6 unmodified lines height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24" ><path d="M16.293 9.293L12 13.586L7.707 9.293l-1.414 1.414L12 16.414l5.707-5.707z" fill="currentColor" /> ><path d="M16.293 9.293L12 13.586L7.707 9.293l-1.414 1.414L12 16.414l5.707-5.707z" fill="currentColor" /></svg>122345<script lang="ts"> export let classNames = ''; export let classNames = "";</script>
<svg122345<script lang="ts"> export let classNames = ''; export let classNames = "";</script>
<svg122345<script lang="ts"> export let classNames = ''; export let classNames = "";</script>
<svg1223458 unmodified lines1415161718192017181920<script lang="ts"> export let classNames = ''; export let classNames = "";</script>
<svg8 unmodified lines preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"> <path d="M12 12h2v12h-2z" fill="currentColor" /><path d="M18 12h2v12h-2z" fill="currentColor" /><path <path d="M12 12h2v12h-2z" fill="currentColor" /><path d="M18 12h2v12h-2z" fill="currentColor" /><path d="M4 6v2h2v20a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8h2V6zm4 22V8h16v20z" fill="currentColor" /><path d="M12 2h8v2h-8z" fill="currentColor" />1223456789105678<script lang="ts"> export let classNames = ''; export let classNames = "";</script>
<svg class={classNames} xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"<svg class={classNames} xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32" ><path fill="currentColor" d="M16 2A14.172 14.172 0 0 0 2 16a14.172 14.172 0 0 0 14 14a14.172 14.172 0 0 0 14-14A14.172 14.172 0 0 0 16 2Zm8 15h-7v7h-2v-7H8v-2h7V8h2v7h7Z"1223458 unmodified lines141516171819201718<script lang="ts"> export let classNames = ''; export let classNames = "";</script>
<svg8 unmodified lines 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" /> <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>12234567891011125678<script lang="ts"> export let classNames = ''; export let classNames = "";</script>
<svg class={classNames} width="1em" height="1em" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg"><svg class={classNames} width="1em" height="1em" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd"122345<script lang="ts"> export let classNames = ''; export let classNames = "";</script>
<svg2 unmodified lines345678910111213141516171867891011121314151617181920212222232425262728282930313132333412 unmodified lines4748495051525051525354553 unmodified lines596061626263646522 unmodified lines888990919192939495969798989910010116 unmodified lines1181191201211221211221231241252 unmodified lines1281291301311311321331342 unmodified lines13713813914014014114214214314414515 unmodified lines1611621631641651641651661671687 unmodified lines1761771781791791801811823 unmodified lines18618718818919019118919019119216 unmodified lines20921021121421221321421522 unmodified lines2382392402432442412422432449 unmodified lines2542552562602612622572582592602 unmodified lines createHfInference, handleStreamingResponse, handleNonStreamingResponse, isSystemPromptSupported } from './inferencePlaygroundUtils'; import GenerationConfig from './InferencePlaygroundGenerationConfig.svelte'; import HFTokenModal from './InferencePlaygroundHFTokenModal.svelte'; import ModelSelector from './InferencePlaygroundModelSelector.svelte'; import Conversation from './InferencePlaygroundConversation.svelte'; import { onDestroy } from 'svelte'; import { type ChatCompletionInputMessage } from '@huggingface/tasks'; import type { ModelEntryWithTokenizer } from '$lib/types'; import { defaultGenerationConfig } from './generationConfigSettings'; import IconShare from '../Icons/IconShare.svelte'; import IconDelete from '../Icons/IconDelete.svelte'; import IconCode from '../Icons/IconCode.svelte'; isSystemPromptSupported, } from "./inferencePlaygroundUtils"; import GenerationConfig from "./InferencePlaygroundGenerationConfig.svelte"; import HFTokenModal from "./InferencePlaygroundHFTokenModal.svelte"; import ModelSelector from "./InferencePlaygroundModelSelector.svelte"; import Conversation from "./InferencePlaygroundConversation.svelte"; import { onDestroy } from "svelte"; import { type ChatCompletionInputMessage } from "@huggingface/tasks"; import type { ModelEntryWithTokenizer } from "$lib/types"; import { defaultGenerationConfig } from "./generationConfigSettings"; import IconShare from "../Icons/IconShare.svelte"; import IconDelete from "../Icons/IconDelete.svelte"; import IconCode from "../Icons/IconCode.svelte";
export let models: ModelEntryWithTokenizer[];
const startMessages: ChatCompletionInputMessage[] = [{ role: 'user', content: '' }]; const startMessages: ChatCompletionInputMessage[] = [{ role: "user", content: "" }];
let conversation: Conversation = { model: models[0], config: defaultGenerationConfig, messages: startMessages, streaming: true streaming: true, };
let systemMessage: ChatCompletionInputMessage = { role: 'system', content: '' }; let systemMessage: ChatCompletionInputMessage = { role: "system", content: "" }; let hfToken: string | undefined = import.meta.env.VITE_HF_TOKEN; let viewCode = false; let showTokenModal = false;12 unmodified lines conversation.messages = [ ...conversation.messages, { role: conversation.messages.at(-1)?.role === 'user' ? 'assistant' : 'user', content: '' } role: conversation.messages.at(-1)?.role === "user" ? "assistant" : "user", content: "", }, ]; }
3 unmodified lines }
function reset() { systemMessage.content = ''; systemMessage.content = ""; conversation.messages = [...startMessages]; }
22 unmodified lines const hf = createHfInference(hfToken);
if (conversation.streaming) { const streamingMessage = { role: 'assistant', content: '' }; const streamingMessage = { role: "assistant", content: "" }; conversation.messages = [...conversation.messages, streamingMessage]; abortController = new AbortController();
await handleStreamingResponse( hf, conversation, (content) => { content => { if (streamingMessage) { streamingMessage.content = content; conversation.messages = [...conversation.messages];16 unmodified lines
addMessage(); } catch (error) { if (error.name !== 'AbortError') { alert('error: ' + (error as Error).message); if (error.name !== "AbortError") { alert("error: " + (error as Error).message); } } finally { loading = false;2 unmodified lines }
function onKeydown(event: KeyboardEvent) { if (!event.shiftKey && event.key === 'Enter') { if (!event.shiftKey && event.key === "Enter") { submit(); } }2 unmodified lines{#if showTokenModal} <HFTokenModal on:close={() => (showTokenModal = false)} on:submit={(e) => { on:submit={e => { const formData = new FormData(e.target); hfToken = formData.get('hf-token'); hfToken = formData.get("hf-token"); submit(); showTokenModal = false; }}15 unmodified lines name="" id="" placeholder={systemPromptSupported ? 'Enter a custom prompt' : 'System prompt is not supported with the chosen model.'} ? "Enter a custom prompt" : "System prompt is not supported with the chosen model."} bind:value={systemMessage.content} class="absolute inset-x-0 bottom-0 h-full resize-none bg-transparent px-3 pt-10 text-sm outline-none" ></textarea>7 unmodified lines index={0} {viewCode} on:addMessage={addMessage} on:deleteMessage={(e) => deleteMessage(e.detail)} on:deleteMessage={e => deleteMessage(e.detail)} /> </div> <div3 unmodified lines type="button" class="flex h-[39px] flex-none gap-2 rounded-lg border border-gray-200 bg-white px-3 py-2.5 text-sm font-medium text-gray-900 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:outline-none focus:ring-4 focus:ring-gray-100 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white dark:focus:ring-gray-700" > <div class="flex size-5 items-center justify-center rounded border border-black/5 bg-black/5 text-xs" > <div class="flex size-5 items-center justify-center rounded border border-black/5 bg-black/5 text-xs"> <IconShare /> </div>
16 unmodified lines class="flex h-[39px] items-center gap-2 rounded-lg border border-gray-200 bg-white px-3 py-2.5 text-sm font-medium text-gray-900 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:outline-none focus:ring-4 focus:ring-gray-100 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white dark:focus:ring-gray-700" > <IconCode /> {!viewCode ? 'View Code' : 'Hide Code'}</button {!viewCode ? "View Code" : "Hide Code"}</button > <button on:click={() => {22 unmodified lines /> </div> {:else} Run <span class="inline-flex gap-0.5 rounded border border-white/20 bg-white/10 px-0.5 text-xs text-white/70" Run <span class="inline-flex gap-0.5 rounded border border-white/20 bg-white/10 px-0.5 text-xs text-white/70" >↵</span > {/if}9 unmodified lines <GenerationConfig bind:conversation /> <div class="mt-auto"> <div class="mb-3 flex items-center justify-between gap-2"> <label for="default-range" class="block text-sm font-medium text-gray-900 dark:text-white" >API Quota</label > <label for="default-range" class="block text-sm font-medium text-gray-900 dark:text-white">API Quota</label> <span class="rounded bg-gray-100 px-1.5 py-0.5 text-xs font-medium text-gray-800 dark:bg-gray-700 dark:text-gray-300" >Free</span12345678910111223456789101112131415161617181920211920212223245 unmodified lines303132333334353636373839404041424243444520 unmodified lines66676869707169707172737475757677782 unmodified lines818283848584858687882 unmodified lines919293949495969798999910010110210310410510610710610710810911011111111211311417 unmodified lines1321331341351361371351361371381391401411411421431442 unmodified lines14714814915015015115215215315415515515615715815916016016116216316416516616716716816916917017117117217317419 unmodified lines19419519619719719819920020120220320420320420520620620720820921021121121221321421521621721821921721821922022122231 unmodified lines254255256257257258259259260261262263264265265266267268<script lang="ts"> import hljs from 'highlight.js/lib/core'; import javascript from 'highlight.js/lib/languages/javascript'; import python from 'highlight.js/lib/languages/python'; import http from 'highlight.js/lib/languages/http'; import type { Conversation } from '$lib/types'; import IconCopyCode from '../Icons/IconCopyCode.svelte'; import { onDestroy } from 'svelte';
hljs.registerLanguage('javascript', javascript); hljs.registerLanguage('python', python); hljs.registerLanguage('http', http); import hljs from "highlight.js/lib/core"; import javascript from "highlight.js/lib/languages/javascript"; import python from "highlight.js/lib/languages/python"; import http from "highlight.js/lib/languages/http"; import type { Conversation } from "$lib/types"; import IconCopyCode from "../Icons/IconCopyCode.svelte"; import { onDestroy } from "svelte";
hljs.registerLanguage("javascript", javascript); hljs.registerLanguage("python", python); hljs.registerLanguage("http", http);
export let conversation: Conversation;
const lanuages = ['javascript', 'python', 'http']; const lanuages = ["javascript", "python", "http"]; type Language = (typeof lanuages)[number]; const labelsByLanguage: Record<Language, string> = { javascript: 'JavaScript', python: 'Python', http: 'Curl' javascript: "JavaScript", python: "Python", http: "Curl", };
interface Snippet {5 unmodified lines $: snippetsByLanguage = { javascript: getJavascriptSnippets(conversation), python: getPythonSnippets(conversation), http: getHttpSnippets(conversation) http: getHttpSnippets(conversation), };
let selectedLanguage: Language = 'javascript'; let selectedLanguage: Language = "javascript"; let timeout: ReturnType<typeof setTimeout>;
function getMessages() { const placeholder = [{ role: 'user', content: 'Tell me a story' }]; const placeholder = [{ role: "user", content: "Tell me a story" }]; let messages = conversation.messages; if (messages.length === 1 && messages[0].role === 'user' && !messages[0].content) { if (messages.length === 1 && messages[0].role === "user" && !messages[0].content) { messages = placeholder; } return messages;20 unmodified lines
const snippets: Snippet[] = []; snippets.push({ label: 'Install @huggingface/inference', language: 'http', code: `npm install --save @huggingface/inference` label: "Install @huggingface/inference", language: "http", code: `npm install --save @huggingface/inference`, }); if (conversation.streaming) { snippets.push({ label: 'Streaming API', label: "Streaming API", code: `import { HfInference } from "@huggingface/inference"
const inference = new HfInference("your HF token")2 unmodified lines
for await (const chunk of inference.chatCompletionStream({ model: "${conversation.model.id}", messages: ${formattedMessages({ sep: ',\n ', start: '[\n ', end: '\n ]' })}, ${formattedConfig({ sep: ',\n ', start: '', end: '' })}, messages: ${formattedMessages({ sep: ",\n ", start: "[\n ", end: "\n ]" })}, ${formattedConfig({ sep: ",\n ", start: "", end: "" })}, seed: 0,})) { if (chunk.choices && chunk.choices.length > 0) {2 unmodified lines console.clear(); console.log(out); } }`}`, }); } else { // non-streaming snippets.push({ label: 'Non-Streaming API', label: "Non-Streaming API", code: `import { HfInference } from '@huggingface/inference'
const inference = new HfInference("your access token")
const out = await inference.chatCompletion({ model: "${conversation.model.id}", messages: ${formattedMessages({ sep: ',\n ', start: '[\n ', end: '\n ]' })}, ${formattedConfig({ sep: ',\n ', start: '', end: '' })}, messages: ${formattedMessages({ sep: ",\n ", start: "[\n ", end: "\n ]" })}, ${formattedConfig({ sep: ",\n ", start: "", end: "" })}, seed: 0,});
console.log(out.choices[0].message);`console.log(out.choices[0].message);`, }); }
17 unmodified lines
const snippets: Snippet[] = []; snippets.push({ label: 'Install huggingface_hub', language: 'http', code: `pip install huggingface_hub` label: "Install huggingface_hub", language: "http", code: `pip install huggingface_hub`, }); if (conversation.streaming) { snippets.push({ label: 'Streaming API', label: "Streaming API", code: `from huggingface_hub import InferenceClient
model_id="${conversation.model.id}"2 unmodified lines
output = ""
messages = ${formattedMessages({ sep: ',\n ', start: `[\n `, end: `\n]` })}messages = ${formattedMessages({ sep: ",\n ", start: `[\n `, end: `\n]` })}
for token in client.chat_completion(messages, stream=True, ${formattedConfig({ sep: ', ', start: '', end: '' })}):for token in client.chat_completion(messages, stream=True, ${formattedConfig({ sep: ", ", start: "", end: "" })}): new_content = token.choices[0].delta.content print(new_content, end="") output += new_content` output += new_content`, }); } else { // non-streaming snippets.push({ label: 'Non-Streaming API', label: "Non-Streaming API", code: `from huggingface_hub import InferenceClient
model_id="${conversation.model.id}"hf_token = "your HF token"inference_client = InferenceClient(model_id, token=hf_token)
messages = ${formattedMessages({ sep: ',\n ', start: `[\n `, end: `\n]` })}messages = ${formattedMessages({ sep: ",\n ", start: `[\n `, end: `\n]` })}
output = inference_client.chat_completion(messages, ${formattedConfig({ sep: ', ', start: '', end: '' })})output = inference_client.chat_completion(messages, ${formattedConfig({ sep: ", ", start: "", end: "" })})
print(output.choices[0].message)`print(output.choices[0].message)`, }); }
19 unmodified lines
if (conversation.streaming) { snippets.push({ label: 'Streaming API', label: "Streaming API", code: `curl 'https://api-inference.huggingface.co/models/${conversation.model.id}/v1/chat/completions' \\--header "Authorization: Bearer {YOUR_HF_TOKEN}" \\--header 'Content-Type: application/json' \\--data '{ "model": "${conversation.model.id}", "messages": ${formattedMessages({ sep: ',\n ', start: `[\n `, end: `\n]` })}, ${formattedConfig({ sep: ',\n ', start: '', end: '' })}, "messages": ${formattedMessages({ sep: ",\n ", start: `[\n `, end: `\n]` })}, ${formattedConfig({ sep: ",\n ", start: "", end: "" })}, "stream": true}'`}'`, }); } else { // non-streaming snippets.push({ label: 'Non-Streaming API', label: "Non-Streaming API", code: `curl 'https://api-inference.huggingface.co/models/${conversation.model.id}/v1/chat/completions' \\--header "Authorization: Bearer {YOUR_HF_TOKEN}" \\--header 'Content-Type: application/json' \\--data '{ "model": "${conversation.model.id}", "messages": ${formattedMessages({ sep: ',\n ', start: `[\n `, end: `\n]` })}, ${formattedConfig({ sep: ',\n ', start: '', end: '' })}}'` "messages": ${formattedMessages({ sep: ",\n ", start: `[\n `, end: `\n]` })}, ${formattedConfig({ sep: ",\n ", start: "", end: "" })}}'`, }); }
31 unmodified lines <h2 class="font-semibold">{label}</h2> <button class="flex items-center gap-x-1.5 rounded-md bg-gray-200 px-1.5 py-0.5 text-sm transition dark:bg-gray-950" on:click={(e) => { on:click={e => { const el = e.currentTarget; el.classList.add('text-green-500'); el.classList.add("text-green-500"); navigator.clipboard.writeText(code); if (timeout) { clearTimeout(timeout); } timeout = setTimeout(() => { el.classList.remove('text-green-500'); el.classList.remove("text-green-500"); }, 1000); }} >1234562345678930 unmodified lines40414243434445464748495050515253<script lang="ts"> import { createEventDispatcher } from 'svelte'; import CodeSnippets from './InferencePlaygroundCodeSnippets.svelte'; import Message from './InferencePlaygroundMessage.svelte'; import IconPlus from '../Icons/IconPlus.svelte'; import type { Conversation } from '$lib/types'; import { createEventDispatcher } from "svelte"; import CodeSnippets from "./InferencePlaygroundCodeSnippets.svelte"; import Message from "./InferencePlaygroundMessage.svelte"; import IconPlus from "../Icons/IconPlus.svelte"; import type { Conversation } from "$lib/types";
export let loading; export let conversation: Conversation;30 unmodified lines <Message class="border-b" {message} on:delete={() => dispatch('deleteMessage', messageIdx)} on:delete={() => dispatch("deleteMessage", messageIdx)} autofocus={!loading && messageIdx === conversation.messages.length - 1} /> {/each}
<button class="flex px-6 py-6 hover:bg-gray-50 dark:hover:bg-gray-800/50" on:click={() => dispatch('addMessage')} on:click={() => dispatch("addMessage")} disabled={loading} > <div class="flex items-center gap-2 !p-0 text-sm font-semibold">122345676789101011121313141516171819192021222324222324252623 unmodified lines505152545556535455563 unmodified lines60616266636465663 unmodified lines7071727673747576<script lang="ts"> import type { Conversation } from '$lib/types'; import type { Conversation } from "$lib/types"; import { GENERATION_CONFIG_KEYS, GENERATION_CONFIG_KEYS_ADVANCED, GENERATION_CONFIG_SETTINGS } from './generationConfigSettings'; GENERATION_CONFIG_SETTINGS, } from "./generationConfigSettings";
export let conversation: Conversation; export let classNames = ''; export let classNames = "";
$: modelMaxLength = conversation.model.tokenizerConfig.model_max_length; $: maxTokens = Math.min(modelMaxLength ?? GENERATION_CONFIG_SETTINGS['max_tokens'].max, 64_000); $: maxTokens = Math.min(modelMaxLength ?? GENERATION_CONFIG_SETTINGS["max_tokens"].max, 64_000);</script>
<div class="flex flex-col gap-y-7 {classNames}"> {#each GENERATION_CONFIG_KEYS as key} {@const { label, min, step } = GENERATION_CONFIG_SETTINGS[key]} {@const max = key === 'max_tokens' ? maxTokens : GENERATION_CONFIG_SETTINGS[key].max} {@const max = key === "max_tokens" ? maxTokens : GENERATION_CONFIG_SETTINGS[key].max} <div> <div class="flex items-center justify-between"> <label for="temperature-range" class="mb-2 block text-sm font-medium text-gray-900 dark:text-white">{label}</label <label for="temperature-range" class="mb-2 block text-sm font-medium text-gray-900 dark:text-white" >{label}</label > <input type="number"23 unmodified lines {@const settings = GENERATION_CONFIG_SETTINGS[key]} <div> <div class="flex items-center justify-between"> <label for="temperature-range" class="mb-2 block text-sm font-medium text-gray-900 dark:text-white" <label for="temperature-range" class="mb-2 block text-sm font-medium text-gray-900 dark:text-white" >{settings.label}</label > <input3 unmodified lines max={settings.max} step={settings.step} value={conversation.config[key] ?? settings.default} on:input={(e) => (conversation.config[key] = Number(e.currentTarget.value))} on:input={e => (conversation.config[key] = Number(e.currentTarget.value))} /> </div> <input3 unmodified lines max={settings.max} step={settings.step} value={conversation.config[key] ?? settings.default} on:input={(e) => (conversation.config[key] = Number(e.currentTarget.value))} on:input={e => (conversation.config[key] = Number(e.currentTarget.value))} class="h-2 w-full cursor-pointer appearance-none rounded-lg bg-gray-200 accent-black dark:bg-gray-700 dark:accent-blue-500" /> </div>123453456782 unmodified lines11121314141516161718192 unmodified lines22232425252627282930303132331 unmodified line353637383839404114 unmodified lines565758596061596061623 unmodified lines666768716970717223 unmodified lines96979810110210399100101102<!-- Main modal --><script lang="ts"> import { createEventDispatcher, onDestroy, onMount } from 'svelte'; import { browser } from '$app/environment'; import IconCross from '../Icons/IconCross.svelte'; import { createEventDispatcher, onDestroy, onMount } from "svelte"; import { browser } from "$app/environment"; import IconCross from "../Icons/IconCross.svelte";
let backdropEl: HTMLDivElement; let modalEl: HTMLDivElement;2 unmodified lines
function handleKeydown(event: KeyboardEvent) { // close on ESC if (event.key === 'Escape') { if (event.key === "Escape") { event.preventDefault(); dispatch('close'); dispatch("close"); } }
2 unmodified lines return; } if (event.target === backdropEl) { dispatch('close'); dispatch("close"); } }
onMount(() => { document.getElementById('app')?.setAttribute('inert', 'true'); document.getElementById("app")?.setAttribute("inert", "true"); modalEl.focus(); });
1 unmodified line 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'); document.getElementById("app")?.removeAttribute("inert"); } });</script>14 unmodified lines on:keydown={handleKeydown} > <form on:submit|preventDefault class="relative rounded-lg bg-white shadow dark:bg-gray-900"> <div class="flex items-center justify-between rounded-t border-b p-4 md:px-5 md:py-4 dark:border-gray-600" > <div class="flex items-center justify-between rounded-t border-b p-4 md:px-5 md:py-4 dark:border-gray-600"> <h3 class="flex items-center gap-2.5 text-lg font-semibold text-gray-900 dark:text-white"> <img alt="Hugging Face's logo"3 unmodified lines </h3> <button type="button" on:click={() => dispatch('close')} on:click={() => dispatch("close")} class="ms-auto inline-flex h-8 w-8 items-center justify-center rounded-lg bg-transparent text-sm text-gray-400 hover:bg-gray-200 hover:text-gray-900 dark:hover:bg-gray-600 dark:hover:text-white" > <IconCross classNames="text-xl" />23 unmodified lines </div>
<!-- Modal footer --> <div class="flex items-center justify-between rounded-b border-t border-gray-200 p-4 md:p-5 dark:border-gray-600" > <div class="flex items-center justify-between rounded-b border-t border-gray-200 p-4 md:p-5 dark:border-gray-600"> <a href="https://huggingface.co/settings/tokens?new_token=true" tabindex="-1"1232345617 unmodified lines2425262727282930<script lang="ts"> import { createEventDispatcher } from 'svelte'; import { type ChatCompletionInputMessage } from '@huggingface/tasks'; import { createEventDispatcher } from "svelte"; import { type ChatCompletionInputMessage } from "@huggingface/tasks";
export let message: ChatCompletionInputMessage; export let autofocus: boolean = false;17 unmodified lines <button tabindex="1" on:click={() => { dispatch('delete'); dispatch("delete"); }} type="button" class="mt-1.5 hidden size-8 rounded-lg border border-gray-200 bg-white text-xs font-medium text-gray-900 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:outline-none focus:ring-4 focus:ring-gray-100 group-hover/message:block dark:border-gray-600 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white dark:focus:ring-gray-700"123423456713 unmodified lines2122232424252627282930313132333435363738373839404142434445434445464 unmodified lines515253565758596054555657<script lang="ts"> import type { Conversation, ModelEntryWithTokenizer } from '$lib/types'; import IconCaret from '../Icons/IconCaret.svelte'; import ModelSelectorModal from './InferencePlaygroundModelSelectorModal.svelte'; import type { Conversation, ModelEntryWithTokenizer } from "$lib/types"; import IconCaret from "../Icons/IconCaret.svelte"; import ModelSelectorModal from "./InferencePlaygroundModelSelectorModal.svelte";
export let models: ModelEntryWithTokenizer[] = []; export let conversation: Conversation;13 unmodified lines }
function changeModel(modelId: string) { const model = models.find((m) => m.id === modelId); const model = models.find(m => m.id === modelId); if (!model) { return; } conversation.model = model; }
$: [nameSpace, modelName] = conversation.model.id.split('/'); $: [nameSpace, modelName] = conversation.model.id.split("/");</script>
{#if showModelPickerModal} <ModelSelectorModal {models} on:modelSelected={(e) => changeModel(e.detail)} on:close={(e) => (showModelPickerModal = false)} on:modelSelected={e => changeModel(e.detail)} on:close={e => (showModelPickerModal = false)} />{/if}
<div class="flex flex-col gap-2"> <label for="countries" class="flex items-baseline text-sm font-medium text-gray-900 dark:text-white" <label for="countries" class="flex items-baseline text-sm font-medium text-gray-900 dark:text-white" >Models<span class="ml-4 font-normal text-gray-400">{models.length}</span> </label>
4 unmodified lines <div class="flex flex-col items-start"> <div class="flex items-center gap-1 text-sm text-gray-500 dark:text-gray-300"> {#await getAvatarUrl(nameSpace) then avatarUrl} <img class="size-3 flex-none rounded bg-gray-200 object-cover" src={avatarUrl} alt="{nameSpace} avatar" /> <img class="size-3 flex-none rounded bg-gray-200 object-cover" src={avatarUrl} alt="{nameSpace} avatar" /> {/await} {nameSpace} </div>1234523456783 unmodified lines12131415151617171819202 unmodified lines23242526262728296 unmodified lines3637383940413940414210 unmodified lines5354555859565758596061626365666465666768693 unmodified lines737475767677787980818081828384858687858687888990<script lang="ts"> import type { ModelEntryWithTokenizer } from '$lib/types'; import { createEventDispatcher } from 'svelte'; import IconSearch from '../Icons/IconSearch.svelte'; import IconStar from '../Icons/IconStar.svelte'; import type { ModelEntryWithTokenizer } from "$lib/types"; import { createEventDispatcher } from "svelte"; import IconSearch from "../Icons/IconSearch.svelte"; import IconStar from "../Icons/IconStar.svelte";
export let models: ModelEntryWithTokenizer[];
3 unmodified lines
function handleKeydown(event: KeyboardEvent) { // close on ESC if (event.key === 'Escape') { if (event.key === "Escape") { event.preventDefault(); dispatch('close'); dispatch("close"); } }
2 unmodified lines return; } if (event.target === backdropEl) { dispatch('close'); dispatch("close"); } }</script>6 unmodified lines on:click|stopPropagation={handleBackdropClick}> <div class="flex w-full max-w-[600px] items-start justify-center p-10"> <div class="flex h-full w-full flex-col overflow-hidden rounded-lg border bg-white text-gray-900 shadow-md" > <div class="flex h-full w-full flex-col overflow-hidden rounded-lg border bg-white text-gray-900 shadow-md"> <div class="flex items-center border-b px-3"> <IconSearch classNames="mr-2 text-sm" /> <input10 unmodified lines <div class="flex cursor-pointer items-center px-2 py-1.5 text-sm hover:bg-gray-100"> <IconStar classNames="lucide lucide-star mr-2 h-4 w-4 text-yellow-400" /> <span class="inline-flex items-center" ><span class="text-gray-500">meta-llama</span><span class="mx-1 text-black">/</span ><span class="text-black">Meta-Llama-3-70B-Instruct</span></span ><span class="text-gray-500">meta-llama</span><span class="mx-1 text-black">/</span><span class="text-black">Meta-Llama-3-70B-Instruct</span ></span > </div> <div class="flex cursor-pointer items-center px-2 py-1.5 text-sm hover:bg-gray-100"> <IconStar classNames="lucide lucide-star mr-2 h-4 w-4 text-yellow-400" /> <span class="inline-flex items-center" ><span class="text-gray-500">mistralai</span><span class="mx-1 text-black">/</span ><span class="text-black">Mixtral-8x7B-Instruct-v0.1</span></span ><span class="text-gray-500">mistralai</span><span class="mx-1 text-black">/</span><span class="text-black">Mixtral-8x7B-Instruct-v0.1</span ></span > </div> </div>3 unmodified lines <div class="px-2 py-1.5 text-xs font-medium text-gray-500">Other Models</div> <div> {#each models as model} {@const [nameSpace, modelName] = model.id.split('/')} {@const [nameSpace, modelName] = model.id.split("/")} <button class="flex cursor-pointer items-center px-2 py-1.5 text-sm hover:bg-gray-100" on:click={() => { dispatch('modelSelected', model.id); dispatch('close'); dispatch("modelSelected", model.id); dispatch("close"); }} > <span class="inline-flex items-center" ><span class="text-gray-500">{nameSpace}</span><span class="mx-1 text-black" >/</span ><span class="text-black">{modelName}</span></span ><span class="text-gray-500">{nameSpace}</span><span class="mx-1 text-black">/</span><span class="text-black">{modelName}</span ></span > </button> {/each}11 unmodified lines1213141515161718192021222223242526272829293031323334353636373839404142434443444546474849495051525354555152535411 unmodified lines step: 0.01, min: 0, max: 2, label: 'Temperature' label: "Temperature", }, max_tokens: { default: 512, step: 1, min: 1, max: 8192, // changed dynamically based on model label: 'Max Tokens' label: "Max Tokens", }, top_p: { default: 0.7, step: 0.01, min: 0, max: 1, label: 'Top-P' label: "Top-P", }, top_k: { default: 50, step: 1, min: 1, max: 100, label: 'Top-K' label: "Top-K", }, repetition_penalty: { default: 1, step: 0.01, min: 1, max: 2, label: 'Repetition Penalty' } label: "Repetition Penalty", },};
export type GenerationConfigKey = keyof typeof GENERATION_CONFIG_SETTINGS;
export const GENERATION_CONFIG_KEYS: GenerationConfigKey[] = ['temperature', 'max_tokens'];export const GENERATION_CONFIG_KEYS: GenerationConfigKey[] = ["temperature", "max_tokens"];
export const GENERATION_CONFIG_KEYS_ADVANCED: GenerationConfigKey[] = [ 'top_p', 'top_k', 'repetition_penalty'];export const GENERATION_CONFIG_KEYS_ADVANCED: GenerationConfigKey[] = ["top_p", "top_k", "repetition_penalty"];
export type GenerationConfig = Record<GenerationConfigKey, number>;
1231234567 unmodified lines1415161718192017181922202122232425282627282910 unmodified lines404142454647484344454647484950555152535455566157585960656162import { type ChatCompletionInputMessage } from '@huggingface/tasks';import { HfInference } from '@huggingface/inference';import type { Conversation, ModelEntryWithTokenizer } from '$lib/types';import { type ChatCompletionInputMessage } from "@huggingface/tasks";import { HfInference } from "@huggingface/inference";import type { Conversation, ModelEntryWithTokenizer } from "$lib/types";
export function createHfInference(token: string): HfInference { return new HfInference(token);7 unmodified lines systemMessage?: ChatCompletionInputMessage): Promise<void> { const messages = [ ...(isSystemPromptSupported(conversation.model) && systemMessage?.content?.length ? [systemMessage] : []), ...conversation.messages ...(isSystemPromptSupported(conversation.model) && systemMessage?.content?.length ? [systemMessage] : []), ...conversation.messages, ]; let out = ''; let out = ""; for await (const chunk of hf.chatCompletionStream( { model: conversation.model.id, messages, temperature: conversation.config.temperature, max_tokens: conversation.config.maxTokens max_tokens: conversation.config.maxTokens, }, { signal: abortController.signal } )) {10 unmodified lines systemMessage?: ChatCompletionInputMessage): Promise<ChatCompletionInputMessage> { const messages = [ ...(isSystemPromptSupported(conversation.model) && systemMessage?.content?.length ? [systemMessage] : []), ...conversation.messages ...(isSystemPromptSupported(conversation.model) && systemMessage?.content?.length ? [systemMessage] : []), ...conversation.messages, ];
const response = await hf.chatCompletion({ model: conversation.model, messages, temperature: conversation.config.temperature, max_tokens: conversation.config.maxTokens max_tokens: conversation.config.maxTokens, });
if (response.choices && response.choices.length > 0) { return response.choices[0].message; } throw new Error('No response from the model'); throw new Error("No response from the model");}
export function isSystemPromptSupported(model: ModelEntryWithTokenizer) { return model.tokenizerConfig?.chat_template?.includes('system'); return model.tokenizerConfig?.chat_template?.includes("system");}123123456import type { GenerationConfig } from '$lib/components/InferencePlayground/generationConfigSettings';import type { ModelEntry } from '@huggingface/hub';import type { ChatCompletionInputMessage } from '@huggingface/tasks';import type { GenerationConfig } from "$lib/components/InferencePlayground/generationConfigSettings";import type { ModelEntry } from "@huggingface/hub";import type { ChatCompletionInputMessage } from "@huggingface/tasks";
type Conversation = { model: ModelEntryWithTokenizer;122345<script> import '../app.css'; import "../app.css";</script>
<slot></slot>1234123456787891011131412131415161719181920213 unmodified lines25262729303128293031import type { ModelEntryWithTokenizer } from '$lib/types';import type { ModelEntry } from '@huggingface/hub';import type { PageServerLoad } from './$types';import { env } from '$env/dynamic/private';import type { ModelEntryWithTokenizer } from "$lib/types";import type { ModelEntry } from "@huggingface/hub";import type { PageServerLoad } from "./$types";import { env } from "$env/dynamic/private";
export const load: PageServerLoad = async ({ fetch }) => { const apiUrl = 'https://huggingface.co/api/models?pipeline_tag=text-generation&inference=Warm&filter=conversational'; const apiUrl = "https://huggingface.co/api/models?pipeline_tag=text-generation&inference=Warm&filter=conversational"; const HF_TOKEN = env.HF_TOKEN;
const res = await fetch(apiUrl, { headers: { Authorization: `Bearer ${HF_TOKEN}` } Authorization: `Bearer ${HF_TOKEN}`, }, }); const compatibleModels: ModelEntry[] = await res.json(); compatibleModels.sort((a, b) => a.id.toLowerCase().localeCompare(b.id.toLowerCase()));
const promises = compatibleModels.map(async (model) => { const promises = compatibleModels.map(async model => { const configUrl = `https://huggingface.co/${model.modelId}/raw/main/tokenizer_config.json`; const res = await fetch(configUrl); if (!res.ok) {3 unmodified lines return { ...model, tokenizerConfig } satisfies ModelEntryWithTokenizer; });
const models: ModelEntryWithTokenizer[] = (await Promise.all(promises)).filter( (model) => model !== null ); const models: ModelEntryWithTokenizer[] = (await Promise.all(promises)).filter(model => model !== null);
return { models };};1233456<script lang="ts"> export let data; import InferencePlayground from '$lib/components/InferencePlayground/InferencePlayground.svelte'; import InferencePlayground from "$lib/components/InferencePlayground/InferencePlayground.svelte";</script>
<InferencePlayground models={data.models} />12123455 unmodified lines11121314151415161718import adapter from '@sveltejs/adapter-node';import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';import adapter from "@sveltejs/adapter-node";import { vitePreprocess } from "@sveltejs/vite-plugin-svelte";
/** @type {import('@sveltejs/kit').Config} */const config = {5 unmodified lines // adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list. // If your environment is not supported, or you settled on a specific environment, switch out the adapter. // See https://kit.svelte.dev/docs/adapters for more information about adapters. adapter: adapter() } adapter: adapter(), },};
export default config;121234556788910111112import type { Config } from 'tailwindcss';import containerQueries from '@tailwindcss/container-queries';import type { Config } from "tailwindcss";import containerQueries from "@tailwindcss/container-queries";
export default { content: ['./src/**/*.{html,js,svelte,ts}'], content: ["./src/**/*.{html,js,svelte,ts}"],
theme: { extend: {} extend: {}, },
plugins: [containerQueries] plugins: [containerQueries],} as Config;121234556import { sveltekit } from '@sveltejs/kit/vite';import { defineConfig } from 'vite';import { sveltekit } from "@sveltejs/kit/vite";import { defineConfig } from "vite";
export default defineConfig({ plugins: [sveltekit()] plugins: [sveltekit()],});.prettierrcDeleted-8
.prettierrc.mjsAdded+11
postcss.config.js+2-2
src/app.css+1-1
src/lib/components/Icons/IconCaret.svelte+2-5
src/lib/components/Icons/IconCode.svelte+1-1
src/lib/components/Icons/IconCopyCode.svelte+1-1
src/lib/components/Icons/IconCross.svelte+1-1
src/lib/components/Icons/IconDelete.svelte+2-5
src/lib/components/Icons/IconPlus.svelte+2-7
src/lib/components/Icons/IconSearch.svelte+2-5
src/lib/components/Icons/IconShare.svelte+2-9
src/lib/components/Icons/IconStar.svelte+1-1
src/lib/components/InferencePlayground/InferencePlayground.svelte+34-39
src/lib/components/InferencePlayground/InferencePlaygroundCodeSnippets.svelte+52-52
src/lib/components/InferencePlayground/InferencePlaygroundConversation.svelte+7-7
src/lib/components/InferencePlayground/InferencePlaygroundGenerationConfig.svelte+11-14
src/lib/components/InferencePlayground/InferencePlaygroundHFTokenModal.svelte+11-15
src/lib/components/InferencePlayground/InferencePlaygroundMessage.svelte+3-3
src/lib/components/InferencePlayground/InferencePlaygroundModelSelector.svelte+9-15
src/lib/components/InferencePlayground/InferencePlaygroundModelSelectorModal.svelte+20-20
src/lib/components/InferencePlayground/generationConfigSettings.ts+8-12
src/lib/components/InferencePlayground/inferencePlaygroundUtils.ts+12-16
src/lib/types/index.d.ts+3-3
src/routes/+layout.svelte+1-1
src/routes/+page.server.ts+9-12
src/routes/+page.svelte+1-1
svelte.config.js+4-4
tailwind.config.ts+5-5
vite.config.ts+3-3