Spaces:
Running
Running
File size: 7,652 Bytes
f60772d 50389d8 d251334 f60772d d251334 f60772d d251334 f60772d d84eaac f60772d d251334 f60772d d251334 f60772d d251334 f60772d d251334 f60772d d251334 f60772d d251334 f60772d d251334 f60772d d251334 f60772d d251334 f60772d d251334 f60772d d251334 f60772d 4e74aba f60772d d251334 f60772d d251334 f60772d d251334 f60772d 5f5f569 d84eaac f60772d 50389d8 f60772d 50389d8 f60772d 5f5f569 f60772d | 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 | <script lang="ts">
import { CodeXml, ExternalLink } from '@lucide/svelte';
import { Button } from '$lib/components/ui/button';
import * as Dialog from '$lib/components/ui/sheet/index.js';
import Code from '$lib/components/chat/markdown/Code.svelte';
import { useSvelteFlow } from '@xyflow/svelte';
import { breakpointsState } from '$lib/state/breakpoints.svelte';
import { modelsState } from '$lib/state/models.svelte';
type Instruction = {
library: string;
doc_link: string;
install: string;
code: string;
};
type Language = {
language: string;
instructions: Instruction[];
};
const { getNodes } = useSvelteFlow();
let firstModelSelection = $derived(
(getNodes()?.[0]?.data as { selectedModels?: string[] })?.selectedModels?.[0] ??
(modelsState.models[0]?.id as string) ??
''
);
const instructions: Language[] = $derived([
{
language: 'Javascript',
instructions: [
{
library: 'openai',
doc_link: 'https://platform.openai.com/docs/libraries',
install: 'npm install --save openai',
code: `import { OpenAI } from "openai";";
const client = new OpenAI({
baseURL: "https://router.huggingface.co/v1",
apiKey: process.env.HF_TOKEN,
});
const stream = await client.chat.completions.create({
model: "${firstModelSelection}",
messages: [
{ role: "user", content: "What is the capital of France?" }
],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}`
},
{
library: 'huggingface.js',
doc_link: 'https://huggingface.co/docs/huggingface.js/inference/README',
install: 'npm install --save @huggingface/inference',
code: `import { InferenceClient } from "@huggingface/inference";
const client = new InferenceClient(process.env.HF_TOKEN);
let out = "";
const stream = client.chatCompletionStream({
model: "${firstModelSelection}",
messages: [
{ role: "user", content: "What is the capital of France?" }
],
});
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);
}
}`
}
]
},
{
language: 'Python',
instructions: [
{
library: 'openai',
doc_link: 'https://platform.openai.com/docs/libraries',
install: 'pip install --upgrade openai',
code: `import os
from openai import OpenAI
client = OpenAI(
base_url="https://router.huggingface.co/v1",
api_key=os.environ.get("HF_TOKEN"),
)
stream = client.chat.completions.create(
model="${firstModelSelection}",
messages=[{"role": "user", "content": "What is the capital of France?"}],
stream=True,
)
for chunk in stream:
print(chunk.choices[0].delta.content, end="")`
},
{
library: 'huggingface_hub',
doc_link: 'https://huggingface.co/docs/huggingface_hub/guides/inference',
install: 'pip install --upgrade huggingface_hub',
code: `import os
from huggingface_hub import InferenceClient
client = InferenceClient(
api_key=os.environ["HF_TOKEN"],
)
stream = client.chat.completions.create(
model="${firstModelSelection}",
messages=[{"role": "user", "content": "What is the capital of France?"}],
stream=True,
)
for chunk in stream:
print(chunk.choices[0].delta.content, end="")`
},
{
library: 'requests',
doc_link: 'https://platform.openai.com/docs/libraries',
install: 'pip install requests',
code: `import os
import json
import requests
API_URL = "https://router.huggingface.co/v1/chat/completions"
headers = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"}
def query(payload):
response = requests.post(API_URL, headers=headers, json=payload, stream=True)
for line in response.iter_lines():
if not line.startswith(b"data:"):
continue
if line.strip() == b"data: [DONE]":
return
yield json.loads(line.decode("utf-8").lstrip("data:"))
chunks = query({
"messages": [{"role": "user", "content": "What is the capital of France?"}],
"model": "${firstModelSelection}",
"stream": True,
})
for chunk in chunks:
print(chunk["choices"][0]["delta"]["content"], end="")`
}
]
},
{
language: 'cURL',
instructions: [
{
library: 'curl',
doc_link: 'https://huggingface.co/docs/api-inference/getting-started',
install: '',
code: `curl https://router.huggingface.co/v1/chat/completions \\
-H "Authorization: Bearer $HF_TOKEN" \\
-H "Content-Type: application/json" \\
-d '{
"model": "${firstModelSelection}",
"messages": [
{ "role": "user", "content": "What is the capital of France?" }
],
"stream": true
}'`
}
]
}
]);
let open = $state(false);
let selectedLanguage = $state<string>('Javascript');
let selectedLibrary = $state<string>('openai');
let languageData = $derived(instructions.find((i) => i.language === selectedLanguage));
let libraryData = $derived(languageData?.instructions.find((i) => i.library === selectedLibrary));
let showLibraryTabs = $derived((languageData?.instructions.length ?? 0) > 1);
function selectLanguage(lang: string) {
selectedLanguage = lang;
const langData = instructions.find((i) => i.language === lang);
if (langData) selectedLibrary = langData.instructions[0].library;
}
</script>
<Dialog.Root bind:open>
<Dialog.Trigger class="">
<Button variant="outline" size={breakpointsState.isMobile ? 'icon-sm' : 'default'}>
<CodeXml />
{#if !breakpointsState.isMobile}
How to use the API
{/if}
</Button>
</Dialog.Trigger>
<Dialog.Content class="max-w-xl! gap-0! p-0!">
<Dialog.Header class="mb-0 gap-1! rounded-none border-b p-5">
<Dialog.Title>Use the API</Dialog.Title>
<Dialog.Description>How to use the API in your application.</Dialog.Description>
</Dialog.Header>
<div class="space-y-4 p-5">
<div class="flex items-center gap-1.5">
{#each instructions as lang}
<Button
variant={selectedLanguage === lang.language ? 'default' : 'outline'}
size="default"
onclick={() => selectLanguage(lang.language)}
>
{lang.language}
</Button>
{/each}
</div>
{#if showLibraryTabs && languageData}
<div class="flex items-center gap-1.5">
{#each languageData.instructions as instr}
<Button
variant={selectedLibrary === instr.library ? 'outline-blue' : 'outline'}
size="xs"
class="rounded-full!"
onclick={() => (selectedLibrary = instr.library)}
>
{instr.library}
</Button>
{/each}
</div>
{/if}
{#if libraryData}
{#if libraryData.install}
<div class="overflow-hidden rounded-lg border border-border">
<div class="flex items-center justify-between border-b border-border px-3.5 py-2.5">
<p class="text-xs font-semibold text-primary">Install</p>
</div>
<Code text={libraryData.install} className="" />
</div>
{/if}
<div class="overflow-hidden rounded-lg border border-border">
<div class="flex items-center justify-between border-b border-border px-3.5 py-2.5">
<p class="text-xs font-semibold text-primary">Streaming API</p>
<div class="flex items-center gap-1.5">
<a href={libraryData.doc_link} target="_blank" rel="noopener noreferrer">
<Button variant="outline" size="2xs">
<ExternalLink class="size-3.5" />
View documentation
</Button>
</a>
</div>
</div>
<Code text={libraryData.code} className="" />
</div>
{/if}
</div>
</Dialog.Content>
</Dialog.Root>
|