Download the PHP package codewithkyrian/huggingface without Composer
On this page you can find all versions of the php package codewithkyrian/huggingface. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download codewithkyrian/huggingface
More information about codewithkyrian/huggingface
Files in codewithkyrian/huggingface
Package huggingface
Short Description Hugging Face Hub client for PHP. Manage repositories, run inference, and access thousands of models and datasets with a robust, type-safe API.
License MIT
Informations about the package huggingface
Hugging Face PHP
A comprehensive PHP client for the Hugging Face Hub. Access thousands of machine learning models, datasets, run inference, and more, all from your PHP application.
- Hub API: Full CRUD support for Repositories (Models, Datasets, Spaces), Files, and Collections.
- Inference API: Run inference on over 100,000+ models using Hugging Face's serverless abstraction. Automatically resolves the best provider for you.
- Smart Caching: Built-in, OS-aware caching system with support for generic file caching and optimization.
- Type-Safe: Fully typed DTOs for strict typing and better developer experience.
- Utilities: Includes specific utilities for various tasks like token classification, zero-shot classification, and more.
Table of Contents
- Installation
- Quick Start
- Configuration
- Hub API
- Repository Basics
- Repository Info
- Creating Repositories
- Updating Repositories
- Repository Operations
- Branch Management
- File Operations
- Downloading Files
- Downloading Entire Repositories
- Uploading Files
- Deleting Files
- Listing Commits
- Collections
- Searching Models, Datasets, and Spaces
- Inference API
- Provider Configuration
- Chat Completion
- Text Generation
- Feature Extraction (Embeddings)
- Text Classification
- Token Classification
- Summarization
- Question Answering
- Translation
- Fill Mask
- Sentence Similarity
- Text to Image
- Image Classification
- Object Detection
- Image to Text
- Text to Speech
- Automatic Speech Recognition
- Caching
- Error Handling
- Examples
- API Reference
Installation
Install the package via Composer:
Requirements
- PHP 8.2 or higher
- A PSR-18 HTTP client (e.g., Guzzle, Symfony HttpClient)
If you don't have a PSR-18 client installed, add Guzzle:
Quick Start
The client works without authentication for public resources:
For operations requiring authentication (private repos, inference, uploads), provide a token:
Configuration
Authentication
A token is optional for public Hub operations (downloading, searching, listing). You need a token for:
- Accessing private repositories
- Running inference on most models
- Uploading files or creating repositories
Getting a token:
- Create a free account at huggingface.co
- Go to Settings → Access Tokens
- Create a token with appropriate permissions
Basic Setup
Environment Variables
The client automatically checks these environment variables:
Advanced Configuration
Use the factory for full control:
Hub API
The Hub API lets you manage repositories, upload models, and search the Hugging Face Hub.
Repository Basics
Get a RepoManager for any repository. All operations (info, files, download, commit) flow through it.
Working with Revisions
By default, operations use the main branch. Use revision() to target a specific branch, tag, or commit.
Repository Info
Get metadata about a repository.
Shorthand methods when you only need metadata:
Creating Repositories
Create Options
| Method | Description |
|---|---|
private() |
Make repository private |
license(string $id) |
Set license (e.g., mit, apache-2.0) |
sdk(SpaceSdk $sdk, string $version) |
Set Space SDK and version (for spaces only) |
hardware(SpaceHardware $hw) |
Set Space hardware tier (for spaces only) |
Updating Repositories
Repository Operations
Branch Management
Deleting Repositories
File Operations
Listing Files
Listing Options
| Method | Description |
|---|---|
files(recursive: true) |
Include files in subdirectories |
files(expand: true) |
Include expanded metadata |
files(path: 'subdir') |
List files in specific directory |
File Information
Downloading Files
Download Options
| Method | Description |
|---|---|
force() |
Re-download even if cached |
useCache(false) |
Skip cache entirely |
save(?string $path) |
Save to directory, or cache if null |
getContent() |
Get raw content as string |
json() |
Parse content as JSON |
Cache Helpers
Downloading Entire Repositories
Download all files to a local cached snapshot.
Snapshots are additive, so you can call snapshot() multiple times to build up a local content cache. Use force: false to skip the remote update check if you already have a cached revision.
Uploading Files
Quick Upload
Commit Builder
For complex operations, use the commit builder:
addFile() accepts: string (content or path), URL, or resource (stream).
Deleting Files
Listing Commits
[!NOTE]
commits()returns a Generator that fetches pages lazily. ThebatchSizeargument (1–1000) controls how many commits are fetched per API request; the generator keeps requesting more pages until all commits are returned, so use abreakwhen you have enough results.
Collections
Collections are curated lists of models, datasets, spaces, or papers.
Listing Collections
Creating Collections
Managing Items
Searching Models, Datasets, and Spaces
Search returns a Generator that fetches results lazily.
Models
Model Search Options
| Method | Description |
|---|---|
search(string $query) |
Full-text search |
task(string $task) |
Filter by pipeline task |
library(string $lib) |
Filter by library (e.g., transformers) |
author(string $author) |
Filter by author/organization |
language(string $lang) |
Filter by language code |
sort(SortField $field) |
Sort by downloads, likes, etc. |
descending() |
Sort in descending order |
limit(int $n) |
Maximum results to fetch |
Datasets
Spaces
[!WARNING] Without
limit(), the generator fetches ALL matching results. Always set a limit or break manually.
Inference API
The Inference API lets you run machine learning models on Hugging Face's infrastructure. It supports text generation, embeddings, classification, image generation, speech recognition, and more.
Provider Configuration
The inference client supports multiple providers. Pass the provider directly to inference():
Supported Providers
| Provider | Slug | Tasks |
|---|---|---|
| Hugging Face | hf-inference (default) |
All tasks |
| Black Forest Labs | black-forest-labs |
Text-to-Image |
| Cerebras | cerebras |
Chat |
| Cohere | cohere |
Chat |
| Fal.ai | fal-ai |
Text-to-Image, Text-to-Video, Image-to-Image, Image-to-Video, ASR, TTS |
| Featherless AI | featherless-ai |
Chat, Text Generation |
| Fireworks AI | fireworks-ai |
Chat |
| Groq | groq |
Chat, Text Generation |
| Hyperbolic | hyperbolic |
Chat, Text Generation, Text-to-Image |
| Nebius | nebius |
Chat, Text Generation, Text-to-Image, Embeddings |
| Novita | novita |
Chat, Text Generation |
| Nscale | nscale |
Chat, Text-to-Image |
| OpenAI | openai |
Chat (requires direct API key) |
| OVHcloud | ovhcloud |
Chat, Text Generation |
| Replicate | replicate |
Text-to-Image |
| Sambanova | sambanova |
Chat, Embeddings |
| Scaleway | scaleway |
Chat, Text Generation, Embeddings |
| Together AI | together |
Chat, Text Generation, Text-to-Image |
| ZAI | zai-org |
Chat, Text-to-Image |
Provider Resolution
When you don't specify a provider (or use InferenceProvider::Auto), the client automatically selects the best available provider for your model. Here's how it works:
- Map Model Providers: The client queries the Hugging Face Hub to find all providers that serve this model following the priority order of providers you've configured in your Inference Provider settings on Hugging Face.
- Availability & Compatibility: It selects the first provider that is currently available and supports the requested task.
- Exception: If no viable provider is found for the model and task, a
RoutingExceptionis thrown.
This ensures you always get the most reliable inference endpoint based on your personal or organization settings.
Billing
Bill requests to an organization:
Chat Completion
Chat with large language models using a conversational interface. Supports system prompts, multi-turn conversations, and streaming.
Multi-turn Conversations
Streaming
Options
| Method | Description |
|---|---|
system(string $content) |
Add a system message |
user(string $content) |
Add a user message |
assistant(string $content) |
Add an assistant message |
maxTokens(int $tokens) |
Maximum tokens to generate |
temperature(float $temp) |
Sampling temperature (0.0–2.0) |
topP(float $p) |
Nucleus sampling probability |
topK(int $k) |
Top-k sampling |
stop(array $sequences) |
Stop sequences |
seed(int $seed) |
Random seed for reproducibility |
frequencyPenalty(float $penalty) |
Reduce repetition of tokens |
presencePenalty(float $penalty) |
Encourage new topics |
logprobs(bool $b, ?int $k) |
Return log probabilities |
responseFormat(array $fmt) |
Set response format (e.g. JSON) |
tool(ChatCompletionTool $tool) |
Add a tool definition |
tools(array<ChatCompletionTool> $tools) |
Add multiple tools |
toolChoice(string\|array $c) |
Control tool choice |
Text Generation
Generate text continuations from a prompt. Unlike chat completion, this is for raw text completion without conversation structure.
Options
| Method | Description |
|---|---|
maxNewTokens(int $n) |
Max new tokens to generate |
temperature(float $t) |
Sampling temperature |
topK(float $k) |
Top-k sampling |
topP(float $p) |
Nucleus sampling |
repetitionPenalty(float $p) |
Repetition penalty (> 1.0) |
doSample(bool $b) |
Enable/disable sampling |
returnFullText(bool $b) |
Include prompt in output |
seed(int $s) |
Random seed |
stop(string\|array $s) |
Stop sequence(s) |
truncate(int $t) |
Truncate inputs to size |
watermark(bool $b) |
Enable watermarking |
frequencyPenalty(float $p) |
Frequency penalty |
bestOf(int $n) |
Generate best of N sequences |
decoderInputDetails(bool $b) |
Return decoder input details |
Also supports: adapterId, details, grammar, topNTokens, typicalP
Feature Extraction (Embeddings)
Generate vector embeddings for text. Useful for semantic search, clustering, and similarity comparisons.
Options
| Method | Description |
|---|---|
normalize() |
Normalize embeddings to unit length |
truncate() |
Truncate input to model's max length |
promptName(string $name) |
Use a specific prompt template |
truncationDirection(TruncationDirection $direction) |
Left or Right truncation |
Text Classification
Classify text into categories. Returns scored labels.
Options
| Method | Description |
|---|---|
topK(int $k) |
Number of predictions to return |
functionToApply(ClassificationOutputTransform $f) |
Function to apply to scores (Sigmoid, Softmax, None) |
Token Classification
Classify individual tokens in a text, such as identifying entities (NER) or parts of speech (POS).
Options
| Method | Description |
|---|---|
aggregationStrategy(AggregationStrategy $s) |
Strategy to fuse tokens (None, Simple, First, Average, Max) |
ignoreLabels(array $labels) |
List of labels to ignore during classification |
stride(int $n) |
Overlap tokens between chunks for long text |
Summarization
Summarize long text into shorter versions.
Options
| Method | Description |
|---|---|
maxLength(int $length) |
Maximum summary length |
minLength(int $length) |
Minimum summary length |
doSample(bool $sample) |
Enable sampling for varied output |
temperature(float $temp) |
Sampling temperature |
Question Answering
Extract answers from a context passage.
Options
| Method | Description |
|---|---|
topK(int $k) |
Number of answers to return |
docStride(int $n) |
Overlap size for long context chunks |
maxAnswerLen(int $n) |
Max answer length |
maxQuestionLen(int $n) |
Max question length |
maxSeqLen(int $n) |
Max chunk length (context + question) |
alignToWords(bool $b) |
Align answer to words (true by default) |
handleImpossibleAnswer(bool $b) |
Accept impossible answers |
Translation
Translate text between languages. Model determines the language pair.
Options
| Method | Description |
|---|---|
srcLang(string $lang) |
Source language code |
tgtLang(string $lang) |
Target language code |
maxNewTokens(int $n) |
Max new tokens to generate |
temperature(float $t) |
Sampling temperature |
doSample(bool $b) |
Enable sampling |
cleanUpTokenizationSpaces(bool $b) |
Clean up spaces |
truncation(TruncationStrategy $s) |
Truncation strategy |
Supports other generation parameters like topK, topP, etc.
Fill Mask
Predict masked tokens in text (like BERT's pre-training task).
Options
| Method | Description |
|---|---|
topK(int $k) |
Number of predictions to return |
targets(array $targets) |
Limit predictions to specific words |
Sentence Similarity
Compare a source sentence against multiple target sentences.
Text to Image
Generate images from text prompts.
Options
| Method | Description |
|---|---|
numInferenceSteps(int $steps) |
Number of denoising steps |
guidanceScale(float $scale) |
How closely to follow the prompt |
width(int $px) |
Output image width |
height(int $px) |
Output image height |
size(int $w, int $h) |
Set both width and height |
seed(int $seed) |
Random seed for reproducibility |
negativePrompt(string $prompt) |
What to avoid in the image |
Image Classification
Classify images into categories.
Options
| Method | Description |
|---|---|
topK(int $k) |
Number of predictions to return |
functionToApply(ClassificationOutputTransform $f) |
Function to apply to scores (Sigmoid, Softmax, None) |
Object Detection
Detect objects in an image with bounding boxes.
Options
| Method | Description |
|---|---|
threshold(float $threshold) |
Probability threshold to make a prediction |
Image to Text
Generate captions for images.
Options
| Method | Description |
|---|---|
maxNewTokens(int $n) |
Max new tokens to generate |
temperature(float $t) |
Sampling temperature |
doSample(bool $b) |
Enable sampling |
topK(int $k) |
Top-k sampling |
topP(float $p) |
Nucleus sampling |
minNewTokens(int $n) |
Min new tokens to generate |
numBeams(int $n) |
Number of beams for beam search |
Supports other standard generation parameters: earlyStopping, numBeamGroups, penaltyAlpha, useCache, etaCutoff, epsilonCutoff, typicalP
Text to Speech
Convert text to audio.
Options
| Method | Description |
|---|---|
maxNewTokens(int $n) |
Max new tokens to generate |
temperature(float $t) |
Sampling temperature |
doSample(bool $b) |
Enable sampling |
topK(int $k) |
Top-k sampling |
topP(float $p) |
Nucleus sampling |
minNewTokens(int $n) |
Min new tokens to generate |
numBeams(int $n) |
Number of beams for beam search |
Supports other standard generation parameters: earlyStopping, numBeamGroups, penaltyAlpha, useCache, etaCutoff, epsilonCutoff, typicalP
Automatic Speech Recognition
Transcribe audio to text.
Zero-Shot Classification
Classify text into arbitrary categories without training.
Options
| Method | Description |
|---|---|
multiLabel(bool $enable) |
Allow multiple labels to be true |
hypothesisTemplate(string $template) |
Custom hypothesis template |
Caching
The library uses a unified repository-based cache system with blob deduplication. This means:
- Files are stored once by their content hash (blob storage)
- Multiple snapshots share the same blob files via symlinks
- Files are only re-downloaded when they change on the server
- Repeated downloads are instant
- Zero-latency file checks using local manifests
- Your internet connection isn't required for cached files
Cache Structure
Cache Management
You can inspect and manage the cache programmatically:
Default Cache Location
The cache is stored in a platform-appropriate location:
- Linux:
~/.cache/huggingface/hubor$XDG_CACHE_HOME/huggingface/hub - macOS:
~/Library/Caches/huggingface/hub - Windows:
%LOCALAPPDATA%\huggingface\hub
You can override with the HF_HUB_CACHE or HF_HOME environment variables.
Custom Cache Directory
Downloading to Cache
Disabling Cache
Force Re-download
Error Handling
The library uses specific exception types for different error conditions:
Automatic Retries
The library automatically retries on transient failures:
- Server errors (5xx): Retried with exponential backoff
- Rate limits (429): Retried after the
Retry-Afterdelay - Network failures: Retried up to 3 times
This happens transparently so you don't need to implement retry logic yourself.
Examples
The examples/ directory contains ready-to-run scripts:
| Directory | Description |
|---|---|
examples/hub/ |
Hub operations (search, download, upload) |
examples/inference/ |
Inference API examples for all tasks |
Run any example:
API Reference
See the API Reference for complete documentation of all classes and methods.
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
License
MIT License. See LICENSE for details.
All versions of huggingface with dependencies
ext-curl Version *
psr/http-client Version ^1.0
psr/http-factory Version ^1.1
php-http/discovery Version ^1.20