02. LangChain Foundations#
A fast, conceptual revision guide for 02-langchain-foundation. Focused on the core LangChain mental models — prompt templates, provider-agnostic chat models, LCEL chains, cloud vs. local trade-offs, AIMessage anatomy, and zero-code observability — without boilerplate code clutter.
Reproducible Setup, Secrets & Provider Portability#
Revision Notes#
Reference files: pyproject.toml, sample.env.example, sample_data.py
Concept#
Building reliable AI workflows starts before writing any prompt: you need locked dependencies, config-driven secrets and model selection, and a fixed test input so you can evaluate model changes objectively.
Key Mental Models#
- Modular LangChain architecture: LangChain splits its ecosystem into focused packages rather than one monolith:
langchain-core— The universal abstractions (PromptTemplate,RunnableSequence,AIMessage).- Provider packages (
langchain-openai,langchain-ollama) — Thin adapters that plug specific LLM backends into those same core interfaces. langchain— High-level orchestration (chains and agents).
- Provider portability via OpenAI-compatible APIs: Many cloud providers (like Groq) implement OpenAI's HTTP schema. Changing
OPENAI_BASE_URL,OPENAI_API_KEY, andOPENAI_MODELin.envswitches providers with zero Python code changes. - Controlled experiments with shared input: Keeping a single biography (
PERSON_INFORMATIONinsample_data.py) across all scripts lets you compare cloud vs. local models on the exact same input — isolating model quality from prompt or data differences. .envdiscipline: Never commit.envto Git; writeKEY=valuewith no spaces around=and no extra quotes.
Code Reference#
"""
===============================================================================
Future with Shivank — AI Harness
Section 1 · Sample input text shared by scripts 02, 03 and 04
===============================================================================
WHY THIS FILE EXISTS
--------------------
Every script in this section asks an LLM to summarise the SAME piece of text,
so you can compare a cloud model (OpenAI) with a local model (Ollama) on an
identical input. Keeping the text in one place means you only edit it once.
TRY THIS
--------
Replace PERSON_INFORMATION with a paragraph about anyone you like (a scientist,
a cricketer, your favourite founder) and re-run the scripts. Nothing else in
the code needs to change — that is the power of a prompt TEMPLATE.
===============================================================================
"""
# Shared fixture constant imported by Scripts 02, 03, and 04 so model comparisons
# hold the input variable fixed while only swapping the LLM provider.
# Triple quotes preserve multi-paragraph formatting inside a single string.
PERSON_INFORMATION = """
Avul Pakir Jainulabdeen Abdul Kalam (15 October 1931 – 27 July 2015) was an
Indian aerospace scientist and statesman who served as the 11th President of
India from 2002 to 2007. He was born into a modest family in Rameswaram, Tamil
Nadu, and as a boy he sold newspapers to support his family's income before
studying physics and then aerospace engineering at the Madras Institute of
Technology.
Kalam spent most of his scientific career at the Defence Research and
Development Organisation (DRDO) and the Indian Space Research Organisation
(ISRO). At ISRO he was project director of SLV-III, India's first indigenously
developed satellite launch vehicle, which placed the Rohini satellite into
orbit in 1980. He later led the development of several missile programmes,
which earned him the popular title "Missile Man of India", and he played a
central organisational role in the Pokhran-II nuclear tests in 1998.
He was awarded the Bharat Ratna, India's highest civilian honour, in 1997.
As President he became known as the "People's President" because of his
simple lifestyle and his habit of speaking directly with students across the
country. His autobiography, "Wings of Fire" (1999), became a bestseller and
remains popular with young readers. Kalam died on 27 July 2015 while
delivering a lecture to students at the Indian Institute of Management
Shillong, doing what he loved most: teaching.
"""
# ↑ Used like this in the other scripts:
# from sample_data import PERSON_INFORMATION
# chain.invoke({"information": PERSON_INFORMATION})
>>> from sample_data import PERSON_INFORMATION
>>> print(len(PERSON_INFORMATION), "chars")
1301 chars
>>> print(PERSON_INFORMATION.strip().splitlines()[0])
Avul Pakir Jainulabdeen Abdul Kalam (15 October 1931 – 27 July 2015) was an
Safe Environment Verification#
Revision Notes#
Reference file: 01_hello_world_env_setup.py (runs with or without an API key)
Concept#
Before making paid network calls, a healthy AI project verifies two basics: the virtual environment is active and required secrets are loaded into os.environ — without ever printing raw API keys to terminals, logs, or screenshots.
Key Mental Models#
- Load environment early: Calling
load_dotenv()at startup populatesos.environfrom.envbefore any SDK initializes. - Precedence rule: Variables already exported in your terminal shell take precedence over
.envby default — useful for temporary overrides in CI/CD or testing. - Safe secret verification: Rather than printing a key, inspect only its prefix (e.g.,
'sk-proj-'vs.'gsk_') and character length. That confirms both presence and key type while preventing accidental credential leaks.
Code Reference#
import os
from dotenv import load_dotenv
# Reads ".env" from the current folder (and its parents) and puts every
# KEY=value pair into os.environ. Existing environment variables win, so a key
# exported in your terminal overrides the one in .env.
load_dotenv()
# -----------------------------------------------------------------------------
# describe_secret()
# -----------------------------------------------------------------------------
# Safely reports whether a secret is loaded WITHOUT printing it.
# Never print a full API key: terminal output ends up in screenshots, screen
# recordings and logs.
#
# Input : name (str) — the environment variable to check, e.g. "OPENAI_API_KEY"
# Output: (str) a human-friendly status line
def describe_secret(name: str) -> str:
# Use .get() instead of os.environ[name] so a missing key returns None
# cleanly rather than crashing with a KeyError.
value = os.environ.get(name)
if not value:
return f"{name} is missing ❌ → copy .env.example to .env and add your key"
# Show only the first 8 characters (`!r` wraps them in quotes), which identify
# the key TYPE (e.g. 'sk-proj-' for an OpenAI project key) without leaking it.
return f"{name} loaded ✅ (starts with {value[:8]!r}, {len(value)} characters)"
# ↑ Examples:
# describe_secret("OPENAI_API_KEY") → "OPENAI_API_KEY loaded ✅ (starts with 'sk-proj-', 164 characters)"
# describe_secret("NOT_A_REAL_VAR") → "NOT_A_REAL_VAR is missing ❌ → copy .env.example ..."
def main() -> None:
print("Hello from Future with Shivank — AI Harness!")
# Verify the key that scripts 02 and 04 need before making any network calls.
print(describe_secret("OPENAI_API_KEY"))
# LangSmith tracing is optional. When LANGSMITH_TRACING=true and
# LANGSMITH_API_KEY are set, every LangChain call is recorded automatically
# (no code changes needed) and you can inspect it at https://smith.langchain.com
tracing = os.environ.get("LANGSMITH_TRACING", "(not set)")
hint = (
"→ tracing is optional, see Script 02"
if tracing != "true"
else "→ runs will appear in LangSmith"
)
print(f"LANGSMITH_TRACING = {tracing} {hint}")
# Standard entry-point guard so importing describe_secret() in tests won't run main().
if __name__ == "__main__":
main()
$ uv run python 01_hello_world_env_setup.py
Hello from Future with Shivank — AI Harness!
OPENAI_API_KEY loaded ✅ (starts with 'sk-proj-', 164 characters)
LANGSMITH_TRACING = (not set) → tracing is optional, see Script 02
Core LangChain Primitives & LCEL Chains#
Revision Notes#
Reference file: 02_summary_chain_openai.py (requires OPENAI_API_KEY)
Concept#
Instead of gluing raw strings and provider-specific HTTP calls together, LangChain models every component as a Runnable — a standard unit with a uniform interface (.invoke(), .batch(), .stream()). Almost every LangChain application starts by composing three primitives using LCEL (LangChain Expression Language):
PromptTemplate: Separates reusable prompt structure (instructions +{placeholder}slots) from dynamic runtime data.- Chat Model (
ChatOpenAI): A standardized wrapper around an LLM provider that accepts formatted prompts and returns structured messages. - Chain (
prompt | llm): The pipe operator (|) composes components into aRunnableSequence, automatically feeding the output of the left step into the input of the right step.
Data Flow#
The pipe operator (prompt | llm) composes independent Runnables into a single sequence: runtime dictionary values populate template placeholders, the chat model executes with uniform settings, and response.text normalizes provider payloads into a plain string.
Key Mental Models#
- Prompt as an output contract: Specifying explicit structure (e.g., "1. headline, 2. three-bullet summary, 3. one interview question") and grounding ("Using only this text") keeps the shape of the output consistent even though exact LLM wording varies across runs.
- Always read
response.textinstead ofresponse.content: Newer OpenAI models use the Responses API, where.contentcan be alistof structured content blocks rather than a string..textnormalizes the reply into a plain Pythonstracross all providers. - Temperature compatibility: Setting
temperature=0requests deterministic sampling; for reasoning models that do not accept custom temperatures, LangChain automatically drops the parameter so your code stays portable.
Code Reference#
"""
===============================================================================
Future with Shivank — AI Harness
Section 1 · Script 02 · Your first LangChain chain: PromptTemplate | ChatOpenAI
===============================================================================
WHAT THIS FILE TEACHES
----------------------
The three building blocks you will use in EVERY later section:
1. PromptTemplate – a prompt with {placeholders} that you fill at run time.
2. Chat model – a Python object that talks to an LLM (here: OpenAI).
3. Chain (`|`) – the pipe operator connects blocks, so the output of one
becomes the input of the next (LCEL = LangChain
Expression Language).
{"information": "<bio text>"}
│
▼
┌───────────────────┐ fills {information} in the template
│ PromptTemplate │
└─────────┬─────────┘
│ StringPromptValue("Here is a short biography: ... interview")
▼
┌───────────────────┐ sends the prompt to OpenAI
│ ChatOpenAI │
└─────────┬─────────┘
│ AIMessage(content=..., response_metadata=...)
▼
response.text → the answer as a plain string
PREREQUISITES (.env)
--------------------
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-5.6-sol # optional — this is the default
# Optional tracing (see the bottom of this docstring):
LANGSMITH_TRACING=true
LANGSMITH_API_KEY=lsv2_...
LANGSMITH_PROJECT=section-01-langchain-foundations
HOW TO RUN
----------
uv run python 02_summary_chain_openai.py
EXPECTED OUTPUT (sample — the wording changes on every run)
-----------------------------------------------------------
Hello from Future with Shivank — AI Harness!
Model: gpt-5.6-sol
1. Headline: From newspaper boy in Rameswaram to India's "Missile Man" and President.
2. Summary for a 12-year-old:
- He was a scientist who helped India build its own rockets and put a
satellite into space.
- People called him the "Missile Man of India", and later he became the
country's 11th President.
- He loved teaching students and was giving a lecture when he died in 2015.
# ... (see full file: 02_summary_chain_openai.py)
# Key pattern in the body:
# - PromptTemplate.from_template(...) binds {information} at invoke() time.
# - ChatOpenAI(temperature=0, model=...) keeps summaries repeatable.
# - `chain = prompt | llm` uses LCEL pipe composition; `response.text` safely
# extracts plain text regardless of whether content is a str or block list.
$ uv run python 02_summary_chain_openai.py
Hello from Future with Shivank — AI Harness!
Model: gpt-5.6-sol
1. Headline: From newspaper boy in Rameswaram to India's "Missile Man" and President.
2. Summary for a 12-year-old:
- He was a scientist who helped India build its own rockets and put a satellite into space.
- People called him the "Missile Man of India", and later he became the country's 11th President.
- He loved teaching students and was giving a lecture when he died in 2015.
3. Interview question:
What kept you curious and humble even after reaching India's highest office?
Cloud vs. Local Models: Swapping to Ollama#
Revision Notes#
Reference file: 03_summary_chain_ollama.py (runs locally — requires Ollama + gemma3:270m)
Concept#
Because every LangChain chat model implements the exact same Runnable contract, swapping a paid cloud API (ChatOpenAI) for a free, private local model (ChatOllama, talking to Ollama's local server at localhost:11434) is a one-line change. The PromptTemplate, pipe operator (|), .invoke(), and response.text remain completely untouched.
Cloud vs. Local Trade-Offs#
- Why run locally (Ollama):
- Zero per-token cost and complete data privacy (prompts never leave your machine).
- Works offline — great for prototyping, air-gapped environments, and learning.
- The model-size vs. instruction-following trade-off:
- Tiny models like
gemma3:270m(~300 MB, 270M parameters) are fast and run on almost any laptop, but frequently struggle with strict formatting contracts (e.g., returning 4 bullets instead of 3 or skipping a requested section). - Larger local models (e.g.,
gemma4, ~10 GB) follow instructions far better, but require significantly more RAM/VRAM and run slower. - Cloud frontier models give the strongest reasoning and instruction adherence, at the cost of API fees, latency over the internet, and sending data to a third party.
- Tiny models like
- Common local failure modes:
ConnectionError→ Ollama's background server isn't running (ollama serve).- Model not found → The weights haven't been downloaded locally yet (
ollama pull <model>).
Because every chat adapter implements LangChain's BaseChatModel interface, switching between frontier cloud APIs, OpenAI-compatible endpoints, and private local Ollama models requires changing at most one line while keeping prompts and downstream code untouched.
Code Reference#
"""
===============================================================================
Future with Shivank — AI Harness
Section 1 · Script 03 · Same chain, LOCAL open-weights model (Ollama)
===============================================================================
WHAT THIS FILE TEACHES
----------------------
LangChain gives every chat model the same interface. To move from a paid cloud
model (OpenAI) to a free model running on YOUR laptop, you change exactly ONE
line — the model object. The prompt, the chain and invoke() stay identical:
Script 02: llm = ChatOpenAI(temperature=0, model="gpt-5.6-sol")
Script 03: llm = ChatOllama(temperature=0, model="gemma3:270m") ← only change
Ollama is a free app that downloads open-weights models (Gemma, Qwen, Llama,
...) and serves them on http://localhost:11434. No API key, no cost, and your
data never leaves your machine.
PREREQUISITES
-------------
1. Install Ollama from https://ollama.com/download and start it.
2. Download the model once (≈300 MB for the tiny 270-million-parameter Gemma):
ollama pull gemma3:270m
3. Optional — use a bigger/better local model by adding to .env:
OLLAMA_MODEL=gemma4 # much better answers, ≈10 GB download
HOW TO RUN
----------
uv run python 03_summary_chain_ollama.py
EXPECTED OUTPUT (sample — small local models vary a lot)
--------------------------------------------------------
Hello from Future with Shivank — AI Harness!
Model: gemma3:270m (local, via Ollama)
**Headline:** Abdul Kalam: The Missile Man of India
**Summary:**
* Abdul Kalam was a scientist who worked at ISRO and DRDO.
* He became the 11th President of India.
* He wrote a book called "Wings of Fire".
* He was born in Rameswaram ...
WHAT TO NOTICE
--------------
The local answer comes back FAST, but a 270M-parameter model is tiny compared
with GPT-class models. It often ignores parts of the instructions — for
example it may write four bullets instead of three, or forget the interview
question. That is the
classic trade-off: cost/privacy/speed versus quality. Try OLLAMA_MODEL=gemma4
and compare.
TROUBLESHOOTING
---------------
ConnectionError / "Failed to connect to Ollama" → the Ollama app is not running.
"model 'gemma3:270m' not found" → run: ollama pull gemma3:270m
===============================================================================
# ... (see full file: 03_summary_chain_ollama.py)
# Key pattern in the body:
# - Swapping ChatOpenAI -> ChatOllama works because both implement LangChain's
# BaseChatModel Runnable interface, so `prompt | llm` needs zero downstream edits.
$ uv run python 03_summary_chain_ollama.py
Hello from Future with Shivank — AI Harness!
Model: gemma3:270m (local, via Ollama)
**Headline:** Abdul Kalam: The Missile Man of India
**Summary:**
* Abdul Kalam was a scientist who worked at ISRO and DRDO.
* He became the 11th President of India.
* He wrote a book called "Wings of Fire".
* He was born in Rameswaram, Tamil Nadu.
Anatomy of the `AIMessage` Response Object#
Revision Notes#
Reference file: 04_inspect_the_response_object.py (supports OpenAI or --local for Ollama)
Concept#
Calling chain.invoke() does not return a bare string — it returns an AIMessage object. Production AI systems need far more than raw text: they need to track token spend, debug provider behavior, distinguish conversation roles, and detect when the model wants to call a tool.
What Lives Inside AIMessage#
type: Always"ai"— distinguishes assistant messages from"human","system", and"tool"messages in multi-turn conversations.textvs.content:.textis the normalized plain-string reply (use this in application logic)..contentis the raw provider payload (either astror alistof content blocks on newer Responses-API models).
tool_calls: An empty list[]for normal text replies; populated with structured tool-invocation requests when building agents. This single field is the bridge from chains to agents.usage_metadata(Standardized): Provider-independent token counts (input_tokens,output_tokens,total_tokens) used for cost estimation, rate-limit tracking, and context budgeting.response_metadata(Provider-Specific): Raw backend details — e.g., OpenAI includesmodel_name,status, andmodel_provider, while Ollama includesmodel,done_reason, andtotal_duration.id: Unique identifier for the individual model response, useful for logging and tracing.
Code Reference#
"""
===============================================================================
Future with Shivank — AI Harness
Section 1 · Script 04 · What exactly comes back from an LLM call?
===============================================================================
WHAT THIS FILE TEACHES
----------------------
In Scripts 02/03 we only printed the answer text. But chain.invoke() returns a
rich object called an AIMessage. Knowing its fields is essential for agents:
in Section 2 onwards, the SAME object carries the model's tool calls.
This script prints every important field — the same things you would see if
you put a breakpoint on `print(response.text)` and explored `response` in your
IDE's debugger.
AIMessage
├── type "ai" (vs "human", "system", "tool")
├── content the raw content (a string, or a list of blocks)
├── text the answer as one plain string ← use this
├── tool_calls [] for now — filled when the model wants a tool
├── usage_metadata input / output / total tokens → cost
├── response_metadata model name, finish reason, provider ...
└── id unique id of this response
PREREQUISITES
-------------
OPENAI_API_KEY in .env (default: cloud model)
or Ollama running + `ollama pull gemma3:270m` (use --local)
HOW TO RUN
----------
uv run python 04_inspect_the_response_object.py # OpenAI
uv run python 04_inspect_the_response_object.py --local # Ollama
EXPECTED OUTPUT (sample; numbers and ids differ on every run)
-------------------------------------------------------------
Calling gpt-5.6-sol ...
type(response) : AIMessage
response.type : ai
response.text[:80] : 1. Headline: From newspaper boy in Rameswaram to India's "Missile Man" and Presi...
response.tool_calls : []
usage_metadata : {'input_tokens': 412, 'output_tokens': 386, 'total_tokens': 798, ...}
response_metadata keys: ['id', 'created_at', 'model', 'status', 'model_provider', 'model_name', ...]
model_name : gpt-5.6-sol
response.id : resp_0a1b2c...
content is a : list (Responses-API content blocks) — that's why we use .text
With --local you will see content is a `str`, a model_name like 'gemma3:270m'
and Ollama-specific metadata such as 'done_reason' and 'total_duration'.
===============================================================================
"""
# `os` reads model overrides from .env; `sys.argv` checks for the `--local` CLI flag.
import os
import sys
# Loads OPENAI_API_KEY / OLLAMA_MODEL before instantiating the selected chat model.
from dotenv import load_dotenv
# ... (see full file: 04_inspect_the_response_object.py)
$ uv run python 04_inspect_the_response_object.py
Calling gpt-5.6-sol ...
type(response) : AIMessage
response.type : ai
response.text[:80] : 1. Headline: From newspaper boy in Rameswaram to India's "Missile Man" and Presi...
response.tool_calls : []
usage_metadata : {'input_tokens': 412, 'output_tokens': 386, 'total_tokens': 798}
response_metadata keys: ['id', 'created_at', 'model', 'status', 'model_provider', 'model_name']
model_name : gpt-5.6-sol
response.id : resp_0a1b2c3d4e5f
content is a : list (Responses-API content blocks) — that's why we use .text
Zero-Code Observability with LangSmith Tracing#
Revision Notes#
Configuration: .env (automatically instruments scripts 02, 03, and 04)
Concept#
Debugging LLM apps with print() statements quickly becomes unmanageable once prompts grow or chains gain multiple steps. Observability lets you inspect the exact prompt sent, the latency of every step, and the token cost — and LangChain enables this natively with LangSmith via three environment variables (LANGSMITH_TRACING=true, LANGSMITH_API_KEY, LANGSMITH_PROJECT) and zero Python code changes.
What a Trace Shows#
- Top-level
RunnableSequencetrace: Groups the entirechain.invoke()execution as one timeline. - Child Step 1 —
PromptTemplate: Displays the exact rendered prompt after{information}substitution, so you can verify what the model actually saw. - Child Step 2 —
ChatOpenAI/ChatOllama: Records latency, input/output token counts, estimated cost, and raw response metadata. - Provider-agnostic comparison: Works identically for OpenAI, Groq, and local Ollama runs, allowing side-by-side quality and latency benchmarking.
Enabling LANGSMITH_TRACING=true in .env automatically instruments every Runnable step without modifying application code, capturing the exact rendered prompt alongside AIMessage token usage, latency, and provider metadata.
How All Building Blocks Connect#
Revision Notes#
- Safe Configuration (
01,sample.env.example):load_dotenv()injects secrets and model overrides from.envintoos.environwithout hardcoding credentials. - Composable Pipelines (
02):PromptTemplate | ChatModelcreates aRunnableSequencethat cleanly separates prompt structure from runtime input (sample_data.py). - Provider Abstraction (
03): Because every chat model shares theRunnableinterface, swappingChatOpenAIforChatOllama(or rerouting to Groq viaOPENAI_BASE_URL) leaves the rest of the pipeline unchanged. - Structured Responses & Agent Readiness (
04): Every call returns anAIMessagecarrying.text, standardizedusage_metadata, providerresponse_metadata, andtool_calls— preparing you directly for tool-calling agents. - Observability (LangSmith): Flipping
LANGSMITH_TRACING=truein.envturns on full prompt, latency, and token visibility without touching code.
Quick Self-Check Questions#
Self-Check Questions#
Why should load_dotenv() run before initializing LangChain models, and what wins if a variable is already exported in your shell?
It populates os.environ so SDKs automatically discover OPENAI_API_KEY and LANGSMITH_*. Already-exported shell variables win over .env by default.
What does the pipe operator (prompt | llm) create in LangChain?
A RunnableSequence (LCEL chain) where calling .invoke({...}) feeds the rendered prompt directly into the chat model.
Why should you read response.text instead of response.content?
Newer OpenAI models using the Responses API can return .content as a list of content blocks; .text always returns a plain string across all providers.
Why does switching from OpenAI to local Ollama only take one line of code, and what trade-off do you make with a tiny local model like gemma3:270m?
Both ChatOpenAI and ChatOllama implement LangChain's Runnable interface. Tiny local models are free, private, and offline, but have weaker instruction-following and formatting reliability than larger local or cloud models.
What is the difference between response.usage_metadata and response.response_metadata on an AIMessage?
usage_metadata gives standardized, provider-independent token counts (input_tokens, output_tokens, total_tokens), whereas response_metadata contains raw provider-specific fields (like OpenAI's status vs. Ollama's total_duration).
How do you enable LangSmith tracing across all scripts without changing Python code?
Set LANGSMITH_TRACING=true, LANGSMITH_API_KEY, and LANGSMITH_PROJECT in .env.