# Hugging Face JS ライブラリ

これは、Hugging Face APIと対話するためのJSライブラリのコレクションです。TS型が含まれています。

- [@huggingface/hub](hub/README): huggingface.co と連携して、リポジトリの作成または削除、ファイルのコミット / ダウンロードを行います
- [@huggingface/inference](inference/README): 対応するすべての（サーバーレス）Inference Providers を使用するか、Inference Endpoints（専用）に切り替えて、10 万以上の Machine Learning モデルに呼び出しを行う
- [@huggingface/mcp-client](mcp-client/README): InferenceClient をベースに構築された、Model Context Protocol (MCP) クライアントおよび小型の Agent ライブラリ。
- [@huggingface/gguf](gguf/README): リモートでホストされているファイルで動作するGGUFパーサー。
- [@huggingface/dduf](dduf/README): DDUF（DDUF Diffusers Unified Format）用の同様のパッケージ
- [@huggingface/lerobot](lerobot/README): LeRobot ロボティクスデータセットのパーサー。範囲指定 HTTP リクエストを通じて v2.x および v3.0 レイアウトを読み取ります。
- [@huggingface/usd-web-viewer](usd-web-viewer/README): Web 用の OpenUSD ビューア: `.usd`、`.usda`、`.usdc`、`.usdz` ファイルを WebAssembly で合成し、three.js でレンダリングします。
- [@huggingface/tasks](tasks/README): Hubの主要なプリミティブ（パイプラインタスク、モデルライブラリなど）の定義ファイルであり、信頼できる情報源です。
- [@huggingface/jinja](jinja/README): Jinja テンプレートエンジンのミニマルな JS 実装。ML チャットテンプレートに使用します。
- [@huggingface/space-header](space-header/README): Hugging Face 外部で Space の `mini_header` を使用します
- [@huggingface/ollama-utils](ollama-utils/README): Hugging Face Hub上のモデルとのOllama互換性を維持するための各種ユーティリティ。
- [@huggingface/tiny-agents](tiny-agents/README): ツールを使用できるAIエージェントを構築するための、軽量でモデル非依存のライブラリ。

ポリフィルや依存関係を回避するために最新の機能を使用しているため、これらのライブラリは最新のブラウザ / Node.js >= 18 / Bun / Denoでのみ動作します。

これらのライブラリはまだ非常に若い段階にあります。問題の報告（issue）を作成して、ぜひご協力ください！

## インストール

### NPMから

NPM経由でインストールするには、必要に応じてライブラリをダウンロードできます:

```bash
npm install @huggingface/hub
npm install @huggingface/inference
npm install @huggingface/mcp-client
```

次に、コード内でライブラリをインポートします:

```ts
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モジュール](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/)、つまり`<script type="module">`を使用すると、コード内でライブラリをインポートできます。

```html
<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

```ts
// 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"
```

## 使用例

[アカウント設定](https://huggingface.co/settings/tokens)でHFアクセストークンを取得してください。

### @huggingface/inference の例

```ts
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://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 の例

```ts
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 の例

```ts
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を確認してください！

## フォーマットとテスト

```console
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` などです。

