# HuggingFace Python API Patterns

## Listing Models (Correct Usage)

```python
from huggingface_hub import HfApi
import json

api = HfApi()

# Basic listing — no 'direction' parameter exists
models = api.list_models(sort="downloads", limit=30)

# With expanded fields (otherwise many fields are None)
models = api.list_models(
    sort="downloads",
    limit=30,
    expand=["downloads", "likes", "pipeline_tag", "library_name", "tags"]
)

# Filter by task/pipeline
text_models = api.list_models(pipeline_tag="text-generation", sort="downloads", limit=20)

# Filter by library
transformer_models = api.list_models(filter="transformers", sort="downloads", limit=20)

# Search by name
results = api.list_models(search="llama", limit=10)

# Convert to JSON
model_list = []
for model in models:
    model_list.append({
        "id": model.id,
        "pipeline_tag": model.pipeline_tag,
        "downloads": model.downloads,
        "likes": model.likes,
        "tags": model.tags[:5] if model.tags else [],
        "library_name": model.library_name
    })
print(json.dumps(model_list, indent=2, ensure_ascii=False))
```

## Model Info (Single Model)

```python
model = api.model_info("meta-llama/Llama-2-7b-hf")
print(model.id, model.downloads, model.pipeline_tag)
```

## Available Sort Options
- `"downloads"` — most downloaded
- `"likes"` — most liked
- `"last_modified"` — recently updated
- `"trending_score"` — trending
- `"created_at"` — newest

## Parameter Notes
| Parameter | Type | Notes |
|-----------|------|-------|
| `sort` | str | One of sort options above |
| `limit` | int | Max results (None = all, can be very slow) |
| `expand` | list[str] | Fields to include: downloads, likes, pipeline_tag, library_name, tags, etc. |
| `filter` | str | Library/tag filter |
| `pipeline_tag` | str | Task filter: text-generation, image-classification, etc. |
| `search` | str | Substring search in model ID |
| `author` | str | Filter by org/user |

## Common Pipeline Tags
- `text-generation` — LLMs
- `text2text-generation` — Seq2seq models
- `text-classification` — Sentiment, etc.
- `token-classification` — NER, POS
- `question-answering` — QA models
- `fill-mask` — Masked LM (BERT-style)
- `feature-extraction` — Embeddings
- `image-classification` — Vision classifiers
- `object-detection` — YOLO, DETR
- `text-to-image` — Stable Diffusion, etc.
- `automatic-speech-recognition` — Whisper, etc.
- `text-to-speech` — TTS models
- `image-text-to-text` — Multimodal (LLaVA, etc.)
