LangChain Tutorial for Beginners: Build LLM Applications
LangChain gives you building blocks for LLM apps: prompt templates, model wrappers, parsers, retrievers and tools. You compose them into a pipeline with a short expression syntax.
Core concepts
A prompt template fills variables into messages. A chat model wrapper calls the provider API. An output parser converts raw text into strings or structured objects. A chain connects them. Tools let a model call your functions, and retrievers fetch documents.
Your first chain
Set an API key as an environment variable, never in source code. The model name is an example; use any chat model your provider offers.
# pip install langchain langchain-openai
import os
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI
assert os.getenv("OPENAI_API_KEY"), "set OPENAI_API_KEY first"
prompt = ChatPromptTemplate.from_messages([
("system", "You are a concise data science tutor."),
("human", "Explain {topic} in {n} sentences."),
])
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
chain = prompt | llm | StrOutputParser()
print(chain.invoke({"topic": "overfitting", "n": 2}))Structured output
Ask for a typed result instead of parsing free text yourself.
from pydantic import BaseModel, Field
class Review(BaseModel):
sentiment: str = Field(description="positive, negative or neutral")
score: int = Field(description="1 to 5")
structured = llm.with_structured_output(Review)
print(structured.invoke("The course was clear and the code ran first try."))Give the model tools
A tool is a plain Python function with a docstring. The model decides when to call it and you execute it.
from langchain_core.tools import tool
@tool
def mean(numbers: list[float]) -> float:
"""Return the arithmetic mean of a list of numbers."""
return sum(numbers) / len(numbers)
llm_tools = llm.bind_tools([mean])
msg = llm_tools.invoke("What is the mean of 4, 8 and 15?")
for call in msg.tool_calls:
print(call["name"], call["args"], "->", mean.invoke(call["args"]))Where to go next
Combine chains with a retriever to build document question answering, covered in the RAG lesson. Add conversation memory, tracing and evaluation before you deploy anything to users.
Hands-on practice
Run the examples in the downloadable Jupyter notebook. The extra checks below focus on mistakes that appear in real projects, not just syntax.
Compose a small runnable chain
from langchain_core.runnables import RunnableLambda
clean=RunnableLambda(lambda x:x.strip().lower())
length=RunnableLambda(lambda x:{'text':x,'chars':len(x)})
print((clean|length).invoke(' Hello LangChain ')){'text': 'hello langchain', 'chars': 15}Use small composable steps so you can test each stage independently.
Return structured data
from pydantic import BaseModel
class Answer(BaseModel):
label:str
confidence:float
print(Answer(label='positive',confidence=.91).model_dump()){'label': 'positive', 'confidence': 0.91}Structured output is easier to validate than free-form text.
Self-check
- Can you explain why the first practice result is trustworthy rather than just plausible?
- What would you monitor or test before using this LangChain Basics workflow in production?
- Which assumption in the example would break first on a larger or messier dataset?
Frequently asked questions
Is LangChain free?
The library is open source. You pay the model provider for API usage unless you run an open model locally.
What is LCEL?
LangChain Expression Language. It composes components with the | operator into runnable chains that support streaming and batching.
Do I need LangChain to build an LLM app?
No. Small apps can call a provider SDK directly. LangChain helps when you combine retrieval, tools and several steps.
Primary references
Use these official sources when exact syntax, defaults or definitions matter beyond the examples here.




















































































































































