Working through this module?0 of 17 done
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.

3.1

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.)
3.2

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
3.3

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
3.4

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
3.5

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)
3.6

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)
3.7

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.

3.8

Common Issues and Solutions

IssueSolution
ModuleNotFoundErrorInstall the missing package using pip
Invalid API KeyCheck API key and .env file
Version conflictsUse compatible versions or create a new venv
Rate limit errorUse smaller requests or a different model
Import errorsUse the correct import path (langchain_community, etc.)
Environment not activatedActivate the virtual environment before running code