Spaces:
Sleeping
Sleeping
Support OAI clients in code snippets (#51)
Browse filesFiles changed (2)
31 unmodified lines3233343536376 unmodified lines44454647484950515253545527 unmodified lines8384858687888958 unmodified lines14814915015115215315441 unmodified lines1961971981992002012024 unmodified lines20720820921021121284 unmodified lines29729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333431 unmodified linesneedsToken?: boolean;}interface MessagesJoiner {sep: string;start: string;6 unmodified lines$: tokenStr = getTokenStr(showToken);let snippetsByLanguage: Record<Language, Snippet[]>;$: snippetsByLanguage = {javascript: getJavascriptSnippets(conversation, tokenStr),python: getPythonSnippets(conversation, tokenStr),http: getHttpSnippets(conversation, tokenStr),};function getTokenStr(showToken: boolean) {if (hfToken && showToken) {27 unmodified linesreturn hljs.highlight(code, { language }).value;}function getJavascriptSnippets(conversation: Conversation, tokenStr: string) {const formattedMessages = ({ sep, start, end }: MessagesJoiner) =>start +getMessages()58 unmodified linesreturn snippets;}function getPythonSnippets(conversation: Conversation, tokenStr: string) {const formattedMessages = ({ sep, start, end }: MessagesJoiner) =>start +getMessages()41 unmodified linesneedsToken: true,code: `from huggingface_hub import InferenceClientmodel_id="${conversation.model.id}"client = InferenceClient(api_key="${tokenStr}")messages = ${formattedMessages({ sep: ",\n\t", start: `[\n\t`, end: `\n]` })}4 unmodified lines${formattedConfig({ sep: ",\n\t", start: "", end: "", connector: "=" })})print(output.choices[0].message)`,});}84 unmodified lines</ul></div>{#each snippetsByLanguage[selectedLanguage] as { label, code, language, needsToken }}<div class="flex items-center justify-between px-2 pb-4 pt-6"><h2 class="font-semibold">{label}</h2><div class="flex items-center gap-x-4">{#if needsToken && hfToken}<label class="flex select-none items-center gap-x-1.5 text-sm"><input type="checkbox" bind:checked={showToken} /><p class="leading-none">With token</p></label>{/if}<buttonclass="flex items-center gap-x-2 rounded-md border bg-white px-1.5 py-0.5 text-sm shadow-sm transition dark:border-gray-800 dark:bg-gray-800"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");}, 400);}}><IconCopyCode classNames="text-xs" /> Copy code</button></div></div><preclass="overflow-x-auto rounded-lg border border-gray-200/80 bg-white px-4 py-6 text-sm shadow-sm dark:border-gray-800 dark:bg-gray-800/50">{@html highlight(code,language ?? selectedLanguage)}</pre>{/each}</div>31 unmodified lines32333435363738394041426 unmodified lines4950515253545556575859606162636465666727 unmodified lines959697989910010158 unmodified lines16016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723841 unmodified lines2802812822832842854 unmodified lines29029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536684 unmodified lines45145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450531 unmodified linesneedsToken?: boolean;}interface ClientSnippet {name: string;snippets: Snippet[];}interface MessagesJoiner {sep: string;start: string;6 unmodified lines$: tokenStr = getTokenStr(showToken);$: clientSnippetsByLang = {javascript: [{ name: "@huggingface/inference", snippets: getJavascriptSnippetsHfClient(conversation, tokenStr) },{ name: "openai", snippets: getJavascriptSnippetsOAIClient(conversation, tokenStr) },],python: [{ name: "huggingface_hub", snippets: getPythonSnippetsHfClient(conversation, tokenStr) },{ name: "openai", snippets: getPythonSnippetsOAIClient(conversation, tokenStr) },],http: [{ name: "curl", snippets: getHttpSnippets(conversation, tokenStr) }],} as Record<Language, ClientSnippet[]>;const selectedClientIdxByLang: Record<Language, number> = Object.fromEntries(lanuages.map(lang => [lang, 0]));function getTokenStr(showToken: boolean) {if (hfToken && showToken) {27 unmodified linesreturn hljs.highlight(code, { language }).value;}function getJavascriptSnippetsHfClient(conversation: Conversation, tokenStr: string) {const formattedMessages = ({ sep, start, end }: MessagesJoiner) =>start +getMessages()58 unmodified linesreturn snippets;}function getJavascriptSnippetsOAIClient(conversation: Conversation, tokenStr: string) {const formattedMessages = ({ sep, start, end }: MessagesJoiner) =>start +getMessages().map(({ role, content }) => `{ role: "${role}", content: "${content}" }`).join(sep) +end;const formattedConfig = ({ sep, start, end }: MessagesJoiner) =>start +Object.entries(conversation.config).map(([key, val]) => `${key}: ${val}`).join(sep) +end;const snippets: Snippet[] = [];snippets.push({label: "Install openai",language: "http",code: `npm install --save openai`,});if (conversation.streaming) {snippets.push({label: "Streaming API",needsToken: true,code: `import { OpenAI } from "openai"const client = new OpenAI({baseURL: "https://api-inference.huggingface.co/models/${conversation.model.id}/v1/",apiKey: "${tokenStr}"})let out = "";for await (const chunk of await client.chat.completions.create({model: "${conversation.model.id}",messages: ${formattedMessages({ sep: ",\n\t", start: "[\n\t", end: "\n ]" })},${formattedConfig({ sep: ",\n ", start: "", end: "" })},stream: true,})) {if (chunk.choices && chunk.choices.length > 0) {const newContent = chunk.choices[0].delta.content;out += newContent;console.log(newContent);}}`,});} else {// non-streamingsnippets.push({label: "Non-Streaming API",needsToken: true,code: `import { OpenAI } from "openai"const client = new OpenAI({baseURL: "https://api-inference.huggingface.co/models/${conversation.model.id}/v1/",apiKey: "${tokenStr}"})const out = await client.chat.completions.create({model: "${conversation.model.id}",messages: ${formattedMessages({ sep: ",\n\t\t", start: "[\n\t\t", end: "\n\t]" })},${formattedConfig({ sep: ",\n\t", start: "", end: "" })}});console.log(out.choices[0].message);`,});}return snippets;}function getPythonSnippetsHfClient(conversation: Conversation, tokenStr: string) {const formattedMessages = ({ sep, start, end }: MessagesJoiner) =>start +getMessages()41 unmodified linesneedsToken: true,code: `from huggingface_hub import InferenceClientclient = InferenceClient(api_key="${tokenStr}")messages = ${formattedMessages({ sep: ",\n\t", start: `[\n\t`, end: `\n]` })}4 unmodified lines${formattedConfig({ sep: ",\n\t", start: "", end: "", connector: "=" })})print(output.choices[0].message)`,});}return snippets;}function getPythonSnippetsOAIClient(conversation: Conversation, tokenStr: string) {const formattedMessages = ({ sep, start, end }: MessagesJoiner) =>start +getMessages().map(({ role, content }) => `{ "role": "${role}", "content": "${content}" }`).join(sep) +end;const formattedConfig = ({ sep, start, end, connector }: MessagesJoiner & { connector: string }) =>start +Object.entries(conversation.config).map(([key, val]) => `${key}${connector}${val}`).join(sep) +end;const snippets: Snippet[] = [];snippets.push({label: "Install the latest openai",language: "http",code: `pip install openai --upgrade`,});if (conversation.streaming) {snippets.push({label: "Streaming API",needsToken: true,code: `from openai import OpenAIclient = OpenAI(base_url="https://api-inference.huggingface.co/models/${conversation.model.id}/v1/",api_key="${tokenStr}")messages = ${formattedMessages({ sep: ",\n\t", start: `[\n\t`, end: `\n]` })}output = client.chat.completions.create(model="${conversation.model.id}",messages=messages,stream=True,${formattedConfig({ sep: ",\n\t", start: "", end: "", connector: "=" })})for chunk in output:print(chunk.choices[0].delta.content)`,});} else {// non-streamingsnippets.push({label: "Non-Streaming API",needsToken: true,code: `from openai import OpenAIclient = OpenAI(base_url="https://api-inference.huggingface.co/models/${conversation.model.id}/v1/",api_key="${tokenStr}")messages = ${formattedMessages({ sep: ",\n\t", start: `[\n\t`, end: `\n]` })}output = client.chat.completions.create(model="${conversation.model.id}",messages=messages,${formattedConfig({ sep: ",\n\t", start: "", end: "", connector: "=" })})print(output.choices[0].message)`,});}84 unmodified lines</ul></div>{#if clientSnippetsByLang[selectedLanguage].length > 1}<div class="flex gap-x-2 px-2 pt-6">{#each clientSnippetsByLang[selectedLanguage] as { name }, idx}<buttonclass="rounded-md px-1.5 py-0.5 leading-tight {idx === selectedClientIdxByLang[selectedLanguage]? 'bg-black text-gray-100 dark:bg-gray-600 dark:text-white': 'text-gray-500 hover:text-gray-600 dark:hover:text-gray-400'}"on:click={() => (selectedClientIdxByLang[selectedLanguage] = idx)}>{name}</button>{/each}</div>{/if}{#each clientSnippetsByLang[selectedLanguage] as { snippets }, idx}{#if idx === selectedClientIdxByLang[selectedLanguage]}{#each snippets as { label, code, language, needsToken }}<div class="flex items-center justify-between px-2 pb-4 pt-6"><h2 class="font-semibold">{label}</h2><div class="flex items-center gap-x-4">{#if needsToken && hfToken}<label class="flex select-none items-center gap-x-1.5 text-sm"><input type="checkbox" bind:checked={showToken} /><p class="leading-none">With token</p></label>{/if}<buttonclass="flex items-center gap-x-2 rounded-md border bg-white px-1.5 py-0.5 text-sm shadow-sm transition dark:border-gray-800 dark:bg-gray-800"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");}, 400);}}><IconCopyCode classNames="text-xs" /> Copy code</button></div></div><preclass="overflow-x-auto rounded-lg border border-gray-200/80 bg-white px-4 py-6 text-sm shadow-sm dark:border-gray-800 dark:bg-gray-800/50">{@html highlight(code,language ?? selectedLanguage)}</pre>{/each}{/if}{/each}</div>
16 unmodified lines17181920212216 unmodified lines{message.role}</div><!-- svelte-ignore a11y-autofocus --><textarea{autofocus}bind:value={message.content}16 unmodified lines1718192021222316 unmodified lines{message.role}</div><!-- svelte-ignore a11y-autofocus --><!-- svelte-ignore a11y-positive-tabindex --><textarea{autofocus}bind:value={message.content}
src/lib/components/InferencePlayground/InferencePlaygroundCodeSnippets.svelte+210-39
src/lib/components/InferencePlayground/InferencePlaygroundMessage.svelte+1