Setting Up Your LangChain Environment

Before you write a single line of LangChain code, you need a working development environment. This topic walks you through every step: installing Python, creating a virtual environment, installing LangChain, storing API keys safely, and verifying that everything works. Follow each step in order and you will have a clean, professional setup by the end.

What You Need Before You Start

You need three things on your computer before installing LangChain:

  • Python 3.9 or higher
  • pip (Python's package manager, comes with Python)
  • A text editor or IDE (VS Code is a great free choice)

You also need an API key from an AI provider. OpenAI is the most common choice for beginners because the documentation is clear and models are reliable. You can sign up at platform.openai.com and generate a key from the API section. Keep this key private — never share it publicly or commit it to a Git repository.

The Kitchen Counter Analogy

Setting up a development environment is like preparing your kitchen before cooking. You need a clean counter (virtual environment), the right tools organized and within reach (installed packages), and your recipe ingredients ready (API keys). Trying to cook in a messy, unprepared kitchen always ends in mistakes. The same is true for coding.

Your Computer
─────────────────────────────────────────
│  Global Python Installation            │
│  ┌──────────────────────────────────┐  │
│  │  Virtual Environment (venv)      │  │
│  │  ┌────────────────────────────┐  │  │
│  │  │  langchain                 │  │  │
│  │  │  langchain-openai          │  │  │
│  │  │  python-dotenv             │  │  │
│  │  │  openai                    │  │  │
│  │  └────────────────────────────┘  │  │
│  └──────────────────────────────────┘  │
│                                        │
│  .env file (stores API keys safely)    │
─────────────────────────────────────────

The virtual environment keeps your LangChain packages separate from other Python projects. This prevents version conflicts — a common headache when multiple projects share the same Python installation.

Step 1: Verify Python Is Installed

Open your terminal (Command Prompt on Windows, Terminal on Mac or Linux) and type:

python --version

You should see something like Python 3.11.4. If Python is not installed, download it from python.org and run the installer. On Windows, check the box that says "Add Python to PATH" during installation — this step is easy to miss and causes problems later.

Step 2: Create a Project Folder

Create a dedicated folder for your LangChain projects. Keeping everything organized from the start saves time later.

mkdir langchain-projects
cd langchain-projects

All your course work lives inside this folder. Each topic can have its own subfolder if you prefer, or you can keep everything in one place to start.

Step 3: Create a Virtual Environment

A virtual environment is a self-contained Python installation inside your project folder. Packages you install here do not affect any other Python project on your machine.

python -m venv venv

This command creates a folder called venv inside your project directory. That folder contains a fresh Python installation ready to receive packages.

Activate the Virtual Environment

You must activate the virtual environment every time you open a new terminal session to work on this project.

On Windows:

venv\Scripts\activate

On Mac or Linux:

source venv/bin/activate

After activation, your terminal prompt changes. You see (venv) at the beginning of the line. This visual indicator confirms that the virtual environment is active and any packages you install go into it.

Step 4: Install LangChain and Related Packages

LangChain is split into several packages. This modular design means you only install what you need. For this course, install the core packages now and add others as topics require them.

pip install langchain langchain-openai python-dotenv

Here is what each package does:

Package             Purpose
────────────────────────────────────────────────────────────
langchain           Core framework (chains, memory, agents)
langchain-openai    Connects LangChain to OpenAI models
python-dotenv       Loads API keys from a .env file safely

Installation takes one to three minutes depending on your internet speed. You see a progress bar for each package. When the terminal returns to your prompt without errors, everything installed successfully.

Verify Installation

Run this command to confirm the packages installed correctly:

pip show langchain

The output shows the installed version and location. As of early 2025, LangChain version 0.3.x is the current stable release. The version number in your terminal may differ but the commands in this course work with any 0.3.x version.

Step 5: Store Your API Key Safely

Hard-coding your API key directly in Python files is a serious security risk. If you ever share your code, push it to GitHub, or send it to a colleague, your key gets exposed. Anyone with your key can run API calls that bill to your account.

The safe approach uses a .env file — a plain text file that lives in your project folder and never gets committed to version control.

Create the .env File

Inside your project folder, create a file named exactly .env (note the dot at the beginning). Add your API key on one line:

OPENAI_API_KEY=sk-your-actual-key-goes-here

Replace sk-your-actual-key-goes-here with your real key from the OpenAI dashboard. Save the file.

Create a .gitignore File

If you use Git for version control (recommended), create a file named .gitignore in your project folder with this content:

.env
venv/
__pycache__/
*.pyc

This tells Git to ignore the .env file so your key never accidentally gets uploaded anywhere.

How .env Loading Works

.env file (on your disk)
┌──────────────────────────────┐
│ OPENAI_API_KEY=sk-abc123...  │
└──────────────┬───────────────┘
               │  python-dotenv reads this
               ▼
Your Python Script
┌──────────────────────────────────────────┐
│ from dotenv import load_dotenv           │
│ import os                                │
│                                          │
│ load_dotenv()   # reads .env file        │
│ key = os.getenv("OPENAI_API_KEY")        │
│ # key now holds your actual API key      │
└──────────────────────────────────────────┘

Step 6: Write and Run Your First LangChain Script

Create a file named hello_langchain.py in your project folder. Type the following code:

from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage

# Load API key from .env file
load_dotenv()

# Create a connection to the AI model
model = ChatOpenAI(model="gpt-3.5-turbo")

# Send a message and get a response
response = model.invoke([HumanMessage(content="Say hello in one sentence.")])

# Print the AI's reply
print(response.content)

Save the file, then run it from your terminal:

python hello_langchain.py

The AI responds with a short greeting. Seeing this output confirms your entire setup — Python, virtual environment, packages, API key, and LangChain — all work correctly together.

Understanding the Script Line by Line

load_dotenv()

This function reads your .env file and loads the OPENAI_API_KEY into your environment variables. LangChain automatically finds and uses this key when connecting to OpenAI. You do not need to pass the key explicitly anywhere in your code.

ChatOpenAI

This object represents your connection to OpenAI's chat models. The parameter model="gpt-3.5-turbo" tells LangChain which specific model to use. You can change this to "gpt-4" or any other model you have access to.

HumanMessage

LangChain represents conversation messages as objects. A HumanMessage represents text sent by the user. You pass it inside a list because a full conversation can contain multiple messages in sequence.

model.invoke()

The invoke method sends your messages to the AI model and waits for a response. The response comes back as an object. The .content attribute holds the actual text of the AI's reply.

Project Folder Structure After Setup

langchain-projects/
├── .env                  ← Your API keys (never share this)
├── .gitignore            ← Tells Git to ignore .env
├── hello_langchain.py    ← Your first script
└── venv/                 ← Virtual environment (auto-generated)
    ├── bin/              ← Executable files (Mac/Linux)
    ├── Scripts/          ← Executable files (Windows)
    └── lib/              ← Installed packages

Common Setup Problems and Fixes

Problem: "python is not recognized as a command"

This happens on Windows when Python was not added to the system PATH during installation. Reinstall Python and check the "Add Python to PATH" box. Alternatively, try using py instead of python in your commands — Windows sometimes uses this shortcut.

Problem: "pip is not recognized"

Try python -m pip install ... instead of just pip install .... This tells Python to run pip as a module, which avoids PATH issues.

Problem: "openai.AuthenticationError: Incorrect API key"

Your API key in the .env file is wrong. Open the .env file and check that there are no extra spaces or quotes around the key. The format must be exactly OPENAI_API_KEY=sk-your-key with no spaces around the equals sign.

Problem: "ModuleNotFoundError: No module named 'langchain'"

Your virtual environment is not activated. Run the activation command again (the one starting with source on Mac/Linux or venv\Scripts\activate on Windows) and then retry your script.

Problem: Packages installed but import still fails

You may have two Python installations on your machine and pip installed the package into the wrong one. Always activate the virtual environment before running pip install to ensure packages go to the right place.

Using Google Gemini Instead of OpenAI

OpenAI requires a paid account for most models. Google Gemini offers a free tier. If you prefer to start without paying anything, install the Gemini integration:

pip install langchain-google-genai

Get a free API key from aistudio.google.com. Add it to your .env file:

GOOGLE_API_KEY=your-google-key-here

Replace the model setup line in your script:

from langchain_google_genai import ChatGoogleGenerativeAI
model = ChatGoogleGenerativeAI(model="gemini-pro")

Everything else in the course works the same way. LangChain's power lies in this interchangeability — you swap the model without rewriting your application logic.

Using a requirements.txt File

As your project grows, track all your installed packages in a requirements.txt file. This lets anyone else recreate your environment exactly.

Generate it with:

pip freeze > requirements.txt

To recreate the environment on a different machine:

pip install -r requirements.txt

This is standard professional practice. Start doing it now and it becomes a habit.

Setting Up VS Code for LangChain Development

VS Code is a free code editor that makes Python development much easier. After installing it from code.visualstudio.com, install the Python extension (search for "Python" in the Extensions panel on the left). Once installed, select your virtual environment as the Python interpreter by clicking the Python version shown in the bottom status bar and choosing the venv interpreter from your project folder.

VS Code then gives you auto-complete suggestions for LangChain classes and methods, highlights syntax errors before you run the code, and lets you run scripts directly from the editor with one click.

Summary

Your LangChain development environment now consists of a project folder, a virtual environment with the required packages installed, a .env file holding your API key, and a working test script. This clean foundation prevents the most common beginner frustrations. Every topic from here forward builds on this setup.

Leave a Comment