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")],};123456export default {plugins: {tailwindcss: {},autoprefixer: {}}};123456export default {plugins: {tailwindcss: {},autoprefixer: {},},};
1234@import 'highlight.js/styles/atom-one-light';@tailwind base;@tailwind components;@tailwind utilities;1234@import "highlight.js/styles/atom-one-light";@tailwind base;@tailwind components;@tailwind utilities;
123456 unmodified lines1213141516171819<script lang="ts">export let classNames = '';</script><svg6 unmodified linesheight="1em"preserveAspectRatio="xMidYMid meet"viewBox="0 0 24 24"><pathd="M16.293 9.293L12 13.586L7.707 9.293l-1.414 1.414L12 16.414l5.707-5.707z"fill="currentColor"/></svg>123456 unmodified lines1213141516<script lang="ts">export let classNames = "";</script><svg6 unmodified linesheight="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" /></svg>
12345<script lang="ts">export let classNames = '';</script><svg12345<script lang="ts">export let classNames = "";</script><svg
12345<script lang="ts">export let classNames = '';</script><svg12345<script lang="ts">export let classNames = "";</script><svg
12345<script lang="ts">export let classNames = '';</script><svg12345<script lang="ts">export let classNames = "";</script><svg
123458 unmodified lines14151617181920212223<script lang="ts">export let classNames = '';</script><svg8 unmodified linespreserveAspectRatio="xMidYMid meet"viewBox="0 0 32 32"><path d="M12 12h2v12h-2z" fill="currentColor" /><pathd="M18 12h2v12h-2z"fill="currentColor"/><pathd="M4 6v2h2v20a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8h2V6zm4 22V8h16v20z"fill="currentColor"/><path d="M12 2h8v2h-8z" fill="currentColor" />123458 unmodified lines14151617181920<script lang="ts">export let classNames = "";</script><svg8 unmodified linespreserveAspectRatio="xMidYMid meet"viewBox="0 0 32 32"><path d="M12 12h2v12h-2z" fill="currentColor" /><path d="M18 12h2v12h-2z" fill="currentColor" /><pathd="M4 6v2h2v20a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8h2V6zm4 22V8h16v20z"fill="currentColor"/><path d="M12 2h8v2h-8z" fill="currentColor" />
12345678910111213<script lang="ts">export let classNames = '';</script><svgclass={classNames}xmlns="http://www.w3.org/2000/svg"width="1em"height="1em"viewBox="0 0 32 32"><pathfill="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"12345678<script lang="ts">export let classNames = "";</script><svg class={classNames} xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><pathfill="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"
123458 unmodified lines1415161718192021<script lang="ts">export let classNames = '';</script><svg8 unmodified linespreserveAspectRatio="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>123458 unmodified lines1415161718<script lang="ts">export let classNames = "";</script><svg8 unmodified linespreserveAspectRatio="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>
123456789101112131415<script lang="ts">export let classNames = '';</script><svgclass={classNames}width="1em"height="1em"viewBox="0 0 24 25"fill="none"xmlns="http://www.w3.org/2000/svg"><pathfill-rule="evenodd"clip-rule="evenodd"12345678<script lang="ts">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"><pathfill-rule="evenodd"clip-rule="evenodd"
12345<script lang="ts">export let classNames = '';</script><svg12345<script lang="ts">export let classNames = "";</script><svg
2 unmodified lines34567891011121314151617181920212223242526272829303132333412 unmodified lines4748495051525354553 unmodified lines5960616263646522 unmodified lines88899091929394959697989910010116 unmodified lines1181191201211221231241252 unmodified lines1281291301311321331342 unmodified lines13713813914014114214314414515 unmodified lines1611621631641651661671687 unmodified lines1761771781791801811823 unmodified lines18618718818919019119219319416 unmodified lines21121221321421521621722 unmodified lines2402412422432442452462479 unmodified lines2572582592602612622632642652 unmodified linescreateHfInference,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';export let models: ModelEntryWithTokenizer[];const startMessages: ChatCompletionInputMessage[] = [{ role: 'user', content: '' }];let conversation: Conversation = {model: models[0],config: defaultGenerationConfig,messages: startMessages,streaming: true};let systemMessage: ChatCompletionInputMessage = { role: 'system', content: '' };let hfToken: string | undefined = import.meta.env.VITE_HF_TOKEN;let viewCode = false;let showTokenModal = false;12 unmodified linesconversation.messages = [...conversation.messages,{role: conversation.messages.at(-1)?.role === 'user' ? 'assistant' : 'user',content: ''}];}3 unmodified lines}function reset() {systemMessage.content = '';conversation.messages = [...startMessages];}22 unmodified linesconst hf = createHfInference(hfToken);if (conversation.streaming) {const streamingMessage = { role: 'assistant', content: '' };conversation.messages = [...conversation.messages, streamingMessage];abortController = new AbortController();await handleStreamingResponse(hf,conversation,(content) => {if (streamingMessage) {streamingMessage.content = content;conversation.messages = [...conversation.messages];16 unmodified linesaddMessage();} catch (error) {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') {submit();}}2 unmodified lines{#if showTokenModal}<HFTokenModalon:close={() => (showTokenModal = false)}on:submit={(e) => {const formData = new FormData(e.target);hfToken = formData.get('hf-token');submit();showTokenModal = false;}}15 unmodified linesname=""id=""placeholder={systemPromptSupported? '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 linesindex={0}{viewCode}on:addMessage={addMessage}on:deleteMessage={(e) => deleteMessage(e.detail)}/></div><div3 unmodified linestype="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"><divclass="flex size-5 items-center justify-center rounded border border-black/5 bg-black/5 text-xs"><IconShare /></div>16 unmodified linesclass="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><buttonon:click={() => {22 unmodified lines/></div>{:else}Run <spanclass="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><spanclass="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</span2 unmodified lines34567891011121314151617181920212223242526272829303132333412 unmodified lines4748495051525354553 unmodified lines5960616263646522 unmodified lines88899091929394959697989910010116 unmodified lines1181191201211221231241252 unmodified lines1281291301311321331342 unmodified lines13713813914014114214314414515 unmodified lines1611621631641651661671687 unmodified lines1761771781791801811823 unmodified lines18618718818919019119216 unmodified lines20921021121221321421522 unmodified lines2382392402412422432449 unmodified lines2542552562572582592602 unmodified linescreateHfInference,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";export let models: ModelEntryWithTokenizer[];const startMessages: ChatCompletionInputMessage[] = [{ role: "user", content: "" }];let conversation: Conversation = {model: models[0],config: defaultGenerationConfig,messages: startMessages,streaming: true,};let systemMessage: ChatCompletionInputMessage = { role: "system", content: "" };let hfToken: string | undefined = import.meta.env.VITE_HF_TOKEN;let viewCode = false;let showTokenModal = false;12 unmodified linesconversation.messages = [...conversation.messages,{role: conversation.messages.at(-1)?.role === "user" ? "assistant" : "user",content: "",},];}3 unmodified lines}function reset() {systemMessage.content = "";conversation.messages = [...startMessages];}22 unmodified linesconst hf = createHfInference(hfToken);if (conversation.streaming) {const streamingMessage = { role: "assistant", content: "" };conversation.messages = [...conversation.messages, streamingMessage];abortController = new AbortController();await handleStreamingResponse(hf,conversation,content => {if (streamingMessage) {streamingMessage.content = content;conversation.messages = [...conversation.messages];16 unmodified linesaddMessage();} catch (error) {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") {submit();}}2 unmodified lines{#if showTokenModal}<HFTokenModalon:close={() => (showTokenModal = false)}on:submit={e => {const formData = new FormData(e.target);hfToken = formData.get("hf-token");submit();showTokenModal = false;}}15 unmodified linesname=""id=""placeholder={systemPromptSupported? "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 linesindex={0}{viewCode}on:addMessage={addMessage}on:deleteMessage={e => deleteMessage(e.detail)}/></div><div3 unmodified linestype="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"><IconShare /></div>16 unmodified linesclass="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><buttonon: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">↵</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><spanclass="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</span
1234567891011121314151617181920212223245 unmodified lines3031323334353637383940414243444520 unmodified lines666768697071727374757677782 unmodified lines81828384858687882 unmodified lines91929394959697989910010110210310410510610710810911011111211311417 unmodified lines1321331341351361371381391401411421431442 unmodified lines14714814915015115215315415515615715815916016116216316416516616716816917017117217317419 unmodified lines19419519619719819920020120220320420520620720820921021121221321421521621721821922022122231 unmodified lines254255256257258259260261262263264265266267268<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);export let conversation: Conversation;const lanuages = ['javascript', 'python', 'http'];type Language = (typeof lanuages)[number];const labelsByLanguage: Record<Language, string> = {javascript: 'JavaScript',python: 'Python',http: 'Curl'};interface Snippet {5 unmodified lines$: snippetsByLanguage = {javascript: getJavascriptSnippets(conversation),python: getPythonSnippets(conversation),http: getHttpSnippets(conversation)};let selectedLanguage: Language = 'javascript';let timeout: ReturnType<typeof setTimeout>;function getMessages() {const placeholder = [{ role: 'user', content: 'Tell me a story' }];let messages = conversation.messages;if (messages.length === 1 && messages[0].role === 'user' && !messages[0].content) {messages = placeholder;}return messages;20 unmodified linesconst snippets: Snippet[] = [];snippets.push({label: 'Install @huggingface/inference',language: 'http',code: `npm install --save @huggingface/inference`});if (conversation.streaming) {snippets.push({label: 'Streaming API',code: `import { HfInference } from "@huggingface/inference"const inference = new HfInference("your HF token")2 unmodified linesfor await (const chunk of inference.chatCompletionStream({model: "${conversation.model.id}",messages: ${formattedMessages({ sep: ',\n ', start: '[\n ', end: '\n ]' })},${formattedConfig({ sep: ',\n ', start: '', end: '' })},seed: 0,})) {if (chunk.choices && chunk.choices.length > 0) {2 unmodified linesconsole.clear();console.log(out);}}`});} else {// non-streamingsnippets.push({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: '' })},seed: 0,});console.log(out.choices[0].message);`});}17 unmodified linesconst snippets: Snippet[] = [];snippets.push({label: 'Install huggingface_hub',language: 'http',code: `pip install huggingface_hub`});if (conversation.streaming) {snippets.push({label: 'Streaming API',code: `from huggingface_hub import InferenceClientmodel_id="${conversation.model.id}"2 unmodified linesoutput = ""messages = ${formattedMessages({ sep: ',\n ', start: `[\n `, end: `\n]` })}for token in client.chat_completion(messages, stream=True, ${formattedConfig({ sep: ', ', start: '', end: '' })}):new_content = token.choices[0].delta.contentprint(new_content, end="")output += new_content`});} else {// non-streamingsnippets.push({label: 'Non-Streaming API',code: `from huggingface_hub import InferenceClientmodel_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]` })}output = inference_client.chat_completion(messages, ${formattedConfig({ sep: ', ', start: '', end: '' })})print(output.choices[0].message)`});}19 unmodified linesif (conversation.streaming) {snippets.push({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: '' })},"stream": true}'`});} else {// non-streamingsnippets.push({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: '' })}}'`});}31 unmodified lines<h2 class="font-semibold">{label}</h2><buttonclass="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) => {const el = e.currentTarget;el.classList.add('text-green-500');navigator.clipboard.writeText(code);if (timeout) {clearTimeout(timeout);}timeout = setTimeout(() => {el.classList.remove('text-green-500');}, 1000);}}>1234567891011121314151617181920212223245 unmodified lines3031323334353637383940414243444520 unmodified lines666768697071727374757677782 unmodified lines81828384858687882 unmodified lines91929394959697989910010110210310410510610710810911011111211311417 unmodified lines1321331341351361371381391401411421431442 unmodified lines14714814915015115215315415515615715815916016116216316416516616716816917017117217317419 unmodified lines19419519619719819920020120220320420520620720820921021121221321421521621721821922022122231 unmodified lines254255256257258259260261262263264265266267268<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);export let conversation: Conversation;const lanuages = ["javascript", "python", "http"];type Language = (typeof lanuages)[number];const labelsByLanguage: Record<Language, string> = {javascript: "JavaScript",python: "Python",http: "Curl",};interface Snippet {5 unmodified lines$: snippetsByLanguage = {javascript: getJavascriptSnippets(conversation),python: getPythonSnippets(conversation),http: getHttpSnippets(conversation),};let selectedLanguage: Language = "javascript";let timeout: ReturnType<typeof setTimeout>;function getMessages() {const placeholder = [{ role: "user", content: "Tell me a story" }];let messages = conversation.messages;if (messages.length === 1 && messages[0].role === "user" && !messages[0].content) {messages = placeholder;}return messages;20 unmodified linesconst snippets: Snippet[] = [];snippets.push({label: "Install @huggingface/inference",language: "http",code: `npm install --save @huggingface/inference`,});if (conversation.streaming) {snippets.push({label: "Streaming API",code: `import { HfInference } from "@huggingface/inference"const inference = new HfInference("your HF token")2 unmodified linesfor await (const chunk of inference.chatCompletionStream({model: "${conversation.model.id}",messages: ${formattedMessages({ sep: ",\n ", start: "[\n ", end: "\n ]" })},${formattedConfig({ sep: ",\n ", start: "", end: "" })},seed: 0,})) {if (chunk.choices && chunk.choices.length > 0) {2 unmodified linesconsole.clear();console.log(out);}}`,});} else {// non-streamingsnippets.push({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: "" })},seed: 0,});console.log(out.choices[0].message);`,});}17 unmodified linesconst snippets: Snippet[] = [];snippets.push({label: "Install huggingface_hub",language: "http",code: `pip install huggingface_hub`,});if (conversation.streaming) {snippets.push({label: "Streaming API",code: `from huggingface_hub import InferenceClientmodel_id="${conversation.model.id}"2 unmodified linesoutput = ""messages = ${formattedMessages({ sep: ",\n ", start: `[\n `, end: `\n]` })}for token in client.chat_completion(messages, stream=True, ${formattedConfig({ sep: ", ", start: "", end: "" })}):new_content = token.choices[0].delta.contentprint(new_content, end="")output += new_content`,});} else {// non-streamingsnippets.push({label: "Non-Streaming API",code: `from huggingface_hub import InferenceClientmodel_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]` })}output = inference_client.chat_completion(messages, ${formattedConfig({ sep: ", ", start: "", end: "" })})print(output.choices[0].message)`,});}19 unmodified linesif (conversation.streaming) {snippets.push({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: "" })},"stream": true}'`,});} else {// non-streamingsnippets.push({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: "" })}}'`,});}31 unmodified lines<h2 class="font-semibold">{label}</h2><buttonclass="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 => {const el = e.currentTarget;el.classList.add("text-green-500");navigator.clipboard.writeText(code);if (timeout) {clearTimeout(timeout);}timeout = setTimeout(() => {el.classList.remove("text-green-500");}, 1000);}}>
12345678930 unmodified lines4041424344454647484950515253<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';export let loading;export let conversation: Conversation;30 unmodified lines<Messageclass="border-b"{message}on:delete={() => dispatch('deleteMessage', messageIdx)}autofocus={!loading && messageIdx === conversation.messages.length - 1}/>{/each}<buttonclass="flex px-6 py-6 hover:bg-gray-50 dark:hover:bg-gray-800/50"on:click={() => dispatch('addMessage')}disabled={loading}><div class="flex items-center gap-2 !p-0 text-sm font-semibold">12345678930 unmodified lines4041424344454647484950515253<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";export let loading;export let conversation: Conversation;30 unmodified lines<Messageclass="border-b"{message}on:delete={() => dispatch("deleteMessage", messageIdx)}autofocus={!loading && messageIdx === conversation.messages.length - 1}/>{/each}<buttonclass="flex px-6 py-6 hover:bg-gray-50 dark:hover:bg-gray-800/50"on:click={() => dispatch("addMessage")}disabled={loading}><div class="flex items-center gap-2 !p-0 text-sm font-semibold">
12345678910111213141516171819202122232425262723 unmodified lines5152535455565758593 unmodified lines636465666768693 unmodified lines73747576777879<script lang="ts">import type { Conversation } from '$lib/types';import {GENERATION_CONFIG_KEYS,GENERATION_CONFIG_KEYS_ADVANCED,GENERATION_CONFIG_SETTINGS} from './generationConfigSettings';export let conversation: Conversation;export let classNames = '';$: modelMaxLength = conversation.model.tokenizerConfig.model_max_length;$: 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}<div><div class="flex items-center justify-between"><labelfor="temperature-range"class="mb-2 block text-sm font-medium text-gray-900 dark:text-white">{label}</label><inputtype="number"23 unmodified lines{@const settings = GENERATION_CONFIG_SETTINGS[key]}<div><div class="flex items-center justify-between"><labelfor="temperature-range"class="mb-2 block text-sm font-medium text-gray-900 dark:text-white">{settings.label}</label><input3 unmodified linesmax={settings.max}step={settings.step}value={conversation.config[key] ?? settings.default}on:input={(e) => (conversation.config[key] = Number(e.currentTarget.value))}/></div><input3 unmodified linesmax={settings.max}step={settings.step}value={conversation.config[key] ?? settings.default}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>123456789101112131415161718192021222324252623 unmodified lines505152535455563 unmodified lines606162636465663 unmodified lines70717273747576<script lang="ts">import type { Conversation } from "$lib/types";import {GENERATION_CONFIG_KEYS,GENERATION_CONFIG_KEYS_ADVANCED,GENERATION_CONFIG_SETTINGS,} from "./generationConfigSettings";export let conversation: Conversation;export let classNames = "";$: modelMaxLength = conversation.model.tokenizerConfig.model_max_length;$: 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}<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><inputtype="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">{settings.label}</label><input3 unmodified linesmax={settings.max}step={settings.step}value={conversation.config[key] ?? settings.default}on:input={e => (conversation.config[key] = Number(e.currentTarget.value))}/></div><input3 unmodified linesmax={settings.max}step={settings.step}value={conversation.config[key] ?? settings.default}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>
123456782 unmodified lines1112131415161718192 unmodified lines2223242526272829303132331 unmodified line3536373839404114 unmodified lines5657585960616263643 unmodified lines6869707172737423 unmodified lines9899100101102103104105106<!-- Main modal --><script lang="ts">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 linesfunction handleKeydown(event: KeyboardEvent) {// close on ESCif (event.key === 'Escape') {event.preventDefault();dispatch('close');}}2 unmodified linesreturn;}if (event.target === backdropEl) {dispatch('close');}}onMount(() => {document.getElementById('app')?.setAttribute('inert', 'true');modalEl.focus();});1 unmodified lineif (!browser) return;// remove inert attribute if this is the last modalif (document.querySelectorAll('[role="dialog"]:not(#app *)').length === 1) {document.getElementById('app')?.removeAttribute('inert');}});</script>14 unmodified lineson:keydown={handleKeydown}><form on:submit|preventDefault class="relative rounded-lg bg-white shadow dark:bg-gray-900"><divclass="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"><imgalt="Hugging Face's logo"3 unmodified lines</h3><buttontype="button"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 --><divclass="flex items-center justify-between rounded-b border-t border-gray-200 p-4 md:p-5 dark:border-gray-600"><ahref="https://huggingface.co/settings/tokens?new_token=true"tabindex="-1"123456782 unmodified lines1112131415161718192 unmodified lines2223242526272829303132331 unmodified line3536373839404114 unmodified lines565758596061623 unmodified lines6667686970717223 unmodified lines96979899100101102<!-- Main modal --><script lang="ts">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 linesfunction handleKeydown(event: KeyboardEvent) {// close on ESCif (event.key === "Escape") {event.preventDefault();dispatch("close");}}2 unmodified linesreturn;}if (event.target === backdropEl) {dispatch("close");}}onMount(() => {document.getElementById("app")?.setAttribute("inert", "true");modalEl.focus();});1 unmodified lineif (!browser) return;// remove inert attribute if this is the last modalif (document.querySelectorAll('[role="dialog"]:not(#app *)').length === 1) {document.getElementById("app")?.removeAttribute("inert");}});</script>14 unmodified lineson: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"><h3 class="flex items-center gap-2.5 text-lg font-semibold text-gray-900 dark:text-white"><imgalt="Hugging Face's logo"3 unmodified lines</h3><buttontype="button"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"><ahref="https://huggingface.co/settings/tokens?new_token=true"tabindex="-1"
12345617 unmodified lines24252627282930<script lang="ts">import { createEventDispatcher } from 'svelte';import { type ChatCompletionInputMessage } from '@huggingface/tasks';export let message: ChatCompletionInputMessage;export let autofocus: boolean = false;17 unmodified lines<buttontabindex="1"on:click={() => {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"12345617 unmodified lines24252627282930<script lang="ts">import { createEventDispatcher } from "svelte";import { type ChatCompletionInputMessage } from "@huggingface/tasks";export let message: ChatCompletionInputMessage;export let autofocus: boolean = false;17 unmodified lines<buttontabindex="1"on:click={() => {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"
123456713 unmodified lines212223242526272829303132333435363738394041424344454647484 unmodified lines5354555657585960616263<script lang="ts">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);if (!model) {return;}conversation.model = model;}$: [nameSpace, modelName] = conversation.model.id.split('/');</script>{#if showModelPickerModal}<ModelSelectorModal{models}on:modelSelected={(e) => changeModel(e.detail)}on:close={(e) => (showModelPickerModal = false)}/>{/if}<div class="flex flex-col gap-2"><labelfor="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}<imgclass="size-3 flex-none rounded bg-gray-200 object-cover"src={avatarUrl}alt="{nameSpace} avatar"/>{/await}{nameSpace}</div>123456713 unmodified lines21222324252627282930313233343536373839404142434445464 unmodified lines51525354555657<script lang="ts">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);if (!model) {return;}conversation.model = model;}$: [nameSpace, modelName] = conversation.model.id.split("/");</script>{#if showModelPickerModal}<ModelSelectorModal{models}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">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" />{/await}{nameSpace}</div>
123456783 unmodified lines1213141516171819202 unmodified lines232425262728296 unmodified lines36373839404142434410 unmodified lines5556575859606162636465666768693 unmodified lines737475767778798081828384858687888990<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';export let models: ModelEntryWithTokenizer[];3 unmodified linesfunction handleKeydown(event: KeyboardEvent) {// close on ESCif (event.key === 'Escape') {event.preventDefault();dispatch('close');}}2 unmodified linesreturn;}if (event.target === backdropEl) {dispatch('close');}}</script>6 unmodified lineson:click|stopPropagation={handleBackdropClick}><div class="flex w-full max-w-[600px] items-start justify-center p-10"><divclass="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></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></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('/')}<buttonclass="flex cursor-pointer items-center px-2 py-1.5 text-sm hover:bg-gray-100"on:click={() => {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></button>{/each}123456783 unmodified lines1213141516171819202 unmodified lines232425262728296 unmodified lines3637383940414210 unmodified lines53545556575859606162636465666768693 unmodified lines737475767778798081828384858687888990<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";export let models: ModelEntryWithTokenizer[];3 unmodified linesfunction handleKeydown(event: KeyboardEvent) {// close on ESCif (event.key === "Escape") {event.preventDefault();dispatch("close");}}2 unmodified linesreturn;}if (event.target === backdropEl) {dispatch("close");}}</script>6 unmodified lineson: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 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><spanclass="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><spanclass="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("/")}<buttonclass="flex cursor-pointer items-center px-2 py-1.5 text-sm hover:bg-gray-100"on:click={() => {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><spanclass="text-black">{modelName}</span></span></button>{/each}
11 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575811 unmodified linesstep: 0.01,min: 0,max: 2,label: 'Temperature'},max_tokens: {default: 512,step: 1,min: 1,max: 8192, // changed dynamically based on modellabel: 'Max Tokens'},top_p: {default: 0.7,step: 0.01,min: 0,max: 1,label: 'Top-P'},top_k: {default: 50,step: 1,min: 1,max: 100,label: 'Top-K'},repetition_penalty: {default: 1,step: 0.01,min: 1,max: 2,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_ADVANCED: GenerationConfigKey[] = ['top_p','top_k','repetition_penalty'];export type GenerationConfig = Record<GenerationConfigKey, number>;11 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535411 unmodified linesstep: 0.01,min: 0,max: 2,label: "Temperature",},max_tokens: {default: 512,step: 1,min: 1,max: 8192, // changed dynamically based on modellabel: "Max Tokens",},top_p: {default: 0.7,step: 0.01,min: 0,max: 1,label: "Top-P",},top_k: {default: 50,step: 1,min: 1,max: 100,label: "Top-K",},repetition_penalty: {default: 1,step: 0.01,min: 1,max: 2,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_ADVANCED: GenerationConfigKey[] = ["top_p", "top_k", "repetition_penalty"];export type GenerationConfig = Record<GenerationConfigKey, number>;
1234567 unmodified lines14151617181920212223242526272829303110 unmodified lines42434445464748495051525354555657585960616263646566import { 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 linessystemMessage?: ChatCompletionInputMessage): Promise<void> {const messages = [...(isSystemPromptSupported(conversation.model) && systemMessage?.content?.length? [systemMessage]: []),...conversation.messages];let out = '';for await (const chunk of hf.chatCompletionStream({model: conversation.model.id,messages,temperature: conversation.config.temperature,max_tokens: conversation.config.maxTokens},{ signal: abortController.signal })) {10 unmodified linessystemMessage?: ChatCompletionInputMessage): Promise<ChatCompletionInputMessage> {const 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});if (response.choices && response.choices.length > 0) {return response.choices[0].message;}throw new Error('No response from the model');}export function isSystemPromptSupported(model: ModelEntryWithTokenizer) {return model.tokenizerConfig?.chat_template?.includes('system');}1234567 unmodified lines1415161718192021222324252627282910 unmodified lines4041424344454647484950515253545556575859606162import { 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 linessystemMessage?: ChatCompletionInputMessage): Promise<void> {const messages = [...(isSystemPromptSupported(conversation.model) && systemMessage?.content?.length ? [systemMessage] : []),...conversation.messages,];let out = "";for await (const chunk of hf.chatCompletionStream({model: conversation.model.id,messages,temperature: conversation.config.temperature,max_tokens: conversation.config.maxTokens,},{ signal: abortController.signal })) {10 unmodified linessystemMessage?: ChatCompletionInputMessage): Promise<ChatCompletionInputMessage> {const 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,});if (response.choices && response.choices.length > 0) {return response.choices[0].message;}throw new Error("No response from the model");}export function isSystemPromptSupported(model: ModelEntryWithTokenizer) {return model.tokenizerConfig?.chat_template?.includes("system");}
123456import type { GenerationConfig } from '$lib/components/InferencePlayground/generationConfigSettings';import type { ModelEntry } from '@huggingface/hub';import type { ChatCompletionInputMessage } from '@huggingface/tasks';type Conversation = {model: ModelEntryWithTokenizer;123456import type { GenerationConfig } from "$lib/components/InferencePlayground/generationConfigSettings";import type { ModelEntry } from "@huggingface/hub";import type { ChatCompletionInputMessage } from "@huggingface/tasks";type Conversation = {model: ModelEntryWithTokenizer;
12345<script>import '../app.css';</script><slot></slot>12345<script>import "../app.css";</script><slot></slot>
123456789101112131415161718192021223 unmodified lines262728293031323334import 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 HF_TOKEN = env.HF_TOKEN;const res = await fetch(apiUrl, {headers: {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 configUrl = `https://huggingface.co/${model.modelId}/raw/main/tokenizer_config.json`;const res = await fetch(configUrl);if (!res.ok) {3 unmodified linesreturn { ...model, tokenizerConfig } satisfies ModelEntryWithTokenizer;});const models: ModelEntryWithTokenizer[] = (await Promise.all(promises)).filter((model) => model !== null);return { models };};1234567891011121314151617181920213 unmodified lines25262728293031import 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 HF_TOKEN = env.HF_TOKEN;const res = await fetch(apiUrl, {headers: {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 configUrl = `https://huggingface.co/${model.modelId}/raw/main/tokenizer_config.json`;const res = await fetch(configUrl);if (!res.ok) {3 unmodified linesreturn { ...model, tokenizerConfig } satisfies ModelEntryWithTokenizer;});const models: ModelEntryWithTokenizer[] = (await Promise.all(promises)).filter(model => model !== null);return { models };};
123456<script lang="ts">export let data;import InferencePlayground from '$lib/components/InferencePlayground/InferencePlayground.svelte';</script><InferencePlayground models={data.models} />123456<script lang="ts">export let data;import InferencePlayground from "$lib/components/InferencePlayground/InferencePlayground.svelte";</script><InferencePlayground models={data.models} />
123455 unmodified lines1112131415161718import 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()}};export default config;123455 unmodified lines1112131415161718import 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(),},};export default config;
123456789101112import type { Config } from 'tailwindcss';import containerQueries from '@tailwindcss/container-queries';export default {content: ['./src/**/*.{html,js,svelte,ts}'],theme: {extend: {}},plugins: [containerQueries]} as Config;123456789101112import type { Config } from "tailwindcss";import containerQueries from "@tailwindcss/container-queries";export default {content: ["./src/**/*.{html,js,svelte,ts}"],theme: {extend: {},},plugins: [containerQueries],} as Config;
123456import { sveltekit } from '@sveltejs/kit/vite';import { defineConfig } from 'vite';export default defineConfig({plugins: [sveltekit()]});123456import { sveltekit } from "@sveltejs/kit/vite";import { defineConfig } from "vite";export default defineConfig({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