DEV Community

Amit Verma
Amit Verma

Posted on Originally published at tayloramitverma.com on

LangChain for JS Developers: Models, Prompts, Memory & Chains

What is LangChain?

LangChain is an open-source framework for building applications powered by Large Language Models (LLMs). Think of it as the Express.js of the AI world — it does not do the heavy lifting itself, but it gives you clean abstractions and composable tools to build fast.

Without LangChain, integrating an LLM into your app means writing a lot of boilerplate: formatting prompts, parsing responses, managing conversation history, and chaining multiple calls together. LangChain handles all of that out of the box.

"LangChain is not about replacing the AI model. It's about connecting your data, your logic, and your LLM — elegantly."

# Install core packages
npm install @langchain/core @langchain/openai langchain

# Or if using Claude (Anthropic)
npm install @langchain/anthropic
Enter fullscreen mode Exit fullscreen mode

1. Models

In LangChain, a model is a wrapper around an LLM API. You initialise it once and reuse it everywhere. LangChain supports OpenAI (GPT-4o), Anthropic (Claude), Google (Gemini), and many more — all sharing the same interface.

import { ChatOpenAI } from "@langchain/openai"
import { ChatAnthropic } from "@langchain/anthropic"

// OpenAI GPT-4o
const openai = new ChatOpenAI({
  model: "gpt-4o",
  temperature: 0.7, // 0 = deterministic, 1 = creative
  maxTokens: 1000,
})

// Claude (Anthropic)
const claude = new ChatAnthropic({
  model: "claude-sonnet-4-20250514",
  temperature: 0,
})

// Just call .invoke() to get a response
const response = await openai.invoke("What is RAG in one sentence?")
console.log(response.content)
Enter fullscreen mode Exit fullscreen mode

Pro tip — model swapping

  • All LangChain models share the same .invoke() interface
  • You can switch from OpenAI to Claude by just changing the import and class name
  • Great for cost optimisation — use cheap models for simple tasks, powerful ones for complex ones

The key benefit is model-agnostic code. You can swap from OpenAI to Claude by changing just one import and class name — your business logic stays untouched. This is great for cost optimisation: use cheaper models for simple tasks and powerful ones for complex reasoning.

2. Prompts & Output Parsers

Raw strings are fragile. LangChain's Prompt Templates let you define reusable prompt structures with typed variables, system roles, and few-shot examples. Think of them as template literals — but type-safe and composable.

import { ChatPromptTemplate } from "@langchain/core/prompts"

// Define a reusable prompt with variables
const prompt = ChatPromptTemplate.fromMessages([
  ["system", "You are a {role} expert. Be concise and practical."],
  ["user", "Explain {topic} in simple words."]
])

// Format the prompt with actual values
const formatted = await prompt.formatMessages({
  role: "Node.js",
  topic: "event loop"
})

// Or pipe directly to the model
const chain = prompt.pipe(openai)
const result = await chain.invoke({
  role: "React",
  topic: "useEffect"
})
Enter fullscreen mode Exit fullscreen mode

Output Parsers take that raw LLM string response and convert it into structured, typed data. Using Zod schemas, you can extract objects, arrays, and enums directly from the model response — no manual string parsing needed.

import { StructuredOutputParser } from "langchain/output_parsers"
import { z } from "zod"

// Define the shape of the output using Zod
const parser = StructuredOutputParser.fromZodSchema(
  z.object({
    summary: z.string().describe("Brief summary"),
    keyPoints: z.array(z.string()).describe("Top 3 key points"),
    difficulty: z.enum(["beginner", "intermediate", "advanced"])
  })
)

const prompt = ChatPromptTemplate.fromMessages([
  ["system", "Analyze the given concept.\n{format_instructions}"],
  ["user", "{concept}"]
])

const chain = prompt.pipe(openai).pipe(parser)

const result = await chain.invoke({
  concept: "RAG in AI",
  format_instructions: parser.getFormatInstructions()
})

// result is now a typed object, not a raw string!
console.log(result.summary) // string
console.log(result.keyPoints) // string[]
console.log(result.difficulty) // "beginner" | "intermediate" | "advanced"
Enter fullscreen mode Exit fullscreen mode

3. Memory

LLMs are stateless by default. Every API call is independent — the model has no memory of what you said before. LangChain's Memory module fixes this by storing conversation history and automatically injecting it into each new request.

import { ConversationChain } from "langchain/chains"
import { BufferMemory } from "langchain/memory"
import { ChatOpenAI } from "@langchain/openai"

const model = new ChatOpenAI({ model: "gpt-4o" })

const memory = new BufferMemory({
  returnMessages: true, // return as message objects
  memoryKey: "history" // variable name in the prompt
})

const chain = new ConversationChain({ llm: model, memory: memory })

// First message
const r1 = await chain.call({ input: "My name is Arjun." })
console.log(r1.response) // "Nice to meet you, Arjun!"

// Second message — model REMEMBERS the name
const r2 = await chain.call({ input: "What is my name?" })
console.log(r2.response) // "Your name is Arjun." ✅

// Inspect stored memory
const history = await memory.loadMemoryVariables({})
console.log(history)
Enter fullscreen mode Exit fullscreen mode

There are three main memory types. Buffer Memory stores the full conversation — simple but costly for long sessions. Window Memory keeps only the last N messages. Summary Memory compresses old messages into a summary — ideal for very long conversations.

4. Chains

A chain is a sequence of steps where the output of one step becomes the input of the next. This is LangChain's core idea — composing small, reusable pieces into powerful AI pipelines using the pipe operator.

LangChain Expression Language (LCEL) makes this clean and readable: prompt | model | parser. Chains also support streaming out of the box — perfect for chat UIs that render responses word by word, pairing naturally with Next.js streaming routes.

Simple Chain (LCEL)

LCEL (LangChain Expression Language) uses the | pipe syntax to compose chains. It's clean, readable, and supports streaming out of the box.

import { ChatOpenAI } from "@langchain/openai"
import { ChatPromptTemplate } from "@langchain/core/prompts"
import { StringOutputParser } from "@langchain/core/output_parsers"

const model = new ChatOpenAI({ model: "gpt-4o" })
const parser = new StringOutputParser()

const prompt = ChatPromptTemplate.fromMessages([
  ["system", "You are a senior {language} developer. Give practical advice."],
  ["user", "{question}"]
])

// The pipe operator — connects all pieces
const chain = prompt.pipe(model).pipe(parser)

const answer = await chain.invoke({
  language: "TypeScript",
  question: "When should I use generics?"
})

console.log(answer) // plain string response
Enter fullscreen mode Exit fullscreen mode

Sequential Chain

You can chain multiple LLM calls together, where each step's output feeds into the next. Useful for multi-step reasoning like summarize → translate → format.

import { RunnableSequence } from "@langchain/core/runnables"

const summarizePrompt = ChatPromptTemplate.fromMessages([
  ["user", "Summarize this in 3 bullet points:\n{text}"]
])

const translatePrompt = ChatPromptTemplate.fromMessages([
  ["user", "Translate to Hindi:\n{summary}"]
])

// Step 1: summarize → Step 2: translate
const pipeline = RunnableSequence.from([
  summarizePrompt,
  model,
  new StringOutputParser(),
  (summary) => ({ summary }), // pass to next prompt
  translatePrompt,
  model,
  new StringOutputParser()
])

const result = await pipeline.invoke({
  text: "LangChain is a framework for building LLM applications..."
})

console.log(result) // Hindi translation of the summary
Enter fullscreen mode Exit fullscreen mode

Streaming Responses

One of LangChain's best features — built-in streaming. Perfect for chat UIs where you want the response to appear word by word, like ChatGPT does.

// Stream tokens as they're generated
const stream = await chain.stream({
  language: "Node.js",
  question: "How do I handle async errors properly?"
})

// Works perfectly with Express SSE or Next.js streaming
for await (const chunk of stream) {
  process.stdout.write(chunk) // prints word by word
}

// In a Next.js API route with SSE (your area of expertise!)
export async function POST(req: Request) {
  const stream = await chain.stream(await req.json())
  return new Response(ReadableStream.from(stream))
}
Enter fullscreen mode Exit fullscreen mode

Where to go next

Once you are comfortable with Models, Prompts, Memory, and Chains, the natural next step is RAG (Retrieval-Augmented Generation) — connecting LangChain to your own data using vector databases like ChromaDB or Pinecone. That is where most real-world AI products live.

The full LangChain JS documentation is available at js.langchain.com — well-structured and full of TypeScript examples to get you started quickly.


Originally published at www.tayloramitverma.com.

Top comments (0)