

Also from Kynth Studios


Also from Kynth Studios


Also from Kynth Studios
1# CLAUDE.md23This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.45# Instructor Development Guide67## Commands8- Install deps: `uv pip install -e ".[dev,anthropic]"` or `poetry install --with dev,anthropic`9- Run tests: `uv run pytest tests/ -n auto`10- Run specific test: `uv run pytest tests/path_to_test.py::test_name`11- Skip LLM tests: `uv run pytest tests/ -k 'not llm and not openai'`12- Type check: `uv run ty check`13- Lint: `uv run ruff check instructor examples tests`14- Format: `uv run ruff format instructor examples tests`15- Generate coverage: `uv run coverage run -m pytest tests/ -k "not docs"` then `uv run coverage report`16- Build documentation: `uv run mkdocs serve` (for local preview) or `./build_mkdocs.sh` (for production)17- Waiting: use `sleep <seconds>` for explicit pauses (e.g., CI waits) or to let external processes finish1819## Installation & Setup20- Fork the repository and clone your fork21- Install UV: `pip install uv`22- Create virtual environment: `uv venv`23- Install dependencies: `uv pip install -e ".[dev]"`24- Install pre-commit: `uv run pre-commit install`25- Run tests to verify: `uv run pytest tests/ -k "not openai"`2627## Code Style Guidelines28- **Typing**: Use strict typing with annotations for all functions and variables29- **Imports**: Standard lib → third-party → local imports30- **Formatting**: Follow Black's formatting conventions (enforced by Ruff)31- **Models**: Define structured outputs as Pydantic BaseModel subclasses32- **Naming**: snake_case for functions/variables, PascalCase for classes33- **Error Handling**: Use custom exceptions from exceptions.py, validate with Pydantic34- **Comments**: Docstrings for public functions, inline comments for complex logic3536## Conventional Commits37- **Format**: `type(scope): description`38- **Types**: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert39- **Examples**:40 - `feat(anthropic): add support for Claude 3.5`41 - `fix(openai): correct response parsing for streaming`42 - `docs(README): update installation instructions`43 - `test(gemini): add validation tests for JSON mode`4445## Core Architecture46- **Base Classes**: `Instructor` and `AsyncInstructor` in client.py are the foundation47- **Factory Pattern**: Provider-specific factory functions (`from_openai`, `from_anthropic`, etc.)48- **Unified Access**: `from_provider()` function in auto_client.py for automatic provider detection49- **Mode System**: `Mode` enum categorizes different provider capabilities (tools vs JSON output)50- **Patching Mechanism**: Uses Python's dynamic nature to patch provider clients for structured outputs51- **Response Processing**: Transforms raw API responses into validated Pydantic models52- **DSL Components**: Special types like Partial, Iterable, Maybe extend the core functionality5354## Provider Architecture55- **Supported Providers**: OpenAI, Anthropic, Gemini, Cohere, Mistral, Groq, VertexAI, Fireworks, Cerebras, Writer, Databricks, Anyscale, Together, LiteLLM, Bedrock, Perplexity56- **Provider Implementation**: Each provider has a dedicated client file (e.g., `client_anthropic.py`) with factory functions57- **Modes**: Different providers support specific modes (`Mode` enum): `ANTHROPIC_TOOLS`, `GEMINI_JSON`, etc.58- **Common Pattern**: Factory functions (e.g., `from_anthropic`) take a native client and return patched `Instructor` instances59- **Provider Testing**: Tests in `tests/llm/` directory, define Pydantic models, make API calls, verify structured outputs60- **Provider Detection**: `get_provider` function analyzes base URL to detect which provider is being used6162## Key Components63- **process_response.py**: Handles parsing and converting LLM outputs to Pydantic models64- **patch.py**: Contains the core patching logic for modifying provider clients65- **function_calls.py**: Handles generating function/tool schemas from Pydantic models66- **hooks.py**: Provides event hooks for intercepting various stages of the LLM request/response cycle67- **dsl/**: Domain-specific language extensions for specialized model types68- **retry.py**: Implements retry logic for handling validation failures69- **validators.py**: Custom validation mechanisms for structured outputs7071## Testing Guidelines72- Tests are organized by provider under `tests/llm/`73- Each provider has its own conftest.py with fixtures74- Standard tests cover: basic extraction, streaming, validation, retries75- Evaluation tests in `tests/llm/test_provider/evals/` assess model capabilities76- Use parametrized tests when testing similar functionality across variants77- **IMPORTANT**: No mocking in tests - tests make real API calls7879## Documentation Guidelines80- Every provider needs documentation in `docs/integrations/` following standard format81- Provider docs should include: installation, basic example, modes supported, special features82- When adding a new provider, update `mkdocs.yml` navigation and redirects83- Example code should include complete imports and environment setup84- Tutorials should progress from simple to complex concepts85- New features should include conceptual explanation in `docs/concepts/`86- **Writing Style**: Grade 10 reading level, all examples must be working code8788## Branch and Development Workflow891. Fork and clone the repository902. Create feature branch: `git checkout -b feat/your-feature`913. Make changes and add tests924. Run tests and linting935. Commit with conventional commit message946. Push to your fork and create PR957. Use stacked PRs for complex features9697## Adding New Providers9899### Step-by-Step Guide1001. **Update Provider Enum** in `instructor/utils.py`:101```python102 class Provider(Enum):103 YOUR_PROVIDER = "your_provider"104```1051062. **Add Provider Modes** in `instructor/mode.py`:107```python108 class Mode(enum.Enum):109 YOUR_PROVIDER_TOOLS = "your_provider_tools"110 YOUR_PROVIDER_JSON = "your_provider_json"111```1121133. **Create Client Implementation** `instructor/client_your_provider.py`:114 - Use overloads for sync/async variants115 - Validate mode compatibility116 - Return appropriate Instructor/AsyncInstructor instance117 - Handle provider-specific edge cases1181194. **Add Conditional Import** in `instructor/__init__.py`:120```python121 if importlib.util.find_spec("your_provider_sdk") is not None:122 from .client_your_provider import from_your_provider123 __all__ += ["from_your_provider"]124```1251265. **Update Auto Client** in `instructor/auto_client.py`:127 - Add to `supported_providers` list128 - Implement provider handling in `from_provider()`129 - Update `get_provider()` function if URL-detectable1301316. **Create Tests** in `tests/llm/test_your_provider/`:132 - `conftest.py` with client fixtures133 - Basic extraction tests134 - Streaming tests135 - Validation/retry tests136 - No mocking - use real API calls1371387. **Add Documentation** in `docs/integrations/your_provider.md`:139 - Installation instructions140 - Basic usage examples141 - Supported modes142 - Provider-specific features1431448. **Update Navigation** in `mkdocs.yml`:145 - Add to integrations section146 - Include redirects if needed147148## Contributing to Evals149- Standard evals for each provider test model capabilities150- Create new evals following existing patterns151- Run evals as part of integration test suite152- Performance tracking and comparison153154## Pull Request Guidelines155- Keep PRs small and focused156- Include tests for all changes157- Update documentation as needed158- Follow PR template159- Link to relevant issues160- **Update CHANGELOG.md**: Every PR that changes behavior (fix, feat, security, deprecation) must add an entry under the current `[Unreleased]` section in `CHANGELOG.md`. Format: `- **Area**: Description ([#PR](url))`161162## Type System and Best Practices163164### Type Checking with ty165- **Type Checker**: Using `ty` for fast, incremental type checking166- **Python Version**: 3.9+ for compatibility167- **Configuration**: Uses `pyproject.toml` settings for type checking168- Run `uv run ty check` before committing - aim for zero errors169170### Code Quality Checks Before Committing171Always run these checks before committing code:1721. **Ruff linting**: `uv run ruff check .` - Fix all errors1732. **Ruff formatting**: `uv run ruff format .` - Apply consistent formatting1743. **Type checking**: `uv run ty check` - Aim for zero type errors1754. **Tests**: Run relevant tests to ensure changes don't break functionality176177### Type Patterns178- **Bounded TypeVars**: Use `T = TypeVar("T", bound=Union[BaseModel, ...])` for constraints179- **Version Compatibility**: Handle Python 3.9 vs 3.10+ typing differences explicitly180- **Union Type Syntax**: Use `from __future__ import annotations` to enable Python 3.10+ union syntax (`|`) in Python 3.9181- **Simple Type Detection**: Special handling for `list[Union[int, str]]` patterns182- **Runtime Type Handling**: Graceful fallbacks for compatibility183184### Pydantic Integration185- Heavy use of `BaseModel` for structured outputs186- `TypeAdapter` used internally for JSON schema generation187- Field validators and custom types188- Models serve dual purpose: validation and documentation189190## Building Documentation191192### Setup193```bash194# Install documentation dependencies195pip install -r requirements-doc.txt196```197198### Local Development199```bash200# Serve documentation locally with hot reload201uv run mkdocs serve202203# Build documentation for production204./build_mkdocs.sh205```206207### Documentation Features208- **Material Theme**: Modern UI with extensive customization209- **Plugins**:210 - `mkdocstrings` - API documentation from docstrings211 - `mkdocs-jupyter` - Notebook integration212 - `mkdocs-redirects` - URL management213 - Custom hooks for code processing214- **Custom Processing**: `hide_lines.py` removes code marked with `# <%hide%>`215- **Redirect Management**: Comprehensive redirect maps for moved content216217### Writing Documentation218- Follow templates in `docs/templates/` for consistency219- Grade 10 reading level for accessibility220- All code examples must be runnable221- Include complete imports and environment setup222- Progressive complexity: simple → advanced223224## Project Structure225- `instructor/` - Core library code226 - Base classes (`client.py`): `Instructor` and `AsyncInstructor`227 - Provider clients (`client_*.py`): Factory functions for each provider228 - DSL components (`dsl/`): Partial, Iterable, Maybe, Citation extensions229 - Core logic: `patch.py`, `process_response.py`, `function_calls.py`230 - CLI tools (`cli/`): Batch processing, file management, usage tracking231- `tests/` - Test suite organized by provider232 - Provider-specific tests in `tests/llm/test_<provider>/`233 - Evaluation tests for model capabilities234 - No mocking - all tests use real API calls235- `docs/` - MkDocs documentation236 - `concepts/` - Core concepts and features237 - `integrations/` - Provider-specific guides238 - `examples/` - Practical examples and cookbooks239 - `learning/` - Progressive tutorial path240 - `blog/posts/` - Technical articles and announcements241 - `templates/` - Templates for new docs (provider, concept, cookbook)242- `examples/` - Runnable code examples243 - Feature demos: caching, streaming, validation, parallel processing244 - Use cases: classification, extraction, knowledge graphs245 - Provider examples: anthropic, openai, groq, mistral246 - Each example has `run.py` as the main entry point247- `typings/` - Type stubs for untyped dependencies248249## Documentation Structure250- **Getting Started Path**: Installation → First Extraction → Response Models → Structured Outputs251- **Learning Patterns**: Simple Objects → Lists → Nested Structures → Validation → Streaming252- **Example Organization**: Self-contained directories with runnable code demonstrating specific features253- **Blog Posts**: Technical deep-dives with code examples in `docs/blog/posts/`254255## Example Patterns256When creating examples:257- Use `run.py` as the main file name258- Include clear imports: stdlib → third-party → instructor259- Define Pydantic models with descriptive fields260- Show expected output in comments261- Handle errors appropriately262- Make examples self-contained and runnable263264## Dependency Management265266### Core Dependencies267- **Minimal core**: `openai`, `pydantic`, `docstring-parser`, `typer`, `rich`268- **Python requirement**: `<4.0,>=3.9`269- **Pydantic version**: `<3.0.0,>=2.8.0` (constrained for stability)270271### Optional Dependencies272Provider-specific packages as extras:273```bash274# Install with specific provider275pip install "instructor[anthropic]"276pip install "instructor[google-generativeai]"277pip install "instructor[groq]"278```279280### Development Dependencies281```bash282# Install all development dependencies283uv pip install -e ".[dev]"284```285Includes:286- ty287- `pytest` and `pytest-asyncio` - Testing288- `ruff` - Linting and formatting289- `coverage` - Test coverage290- `mkdocs` and plugins - Documentation291292### Version Constraints293- **Upper bounds on all dependencies** for stability294- **Provider SDK versions** pinned to tested versions295- **Test dependencies** include evaluation frameworks296297### Managing Dependencies298- Update `pyproject.toml` for new dependencies299- Test with multiple Python versions (3.9-3.12)300- Run full test suite after dependency updates301- Document any provider-specific version requirements302303The library enables structured LLM outputs using Pydantic models across multiple providers with type safety.304
One repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| 567-labs/instructor.cursor/rules/documentation-sync.mdc · 14k | Cursor rules | no sections | 36/100 | today | |
| 567-labs/instructor.cursor/rules/followups.mdc · 14k | Cursor rules | no sections | 4/100 | today | |
| 567-labs/instructor.cursor/rules/new-features-planning.mdc · 14k | Cursor rules | git | 51/100 | today | |
| 567-labs/instructor.cursor/rules/simple-language.mdc · 14k | Cursor rules | no sections | 16/100 | today |
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| dotCMS/corecore-web/CLAUDE.md · 949 | CLAUDE.md | teststylearchtesting-strategy+3 | 100/100 | 14 days ago | |
| tyrchen/geektime-bootcamp-aiw7/genslides/backend/CLAUDE.md · 230 | CLAUDE.md | testlint-formatstylearch+6 | 100/100 | 9 days ago | |
| Adit-Jain-srm/NightmareNetCLAUDE.md · 46 | CLAUDE.md | buildtestlint-formatstyle+6 | 100/100 | 14 days ago | |
| dotCMS/coreCLAUDE.md · 949 | CLAUDE.md | setupbuildteststyle+7 | 99/100 | today | |
| supabase/supabase.claude/CLAUDE.md · 108k | CLAUDE.md | testlint-formatstylearch+1 | 97/100 | 14 days ago | |
| dotCMS/corecore-web/libs/sdk/client/CLAUDE.md · 949 | CLAUDE.md | setupbuildtestlint-format+9 | 97/100 | 14 days ago | |
| dotCMS/corecore-web/libs/sdk/react/CLAUDE.md · 949 | CLAUDE.md | setupbuildtestlint-format+9 | 97/100 | 14 days ago | |
| modelcontextprotocol/serversCLAUDE.md · 90k | CLAUDE.md | setupbuildtestlint-format+6 | 97/100 | 14 days ago |
A badge carrying the measured quality of the strongest agent config file in this repository, out of 100. It reads from this index every time somebody loads your page, so it changes when the measurement changes and there is nothing to keep up to date. Free, no account, and the value is not something you or we can set by hand.
[](https://rulestack.kynth.studio/configs/567-labs-instructor-claude)Would rather not hotlink us? Every badge is also served in shields.io’s endpoint schema, so shields renders the image and your readers never talk to our domain:
Published by Toolproof, the masthead over this index and eight others. The method behind the number is at toolproof.kynth.studio/methodology, and the whole thing is readable as JSON with no key at /api.