File size: 15,284 Bytes
8000347
53b45af
4b8b411
8709c70
60216ec
 
 
 
4b8b411
60216ec
812e078
60216ec
 
 
 
c02e352
79d3242
ce92b65
6bcbb4b
8709c70
 
60216ec
c02e352
 
60216ec
 
 
c02e352
 
79d3242
 
 
05476c1
ce92b65
79d3242
877b369
7083ad1
 
 
 
 
075289c
 
 
 
 
 
ce92b65
 
 
 
 
 
7083ad1
 
 
 
 
 
 
 
 
 
 
 
 
c02e352
b6d0c8a
 
ce92b65
 
 
 
877b369
635c529
60216ec
812e078
 
60216ec
78b198f
 
812e078
 
 
 
 
 
6aa1896
 
 
 
 
bd9c03c
e08d702
 
c02e352
877b369
 
 
7083ad1
075289c
d48b731
 
6aa1896
d48b731
 
 
075289c
d48b731
 
 
 
 
 
79d3242
 
60216ec
 
 
79d3242
d5e14b5
79d3242
60216ec
ce92b65
05476c1
e1cf22b
8f8cae4
05476c1
 
 
8f8cae4
 
2271079
5818d80
8f8cae4
 
 
 
 
 
 
 
60216ec
c02e352
 
 
 
60216ec
ce92b65
05476c1
 
8f8cae4
05476c1
8f8cae4
88290ae
 
 
05476c1
 
8f8cae4
c02e352
 
 
 
 
 
7083ad1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f8cae4
7083ad1
 
 
 
 
8f8cae4
 
2271079
5818d80
8f8cae4
 
 
 
 
 
 
 
 
7083ad1
 
 
 
 
 
 
 
 
 
8f8cae4
7083ad1
 
 
8f8cae4
7083ad1
 
 
 
 
8f8cae4
7083ad1
 
 
 
 
 
 
075289c
d48b731
 
6aa1896
d48b731
 
 
7660429
d48b731
 
7660429
d48b731
 
 
c02e352
 
7660429
60216ec
7660429
c02e352
d5e14b5
c02e352
60216ec
ce92b65
635c529
c02e352
ce92b65
635c529
7660429
635c529
8f8cae4
7660429
 
8f8cae4
 
7660429
635c529
8f8cae4
7660429
c02e352
 
 
 
60216ec
ce92b65
635c529
 
ce92b65
635c529
7660429
635c529
8f8cae4
7660429
 
 
 
635c529
8f8cae4
7083ad1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94003fb
7083ad1
 
 
 
 
8f8cae4
7083ad1
 
8f8cae4
 
7083ad1
 
8f8cae4
7083ad1
 
 
 
 
 
 
 
 
 
94003fb
7083ad1
 
 
 
 
8f8cae4
7083ad1
 
 
 
 
8f8cae4
c02e352
 
 
 
 
 
ce92b65
b6d0c8a
ce92b65
 
075289c
d48b731
 
d88d726
 
 
 
 
d48b731
 
 
075289c
d48b731
 
15a83db
d48b731
 
 
c02e352
 
d5e14b5
c02e352
60216ec
ce92b65
54f6626
ce92b65
54f6626
f1b84d3
ef1a1c6
60216ec
 
f1b84d3
60216ec
79d3242
 
 
 
60216ec
ce92b65
54f6626
ce92b65
54f6626
f1b84d3
ef1a1c6
60216ec
 
 
79d3242
 
 
 
 
b37c7b7
 
 
 
 
 
e1cf22b
 
6fdab00
bdc9315
 
 
 
c02e352
 
 
 
 
 
 
 
 
 
 
8709c70
 
 
 
 
 
 
 
 
 
bdc9315
 
e1cf22b
7083ad1
 
 
f250f57
31df156
 
 
7083ad1
f250f57
7083ad1
ce92b65
7083ad1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79d3242
e1cf22b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
<script lang="ts">
	import type { Conversation } from "./types";

	import { createEventDispatcher, onDestroy } from "svelte";
	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 IconCopyCode from "../Icons/IconCopyCode.svelte";
	import { isSystemPromptSupported } from "./inferencePlaygroundUtils";

	hljs.registerLanguage("javascript", javascript);
	hljs.registerLanguage("python", python);
	hljs.registerLanguage("http", http);

	export let conversation: Conversation;
	export let hfToken: string;

	const dispatch = createEventDispatcher<{ closeCode: void }>();

	const lanuages = ["javascript", "python", "http"];
	type Language = (typeof lanuages)[number];
	const labelsByLanguage: Record<Language, string> = {
		javascript: "JavaScript",
		python: "Python",
		http: "Curl",
	};

	interface Snippet {
		label: string;
		code: string;
		language?: Language;
		needsToken?: boolean;
	}

	interface ClientSnippet {
		name: string;
		snippets: Snippet[];
	}

	interface MessagesJoiner {
		sep: string;
		start: string;
		end: string;
	}

	let selectedLanguage: Language = "javascript";
	let timeout: ReturnType<typeof setTimeout>;
	let showToken = false;

	$: 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) {
			return hfToken;
		}
		return "YOUR_HF_TOKEN";
	}

	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;
		}

		const { model, systemMessage } = conversation;
		if (isSystemPromptSupported(model) && systemMessage.content?.length) {
			messages.unshift(systemMessage);
		}

		messages = messages.map(({ role, content }) => ({
			role,
			content: JSON.stringify(content).slice(1, -1),
		}));

		return messages;
	}

	function highlight(code: string, language: Language) {
		return hljs.highlight(code, { language }).value;
	}

	function getJavascriptSnippetsHfClient(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 @huggingface/inference",
			language: "http",
			code: `npm install --save @huggingface/inference`,
		});
		if (conversation.streaming) {
			snippets.push({
				label: "Streaming API",
				needsToken: true,
				code: `import { HfInference } from "@huggingface/inference"

const client = new HfInference("${tokenStr}")

let out = "";

const stream = client.chatCompletionStream({
	model: "${conversation.model.id}",
	messages: ${formattedMessages({ sep: ",\n\t\t", start: "[\n\t\t", end: "\n\t]" })},
	${formattedConfig({ sep: ",\n\t", start: "", end: "" })}
});

for await (const chunk of stream) {
	if (chunk.choices && chunk.choices.length > 0) {
		const newContent = chunk.choices[0].delta.content;
		out += newContent;
		console.log(newContent);
	}  
}`,
			});
		} else {
			// non-streaming
			snippets.push({
				label: "Non-Streaming API",
				needsToken: true,
				code: `import { HfInference } from '@huggingface/inference'

const client = new HfInference("${tokenStr}")

const chatCompletion = await client.chatCompletion({
	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(chatCompletion.choices[0].message);`,
			});
		}

		return 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/v1/",
    apiKey: "${tokenStr}"
})

let out = "";

const stream = 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: "" })},
	stream: true,
});

for await (const chunk of stream) {
	if (chunk.choices && chunk.choices.length > 0) {
		const newContent = chunk.choices[0].delta.content;
		out += newContent;
		console.log(newContent);
	}  
}`,
			});
		} else {
			// non-streaming
			snippets.push({
				label: "Non-Streaming API",
				needsToken: true,
				code: `import { OpenAI } from "openai"

const client = new OpenAI({
    baseURL: "https://api-inference.huggingface.co/v1/",
    apiKey: "${tokenStr}"
})

const chatCompletion = 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(chatCompletion.choices[0].message);`,
			});
		}

		return snippets;
	}

	function getPythonSnippetsHfClient(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 huggingface_hub",
			language: "http",
			code: `pip install huggingface_hub --upgrade`,
		});
		if (conversation.streaming) {
			snippets.push({
				label: "Streaming API",
				needsToken: true,
				code: `from huggingface_hub import InferenceClient

client = InferenceClient(api_key="${tokenStr}")

messages = ${formattedMessages({ sep: ",\n\t", start: `[\n\t`, end: `\n]` })}

stream = client.chat.completions.create(
    model="${conversation.model.id}", 
	messages=messages, 
	${formattedConfig({ sep: ",\n\t", start: "", end: "", connector: "=" })},
	stream=True
)

for chunk in stream:
    print(chunk.choices[0].delta.content)`,
			});
		} else {
			// non-streaming
			snippets.push({
				label: "Non-Streaming API",
				needsToken: true,
				code: `from huggingface_hub import InferenceClient

client = InferenceClient(api_key="${tokenStr}")

messages = ${formattedMessages({ sep: ",\n\t", start: `[\n\t`, end: `\n]` })}

completion = client.chat.completions.create(
    model="${conversation.model.id}", 
	messages=messages, 
	${formattedConfig({ sep: ",\n\t", start: "", end: "", connector: "=" })}
)

print(completion.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 OpenAI

client = OpenAI(
	base_url="https://api-inference.huggingface.co/v1/",
	api_key="${tokenStr}"
)

messages = ${formattedMessages({ sep: ",\n\t", start: `[\n\t`, end: `\n]` })}

stream = client.chat.completions.create(
    model="${conversation.model.id}", 
	messages=messages, 
	${formattedConfig({ sep: ",\n\t", start: "", end: "", connector: "=" })},
	stream=True
)

for chunk in stream:
    print(chunk.choices[0].delta.content)`,
			});
		} else {
			// non-streaming
			snippets.push({
				label: "Non-Streaming API",
				needsToken: true,
				code: `from openai import OpenAI

client = OpenAI(
	base_url="https://api-inference.huggingface.co/v1/",
	api_key="${tokenStr}"
)

messages = ${formattedMessages({ sep: ",\n\t", start: `[\n\t`, end: `\n]` })}

completion = client.chat.completions.create(
    model="${conversation.model.id}", 
	messages=messages, 
	${formattedConfig({ sep: ",\n\t", start: "", end: "", connector: "=" })}
)

print(completion.choices[0].message)`,
			});
		}

		return snippets;
	}

	function getHttpSnippets(conversation: Conversation, tokenStr: string) {
		if (tokenStr === "YOUR_HF_TOKEN") {
			tokenStr = "{YOUR_HF_TOKEN}";
		}
		const formattedMessages = ({ sep, start, end }: MessagesJoiner) =>
			start +
			getMessages()
				.map(({ role, content }) => {
					// escape single quotes since single quotes is used to define http post body inside curl requests
					content = content?.replace(/'/g, "'\\''");
					return `{ "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[] = [];

		if (conversation.streaming) {
			snippets.push({
				label: "Streaming API",
				needsToken: true,
				code: `curl 'https://api-inference.huggingface.co/models/${conversation.model.id}/v1/chat/completions' \\
--header "Authorization: Bearer ${tokenStr}" \\
--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-streaming
			snippets.push({
				label: "Non-Streaming API",
				needsToken: true,
				code: `curl 'https://api-inference.huggingface.co/models/${conversation.model.id}/v1/chat/completions' \\
--header "Authorization: Bearer ${tokenStr}" \\
--header 'Content-Type: application/json' \\
--data '{
    "model": "${conversation.model.id}",
    "messages": ${formattedMessages({ sep: ",\n    ", start: `[\n    `, end: `\n]` })},
    ${formattedConfig({ sep: ",\n    ", start: "", end: "" })}
}'`,
			});
		}

		return snippets;
	}

	onDestroy(() => {
		if (timeout) {
			clearTimeout(timeout);
		}
	});
</script>

<div class="px-2 pt-2">
	<div
		class="border-b border-gray-200 text-center text-sm font-medium text-gray-500 dark:border-gray-700 dark:text-gray-400"
	>
		<ul class="-mb-px flex flex-wrap">
			{#each Object.entries(labelsByLanguage) as [language, label]}
				<li>
					<button
						on:click={() => (selectedLanguage = language)}
						class="inline-block rounded-t-lg border-b-2 p-4 {language === selectedLanguage
							? 'border-black text-black dark:border-blue-500 dark:text-blue-500'
							: 'border-transparent hover:border-gray-300 hover:text-gray-600 dark:hover:text-gray-300'}"
						aria-current="page">{label}</button
					>
				</li>
			{/each}
			<li class="ml-auto self-center max-sm:hidden">
				<button
					on:click={() => {
						dispatch("closeCode");
					}}
					class="flex size-7 items-center justify-center rounded-lg px-3 py-2.5 text-xs font-medium text-gray-900 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"
				>

				</button>
			</li>
		</ul>
	</div>

	{#if clientSnippetsByLang[selectedLanguage].length > 1}
		<div class="flex gap-x-2 px-2 pt-6">
			{#each clientSnippetsByLang[selectedLanguage] as { name }, idx}
				<button
					class="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}
						<button
							class="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>
				<pre
					class="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>