Huggingface.js documentation
Hugging Face JS 라이브러리
@huggingface/inference
Inference Client 사용API 참조
클래스
HfInferenceInferenceClientInferenceClientEndpointInferenceClientErrorInferenceClientHubApiErrorInferenceClientInputErrorInferenceClientProviderApiErrorInferenceClientProviderOutputErrorInferenceClientRoutingError
인터페이스
AudioToAudioOutputAudioToAudioOutputElemBaseArgsBodyParamsHeaderParamsInferenceProviderMappingEntry로거옵션TextGenerationInputTextGenerationOutputTextGenerationStreamBestOfSequenceTextGenerationStreamDetailsTextGenerationStreamOutputTextGenerationStreamPrefillTokenTextGenerationStreamTokenUrlParams
모듈
@huggingface/hub
Hub와 상호작용하기API 참고
클래스
인터페이스
AuthInfoCachedFileInfoCachedRepoInfoCachedRevisionInfoCommitCopyFileCommitDataCommitDeletedEntryCommitEditFileCommitEditFileParamsCommitFileCommitInfoCommitOutputCopyDestinationCopyFilesEntryCopyProgressEventCopySource자격 증명DatasetEntryFileDownloadInfoOutputHFCacheInfoJobVolumeLfsPathInfoListFileEntryMlxQuantizationConfigModelConfigModelDerivedFieldsModelEntryOAuthResultParallelDownloadOptionsPathInfoQuantizationConfigRangeEditCacheEntryRepoIdSafetensorsIndexJsonSafetensorsShardFileInfoSecurityFileStatusSpaceEntrySpaceResourceConfigSpaceResourceRequirementSpaceRuntimeTensorInfoUserInfoWhoAmIAppWhoAmIOrgWhoAmIUserXetFileInfoXetReadToken
@huggingface/mcp-client
@huggingface/tiny-agents
@huggingface/space-header
@huggingface/gguf
@huggingface/lerobot
@huggingface/usd-web-viewer
// Programmatically interact with the Hub
await createRepo({
repo: { type: "model", name: "my-user/nlp-model" },
accessToken: HF_TOKEN
});
await uploadFile({
repo: "my-user/nlp-model",
accessToken: HF_TOKEN,
// Can work with native File in browsers
file: {
path: "pytorch_model.bin",
content: new Blob(...)
}
});
// Use all supported Inference Providers!
await inference.chatCompletion({
model: "meta-llama/Llama-3.1-8B-Instruct",
provider: "sambanova", // or together, fal-ai, replicate, cohere …
messages: [
{
role: "user",
content: "Hello, nice to meet you!",
},
],
max_tokens: 512,
temperature: 0.5,
});
await inference.textToImage({
model: "black-forest-labs/FLUX.1-dev",
provider: "replicate",
inputs: "a picture of a green bird",
});
// and much more…Hugging Face JS 라이브러리
이것은 TS 타입이 포함된 Hugging Face API와 상호작용하기 위한 JS 라이브러리 모음입니다.
- @huggingface/hub: huggingface.co와 상호작용하여 저장소를 생성하거나 삭제하고 파일을 커밋/다운로드합니다
- @huggingface/inference: 지원되는 모든 (서버리스) Inference Providers를 사용하거나 Inference Endpoints(전용)로 전환하여 100,000개 이상의 Machine Learning 모델에 호출을 수행합니다
- @huggingface/mcp-client: InferenceClient를 기반으로 구축된 Model Context Protocol(MCP) 클라이언트 및 소형 Agent 라이브러리입니다.
- @huggingface/gguf: 원격 호스팅 파일에서 작동하는 GGUF 파서입니다.
- @huggingface/dduf: DDUF(DDUF Diffusers Unified Format)용 유사한 패키지
- @huggingface/lerobot: LeRobot 로봇 데이터셋을 위한 파서로, ranged HTTP 요청을 통해 v2.x 및 v3.0 레이아웃을 읽습니다.
- @huggingface/usd-web-viewer: 웹용 OpenUSD 뷰어:
.usd,.usda,.usdc,.usdz파일을 WebAssembly에서 구성하고 three.js로 렌더링합니다. - @huggingface/tasks: Hub의 주요 원시 요소인 pipeline 작업, 모델 라이브러리 등의 정의 파일 및 신뢰할 수 있는 출처
- @huggingface/jinja: ML 채팅 템플릿에 사용될 Jinja 템플릿 엔진의 최소한적인 JS 구현입니다.
- @huggingface/space-header: Hugging Face 외부에서 Space
mini_header사용 - @huggingface/ollama-utils: Hugging Face Hub의 모델과 Ollama 호환성을 유지하기 위한 다양한 유틸리티.
- @huggingface/tiny-agents: 도구를 사용할 수 있는 AI 에이전트를 구축하기 위한 작고 모델 비종속적인 라이브러리.
폴리필과 의존성을 피하기 위해 최신 기능을 사용하므로, 해당 라이브러리는 최신 브라우저 / Node.js >= 18 / Bun / Deno에서만 작동합니다.
라이브러리는 아직 매우 초기 단계이므로, 이슈를 열어 주시면 큰 도움이 됩니다!
설치
NPM에서
NPM을 통해 설치하려면 필요한 라이브러리를 다운로드할 수 있습니다:
npm install @huggingface/hub npm install @huggingface/inference npm install @huggingface/mcp-client
그런 다음 코드에서 라이브러리를 가져옵니다:
import { createRepo, commit, deleteRepo, listFiles } from "@huggingface/hub";
import { InferenceClient } from "@huggingface/inference";
import { McpClient } from "@huggingface/mcp-client";
import type { RepoId } from "@huggingface/hub";CDN 또는 정적 호스팅
CDN 또는 정적 호스팅을 사용하면 번들러 없이 순수 JS로 패키지를 실행할 수 있습니다. ES 모듈, 즉 <script type="module">을 사용하면 코드로 라이브러리를 가져올 수 있습니다:
<script type="module">
import { InferenceClient } from 'https://cdn.jsdelivr.net/npm/@huggingface/inference@4.13.32/+esm';
import { createRepo, commit, deleteRepo, listFiles } from "https://cdn.jsdelivr.net/npm/@huggingface/hub@2.17.10/+esm";
</script>Deno
// esm.sh
import { InferenceClient } from "https://esm.sh/@huggingface/inference"
import { createRepo, commit, deleteRepo, listFiles } from "https://esm.sh/@huggingface/hub"
// or npm:
import { InferenceClient } from "npm:@huggingface/inference"
import { createRepo, commit, deleteRepo, listFiles } from "npm:@huggingface/hub"사용 예시
계정 설정에서 HF 액세스 토큰을 가져오세요.
@huggingface/inference 예제
import { InferenceClient } from "@huggingface/inference";
const HF_TOKEN = "hf_...";
const client = new InferenceClient(HF_TOKEN);
// Chat completion API
const out = await client.chatCompletion({
model: "meta-llama/Llama-3.1-8B-Instruct",
messages: [{ role: "user", content: "Hello, nice to meet you!" }],
max_tokens: 512
});
console.log(out.choices[0].message);
// Streaming chat completion API
for await (const chunk of client.chatCompletionStream({
model: "meta-llama/Llama-3.1-8B-Instruct",
messages: [{ role: "user", content: "Hello, nice to meet you!" }],
max_tokens: 512
})) {
console.log(chunk.choices[0].delta.content);
}
/// Using a third-party provider:
await client.chatCompletion({
model: "meta-llama/Llama-3.1-8B-Instruct",
messages: [{ role: "user", content: "Hello, nice to meet you!" }],
max_tokens: 512,
provider: "sambanova", // or together, fal-ai, replicate, cohere …
})
await client.textToImage({
model: "black-forest-labs/FLUX.1-dev",
inputs: "a picture of a green bird",
provider: "fal-ai",
})
// You can also omit "model" to use the recommended model for the task
await client.translation({
inputs: "My name is Wolfgang and I live in Amsterdam",
parameters: {
src_lang: "en",
tgt_lang: "fr",
},
});
// pass multimodal files or URLs as inputs
await client.imageToText({
model: 'nlpconnect/vit-gpt2-image-captioning',
data: await (await fetch('https://picsum.photos/300/300')).blob(),
})
// Using your own dedicated inference endpoint: https://hf.co/docs/inference-endpoints/
const gpt2Client = client.endpoint('https://xyz.eu-west-1.aws.endpoints.huggingface.cloud/gpt2');
const { generated_text } = await gpt2Client.textGeneration({ inputs: 'The answer to the universe is' });
// Chat Completion
const llamaEndpoint = client.endpoint(
"https://huggingface.co/proxy/router.huggingface.co/hf-inference/models/meta-llama/Llama-3.1-8B-Instruct"
);
const out = await llamaEndpoint.chatCompletion({
model: "meta-llama/Llama-3.1-8B-Instruct",
messages: [{ role: "user", content: "Hello, nice to meet you!" }],
max_tokens: 512,
});
console.log(out.choices[0].message);@huggingface/hub 예제
import { createRepo, uploadFile, deleteFiles } from "@huggingface/hub";
const HF_TOKEN = "hf_...";
await createRepo({
repo: "my-user/nlp-model", // or { type: "model", name: "my-user/nlp-test" },
accessToken: HF_TOKEN
});
await uploadFile({
repo: "my-user/nlp-model",
accessToken: HF_TOKEN,
// Can work with native File in browsers
file: {
path: "pytorch_model.bin",
content: new Blob(...)
}
});
await deleteFiles({
repo: { type: "space", name: "my-user/my-space" }, // or "spaces/my-user/my-space"
accessToken: HF_TOKEN,
paths: ["README.md", ".gitattributes"]
});@huggingface/mcp-client 예시
import { Agent } from '@huggingface/mcp-client';
const HF_TOKEN = "hf_...";
const agent = new Agent({
provider: "auto",
model: "Qwen/Qwen2.5-72B-Instruct",
apiKey: HF_TOKEN,
servers: [
{
// Playwright MCP
command: "npx",
args: ["@playwright/mcp@latest"],
},
],
});
await agent.loadTools();
for await (const chunk of agent.run("What are the top 5 trending models on Hugging Face?")) {
if ("choices" in chunk) {
const delta = chunk.choices[0]?.delta;
if (delta.content) {
console.log(delta.content);
}
}
}물론 더 많은 기능이 있으니, 각 라이브러리의 README를 확인해 보세요!
포맷팅 및 테스트
sudo corepack enable pnpm install pnpm -r format:check pnpm -r lint:check pnpm -r test
빌드
pnpm -r build이렇게 하면 packages/*/dist에 ESM 및 CJS JavaScript 파일이 생성됩니다. 예를 들어 packages/inference/dist/index.mjs와 같습니다.