mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Add comprehensive MDC files for various technologies and frameworks
Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including: - AI/ML libraries (PyTorch, TensorFlow, scikit-learn) - Backend frameworks (Django, FastAPI, Express, Spring Boot) - Frontend frameworks (React, Vue, Angular) - Cloud platforms (AWS, Azure, GCP) - Development tools (Docker, Kubernetes, Terraform) - State management libraries - UI component libraries - Web technologies and APIs Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
@@ -0,0 +1,342 @@
|
||||
---
|
||||
description: This rule provides guidelines for best practices when working with the Hugging Face Transformers library, covering code organization, performance, testing, security, and common pitfalls. It emphasizes community standards and maintainability.
|
||||
globs: **/*.py
|
||||
---
|
||||
# Hugging Face Transformers Library Best Practices
|
||||
|
||||
This document outlines best practices and coding standards for using the Hugging Face Transformers library. It covers various aspects, including code organization, performance, testing, security, and common pitfalls.
|
||||
|
||||
## Philosophy: Embrace the Single Model File Policy
|
||||
|
||||
- **Single Model File Policy:** Prioritize having all the code for a model's forward pass within a single file. While it might seem to contradict the DRY (Don't Repeat Yourself) principle, this improves readability and accessibility, especially for newcomers. This makes it easier to understand the entire model architecture without navigating through multiple files.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure
|
||||
|
||||
While the Transformers library promotes the single model file policy, good project-level organization is still crucial. A typical project structure might look like this:
|
||||
|
||||
|
||||
my_project/
|
||||
├── data/
|
||||
│ ├── raw/
|
||||
│ ├── processed/
|
||||
│ └── ...
|
||||
├── models/
|
||||
│ ├── modeling_bert.py # Example: BERT model definition
|
||||
│ ├── ...
|
||||
├── scripts/
|
||||
│ ├── train.py
|
||||
│ ├── evaluate.py
|
||||
│ ├── preprocess.py
|
||||
│ └── ...
|
||||
├── utils/
|
||||
│ ├── data_utils.py
|
||||
│ ├── model_utils.py
|
||||
│ └── ...
|
||||
├── tests/
|
||||
│ ├── test_models.py
|
||||
│ ├── test_data_utils.py
|
||||
│ └── ...
|
||||
├── notebooks/ # optional
|
||||
│ ├── exploration.ipynb
|
||||
│ └── ...
|
||||
├── requirements.txt
|
||||
├── pyproject.toml
|
||||
└── README.md
|
||||
|
||||
|
||||
- **`data/`:** Stores raw and processed datasets.
|
||||
- **`models/`:** Contains model definitions (adhering to the single model file policy).
|
||||
- **`scripts/`:** Holds training, evaluation, and preprocessing scripts.
|
||||
- **`utils/`:** Includes utility functions for data handling, model management, etc.
|
||||
- **`tests/`:** Contains unit, integration, and end-to-end tests.
|
||||
- **`notebooks/`:** (Optional) Jupyter notebooks for experimentation.
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
- Use descriptive and consistent file names.
|
||||
- For model files, follow the naming convention `modeling_<model_name>.py` (e.g., `modeling_bert.py`).
|
||||
- For utility files, use `*_utils.py` (e.g., `data_utils.py`).
|
||||
- Use lowercase letters and underscores for file names (snake_case).
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
- Keep modules focused and avoid creating overly large modules. Each module should have a clear responsibility.
|
||||
- Import necessary modules within functions or classes to improve readability and avoid unnecessary dependencies at the module level.
|
||||
- Use relative imports within the project structure (e.g., `from . import data_utils`) to avoid conflicts and improve portability.
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
- Design models as modular components. While adhering to the single model file policy, the internal structure of the model can be highly modular. Use classes to encapsulate different parts of the model (e.g., embedding layer, attention mechanism, feedforward network).
|
||||
- Each component should have a well-defined interface.
|
||||
- Leverage inheritance when appropriate to share common functionality between similar components.
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
- For extremely large models, consider splitting the model definition into multiple files, but maintain a clear entry point that encapsulates the entire model. A primary file should import and orchestrate the other components.
|
||||
- Consider splitting preprocessing and postprocessing logic into separate modules to improve readability and maintainability.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to Hugging Face
|
||||
|
||||
- **Configuration-Driven Design:** Use `PretrainedConfig` objects to define model parameters. This allows for easy configuration and sharing of model architectures.
|
||||
- **Tokenizers and Pipelines:** Leverage the built-in tokenizers and pipelines for efficient text processing. Understand how to customize them for specific tasks.
|
||||
- **Model Cards:** Create comprehensive model cards that document the model's architecture, training data, evaluation metrics, and intended use cases. This is crucial for reproducibility and transparency.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
- **Loading Pre-trained Models:** Use `AutoModel` and `AutoTokenizer` classes to automatically load the appropriate model and tokenizer based on the model name.
|
||||
|
||||
python
|
||||
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
||||
|
||||
model_name = "bert-base-uncased"
|
||||
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
||||
|
||||
|
||||
- **Fine-tuning Models:** Use the `Trainer` class for efficient fine-tuning. Customize the training loop when necessary for advanced control.
|
||||
|
||||
python
|
||||
from transformers import Trainer, TrainingArguments
|
||||
|
||||
training_args = TrainingArguments(
|
||||
output_dir="./results",
|
||||
evaluation_strategy="epoch",
|
||||
num_train_epochs=3
|
||||
)
|
||||
|
||||
trainer = Trainer(
|
||||
model=model,
|
||||
args=training_args,
|
||||
train_dataset=train_dataset,
|
||||
eval_dataset=eval_dataset
|
||||
)
|
||||
|
||||
trainer.train()
|
||||
|
||||
|
||||
- **Inference:** Use pipelines for simple inference tasks or write custom inference loops for more control.
|
||||
|
||||
python
|
||||
from transformers import pipeline
|
||||
|
||||
classifier = pipeline("sentiment-analysis")
|
||||
result = classifier("This is a great movie!")
|
||||
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
- **Ignoring `model_max_length`:** When initializing tokenizers and models, be mindful of the `model_max_length` parameter. Ensure that input sequences are properly truncated or padded to avoid errors or performance issues.
|
||||
- **Hardcoding Paths:** Avoid hardcoding file paths. Use relative paths or environment variables to make the code more portable.
|
||||
- **Lack of Documentation:** Write clear and concise documentation for all functions, classes, and modules. This is especially important given the single model file policy, as comprehensive inline documentation becomes critical.
|
||||
- **Over-Complicating Model Definitions:** Keep model definitions as simple as possible while still meeting the requirements. Avoid unnecessary complexity.
|
||||
- **Ignoring Warnings:** Pay attention to warnings raised by the Transformers library. They often indicate potential issues.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
- Avoid global variables. Encapsulate state within classes or functions.
|
||||
- Use immutable data structures when possible to prevent accidental modifications.
|
||||
- Manage model weights carefully. Load and save weights using the `state_dict` method.
|
||||
|
||||
python
|
||||
# Save model weights
|
||||
torch.save(model.state_dict(), "model.pth")
|
||||
|
||||
# Load model weights
|
||||
model.load_state_dict(torch.load("model.pth"))
|
||||
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
- Use `try...except` blocks to handle potential exceptions, such as file not found errors or invalid input data.
|
||||
- Provide informative error messages to help users understand the cause of the error.
|
||||
- Use logging to record errors and debug information.
|
||||
|
||||
python
|
||||
import logging
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
try:
|
||||
model = AutoModelForSequenceClassification.from_pretrained("invalid-model")
|
||||
except OSError as e:
|
||||
logging.error(f"Failed to load model: {e}")
|
||||
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
- **Mixed Precision Training:** Use mixed precision training (e.g., using `torch.cuda.amp` in PyTorch) to reduce memory usage and improve training speed.
|
||||
- **Gradient Accumulation:** Use gradient accumulation to simulate larger batch sizes when memory is limited.
|
||||
- **Quantization:** Quantize models to reduce their size and improve inference speed.
|
||||
- **ONNX Runtime:** Convert models to ONNX format and use the ONNX Runtime for faster inference.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
- Delete unused variables and tensors to free up memory.
|
||||
- Use `torch.no_grad()` during inference to disable gradient calculations and reduce memory usage.
|
||||
- Consider using techniques like gradient checkpointing to reduce memory usage during training, especially for very large models.
|
||||
|
||||
### 3.3 Rendering Optimization (If Applicable)
|
||||
|
||||
- If the application involves rendering model outputs (e.g., text generation), optimize the rendering process to minimize latency and improve user experience.
|
||||
- Use efficient text rendering libraries.
|
||||
- Cache rendered outputs when possible.
|
||||
|
||||
### 3.4 Bundle Size Optimization (If Applicable)
|
||||
|
||||
- If the application is deployed as a web application or mobile app, optimize the bundle size to reduce download times.
|
||||
- Use code splitting to load only the necessary code for each feature.
|
||||
- Use minification and compression to reduce the size of JavaScript and CSS files.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
- Load models and data lazily to reduce startup time and memory usage.
|
||||
- Use generators to process large datasets in chunks.
|
||||
- Only load the parts of the model that are needed for the current task.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
- **Prompt Injection:** Be aware of prompt injection attacks, where malicious users craft inputs that can manipulate the model's behavior. Implement input validation and sanitization techniques to mitigate this risk.
|
||||
- **Data Poisoning:** Protect against data poisoning attacks by carefully vetting training data sources.
|
||||
- **Model Stealing:** Implement measures to protect model weights from being stolen. Consider using encryption or access controls.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
- Validate all inputs to ensure that they are within the expected range and format.
|
||||
- Sanitize inputs to remove potentially harmful characters or code.
|
||||
- Use regular expressions to enforce input constraints.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
- Implement authentication to verify the identity of users.
|
||||
- Use authorization to control access to resources based on user roles.
|
||||
- Store credentials securely using encryption and hashing.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use access controls to restrict access to data.
|
||||
- Anonymize or pseudonymize data to protect user privacy.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
- Use HTTPS to encrypt communication between the client and the server.
|
||||
- Use API keys or tokens to authenticate requests.
|
||||
- Implement rate limiting to prevent abuse.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
- Write unit tests for all individual functions, classes, and modules.
|
||||
- Use a testing framework like `pytest` or `unittest`.
|
||||
- Test edge cases and boundary conditions.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
- Write integration tests to verify the interaction between different components of the system.
|
||||
- Test the flow of data through the system.
|
||||
- Use mocks and stubs to isolate components during testing.
|
||||
|
||||
### 5.3 End-to-end Testing
|
||||
|
||||
- Write end-to-end tests to verify the entire system from end to end.
|
||||
- Simulate user interactions to test the system's functionality.
|
||||
- Use a testing framework like `Selenium` or `Cypress` for web applications.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
- Organize tests into separate files or directories based on the component being tested.
|
||||
- Use descriptive names for test functions and classes.
|
||||
- Keep tests concise and focused.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
- Use mocks and stubs to isolate components during testing.
|
||||
- Mock external dependencies, such as API calls or database connections.
|
||||
- Use a mocking library like `unittest.mock` or `pytest-mock`.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
|
||||
- **Incorrect Tokenization:** Using the wrong tokenizer or not properly handling special tokens can lead to inaccurate results.
|
||||
- **Oversized Inputs:** Forgetting to truncate or pad input sequences to the model's maximum length can cause errors or performance issues.
|
||||
- **Incorrect Device Placement:** Running models on the CPU when a GPU is available can significantly slow down training and inference.
|
||||
- **Ignoring Data Preprocessing:** Failing to properly preprocess data (e.g., cleaning, normalizing) can negatively impact model performance.
|
||||
|
||||
### 6.2 Edge Cases to be Aware Of
|
||||
|
||||
- **Rare Words:** Handle rare or out-of-vocabulary words gracefully.
|
||||
- **Long Sequences:** Models may struggle with extremely long sequences.
|
||||
- **Adversarial Examples:** Models can be fooled by adversarial examples.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
- Be aware of breaking changes in new versions of the Transformers library.
|
||||
- Check the release notes for details on any changes that may affect your code.
|
||||
- Use version pinning in `requirements.txt` or `pyproject.toml` to ensure that your code runs with the correct version of the library.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
- Ensure that your code is compatible with the target hardware and software environment.
|
||||
- Test your code on different platforms and configurations.
|
||||
- Use conditional imports to handle different dependencies.
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
- Use logging to track the flow of execution and identify errors.
|
||||
- Use a debugger to step through the code and inspect variables.
|
||||
- Use print statements to output intermediate values.
|
||||
- Use a profiler to identify performance bottlenecks.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
- **IDE:** Visual Studio Code, PyCharm
|
||||
- **Version Control:** Git
|
||||
- **Package Manager:** pip, conda, uv
|
||||
- **Testing Framework:** pytest
|
||||
- **Linting:** pylint, flake8
|
||||
- **Formatting:** black, autopep8
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
- Use `requirements.txt` or `pyproject.toml` to manage dependencies.
|
||||
- Use a build system like `Make` or `Poetry` to automate the build process.
|
||||
- Create a virtual environment for each project to isolate dependencies.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
- Use a linter to enforce code style guidelines.
|
||||
- Use a formatter to automatically format code.
|
||||
- Configure the linter and formatter to run automatically on save.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
- Containerize your application using Docker.
|
||||
- Use a cloud platform like AWS, Azure, or GCP to deploy your application.
|
||||
- Use a deployment tool like Kubernetes to manage your application.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
- Use a CI/CD pipeline to automate the testing and deployment process.
|
||||
- Use a CI/CD tool like Jenkins, GitHub Actions, or GitLab CI.
|
||||
- Run tests automatically on every commit.
|
||||
- Deploy the application automatically when tests pass.
|
||||
|
||||
## Additional Recommendations
|
||||
|
||||
- **Utilize NVIDIA RTX GPUs:** Leverage RTX GPUs for enhanced performance due to their high-speed VRAM and dedicated AI accelerators. This is especially important for larger models and higher batch sizes.
|
||||
- **Token Management:** Understand how to manage tokens effectively to optimize performance, as performance is often measured in tokens per second.
|
||||
- **Batch API:** Consider using the OpenAI Batch API for cost efficiency and higher rate limits, especially when immediate responses are not required.
|
||||
|
||||
By following these best practices, you can write more maintainable, efficient, and secure code when working with the Hugging Face Transformers library.
|
||||
@@ -0,0 +1,310 @@
|
||||
---
|
||||
description: This rule provides best practices for developing LangChain applications, covering code organization, performance, security, testing, and common pitfalls. It aims to improve code quality, maintainability, and overall project success.
|
||||
globs: **/*.py
|
||||
---
|
||||
# LangChain Development Best Practices
|
||||
|
||||
This document outlines the best practices for developing LangChain applications to ensure code quality, maintainability, performance, security, and overall project success. These guidelines cover various aspects of development, from code organization to testing and deployment.
|
||||
|
||||
## 1. Code Organization and Structure
|
||||
|
||||
### 1.1 Directory Structure Best Practices
|
||||
|
||||
Adopt a clear and consistent directory structure to improve code discoverability and maintainability. A recommended structure is:
|
||||
|
||||
|
||||
project_root/
|
||||
├── data/ # Raw data, processed data, and datasets
|
||||
├── src/ # Source code directory
|
||||
│ ├── components/ # Reusable LangChain components (e.g., custom chains, tools)
|
||||
│ ├── chains/ # Definitions of LangChain chains
|
||||
│ ├── agents/ # Agent implementations
|
||||
│ ├── memory/ # Memory implementations
|
||||
│ ├── utils/ # Utility functions and modules
|
||||
│ ├── models/ # Custom model definitions or wrappers
|
||||
│ ├── callbacks/ # Custom callback handlers
|
||||
│ ├── vectorstores/ # Vectorstore configurations and connections
|
||||
│ ├── document_loaders/ # Custom document loaders
|
||||
│ ├── prompts/ # Prompt templates and management
|
||||
│ ├── config/ # Configuration files
|
||||
│ └── main.py # Entry point of the application
|
||||
├── tests/ # Unit and integration tests
|
||||
├── notebooks/ # Jupyter notebooks for experimentation and documentation
|
||||
├── docs/ # Project documentation
|
||||
├── requirements.txt # Project dependencies
|
||||
├── pyproject.toml # Project metadata and build configuration
|
||||
└── README.md # Project README file
|
||||
|
||||
|
||||
### 1.2 File Naming Conventions
|
||||
|
||||
Use descriptive and consistent file names:
|
||||
|
||||
- `module_name.py`: For general modules.
|
||||
- `component_name.py`: For LangChain components (e.g., `custom_chain.py`).
|
||||
- `test_module_name.py`: For test files.
|
||||
- Use lowercase and underscores for file names (snake_case).
|
||||
|
||||
### 1.3 Module Organization
|
||||
|
||||
Organize code into logical modules based on functionality. Each module should have a clear purpose and minimal dependencies.
|
||||
|
||||
- **Cohesion**: Modules should have high cohesion, meaning their elements are closely related.
|
||||
- **Coupling**: Modules should have low coupling, meaning they are independent of each other as much as possible.
|
||||
|
||||
### 1.4 Component Architecture
|
||||
|
||||
Design LangChain applications using a component-based architecture. Components should be reusable, testable, and well-defined.
|
||||
|
||||
- **Chains**: Define chains as reusable components that encapsulate specific workflows.
|
||||
- **Agents**: Implement agents as modular entities that interact with the environment using tools.
|
||||
- **Memory**: Manage conversation history and state using memory components.
|
||||
- **Tools**: Create tools as independent units that perform specific actions.
|
||||
- **Callbacks**: Utilize callbacks for logging, monitoring, and custom event handling.
|
||||
|
||||
### 1.5 Code Splitting Strategies
|
||||
|
||||
Split large files into smaller, manageable chunks to improve readability and maintainability.
|
||||
|
||||
- **Function-level splitting**: Break down large functions into smaller, single-purpose functions.
|
||||
- **Class-level splitting**: Divide large classes into smaller, more focused classes.
|
||||
- **Module-level splitting**: Separate modules based on functionality to reduce complexity.
|
||||
|
||||
## 2. Common Patterns and Anti-patterns
|
||||
|
||||
### 2.1 Design Patterns Specific to LangChain
|
||||
|
||||
- **Chain of Responsibility**: Implement chains of operations where each component handles a specific task, passing the result to the next component.
|
||||
- **Strategy Pattern**: Use strategy patterns to encapsulate different algorithms or behaviors within interchangeable strategy objects.
|
||||
- **Template Method**: Define the skeleton of an algorithm in a base class, allowing subclasses to override specific steps without changing the algorithm's structure.
|
||||
- **Factory Pattern**: Use factory patterns to create instances of LangChain components dynamically, based on configuration or runtime conditions.
|
||||
|
||||
### 2.2 Recommended Approaches for Common Tasks
|
||||
|
||||
- **Prompt Engineering**: Use prompt templates to manage and reuse prompts. Optimize prompts for clarity, context, and desired output.
|
||||
- **Data Loading**: Implement custom data loaders to handle various data sources and formats. Use text splitters to chunk large documents into smaller pieces for retrieval.
|
||||
- **Vector Storage**: Use vector stores to store and retrieve embeddings efficiently. Choose the appropriate vector store based on performance, scalability, and cost.
|
||||
- **Agent Design**: Design agents with clear objectives, tools, and decision-making logic. Use observation logs to track agent actions and outcomes.
|
||||
- **Memory Management**: Implement memory components to maintain conversation history and context. Use sliding window or summarization techniques to manage long conversations.
|
||||
|
||||
### 2.3 Anti-patterns and Code Smells to Avoid
|
||||
|
||||
- **God Classes**: Avoid creating large classes that handle too many responsibilities.
|
||||
- **Long Methods**: Avoid creating long methods that are difficult to understand and maintain.
|
||||
- **Duplicated Code**: Avoid duplicating code across multiple modules. Extract common code into reusable functions or components.
|
||||
- **Magic Numbers**: Avoid using magic numbers or hardcoded values. Define constants or configuration variables instead.
|
||||
- **Tight Coupling**: Avoid creating tight coupling between modules. Use interfaces and dependency injection to promote loose coupling.
|
||||
|
||||
### 2.4 State Management Best Practices
|
||||
|
||||
- **Stateless Components**: Design components to be stateless whenever possible. This improves testability and scalability.
|
||||
- **Centralized State**: Manage application state in a centralized location (e.g., a state management class or library).
|
||||
- **Immutable State**: Use immutable data structures to prevent unintended side effects and improve predictability.
|
||||
- **Explicit State Transitions**: Define explicit state transitions to make state changes clear and traceable.
|
||||
|
||||
### 2.5 Error Handling Patterns
|
||||
|
||||
- **Try-Except Blocks**: Use try-except blocks to handle exceptions and prevent application crashes.
|
||||
- **Logging**: Log errors and exceptions to facilitate debugging and monitoring.
|
||||
- **Custom Exceptions**: Define custom exceptions to represent specific error conditions.
|
||||
- **Retry Logic**: Implement retry logic for transient errors (e.g., network timeouts).
|
||||
- **Fallback Strategies**: Implement fallback strategies for critical operations to ensure application resilience.
|
||||
|
||||
## 3. Performance Considerations
|
||||
|
||||
### 3.1 Optimization Techniques
|
||||
|
||||
- **Caching**: Implement caching mechanisms to store frequently accessed data and results.
|
||||
- **Batch Processing**: Process data in batches to reduce overhead and improve throughput.
|
||||
- **Asynchronous Operations**: Use asynchronous operations to perform non-blocking I/O and improve responsiveness.
|
||||
- **Connection Pooling**: Use connection pooling to reuse database connections and reduce latency.
|
||||
- **Data Compression**: Compress data to reduce storage space and network bandwidth.
|
||||
- **Vectorstore Optimization**: Use efficient vectorstore implementations (e.g., FAISS, Annoy) and optimize indexing parameters for fast retrieval.
|
||||
|
||||
### 3.2 Memory Management
|
||||
|
||||
- **Object Pooling**: Use object pooling to reuse objects and reduce memory allocation overhead.
|
||||
- **Garbage Collection**: Monitor garbage collection performance and tune parameters to minimize pauses.
|
||||
- **Memory Profiling**: Use memory profiling tools to identify memory leaks and optimize memory usage.
|
||||
- **Lazy Loading**: Load data on demand to reduce initial memory footprint.
|
||||
- **Chunking Large Documents**: Process large documents in smaller chunks to avoid memory overflow.
|
||||
|
||||
### 3.3 Rendering Optimization (if applicable for UI components)
|
||||
|
||||
- **Virtualization**: Use virtualization techniques to render large lists efficiently.
|
||||
- **Debouncing and Throttling**: Use debouncing and throttling to reduce the frequency of UI updates.
|
||||
- **Memoization**: Use memoization to cache expensive rendering calculations.
|
||||
|
||||
### 3.4 Bundle Size Optimization (if applicable for web apps)
|
||||
|
||||
- **Code Splitting**: Split code into smaller chunks to reduce initial load time.
|
||||
- **Tree Shaking**: Use tree shaking to remove unused code from bundles.
|
||||
- **Minification and Compression**: Minify and compress code to reduce bundle size.
|
||||
- **Lazy Loading**: Load components and modules on demand.
|
||||
|
||||
### 3.5 Lazy Loading Strategies
|
||||
|
||||
- **On-Demand Loading**: Load data or components only when they are needed.
|
||||
- **Intersection Observer**: Use the Intersection Observer API to load components when they become visible in the viewport.
|
||||
- **Dynamic Imports**: Use dynamic imports to load modules asynchronously.
|
||||
|
||||
## 4. Security Best Practices
|
||||
|
||||
### 4.1 Common Vulnerabilities and How to Prevent Them
|
||||
|
||||
- **Prompt Injection**: Prevent prompt injection by validating and sanitizing user inputs. Use prompt templates and parameterized queries to avoid direct injection of malicious code.
|
||||
- **Data Exfiltration**: Prevent data exfiltration by restricting access to sensitive data and implementing data masking techniques.
|
||||
- **Code Execution**: Prevent arbitrary code execution by avoiding the use of `eval()` or similar functions. Use safe alternatives for dynamic code generation.
|
||||
- **Denial of Service (DoS)**: Prevent DoS attacks by implementing rate limiting, input validation, and resource quotas.
|
||||
|
||||
### 4.2 Input Validation
|
||||
|
||||
- **Whitelisting**: Validate inputs against a whitelist of allowed values or patterns.
|
||||
- **Sanitization**: Sanitize inputs to remove or escape potentially harmful characters or code.
|
||||
- **Type Checking**: Enforce type checking to ensure that inputs conform to expected data types.
|
||||
- **Length Limits**: Enforce length limits to prevent buffer overflows or excessive memory usage.
|
||||
|
||||
### 4.3 Authentication and Authorization Patterns
|
||||
|
||||
- **Authentication**: Use strong authentication mechanisms (e.g., multi-factor authentication) to verify user identities.
|
||||
- **Authorization**: Implement role-based access control (RBAC) to restrict access to resources based on user roles.
|
||||
- **Least Privilege**: Grant users the minimum necessary privileges to perform their tasks.
|
||||
- **Secure Storage**: Store sensitive credentials (e.g., API keys) securely using encryption or secret management tools.
|
||||
|
||||
### 4.4 Data Protection Strategies
|
||||
|
||||
- **Encryption**: Encrypt sensitive data at rest and in transit.
|
||||
- **Data Masking**: Mask sensitive data to protect it from unauthorized access.
|
||||
- **Data Anonymization**: Anonymize data to remove personally identifiable information (PII).
|
||||
- **Access Logging**: Log all data access events to track and monitor usage.
|
||||
- **Data Retention**: Define and enforce data retention policies to minimize the risk of data breaches.
|
||||
|
||||
### 4.5 Secure API Communication
|
||||
|
||||
- **HTTPS**: Use HTTPS to encrypt communication between clients and servers.
|
||||
- **API Keys**: Protect API keys and other sensitive credentials.
|
||||
- **Rate Limiting**: Implement rate limiting to prevent abuse and DoS attacks.
|
||||
- **Input Validation**: Validate all API inputs to prevent injection attacks.
|
||||
- **Output Encoding**: Encode API outputs to prevent cross-site scripting (XSS) attacks.
|
||||
|
||||
## 5. Testing Approaches
|
||||
|
||||
### 5.1 Unit Testing Strategies
|
||||
|
||||
- **Test-Driven Development (TDD)**: Write unit tests before writing the code to be tested.
|
||||
- **Mocking**: Use mocking to isolate components and test them independently.
|
||||
- **Assertion**: Use assertions to verify that the code behaves as expected.
|
||||
- **Coverage**: Aim for high code coverage to ensure that all code paths are tested.
|
||||
- **Parameterized Tests**: Use parameterized tests to test multiple scenarios with different inputs.
|
||||
|
||||
### 5.2 Integration Testing
|
||||
|
||||
- **Component Integration**: Test the integration between components to ensure that they work together correctly.
|
||||
- **API Integration**: Test the integration with external APIs to ensure that data is exchanged correctly.
|
||||
- **Database Integration**: Test the integration with databases to ensure that data is stored and retrieved correctly.
|
||||
- **End-to-End Flows**: Test end-to-end flows to ensure that the application works as a whole.
|
||||
|
||||
### 5.3 End-to-End Testing
|
||||
|
||||
- **UI Testing**: Test the user interface to ensure that it is functional and user-friendly.
|
||||
- **Functional Testing**: Test the functional requirements of the application to ensure that it meets the specifications.
|
||||
- **Performance Testing**: Test the performance of the application to ensure that it is responsive and scalable.
|
||||
- **Security Testing**: Test the security of the application to identify and mitigate vulnerabilities.
|
||||
- **Accessibility Testing**: Test the accessibility of the application to ensure that it is usable by people with disabilities.
|
||||
|
||||
### 5.4 Test Organization
|
||||
|
||||
- **Test Suites**: Organize tests into test suites based on functionality or component.
|
||||
- **Test Naming**: Use descriptive test names to make it clear what each test is testing.
|
||||
- **Test Data**: Use realistic test data to simulate real-world scenarios.
|
||||
- **Test Environment**: Set up a dedicated test environment to isolate tests from production data.
|
||||
|
||||
### 5.5 Mocking and Stubbing
|
||||
|
||||
- **Mocking**: Use mocking to replace external dependencies with controlled substitutes.
|
||||
- **Stubbing**: Use stubbing to provide predefined responses to external dependencies.
|
||||
- **Dependency Injection**: Use dependency injection to make it easier to mock and stub dependencies.
|
||||
- **Mocking Frameworks**: Use mocking frameworks (e.g., `unittest.mock`) to simplify the mocking process.
|
||||
|
||||
## 6. Common Pitfalls and Gotchas
|
||||
|
||||
### 6.1 Frequent Mistakes Developers Make
|
||||
|
||||
- **Hardcoding API Keys**: Storing API keys directly in the code instead of using environment variables.
|
||||
- **Ignoring Rate Limits**: Failing to handle API rate limits, leading to errors and service disruptions.
|
||||
- **Lack of Input Validation**: Not validating user inputs, making the application vulnerable to prompt injection attacks.
|
||||
- **Insufficient Error Handling**: Not handling errors properly, leading to application crashes and data loss.
|
||||
- **Over-Reliance on Default Settings**: Using default settings without considering their impact on performance and security.
|
||||
|
||||
### 6.2 Edge Cases to Be Aware Of
|
||||
|
||||
- **Empty Inputs**: Handling empty inputs gracefully to prevent errors.
|
||||
- **Long Inputs**: Handling long inputs efficiently to avoid performance issues.
|
||||
- **Special Characters**: Handling special characters correctly to prevent injection attacks.
|
||||
- **Unicode Support**: Ensuring proper Unicode support to handle different languages and character sets.
|
||||
- **Network Errors**: Handling network errors gracefully to ensure application resilience.
|
||||
|
||||
### 6.3 Version-Specific Issues
|
||||
|
||||
- **API Changes**: Being aware of API changes in different LangChain versions and updating code accordingly.
|
||||
- **Compatibility**: Ensuring compatibility between different LangChain components and versions.
|
||||
- **Deprecated Features**: Avoiding the use of deprecated features and migrating to their replacements.
|
||||
|
||||
### 6.4 Compatibility Concerns
|
||||
|
||||
- **Python Versions**: Ensuring compatibility with different Python versions.
|
||||
- **Operating Systems**: Ensuring compatibility with different operating systems (e.g., Windows, macOS, Linux).
|
||||
- **Dependency Conflicts**: Resolving dependency conflicts between different libraries.
|
||||
|
||||
### 6.5 Debugging Strategies
|
||||
|
||||
- **Logging**: Use logging to track the execution flow and identify errors.
|
||||
- **Debugging Tools**: Use debugging tools (e.g., `pdb`) to step through code and inspect variables.
|
||||
- **Print Statements**: Use print statements strategically to output debugging information.
|
||||
- **Error Messages**: Pay attention to error messages and stack traces to understand the root cause of errors.
|
||||
- **Remote Debugging**: Use remote debugging to debug applications running on remote servers.
|
||||
|
||||
## 7. Tooling and Environment
|
||||
|
||||
### 7.1 Recommended Development Tools
|
||||
|
||||
- **IDE**: Use a powerful IDE (e.g., VS Code, PyCharm) with support for Python and LangChain.
|
||||
- **Linters**: Use linters (e.g., `flake8`, `pylint`) to enforce code style and identify potential errors.
|
||||
- **Formatters**: Use formatters (e.g., `black`, `autopep8`) to automatically format code according to PEP 8 standards.
|
||||
- **Debuggers**: Use debuggers (e.g., `pdb`, `ipdb`) to step through code and inspect variables.
|
||||
- **Version Control**: Use Git for version control and collaboration.
|
||||
|
||||
### 7.2 Build Configuration
|
||||
|
||||
- **`pyproject.toml`**: Use `pyproject.toml` file to manage project metadata, dependencies, and build configuration.
|
||||
- **`requirements.txt`**: Generate and update the `requirements.txt` file to specify project dependencies.
|
||||
- **Virtual Environments**: Use virtual environments (`venv`, `conda`) to isolate project dependencies.
|
||||
|
||||
### 7.3 Linting and Formatting
|
||||
|
||||
- **Linting**: Configure linters to enforce code style and identify potential errors automatically.
|
||||
- **Formatting**: Configure formatters to automatically format code according to PEP 8 standards.
|
||||
- **Pre-commit Hooks**: Use pre-commit hooks to run linters and formatters before committing code.
|
||||
|
||||
### 7.4 Deployment Best Practices
|
||||
|
||||
- **Containerization**: Use containerization (e.g., Docker) to package the application and its dependencies.
|
||||
- **Orchestration**: Use orchestration tools (e.g., Kubernetes) to manage and scale the application.
|
||||
- **Infrastructure as Code (IaC)**: Use IaC tools (e.g., Terraform, CloudFormation) to provision and manage infrastructure.
|
||||
- **Monitoring**: Implement monitoring and logging to track application performance and identify issues.
|
||||
- **Continuous Deployment**: Implement continuous deployment to automate the deployment process.
|
||||
|
||||
### 7.5 CI/CD Integration
|
||||
|
||||
- **Continuous Integration (CI)**: Use CI tools (e.g., GitHub Actions, GitLab CI, Jenkins) to automatically build, test, and analyze code.
|
||||
- **Continuous Delivery (CD)**: Use CD tools to automatically deploy code to staging or production environments.
|
||||
- **Automated Testing**: Integrate automated testing into the CI/CD pipeline to ensure code quality.
|
||||
- **Rollback Strategies**: Implement rollback strategies to quickly revert to previous versions in case of deployment failures.
|
||||
|
||||
By following these best practices, developers can build robust, scalable, and maintainable LangChain applications that meet the needs of their users and stakeholders.
|
||||
|
||||
This comprehensive guide is designed to help developers create high-quality LangChain applications by adhering to industry-standard coding practices and principles.
|
||||
|
||||
|
||||
@file best_practices_python.mdc
|
||||
@file best_practices_langchain_specific.mdc
|
||||
@@ -0,0 +1,140 @@
|
||||
---
|
||||
description: This rule outlines the best practices and coding standards for developing with the vllm library, ensuring code quality, performance, and maintainability. It covers code organization, performance considerations, security, testing, and common pitfalls.
|
||||
globs: **/*.py
|
||||
---
|
||||
- ## General
|
||||
- Adhere to the Google Python Style Guide: vllm projects should strictly follow the Google Python Style Guide for consistency and readability.
|
||||
- Adhere to the Google C++ Style Guide (where applicable, especially for backend components).
|
||||
- Pass all linter checks: Ensure code passes all configured linter checks (e.g., pylint, flake8) before committing.
|
||||
- Always use UV when installing dependencies.
|
||||
- Always use Python 3.12 or higher.
|
||||
- Prefer classes over bare functions for better code organization and state management (where appropriate).
|
||||
|
||||
- ## Code Organization and Structure:
|
||||
- **Directory Structure Best Practices:**
|
||||
- `vllm/` (Root directory):
|
||||
- `api/`: Contains API endpoints and related logic.
|
||||
- `core/`: Core functionalities and algorithms.
|
||||
- `layers/`: Custom layers for the models.
|
||||
- `models/`: Model definitions and configurations.
|
||||
- `sampling/`: Sampling algorithms.
|
||||
- `sequence/`: Sequence management and data structures.
|
||||
- `utils/`: Utility functions and helper modules.
|
||||
- `tests/`: Unit and integration tests.
|
||||
- `examples/`: Example usage and demonstrations.
|
||||
- `docs/`: Documentation.
|
||||
- Maintain clear separation of concerns.
|
||||
- **File Naming Conventions:**
|
||||
- Use descriptive and meaningful names for files and modules (e.g., `attention_layer.py`, `model_loader.py`).
|
||||
- Follow snake_case for Python files and variables.
|
||||
- **Module Organization:**
|
||||
- Group related functionalities into modules.
|
||||
- Use `__init__.py` files to define packages and control module imports.
|
||||
- **Component Architecture:**
|
||||
- Design components with clear interfaces and responsibilities.
|
||||
- Favor composition over inheritance to promote flexibility and reusability.
|
||||
- **Code Splitting Strategies:**
|
||||
- Break down large modules into smaller, more manageable files.
|
||||
- Utilize lazy loading or dynamic imports to reduce startup time.
|
||||
|
||||
- ## Common Patterns and Anti-patterns:
|
||||
- **Design Patterns Specific to vllm:**
|
||||
- **Model Abstraction:** Decouple the model implementation from the core engine.
|
||||
- **Sequence Manager:** Centralized management of sequences and their states.
|
||||
- **Asynchronous Execution:** Use asyncio to handle concurrent requests and I/O operations.
|
||||
- **Recommended Approaches for Common Tasks:**
|
||||
- **Model Loading:** Implement a robust model loading mechanism with caching and error handling.
|
||||
- **Tokenization:** Use a dedicated tokenizer class to handle tokenization and detokenization.
|
||||
- **Inference:** Design an efficient inference pipeline with batching and optimized tensor operations.
|
||||
- **Anti-patterns and Code Smells to Avoid:**
|
||||
- **God Classes:** Avoid creating large classes with too many responsibilities.
|
||||
- **Code Duplication:** Refactor duplicated code into reusable functions or classes.
|
||||
- **Magic Numbers:** Use named constants for configuration values.
|
||||
- **State Management Best Practices:**
|
||||
- Use immutable data structures to avoid unintended side effects.
|
||||
- Manage state within dedicated classes or modules.
|
||||
- Avoid global state where possible.
|
||||
- **Error Handling Patterns:**
|
||||
- Use exceptions to handle errors and unexpected conditions.
|
||||
- Provide informative error messages.
|
||||
- Implement retry mechanisms for transient errors.
|
||||
|
||||
- ## Performance Considerations:
|
||||
- **Optimization Techniques:**
|
||||
- **Tensor Optimization:** Use optimized tensor operations and data layouts (e.g., `torch.compile`).
|
||||
- **Kernel Fusion:** Fuse multiple operations into a single kernel to reduce overhead.
|
||||
- **Quantization:** Use quantization techniques to reduce model size and memory footprint.
|
||||
- **Memory Management:**
|
||||
- Minimize memory allocations and deallocations.
|
||||
- Use memory pooling to reuse memory buffers.
|
||||
- Profile memory usage to identify bottlenecks.
|
||||
- **Bundle Size Optimization:**
|
||||
- Remove unused dependencies.
|
||||
- **Lazy Loading Strategies:**
|
||||
- Use lazy loading for large modules or resources.
|
||||
- Implement asynchronous loading for non-critical components.
|
||||
|
||||
- ## Security Best Practices:
|
||||
- **Common Vulnerabilities and How to Prevent Them:**
|
||||
- **Injection Attacks:** Sanitize user inputs to prevent injection attacks.
|
||||
- **Denial of Service (DoS):** Implement rate limiting and resource management to protect against DoS attacks.
|
||||
- **Data Breaches:** Protect sensitive data with encryption and access controls.
|
||||
- **Input Validation:**
|
||||
- Validate all user inputs before processing.
|
||||
- Use regular expressions or schema validation to enforce input constraints.
|
||||
- **Authentication and Authorization Patterns:**
|
||||
- Implement authentication to verify user identities.
|
||||
- Use authorization to control access to resources.
|
||||
- **Data Protection Strategies:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure storage mechanisms.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for API communication.
|
||||
- Implement API authentication and authorization.
|
||||
|
||||
- ## Testing Approaches:
|
||||
- **Unit Testing Strategies:**
|
||||
- Write unit tests for individual functions and classes.
|
||||
- Use mocking and stubbing to isolate units of code.
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between different modules and components.
|
||||
- **End-to-End Testing:**
|
||||
- Test the entire system from end to end.
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate directories.
|
||||
- Use descriptive names for test files and functions.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mocking to replace external dependencies with controlled substitutes.
|
||||
- Use stubbing to provide predefined responses for function calls.
|
||||
|
||||
- ## Common Pitfalls and Gotchas:
|
||||
- **Frequent Mistakes Developers Make:**
|
||||
- **Incorrect Tensor Shapes:** Ensure tensor shapes are compatible for operations.
|
||||
- **Memory Leaks:** Properly release allocated memory to prevent memory leaks.
|
||||
- **Synchronization Issues:** Avoid race conditions and deadlocks in concurrent code.
|
||||
- **Edge Cases to be Aware Of:**
|
||||
- **Handling Empty Sequences:** Handle empty sequences gracefully.
|
||||
- **Dealing with Unknown Tokens:** Implement a mechanism to handle unknown tokens.
|
||||
- **Version-Specific Issues:**
|
||||
- Keep dependencies up-to-date and be aware of breaking changes when upgrading.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure compatibility with different hardware platforms (CPU, GPU).
|
||||
- Consider different versions of Python and PyTorch.
|
||||
- **Debugging Strategies:**
|
||||
- Use logging to track program execution.
|
||||
- Use a debugger to step through code and inspect variables.
|
||||
- Profile performance to identify bottlenecks.
|
||||
|
||||
- ## Tooling and Environment:
|
||||
- **Recommended Development Tools:**
|
||||
- **VS Code:** A popular code editor with Python and C++ support.
|
||||
- **PyCharm:** An IDE specifically designed for Python development.
|
||||
- **Build Configuration:**
|
||||
- Use `setup.py` or `pyproject.toml` to define project dependencies and build configurations.
|
||||
- **Linting and Formatting:**
|
||||
- Use pylint, flake8, and black to enforce code style.
|
||||
- **Deployment Best Practices:**
|
||||
- Use Docker to containerize the application.
|
||||
- Deploy to a cloud platform such as AWS, Google Cloud, or Azure.
|
||||
- **CI/CD Integration:**
|
||||
- Use a CI/CD pipeline to automate testing and deployment.
|
||||
Reference in New Issue
Block a user