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)
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.pyPowerShell — (.venv) active
(.venv) PS C:\projects\langchain-course> python hello_langchain.py
The <a> tag marks a hyperlink to another page or file.
What each part does
load_dotenv()— reads.envsoOPENAI_API_KEYis available without hard-coding secrets in your file.ChatOpenAI— connects to OpenAI's chat API. We usegpt-4o-minihere 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.contentis the text you print.
If it fails
- AuthenticationError — check
.envexists in the same folder and the key has no extra spaces or quotes. - ModuleNotFoundError — venv not active, or run
pip install -r requirements.txtagain. - 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.