LangChain Essentials

Generative & Agentic AI · Agent Frameworks & Protocols · Intermediate · 24 min

Know what LangChain gives you and when to skip it: chat models on Amazon Bedrock, prompt templates, parsers and structured output, composing steps with the pipe, retrievers, tools and create_agent, plus tracing.

A row of kitchen machines joined by conveyor belts: a recipe card goes in, a dough mixer, an oven and a slicer each do one job, and a loaf comes out. Swap the oven for a different brand and the belts still fit.

The idea in everyday words

Think of LEGO. You could carve every toy from a block of wood (call the model API yourself), or snap together standard bricks that all share the same studs. LangChain is the box of bricks for LLM apps: a prompt brick, a model brick, a parser brick, a retriever brick. Every brick has the same connector, so any brick can plug into the next one. For a single small toy, carving is faster than opening the box.

What LangChain is, and when not to use it

LangChain is an open-source framework (Python and JavaScript) for building apps on top of LLMs. It gives you standard building blocks with one shared interface, plus integrations with hundreds of model providers, vector stores and tools.

It is really a family of packages:

Package What is inside
langchain-core the base pieces: messages, prompt templates, output parsers, the Runnable interface and the pipe
langchain the high-level parts, most importantly create_agent
langchain-aws the AWS integration: Bedrock chat models, Knowledge Bases retrievers and more
langgraph the low-level engine for stateful agents (next lesson); LangChain's agents run on it
langchain-classic older chains and helpers kept for existing code
LangSmith a hosted service (not a library) for tracing, evaluation and prompt testing

Why teams use it: swapping a model is one line, the same code works for many providers, and you get retries, streaming, batching, structured output and tracing without writing them.

When NOT to use a framework:

Situation Better choice
One model call in a Lambda function (summarise this ticket) Call the Bedrock Converse API with boto3. Fewer moving parts.
A standard agent you want AWS to run and manage Amazon Bedrock Agents (configure, do not code the loop)
You want an AWS-built, code-first agent SDK Strands Agents
You need to debug every token and cannot afford hidden prompts Your own small loop (see Build a ReAct Agent from Scratch)

The costs of any framework: an extra layer between you and the API, fast-moving versions (check the docs for the version you install), and error messages that point into library code. Key idea: use a framework when it removes code you would otherwise write and test; skip it when your app is one call.

Chat models and messages on Amazon Bedrock

A chat model in LangChain is an object that takes a list of messages and returns a message. Every provider's model has the same methods: invoke (one call), stream (tokens as they arrive), batch (many inputs at once), and async versions (ainvoke).

For Amazon Bedrock, install langchain-aws and use ChatBedrockConverse, which talks to the Bedrock Converse API (the docs recommend it unless you use custom models). Credentials come from the normal AWS chain: an IAM role in Lambda, ECS or AgentCore, or your local profile. You also need access to the model in your account and Region.

from langchain_aws import ChatBedrockConverse
from langchain.messages import SystemMessage, HumanMessage

model = ChatBedrockConverse(
    model_id="<a Bedrock model id or inference profile id>",
    region_name="us-east-1",
    temperature=0,
)

reply = model.invoke([
    SystemMessage("You answer in one short sentence."),
    HumanMessage("Why is the sky blue?"),
])
print(reply.content)          # the text
print(reply.usage_metadata)   # input_tokens, output_tokens, total_tokens

The same model from a string, handy for config files:

from langchain.chat_models import init_chat_model
model = init_chat_model("<bedrock model id>", model_provider="bedrock_converse")

Messages can also be plain dicts: {"role": "user", "content": "Hi"}. The reply is an AIMessage with .content, .tool_calls (empty unless the model asked for a tool) and .usage_metadata.

Key idea: a chat model is just "messages in, message out" behind a standard interface. Changing from one Bedrock model to another, or to another provider, does not change the rest of your code.

Prompt templates, parsers and structured output

A prompt template is a message list with blanks. You fill the blanks with a dict of variables.

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a support assistant for ShopCo."),
    ("human", "Context:\n{context}\n\nQuestion: {question}"),
])
prompt.invoke({"context": "Refunds take 5 days.", "question": "How long do refunds take?"})

If a variable is missing from the dict, filling the template raises an error. That is a feature: a prompt that silently says "{question}" to the model is a bug you would never notice.

An output parser turns the model's message into something your code can use. StrOutputParser returns just the text. A JSON parser turns the text into a dict. Models often wrap JSON in a markdown code fence (three backticks and the word json), so a good parser strips the fence before parsing:

import json

fence = "`" * 3
reply = fence + 'json\n{"answer": "5 days"}\n' + fence
text = reply.strip()
if text.startswith(fence):
    text = text.split("\n", 1)[1].rsplit(fence, 1)[0]
print(json.loads(text)["answer"])

Parsing free text is fragile. The more reliable way is structured output: give the model a schema and let it fill it. LangChain does this with with_structured_output, which uses the provider's tool calling or native structured output under the hood and hands you a validated object:

from pydantic import BaseModel, Field

class Ticket(BaseModel):
    category: str = Field(description="billing, shipping or other")
    urgent: bool

tagger = model.with_structured_output(Ticket)
ticket = tagger.invoke("I was charged twice and I need the money back today!")
print(ticket.category, ticket.urgent)   # billing True

Key idea: fail loudly on a bad template, and prefer a schema over "please reply in JSON".

Composing a chain: the pipe and Runnables

Every building block (prompt, model, parser, retriever) is a Runnable: it has invoke, batch and stream. The pipe operator | joins two Runnables into a new Runnable whose output flows into the next one. This style is called LCEL (LangChain Expression Language).

from langchain_core.output_parsers import StrOutputParser

chain = prompt | model | StrOutputParser()
chain.invoke({"context": "...", "question": "How long do refunds take?"})
chain.batch([{...}, {...}])           # many inputs, run concurrently
for piece in chain.stream({...}):     # stream the answer token by token
    print(piece, end="")

How does | work? Python lets a class define what a | b means. Here is the whole trick in plain Python:

class Step:
    def __init__(self, fn):
        self.fn = fn
    def __or__(self, other):          # a | b  makes a new Step
        return Step(lambda x: other.fn(self.fn(x)))
    def invoke(self, x):
        return self.fn(x)

prompt = Step(lambda d: "Q: " + d["question"])
model = Step(lambda p: "A: 5 days (you asked '" + p + "')")
parser = Step(lambda m: m.split(" (")[0])
chain = prompt | model | parser
print(chain.invoke({"question": "How long do refunds take?"}))

Retrievers are Runnables too: text in, a list of documents out. For a Bedrock Knowledge Base:

from langchain_aws.retrievers import AmazonKnowledgeBasesRetriever
from langchain_core.runnables import RunnablePassthrough

retriever = AmazonKnowledgeBasesRetriever(
    knowledge_base_id="<your KB id>",
    retrieval_config={"vectorSearchConfiguration": {"numberOfResults": 4}},
)

def join_docs(docs):
    return "\n\n".join(d.page_content for d in docs)

rag_chain = (
    {"context": retriever | join_docs, "question": RunnablePassthrough()}
    | prompt | model | StrOutputParser()
)
rag_chain.invoke("How long do refunds take?")

The dict at the front runs both branches on the same input (the question): one fetches and joins documents, the other passes the question through. Their outputs become the variables the prompt needs. A plain function in a chain (like join_docs) is wrapped into a Runnable for you.

The order of steps is the contract: each step's output must be what the next step expects. A dict must reach the prompt, text must reach the model, a message must reach the parser. Key idea: a chain is a pipeline of small functions with one shared interface, so you can test, swap and reuse each piece. If any step raises, the whole chain stops there.

Tools, the agent entry point and tracing

A tool is a function the model may ask you to run. The decorator reads the function name, the docstring (the description the model sees) and the type hints (the input schema):

from langchain.tools import tool

@tool
def order_status(order_id: str) -> str:
    """Look up the delivery status of an order, for example A1."""
    return {"A1": "delivered on 2 Nov"}.get(order_id, "unknown order")

with_tools = model.bind_tools([order_status])
msg = with_tools.invoke("Where is order A1?")
print(msg.tool_calls)   # [{"name": "order_status", "args": {"order_id": "A1"}, "id": "...", ...}]

bind_tools only lets the model ask. Your code must run the tool and send the result back. The loop that does this for you is an agent. In LangChain 1.x the entry point is create_agent, which replaced the older create_react_agent from langgraph.prebuilt and runs on LangGraph:

from langchain.agents import create_agent

agent = create_agent(
    model=model,                      # or a "provider:model" string
    tools=[order_status],
    system_prompt="You are ShopCo's support assistant. Be brief.",
)
result = agent.invoke({"messages": [{"role": "user", "content": "Where is order A1?"}]})
print(result["messages"][-1].content)

It also takes response_format (a schema, and the result lands in result["structured_response"]), a checkpointer for memory across turns (with a thread_id in the config), and middleware (prebuilt hooks such as human approval for tool calls, conversation summarisation, retries).

Tracing with LangSmith. Set two environment variables and every chain and agent run is recorded as a trace (each step's inputs, outputs, tokens and latency): LANGSMITH_TRACING=true and LANGSMITH_API_KEY=.... On AWS you can also send OpenTelemetry traces to CloudWatch through AgentCore Observability.

On AWS: run the chain in Lambda or ECS, or host an agent on Amazon Bedrock AgentCore Runtime; models come from Amazon Bedrock (ChatBedrockConverse), documents from Bedrock Knowledge Bases (AmazonKnowledgeBasesRetriever), secrets in Secrets Manager. Elsewhere: LlamaIndex and Haystack are similar open-source frameworks; Semantic Kernel (Azure) and Google's Agent Development Kit (GCP) fill the same role; LangChain.js (@langchain/core, @langchain/aws) has the same ideas for JavaScript.

Key idea: tools let the model ask, the agent loop does the asking and answering for you, and tracing shows you what really happened.

Step by step

  1. The input:

    The chain gets a dict: {question: "How long do refunds take?"}. Steps: retrieve (k = 2) → prompt → model → parse_json. Each step's output becomes the next step's input.

  2. Retrieve:

    Question words: how, long, do, refunds, take. "Refunds take 5 days." shares refunds + take (score 2). "Shipping is free over $50." shares nothing (0, dropped). "Refunds go to the original card." shares refunds (1). Keep the top 2 and add them to a NEW dict as context.

  3. Fill the template:

    The template has {context} and {question}. Both are in the dict, so every blank is filled. Had one been missing, the chain would stop here with "missing variable".

  4. The model replies:

    The (fake) model gets the prompt text and replies with JSON wrapped in a code fence: three backticks, json, the object, three backticks.

  5. Parse:

    The parser strips the fence and parses {"answer": "5 days"}. It is an object, so the chain returns it, together with a trace of every step's output.

  6. When it breaks:

    If the model had said "Sure! Refunds take 5 days.", parsing fails: the chain stops at step 3 with "invalid JSON" and the trace shows exactly which step broke. A schema (with_structured_output) avoids this.

Code example

# A tiny chain composer: the idea behind LangChain's prompt | model | parser.
# The "model" is fake so this runs anywhere; swap in ChatBedrockConverse for real.
import json

def pipe(*steps):
    def run(value):
        for step in steps:
            value = step(value)  # each step's output is the next step's input
        return value
    return run

def template(text):
    def fill(variables):
        return text.format(**variables)  # raises KeyError if a variable is missing
    return fill

def fake_model(prompt):
    if "JSON" in prompt:
        return '```json\n{"answer": "5 days"}\n```'
    return "Refunds take about 5 days."

def json_parser(reply):
    text = reply.strip()
    if text.startswith("```"):
        text = text.split("\n", 1)[1].rsplit("```", 1)[0]
    return json.loads(text)

chain = pipe(template("Q: {question}\nReply as JSON with the key answer."), fake_model, json_parser)
print(chain({"question": "How long do refunds take?"}))

# Chains are steps too, so they compose:
short_answer = pipe(chain, lambda d: d["answer"])
print(short_answer({"question": "How long do refunds take?"}))

# A missing variable stops the chain at the template, loudly:
try:
    chain({"q": "typo in the key"})
except KeyError as e:
    print("chain stopped: missing variable", e)

Complexity

  • Time: O(total text size): each step reads its input once; the retriever scores every doc against the question's words
  • Space: O(total text size) for the trace of every step's output

Interview tips

  • When would you use LangChain, and when would you call the Bedrock Converse API directly? Give a concrete example of each.

  • Explain LCEL: what a Runnable is, what the pipe does, and how a dict of Runnables at the start of a chain works (a RAG chain is the classic example).

  • How do you get reliable JSON out of a model? Compare asking in the prompt plus a parser, with_structured_output, and validating with a schema.

  • What is the difference between bind_tools and create_agent? Who runs the tool in each case?

  • How would you debug a chain that gives wrong answers in production? (Tracing with LangSmith or OpenTelemetry, a fake model in unit tests, checking each step's output.)

Challenge: Run a tiny chain

Build the core of a chain runner. run_chain(steps, inputs) runs the steps in order: the output of each step is the input of the next.

Each step is a dict with an "op":

op input does error (stop the chain)
"retrieve" a dict with "question" scores each text in step["docs"] by how many distinct question words it shares (lower-case, words are runs of a-z / 0-9), drops scores of 0, keeps the best step["k"] (ties keep the docs' order), and returns a new dict: the input plus step["into"] = the kept docs joined with "\n" "missing variable: question"
"prompt" a dict replaces every {name} in step["template"] with str(value[name]) not a dict: "prompt needs an object"; a name missing: "missing variable: <name>" (the first missing one in the template)
"model" a string (the prompt) a fake model: returns step["reply"] not a string: "model needs a prompt string"
"parse_json" a string strips spaces; if it starts with a code fence (three backticks) drops the first line and a closing fence; parses JSON not valid JSON: "invalid JSON"; valid but not an object: "expected a JSON object"

Any other op: "unknown step: <op>".

Return {"output": final_value, "trace": [output of each step]}. At the first error, stop and return {"error": message, "at": step_index, "trace": [outputs before it]}.

run_chain([{"op": "prompt", "template": "Say hi to {name}"},
           {"op": "model", "reply": '{"text": "Hi Ada!"}'},
           {"op": "parse_json"}], {"name": "Ada"})
# → {"output": {"text": "Hi Ada!"},
#    "trace": ["Say hi to Ada", '{"text": "Hi Ada!"}', {"text": "Hi Ada!"}]}

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Agent Frameworks & Protocols

Previous: Multi-Agent Systems · Next: LangGraph: Agents as Graphs