Setup & Installation
Comprehensive guide to Environment Setup in LangChain.
In this lesson, we will cover how to set up your environment for building LangChain applications. We'll verify everything is working by installing the necessary packages, configuring your API keys, and running a simple completion.
Project Setup
First, let's create a directory for our project.
mkdir my-langchain-app
cd my-langchain-appNow, we need to set up a virtual environment and install LangChain. You can choose between the standard Python tools or the modern uv package manager.
python -m venv .venv
# Activate the virtual environment
# On macOS/Linux:
source .venv/bin/activate
# On Windows:
# .venv\Scripts\activate
# Install LangChain and integration packages
pip install langchain langchain-openai langchain-anthropic langchain-google-genai langchain-communityOptional: Installing Ollama (Local Models)
If you want to run models locally (free & private), you need to install Ollama.
# macOS / Linux
curl -fsSL https://ollama.com/install.sh | sh
# Windows
# Download from https://ollama.com/downloadOnce installed, you can talk to the model directly in your terminal to verify it works:
# Start an interactive chat session
ollama run llama3
# You should see a prompt like:
# >>> Hello!
# Hello! How can I help you today?Environment Configuration
To use LLMs like OpenAI's GPT-4 or Google's Gemini, you need to set your API keys as environment variables. This creates a secure way for the LangChain library to access your credentials without hardcoding them in scripts.
Get your API keys here:
- OpenAI: platform.openai.com/api-keys
- Anthropic: console.anthropic.com/settings/keys
- Google Gemini: aistudio.google.com/app/apikey
export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."
export GOOGLE_API_KEY="AIza..."Basic Example
Now that we have the library installed and the environment configured, let's run a simple script to verify our setup. We'll initialize a Chat Model and ask it a question.
from langchain_openai import ChatOpenAI
# Or for Google Gemini:
# from langchain_google_genai import ChatGoogleGenerativeAI
# Initialize the model
llm = ChatOpenAI()
# llm = ChatGoogleGenerativeAI(model="gemini-pro")
# Invoke the model
response = llm.invoke("Hello, how are you?")
print(response.content)Summary
You have now successfully:
- Created a project directory and virtual environment.
- Installed LangChain and integration packages (OpenAI, Google) using
piporuv. - Configured your API keys.
- Verified the setup with a simple Python script.
You are ready to start building!