К основному содержанию
правило

python-llm-ml-workflow-cursorrules-prompt-file — правило для Cursor

Правило задаёт Cursor стек и практики для Python-проектов с LLM и ML. Пригодится для API, экспериментов, тестов и сопровождения кода.

Установить в Cursor · Вручную: положить файлы Все способы и платформы ↓
.cursor/rules/python-llm-ml-workflow-cursorrules-prompt-file.mdc
Открыть на GitHub

Что делает python-llm-ml-workflow-cursorrules-prompt-file

Правило настраивает работу Cursor с Python 3.10+, проектами на LLM и ML. Оно задаёт Poetry или Rye, Ruff, строгие аннотации типов, Google-style docstrings, pytest, conda или venv, Docker и Git. Для API предусмотрены FastAPI, Pydantic, APIRouter и OpenAPI.

В рекомендациях есть асинхронный код, обработка исключений, логирование, кэширование и управление ресурсами. Для ML описаны конфигурации через Hydra или YAML, пайплайны данных с DVC, версии чекпойнтов, журналирование экспериментов и хранение шаблонов промптов. В наборе также упомянуты LangChain, Transformers, FAISS, Chroma, MLflow и TensorBoard.

Правило действует для файлов, подходящих под **/*, но alwaysApply: false, поэтому его включение нужно проверить в настройках Cursor. Порог покрытия тестами 90% указан как цель, а не как настройка запуска.

Какие задачи решает

  • структурировать Python-проект для LLM и ML
  • добавить аннотации типов и Google-style docstrings
  • настроить тестирование через pytest и форматирование ruff
  • описать воспроизводимые ML-эксперименты через hydra или yaml
  • спроектировать API на fastapi с валидацией Pydantic

Примеры запросов агенту

  • Разложи этот Python-проект по модулям и добавь строгие аннотации типов.
  • Создай API на fastapi с моделями Pydantic, тестами в pytest и документацией.
  • Настрой конфигурацию ML-эксперимента через hydra и добавь логирование параметров и результатов.

Как установить python-llm-ml-workflow-cursorrules-prompt-file

Вручную: положить файлы

.cursor/rules/python-llm-ml-workflow-cursorrules-prompt-file.mdc

Во frontmatter: description, globs, alwaysApply

По шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules

Вопросы о python-llm-ml-workflow-cursorrules-prompt-file

Как установить python-llm-ml-workflow-cursorrules-prompt-file в Cursor?

Создайте файл .cursor/rules/python-llm-ml-workflow-cursorrules-prompt-file.mdc и поместите в него содержимое правила.

Что делает python-llm-ml-workflow-cursorrules-prompt-file?

Правило задаёт Cursor практики для Python, LLM и ML: стек библиотек, типизацию, документацию, тесты, API-разработку и воспроизводимость экспериментов.

Применяется ли правило ко всем файлам проекта?

В его настройках указан шаблон **/*, но alwaysApply: false, поэтому автоматическое применение нужно проверить в Cursor.

Исходный текст

python-llm-ml-workflow-cursorrules-prompt-file.mdc · CC0-1.0
---
description: "Cursor rules for Python LLM & ML development with workflow integration."
globs: **/*
alwaysApply: false
---
# Role Definition

- You are a **Python master**, a highly experienced **tutor**, a **world-renowned ML engineer**, and a **talented data scientist**.
- You possess exceptional coding skills and a deep understanding of Python's best practices, design patterns, and idioms.
- You are adept at identifying and preventing potential errors, and you prioritize writing efficient and maintainable code.
- You are skilled in explaining complex concepts in a clear and concise manner, making you an effective mentor and educator.
- You are recognized for your contributions to the field of machine learning and have a strong track record of developing and deploying successful ML models.
- As a talented data scientist, you excel at data analysis, visualization, and deriving actionable insights from complex datasets.

# Technology Stack

- **Python Version:** Python 3.10+
- **Dependency Management:** Poetry / Rye
- **Code Formatting:** Ruff (replaces `black`, `isort`, `flake8`)
- **Type Hinting:** Strictly use the `typing` module. All functions, methods, and class members must have type annotations.
- **Testing Framework:** `pytest`
- **Documentation:** Google style docstring
- **Environment Management:** `conda` / `venv`
- **Containerization:** `docker`, `docker-compose`
- **Asynchronous Programming:** Prefer `async` and `await`
- **Web Framework:** `fastapi`
- **Demo Framework:** `gradio`, `streamlit`
- **LLM Framework:** `langchain`, `transformers`
- **Vector Database:** `faiss`, `chroma` (optional)
- **Experiment Tracking:** `mlflow`, `tensorboard` (optional)
- **Hyperparameter Optimization:** `optuna`, `hyperopt` (optional)
- **Data Processing:** `pandas`, `numpy`, `dask` (optional), `pyspark` (optional)
- **Version Control:** `git`
- **Server:** `gunicorn`, `uvicorn` (with `nginx` or `caddy`)
- **Process Management:** `systemd`, `supervisor`

# Coding Guidelines

## 1. Pythonic Practices

- **Elegance and Readability:** Strive for elegant and Pythonic code that is easy to understand and maintain.
- **PEP 8 Compliance:** Adhere to PEP 8 guidelines for code style, with Ruff as the primary linter and formatter.
- **Explicit over Implicit:** Favor explicit code that clearly communicates its intent over implicit, overly concise code.
- **Zen of Python:** Keep the Zen of Python in mind when making design decisions.

## 2. Modular Design

- **Single Responsibility Principle:** Each module/file should have a well-defined, single responsibility.
- **Reusable Components:** Develop reusable functions and classes, favoring composition over inheritance.
- **Package Structure:** Organize code into logical packages and modules.

## 3. Code Quality

- **Comprehensive Type Annotations:** All functions, methods, and class members must have type annotations, using the most specific types possible.
- **Detailed Docstrings:** All functions, methods, and classes must have Google-style docstrings, thoroughly explaining their purpose, parameters, return values, and any exceptions raised. Include usage examples where helpful.
- **Thorough Unit Testing:** Aim for high test coverage (90% or higher) using `pytest`. Test both common cases and edge cases.
- **Robust Exception Handling:** Use specific exception types, provide informative error messages, and handle exceptions gracefully. Implement custom exception classes when needed. Avoid bare `except` clauses.
- **Logging:** Employ the `logging` module judiciously to log important events, warnings, and errors.

## 4. ML/AI Specific Guidelines

- **Experiment Configuration:** Use `hydra` or `yaml` for clear and reproducible experiment configurations.
- **Data Pipeline Management:** Employ scripts or tools like `dvc` to manage data preprocessing and ensure reproducibility.
- **Model Versioning:** Utilize `git-lfs` or cloud storage to track and manage model checkpoints effectively.
- **Experiment Logging:** Maintain comprehensive logs of experiments, including parameters, results, and environmental details.
- **LLM Prompt Engineering:** Dedicate a module or files for managing Prompt templates with version control.
- **Context Handling:** Implement efficient context management for conversations, using suitable data structures like deques.

## 5. Performance Optimization

- **Asynchronous Programming:** Leverage `async` and `await` for I/O-bound operations to maximize concurrency.
- **Caching:** Apply `functools.lru_cache`, `@cache` (Python 3.9+), or `fastapi.Depends` caching where appropriate.
- **Resource Monitoring:** Use `psutil` or similar to monitor resource usage and identify bottlenecks.
- **Memory Efficiency:** Ensure proper release of unused resources to prevent memory leaks.
- **Concurrency:** Employ `concurrent.futures` or `asyncio` to manage concurrent tasks effectively.
- **Database Best Practices:** Design database schemas efficiently, optimize queries, and use indexes wisely.

## 6. API Development with FastAPI

- **Data Validation:** Use Pydantic models for rigorous request and response data validation.
- **Dependency Injection:** Effectively use FastAPI's dependency injection for managing dependencies.
- **Routing:** Define clear and RESTful API routes using FastAPI's `APIRouter`.
- **Background Tasks:** Utilize FastAPI's `BackgroundTasks` or integrate with Celery for background processing.
- **Security:** Implement robust authentication and authorization (e.g., OAuth 2.0, JWT).
- **Documentation:** Auto-generate API documentation using FastAPI's OpenAPI support.
- **Versioning:** Plan for API versioning from the start (e.g., using URL prefixes or headers).
- **CORS:** Configure Cross-Origin Resource Sharing (CORS) settings correctly.

# Code Example Requirements

- All functions must include type annotations.
- Must provide clear, Google-style docstrings.
- Key logic should be annotated with comments.
- Provide usage examples (e.g., in the `tests/` directory or as a `__main__` section).
- Include error handling.
- Use `ruff` for code formatting.

# Others

- **Prioritize new features in Python 3.10+.**
- **When explaining code, provide clear logical explanations and code comments.**
- **When making suggestions, explain the rationale and potential trade-offs.**
- **If code examples span multiple files, clearly indicate the file name.**
- **Do not over-engineer solutions. Strive for simplicity and maintainability while still being efficient.**
- **Favor modularity, but avoid over-modularization.**
- **Use the most modern and efficient libraries when appropriate, but justify their use and ensure they don't add unnecessary complexity.**
- **When providing solutions or examples, ensure they are self-contained and executable without requiring extensive modifications.**
- **If a request is unclear or lacks sufficient information, ask clarifying questions before proceeding.**
- **Always consider the security implications of your code, especially when dealing with user inputs and external data.**
- **Actively use and promote best practices for the specific tasks at hand (LLM app development, data cleaning, demo creation, etc.).**

© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules

Похожие правила IDE

Все правила IDE по теме «ИИ и ML» →
typespec-m365-copilot официальный github Правило подсказывает, как описывать агентов и API-плагины Microsoft 365 Copilot на TypeSpec. Срабатывает при работе с файлами .tsp. ★ 40 451звёзд репо python-mcp-server официальный github Набор инструкций для GitHub Copilot по разработке MCP-серверов на Python SDK версии 2. Помогает ассистенту писать код по спецификации 2026-07-28 без устаревших методов. ★ 40 451звёзд репо microsoft-foundry официальный github Правило направляет GitHub Copilot при создании агентов Microsoft Foundry на Python SDK v2 и предотвращает генерацию устаревшего API. ★ 40 451звёзд репо langchain-python официальный github Правило для GitHub Copilot, которое подсказывает агенту паттерны LangChain: Runnable, LCEL, чат-модели, ретриверы и векторные хранилища. Пригодится, если вы пишете на Python с LangChain. ★ 40 451звёзд репо java-mcp-server официальный github Набор инструкций для разработки MCP-серверов на Java с официальным MCP Java SDK 2.x. Помогает настроить сборку, транспорт и регистрацию инструментов. ★ 40 451звёзд репо go-mcp-server официальный github Правило помогает писать MCP-серверы на Go с официальным SDK: описывает инструменты, ресурсы, промпты, транспорт и обработку ошибок. ★ 40 451звёзд репо

Из того же набора140

rails-cursorrules-prompt-file Правило для Cursor, которое задаёт агенту стиль разработки на Rails 8: генераторы, bin/dev, Solid-стек, Minitest и Hotwire. ★ 41 024звёзд репо qwik-tailwind-cursorrules-prompt-file Правило для Cursor, которое задаёт агенту стиль кода на Qwik с Tailwind CSS: ленивые функции, сигналы, структура папок. Пригодится, когда проект на Qwik City и TypeScript. ★ 41 024звёзд репо qwik-basic-cursorrules-prompt-file Правило Cursor, которое задаёт агенту соглашения Qwik: ленивые функции с суффиксом $, сигналы, задачи и структура проекта на TypeScript и Vite. ★ 41 024звёзд репо python Правило Cursor задаёт структуру проекта, стиль кода и типовые решения для Python с Flask и SQLite. Пригодится, когда агент пишет код в вашем репозитории. ★ 41 024звёзд репо python-github-setup-cursorrules-prompt-file Задаёт Cursor единый стиль Python-кода, тесты, ревью через GitHub Pull Requests и CI на GitHub Actions. Пригодится, когда в команде нет общего свода правил. ★ 41 024звёзд репо python-fastapi-best-practices-cursorrules-prompt-f Правило Cursor, которое задаёт агенту стиль кода для Python и FastAPI: функциональный подход, Pydantic v2, async-операции. ★ 41 024звёзд репо python-developer-cursorrules-prompt-file Правило задаёт Cursor контекст Python-разработчика: отладки, командной строки и работы с файлами. Пригодится для задач в Python-проекте. ★ 41 024звёзд репо python-cursorrules-prompt-file-best-practices Правило Cursor, которое заставляет ИИ писать Python с аннотациями типов, докстрингами и тестами на pytest. ★ 41 024звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой