LangChain BasicsLesson 1

LangChain Basics

Project setup is done. This lesson is your first working script: read the API key from .env, send the HTML question from What is LangChain? to OpenAI, and print the reply.

Before you run

Open a terminal in your langchain-course folder. Activate the venv from Project Setup and confirm pip show langchain works.

Your .env file needs a valid OPENAI_API_KEY from OpenAI Account Setup. LangChain reads it automatically once you call load_dotenv().

The script

Create hello_langchain.py with the code below. The file is short: a few imports, one API call, one print.

hello_langchain.py
"""LangChain Basics — first OpenAI call"""
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
load_dotenv()
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
question = "What does the HTML <a> tag do? Answer in one sentence."
response = llm.invoke([HumanMessage(content=question)])
print(response.content)
Save as hello_langchain.py in your project folder — included in the starter ZIP from Project Setup.

Run it

With the venv active, run:

python hello_langchain.py
PowerShell — (.venv) active
(.venv) PS C:\projects\langchain-course> python hello_langchain.py
The <a> tag marks a hyperlink to another page or file.
Your terminal should print one line of text like this. The exact sentence can differ between runs.

What each part does

  • load_dotenv() — reads .env so OPENAI_API_KEY is available without hard-coding secrets in your file.
  • ChatOpenAI — connects to OpenAI's chat API. We use gpt-4o-mini here to keep practice runs inexpensive. See OpenAI models for other model IDs.
  • HumanMessage — puts your question in the shape LangChain expects. Later lessons add system messages and back-and-forth chats.
  • invoke — posts the message and waits for OpenAI's reply. response.content is the text you print.

If it fails

  • AuthenticationError — check .env exists in the same folder and the key has no extra spaces or quotes.
  • ModuleNotFoundError — venv not active, or run pip install -r requirements.txt again.
  • Rate limit / billing — confirm credits on your OpenAI account from the setup lesson.

The official LangChain quickstart follows the same pattern if you want a second reference.

What's Next

You have a working OpenAI script. Next: repeat the same steps with Ollama on your PC.