由 eda 出售

A comprehensive TypeScript monorepo for interacting with the Hugging Face Hub, running inference across 100,000+ models, building AI agents with MCP tool use, and parsing ML model formats like GGUF and DDUF.
This block provides the full source of the Hugging Face JavaScript/TypeScript library monorepo, covering Hub interaction, model inference, BLAKE3 hashing, GGUF/DDUF parsing, Jinja templating, agent construction, and more. It targets TypeScript projects running on Node.js 18+, Bun, or Deno that need to interact with the Hugging Face ecosystem without taking a bundled NPM dependency.
agents/ - HfAgent class and tool definitions for building LLM-powered agentsblake3-jit/ - Pure JS BLAKE3 hashing with optional WASM SIMD accelerationblob/ - FileBlob and WebBlob utilities for cross-environment binary data handlingdduf/ - Parser for DDUF (Diffusers Unified Format) model archivesdoc-internal/ - Internal documentation tooling, not for production usegearhash-jit/ - JIT-compiled gear hash implementation for chunkinggguf/ - GGUF model file parser for remotely hosted fileshub/ - Full Hugging Face Hub API client (repo creation, file upload, listing)inference/ - InferenceClient for serverless and dedicated inference endpointsjinja/ - Minimalist Jinja2 template engine for ML chat templateslanguages/ - Language metadata definitions used by the Hubmcp-client/ - Model Context Protocol client and tiny agent libraryollama-utils/ - Utilities for Ollama compatibility with Hub-hosted modelsspace-header/ - Space mini-header component for embedding outside HFsplitmix64-wasm/ - WASM-backed splitmix64 PRNGtasks/ - Source-of-truth definitions for Hub pipeline tasks and model librariestasks-gen/ - Code-generation tooling for tasks definitionstiny-agents/ - Lightweight, model-agnostic agent library built on InferenceClientxetchunk-wasm/ - WASM chunker for efficient file transfernpm install @huggingface/hub
npm install @huggingface/inference
npm install @huggingface/agents
npm install @huggingface/gguf
npm install @huggingface/dduf
npm install @huggingface/jinja
npm install @huggingface/mcp-client
npm install @huggingface/tasks
npm install typescript tsx
启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This TypeScript cli / script completed archive review with strong static results. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 4bdf9d2ccd4dc39d…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
No native build steps, iOS pods, or Android linking are required. All WASM modules are bundled inline. Node.js >= 18 is mandatory for the native fetch and Blob APIs.
source/ directory into your project root, e.g. ./vendor/hf-js/.tsconfig.json, add path aliases if you want to import directly from source instead of compiled output:{
"compilerOptions": {
"moduleResolution": "bundler",
"target": "ES2022",
"module": "ESNext",
"strict": true,
"paths": {
"@hf/agents": ["./vendor/hf-js/agents/src/index.ts"],
"@hf/blake3": ["./vendor/hf-js/blake3-jit/src/index.ts"],
"@hf/blob": ["./vendor/hf-js/blob/src/index.ts"]
}
}
}
.env or your deployment environment:HF_TOKEN=hf_your_access_token_here
For the agents package, an InferenceClient-compatible LLM endpoint or Hub model ID is required at runtime. No compile-time configuration is needed beyond the token.
If using tsx for development, run scripts with npx tsx your-script.ts. For production, compile with tsc and run with node.
import { HfAgent } from "./vendor/hf-js/agents/src/index";
class HfAgent {
constructor(
accessToken: string,
llm?: (prompt: string) => Promise<string>,
tools?: Tool[]
);
run(task: string): Promise<unknown>;
}
Use HfAgent when you want to compose multi-step tasks using Hugging Face-hosted models as tools. Pass a custom llm function to swap the underlying language model, or use the defaults which call Hub-hosted models.
import { LLMFromHub, LLMFromEndpoint } from "./vendor/hf-js/agents/src/llms/LLMHF";
function LLMFromHub(
accessToken: string,
model: string
): (prompt: string) => Promise<string>;
function LLMFromEndpoint(
accessToken: string,
endpointUrl: string
): (prompt: string) => Promise<string>;
LLMFromHub wraps a Hub-hosted model as the agent's LLM backend. LLMFromEndpoint targets a dedicated Inference Endpoint URL instead. Use LLMFromEndpoint when you need guaranteed capacity or private models.
import { hash, hashInto, warmupSimd } from "./vendor/hf-js/blake3-jit/src/index";
function hash(input: Uint8Array, outputLength?: number): Uint8Array;
function hashInto(input: Uint8Array, output: Uint8Array): void;
function warmupSimd(): Promise<void>;
hash produces a BLAKE3 digest of arbitrary input bytes, defaulting to 32 bytes of output. Call warmupSimd() once at startup to pre-compile the WASM SIMD path, which significantly accelerates hashing of inputs larger than a few kilobytes.
import { defaultTools } from "./vendor/hf-js/agents/src/tools/index";
import type { Tool } from "./vendor/hf-js/agents/src/types";
const defaultTools: Array<Tool>;
A ready-made array of four tools: textToImageTool, imageToTextTool, textToSpeechTool, speechToTextTool. Pass to HfAgent as-is or spread and extend with custom tools.
import { createKeyed } from "./vendor/hf-js/blake3-jit/src/index";
function createKeyed(key: Uint8Array): Hasher;
// Hasher exposes .update(data: Uint8Array): Hasher and .finalize(length?: number): Uint8Array
Produces an HMAC-like keyed hash. Use this instead of plain hash when you need message authentication with a 32-byte secret key.
Create an agent backed by a Hub-hosted LLM and execute a multimodal task using the built-in tool set.
import { HfAgent, LLMFromHub, defaultTools } from "./vendor/hf-js/agents/src/index";
const HF_TOKEN = process.env.HF_TOKEN ?? "";
const llm = LLMFromHub(HF_TOKEN, "OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5");
const agent = new HfAgent(HF_TOKEN, llm, [...defaultTools]);
const result = await agent.run("Generate an image of a red fox in a snowy forest.");
console.log("Agent result:", result);
Hash a file buffer and compare against a known digest to verify integrity. Warm up SIMD first for large files.
import { hash, warmupSimd } from "./vendor/hf-js/blake3-jit/src/index";
import { readFileSync } from "fs";
await warmupSimd();
const fileBuffer = readFileSync("./model.gguf");
const input = new Uint8Array(fileBuffer.buffer, fileBuffer.byteOffset, fileBuffer.byteLength);
const digest = hash(input);
const hex = Buffer.from(digest).toString("hex");
console.log("BLAKE3 digest:", hex);
const expectedHex = "your_known_hex_digest_here";
if (hex !== expectedHex) {
throw new Error("Integrity check failed");
}
Use createKeyed to produce a message authentication code over a request payload before sending it to an endpoint.
import { createKeyed } from "./vendor/hf-js/blake3-jit/src/index";
const secretKey = new Uint8Array(32);
crypto.getRandomValues(secretKey); // In practice, load from a secure store
const payload = new TextEncoder().encode(JSON.stringify({ model: "flux", prompt: "a cat" }));
const mac = createKeyed(secretKey)
.update(payload)
.finalize(); // returns 32-byte Uint8Array
const macHex = Buffer.from(mac).toString("hex");
console.log("Request MAC:", macHex);
// Attach macHex as a request header for server-side verification
Combine the built-in textToImageTool with a custom tool and hand the array to HfAgent.
import { HfAgent, LLMFromEndpoint, textToImageTool } from "./vendor/hf-js/agents/src/index";
import type { Tool } from "./vendor/hf-js/agents/src/types";
const HF_TOKEN = process.env.HF_TOKEN ?? "";
const ENDPOINT_URL = process.env.HF_ENDPOINT_URL ?? "";
const translationTool: Tool = {
name: "translation",
description: "Translates text from one language to another",
examples: [],
call: async (input: unknown) => {
// custom implementation
return String(input);
},
};
const llm = LLMFromEndpoint(HF_TOKEN, ENDPOINT_URL);
const agent = new HfAgent(HF_TOKEN, llm, [textToImageTool, translationTool]);
const result = await agent.run("Translate 'hello world' to French and then generate an image of it.");
console.log(result);
agents/ - HfAgent orchestrator, LLM adapters (LLMFromHub, LLMFromEndpoint), and four multimodal tools; entry point is agents/src/index.ts.blake3-jit/ - Self-contained BLAKE3 implementation with JIT WASM SIMD path; exports hash, hashInto, warmupSimd, createKeyed, createDeriveKey, Hasher, XofReader.blob/ - Environment-agnostic blob helpers (FileBlob, WebBlob, createBlob); used internally by hub and inference packages.dduf/ - Streaming parser for DDUF archives, analogous to gguf but targeting Diffusers model format.doc-internal/ - Internal tooling for generating API documentation; not imported at runtime.gearhash-jit/ - JIT gear hash used by the chunking layer for content-defined splitting.gguf/ - Parses GGUF metadata and tensor headers from local or remote files without full download.hub/ - Complete Hub REST client: createRepo, uploadFile, deleteRepo, listFiles, downloadFile, commit APIs.inference/ - InferenceClient supporting 100k+ models across providers: chat completion, text-to-image, ASR, and more.jinja/ - Jinja2 subset interpreter for rendering ML chat prompt templates stored in tokenizer_config.json.languages/ - Static metadata (display names, codes) for programming and spoken languages used by Hub UI.mcp-client/ - MCP-protocol client plus a lightweight agent layer built on InferenceClient.ollama-utils/ - Helpers for converting Hub model metadata into Ollama-compatible format.space-header/ - Web component that renders the HF Space mini-header outside huggingface.co.splitmix64-wasm/ - WASM-backed splitmix64 PRNG used by chunking and hashing utilities.tasks/ - JSON/TS definitions for every Hub pipeline task, model library, and widget type.tasks-gen/ - Scripts that regenerate tasks/ source from upstream definitions; not a runtime dependency.tiny-agents/ - Minimal agent loop with tool-use, built directly on InferenceClient without the heavier agents package.xetchunk-wasm/ - WASM-backed content-defined chunker used by hub for efficient large-file uploads.fetch and Blob are not available; upgrade to Node.js 18+ or polyfill with node-fetch and @web-std/blob."type": "commonjs", either set "moduleResolution": "bundler" in tsconfig or use dynamic import() at the call site.HF_TOKEN: Requests to private models or write operations silently fail with a 401; always validate process.env.HF_TOKEN at startup.transformIgnorePatterns or mock warmupSimd in test setup.createKeyed key length: The key must be exactly 32 bytes; passing any other length throws at runtime with a non-obvious error message.Range header and that CORS headers allow it in browser environments.I have dropped the Hugging Face JS monorepo source into ./vendor/hf-js/ in my project.
The integration guide is at ./USAGE.md. The upstream package collection is huggingface-js (plugin domain).
Please help me integrate the following packages from source/ into my existing TypeScript project step by step:
1. Read USAGE.md fully before writing any code.
2. Add tsconfig.json path aliases for the packages I need (agents, blake3-jit, hub, inference).
3. Set up environment variable loading for HF_TOKEN.
4. Create a src/hf/ directory that re-exports the symbols I need from vendor/hf-js/.
5. Write a working example in src/hf/example.ts that:
- Hashes a string using blake3-jit hash()
- Creates an HfAgent with LLMFromHub and defaultTools
- Runs a simple agent task
6. Make sure all imports reference real exported symbols from the file excerpts in USAGE.md.
7. Do not install the NPM packages; import directly from the local source paths.
8. Point out any Node.js version or ESM configuration changes needed.
The individual packages carry their own licenses located at source/<package>/LICENSE within each subdirectory. The majority of packages are released under the Apache 2.0 license; check each LICENSE file for the exact terms.
Upstream repository: https://github.com/huggingface/huggingface.js
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
SaaS, AI & Subscription Products
免费