python-skills
Shared Python best practices for LlamaFarm. Covers patterns, async, typing, testing, error handling, and security.
Best use case
python-skills is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Shared Python best practices for LlamaFarm. Covers patterns, async, typing, testing, error handling, and security.
Teams using python-skills should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/python-skills/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How python-skills Compares
| Feature / Agent | python-skills | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Shared Python best practices for LlamaFarm. Covers patterns, async, typing, testing, error handling, and security.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
SKILL.md Source
# Python Skills for LlamaFarm
Shared Python best practices and code review checklists for all Python components in the LlamaFarm monorepo.
## Applicable Components
| Component | Path | Python | Key Dependencies |
|-----------|------|--------|-----------------|
| Server | `server/` | 3.12+ | FastAPI, Celery, Pydantic, structlog |
| RAG | `rag/` | 3.11+ | LlamaIndex, ChromaDB, Celery |
| Universal Runtime | `runtimes/universal/` | 3.11+ | PyTorch, transformers, FastAPI |
| Config | `config/` | 3.11+ | Pydantic, JSONSchema |
| Common | `common/` | 3.10+ | HuggingFace Hub |
## Quick Reference
| Topic | File | Key Points |
|-------|------|------------|
| Patterns | [patterns.md](patterns.md) | Dataclasses, Pydantic, comprehensions, imports |
| Async | [async.md](async.md) | async/await, asyncio, concurrent execution |
| Typing | [typing.md](typing.md) | Type hints, generics, protocols, Pydantic |
| Testing | [testing.md](testing.md) | Pytest fixtures, mocking, async tests |
| Errors | [error-handling.md](error-handling.md) | Custom exceptions, logging, context managers |
| Security | [security.md](security.md) | Path traversal, injection, secrets, deserialization |
## Code Style
LlamaFarm uses `ruff` with shared configuration in `ruff.toml`:
```toml
line-length = 88
target-version = "py311"
select = ["E", "F", "I", "B", "UP", "SIM"]
```
Key rules:
- **E, F**: Core pyflakes and pycodestyle
- **I**: Import sorting (isort)
- **B**: Bugbear (common pitfalls)
- **UP**: Upgrade syntax to modern Python
- **SIM**: Simplify code patterns
## Architecture Patterns
### Settings with pydantic-settings
```python
from pydantic_settings import BaseSettings
class Settings(BaseSettings, env_file=".env"):
LOG_LEVEL: str = "INFO"
HOST: str = "0.0.0.0"
PORT: int = 14345
settings = Settings() # Singleton at module level
```
### Structured Logging with structlog
```python
from core.logging import FastAPIStructLogger # Server
from core.logging import RAGStructLogger # RAG
from core.logging import UniversalRuntimeLogger # Runtime
logger = FastAPIStructLogger(__name__)
logger.info("Operation completed", extra={"count": 10, "duration_ms": 150})
```
### Abstract Base Classes for Extensibility
```python
from abc import ABC, abstractmethod
class Component(ABC):
def __init__(self, name: str, config: dict[str, Any] | None = None):
self.name = name or self.__class__.__name__
self.config = config or {}
@abstractmethod
def process(self, documents: list[Document]) -> ProcessingResult:
pass
```
### Dataclasses for Internal Data
```python
from dataclasses import dataclass, field
@dataclass
class Document:
content: str
metadata: dict[str, Any] = field(default_factory=dict)
id: str = field(default_factory=lambda: str(uuid.uuid4()))
```
### Pydantic Models for API Boundaries
```python
from pydantic import BaseModel, Field, ConfigDict
class EmbeddingRequest(BaseModel):
model: str
input: str | list[str]
encoding_format: Literal["float", "base64"] | None = "float"
model_config = ConfigDict(str_strip_whitespace=True)
```
## Directory Structure
Each Python component follows this structure:
```
component/
├── pyproject.toml # UV-managed dependencies
├── core/ # Core functionality
│ ├── __init__.py
│ ├── settings.py # Pydantic Settings
│ └── logging.py # structlog setup
├── services/ # Business logic (server)
├── models/ # ML models (runtime)
├── tasks/ # Celery tasks (rag)
├── utils/ # Utility functions
└── tests/
├── conftest.py # Shared fixtures
└── test_*.py
```
## Review Checklist Summary
When reviewing Python code in LlamaFarm:
1. **Patterns** (Medium priority)
- Modern Python syntax (3.10+ type hints)
- Dataclass vs Pydantic used appropriately
- No mutable default arguments
2. **Async** (High priority)
- No blocking calls in async functions
- Proper asyncio.Lock usage
- Cancellation handled correctly
3. **Typing** (Medium priority)
- Complete return type hints
- Generic types parameterized
- Pydantic v2 patterns
4. **Testing** (Medium priority)
- Fixtures properly scoped
- Async tests use pytest-asyncio
- Mocks cleaned up
5. **Errors** (High priority)
- Custom exceptions with context
- Structured logging with extra dict
- Proper exception chaining
6. **Security** (Critical priority)
- Path traversal prevention
- Input sanitization
- Safe deserialization
See individual topic files for detailed checklists with grep patterns.Related Skills
typescript-skills
Shared TypeScript best practices for Designer and Electron subsystems.
server-skills
Server-specific best practices for FastAPI, Celery, and Pydantic. Extends python-skills with framework-specific patterns.
runtime-skills
Universal Runtime best practices for PyTorch inference, Transformers models, and FastAPI serving. Covers device management, model loading, memory optimization, and performance tuning.
react-skills
React 18 patterns for LlamaFarm Designer. Covers components, hooks, TanStack Query, and testing.
rag-skills
RAG-specific best practices for LlamaIndex, ChromaDB, and Celery workers. Covers ingestion, retrieval, embeddings, and performance.
go-skills
Shared Go best practices for LlamaFarm CLI. Covers idiomatic patterns, error handling, and testing.
generate-subsystem-skills
Generate specialized skills for each subsystem in the monorepo. Creates shared language skills and subsystem-specific checklists for high-quality AI code generation.
config-skills
Configuration module patterns for LlamaFarm. Covers Pydantic v2 models, JSONSchema generation, YAML processing, and validation.
common-skills
Best practices for the Common utilities package in LlamaFarm. Covers HuggingFace Hub integration, GGUF model management, and shared utilities.
cli-skills
CLI best practices for LlamaFarm. Covers Cobra, Bubbletea, Lipgloss patterns for Go CLI development.
electron-skills
Electron patterns for LlamaFarm Desktop. Covers main/renderer processes, IPC, security, and packaging.
designer-skills
Designer subsystem patterns for LlamaFarm. Covers React 18, TanStack Query, TailwindCSS, and Radix UI.