Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 32 ยท Getting Started

Installing LangChain and Setting Up Keys

Install LangChain in a virtual environment, add a provider package, keep API keys in environment variables and run your first model call safely, step by step.

Setting up LangChain takes four steps: create a virtual environment, install langchain plus one provider package, put your API key in an environment variable, and make a test call. None of it needs special tooling. This lesson shows the commands (read-only, since they run on your machine rather than in the browser) and then practices the part that does run here: reading configuration safely and failing with a clear message when a key is missing.

Requirements

You need a recent Python (3.10 or newer; use the newest your platform offers) and an account with at least one model provider. LangChain is provider-neutral, so pick whichever you have: OpenAI, Anthropic, Google, a cloud provider, or a local runtime like Ollama that needs no key.

Create a virtual environment and install

A virtual environment keeps this project's packages separate from everything else on your computer.

Terminal
python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate

pip install -U langchain langchain-core
pip install -U langchain-openai   # or langchain-anthropic, langchain-google-genai, langchain-ollama

Installing langchain pulls in langchain-core and langgraph. Provider packages are separate on purpose: you only install the vendors you use. A few extras you will want later:

Terminal
pip install -U langchain-community langchain-text-splitters   # loaders, splitters
pip install -U langsmith                                      # tracing and evaluation
pip install -U python-dotenv                                  # load .env files

Pin versions in a requirements.txt (or pyproject.toml) for anything you deploy. LangChain moves quickly, and a lock file prevents surprises.

Package names use hyphens (langchain-openai) but import names use underscores (langchain_openai). Mixing those up is the most common first error.

Keep keys out of your code

An API key is a password that is billed to you. Never write it in source code, never commit it to Git, and never paste it into a notebook you share. Read it from the environment instead.

Terminal
# macOS / Linux
export OPENAI_API_KEY="sk-..."

# Windows PowerShell
$env:OPENAI_API_KEY = "sk-..."

For a project, store keys in a .env file that is listed in .gitignore, and load it at program start:

Python
from dotenv import load_dotenv
load_dotenv()          # reads .env and fills os.environ

Provider packages look for their usual variable names automatically (OPENAI_API_KEY, ANTHROPIC_API_KEY, GOOGLE_API_KEY), so you rarely pass the key explicitly.

Your first real model call

This is the real code, read-only here:

Python
from langchain.chat_models import init_chat_model

model = init_chat_model("openai:gpt-4o-mini", temperature=0)
reply = model.invoke("Say hello in French.")
print(reply.content)      # for example: Bonjour !
print(type(reply))        # <class 'langchain_core.messages.ai.AIMessage'>

Two details to notice. The string "openai:gpt-4o-mini" names provider:model; swap it for "anthropic:..." and the rest of the program is unchanged. And the reply is not a plain string but an AIMessage object whose text is in .content, next to metadata like token usage. The next lessons look at both.

Checking your configuration (runnable)

A missing key produces a confusing error deep inside an HTTP client. It is kinder to check early. This stand-in simulates the environment with a dictionary so it runs anywhere.

Python Stand-in: validate settings before calling a model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Masking secrets before logging is a good habit: logs travel to places your code does not.

Splitting model name from provider (runnable)

The "provider:model" convention is just a string with a colon. A tiny parser shows how a helper like init_chat_model can choose a class from it.

Python Stand-in: a factory that picks a class from provider:model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Turning on tracing

LangSmith records every step of a run (the prompt, the reply, timings, token counts). It is optional, free to start, and so useful that most teams enable it from day one. It is switched on with environment variables only, with no code change:

Terminal
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY="lsv2_..."
export LANGSMITH_PROJECT="my-first-app"

Troubleshooting checklist

Symptom Likely cause
ModuleNotFoundError: langchain_openai Provider package not installed in this environment
AuthenticationError or a 401 Key missing, mistyped, or for the wrong provider
RateLimitError or a 429 Too many requests or no billing credit on the account
Imports from langchain.chains fail Old tutorial; use LCEL (see LCEL and the Pipe Operator)
Works in terminal, not in notebook The notebook kernel uses a different environment

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should an API key live?

    Keys are secrets. Read them from the environment and keep .env out of version control.
  2. 2. How do you install the OpenAI integration for LangChain?

    The package name uses a hyphen; the import name langchain_openai uses an underscore.
  3. 3. In init_chat_model('openai:gpt-4o-mini'), what does the part before the colon select?

    The prefix chooses the provider; the part after it is that provider's model name.
  4. 4. What type does model.invoke('hi') return for a chat model?

    Chat models return message objects, which also carry metadata such as token usage.

Summary

  • Use a virtual environment; install langchain and one provider package per vendor.
  • Package names have hyphens, imports have underscores.
  • Keep keys in environment variables or an ignored .env file, and mask them in logs.
  • init_chat_model("provider:model") returns a chat model; invoke returns an AIMessage.
  • LangSmith tracing is enabled with environment variables alone.

Next: Messages and Your First Chat