# How can I install and import the Sentence Transformers library in my Python environment?

Source: https://zilliz.com/ai-faq/how-can-i-install-and-import-the-sentence-transformers-library-in-my-python-environment
Author: zilliz

To install and use the Sentence Transformers library, follow these steps:

**Installation** 
Start by installing the library via pip. Open a terminal and run `pip install sentence-transformers`. This command automatically installs the core library along with dependencies like PyTorch and Hugging Face Transformers. If you’re using a virtual environment, activate it first. For GPU support, ensure PyTorch is configured for CUDA (e.g., install it separately via `pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cu117` before installing Sentence Transformers). If installation fails, upgrade pip (`pip install --upgrade pip`) and verify Python version compatibility (requires Python 3.6+).

**Importing and Basic Usage** 
After installation, import the library in your Python script using `from sentence_transformers import SentenceTransformer`. To generate embeddings, load a pre-trained model like `model = SentenceTransformer('all-MiniLM-L6-v2')` and encode text with `embeddings = model.encode(["Your text here"])`. The `encode()` method accepts single strings or lists, returning NumPy arrays (or PyTorch/TensorFlow tensors if configured). For example, `embeddings = model.encode(["Hello world", "How are you?"])` produces a 2D array where each row corresponds to a sentence’s embedding.

**Troubleshooting and Considerations** 
If imports fail, confirm the installation succeeded with `pip show sentence-transformers`. Common issues include environment conflicts (resolve with virtual environments) or missing dependencies like `transformers` or `scikit-learn`. Models download to `~/.cache/torch/sentence_transformers` on first use, so ensure internet access. For offline use, pre-download models or specify a local path with `model = SentenceTransformer('/path/to/model')`. In Jupyter notebooks, restart the kernel after installation. If you encounter `ModuleNotFoundError`, reinstall the library and check for typos in import statements.
