Working through this module?
Module 03 · Page 4 of 20 · 8 sections
Setting Up LangChain (Environment and Installation)
Prerequisites, a virtual environment, package installation, API keys and a .env file, a quick install check, project layout and fixes for common errors.
Prerequisites
- Python 3.8 or higher
- Basic knowledge of Python
- Familiarity with LLM concepts (optional)
- API keys for LLM providers (e.g., OpenAI)
- Virtual environment (recommended)
- Code editor (VS Code, PyCharm, etc.)
Create a Virtual Environment
shell
# Create virtual environment python -m venv langchain_env # Activate (Windows) langchain_env\Scripts\activate # Activate (Mac/Linux) source langchain_env/bin/activate
Install LangChain and Required Packages
shell
# Install LangChain (latest version) pip install langchain # Install community integrations pip install langchain-community # Install OpenAI support pip install langchain-openai # Other useful packages pip install python-dotenv pip install faiss-cpu pip install chromadb pip install tiktoken pip install pypdf
Set Up API Keys
- Create an account at OpenAI (or another provider).
- Generate an API key.
- Keep the API key secure (do not hard-code it).
- Use environment variables for security.
- Create a .env file in your project root.
shell
OPENAI_API_KEY=your_api_key_here LANGCHAIN_TRACING_V2=true LANGCHAIN_API_KEY=your_langchain_key
Load Environment Variables in Code
python
from dotenv import load_dotenv import os load_dotenv() api_key = os.getenv("OPENAI_API_KEY") print(api_key)
Verify Installation
python
from langchain_openai import ChatOpenAI llm = ChatOpenAI(model="gpt-3.5-turbo") response = llm.invoke("Hello! LangChain is working.") print(response.content)
Project Structure (Simple)
text
langchain-project/ |-- .env |-- app.py |-- requirements.txt |-- data/ | `-- sample.pdf |-- notebooks/ `-- README.md
A matching requirements.txt lists langchain, langchain-community, langchain-openai, python-dotenv, faiss-cpu, chromadb, pypdf and tiktoken.
Common Issues and Solutions
| Issue | Solution |
|---|---|
| ModuleNotFoundError | Install the missing package using pip |
| Invalid API Key | Check API key and .env file |
| Version conflicts | Use compatible versions or create a new venv |
| Rate limit error | Use smaller requests or a different model |
| Import errors | Use the correct import path (langchain_community, etc.) |
| Environment not activated | Activate the virtual environment before running code |