# LangChain | Part 1/3 of Generative AI for JS Developers

# Introduction

LangChain is one of the frameworks that stands at the forefront in building applications that use large language models (LLMs).

Initially, it was gaining traction in Python ecosystem, but now it has equally good support in JavaScript and TypeScript, making it suitable for Node.js and even browser applications.

In this article, we’ll deep dive with JavaScript developers for an overview of LangChain, detailing its concepts, use cases and providing code snippets to help you get started.

# What is LangChain?

LangChain is a framework that focuses on building applications with LLMs more efficiently. Rather than the traditional way of calling a model with a prompt, LangChain provides a set of abstractions and utilities to:

* Manage prompts effectively
    
* Chain multiple calls and logic together
    
* Integrate with external APIs and data sources
    
* Enable memory (context persistence)
    
* Build production-ready applications like chatbots, agents, and knowledge retrieval systems
    

Think of LangChain as the **middleware between your application and LLM APIs (like OpenAI, Anthropic, or Hugging Face).**

If you’re a NodeJS developer, think of LangChain as ExpressJS for LLMs.

# Installing LangChain

To start with LangChain in JavaScript/TypeScript:

```bash
npm install langchain openai

# Optionally, install other integrations as needed:
npm install @pinecone-database/pinecone @azure/storage-blob
```

# Basic Usage

## Example: Calling OpenAI with LangChain

```typescript
import { ChatOpenAI } from 'langchain/chat_models/openai';
import { HumanMessage } from 'langchain/schema';

const model = new ChatOpenAI({
  openAIApiKey: process.env.OPENAI_API_KEY,
  temperature: 0.7,
});

async function run() {
  const response = await model.call([new HumanMessage('Write a short poem about JavaScript.')]);
  console.log(response.content);
}

run();
```

Here’s what’s happening:

* `ChatOpenAI` is a wrapper for OpenAI’s GPT models.
    
* `HumanMessage` represents user input.
    
* The model call returns a structured response object.
    

# Chains

Chains allow you to link together multiple components (LLMs, prompts, tools, APIs) into a pipeline.

## Example: Simple LLMChain

```typescript
import { ChatOpenAI } from 'langchain/chat_models/openai';
import { PromptTemplate } from 'langchain/prompts';
import { LLMChain } from 'langchain/chains';

const model = new ChatOpenAI({ openAIApiKey: process.env.OPENAI_API_KEY });

const prompt = new PromptTemplate({
  template: 'Translate the following text to French: {text}',

  inputVariables: ['text'],
});

const chain = new LLMChain({ llm: model, prompt });

async function run() {
  const res = await chain.call({ text: 'Hello, how are you?' });
  console.log(res.text);
}

run();
```

* `PromptTemplate` defines a reusable structured prompt.
    
* `LLMChain` executes the template + LLM as a single unit.
    

# Memory

LLMs don’t remember past interactions by default. LangChain provides **memory modules** to maintain context.

## Example: Conversation with Memory

```typescript
import { ConversationChain } from 'langchain/chains';
import { ChatOpenAI } from 'langchain/chat_models/openai';
import { BufferMemory } from 'langchain/memory';

const model = new ChatOpenAI({
  openAIApiKey: process.env.OPENAI_API_KEY,
  temperature: 0,
});

const memory = new BufferMemory();

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

async function run() {
  await chain.call({ input: 'Hi, I’m Utkarsh.' });
  const res = await chain.call({ input: 'What’s my name?' });
  console.log(res.response);
}

run();
```

Here, `BufferMemory` stores previous interactions, so the model can recall “Utkarsh.”

# Retrieval and Vector Stores

LangChain enables connecting LLMs with **external knowledge bases** using embeddings and vector databases (like Pinecone, Weaviate, or Chroma).

## Example: Simple Retrieval

```typescript
import { OpenAIEmbeddings } from 'langchain/embeddings/openai';
import { MemoryVectorStore } from 'langchain/vectorstores/memory';

const embeddings = new OpenAIEmbeddings({ openAIApiKey: process.env.OPENAI_API_KEY });

async function run() {
  const store = await MemoryVectorStore.fromTexts(
    [
      'JavaScript is a versatile programming language.',
      'LangChain helps connect LLMs with data.',
      'Node.js allows running JS on the server.',
    ],
    ['JS', 'LangChain', 'Node'],
    embeddings
  );

  const result = await store.similaritySearch('What is LangChain?', 1);
  console.log(result);
}

run();
```

This creates embeddings for your documents and enables semantic search.

# Agents

Agents are LLM-powered decision makers. They choose which tools to use (APIs, functions, search engines) to answer a query.

## Example: Simple Tool-Using Agent

```typescript
import { initializeAgentExecutorWithOptions } from 'langchain/agents';
import { ChatOpenAI } from 'langchain/chat_models/openai';
import { SerpAPI } from 'langchain/tools';

const model = new ChatOpenAI({ openAIApiKey: process.env.OPENAI_API_KEY });

const tool = new SerpAPI(process.env.SERPAPI_API_KEY);

async function run() {
  const executor = await initializeAgentExecutorWithOptions(
    [tool],
    model,
    { agentType: 'chat-zero-shot-react-description' }
  );

  const result = await executor.call({ input: 'What’s the weather in New York today?' });
  console.log(result.output);
}

run();
```

Here, the agent dynamically decides to use the **SerpAPI** search tool to fetch live information.

# Popular Use Cases for JS Developers

* **Chatbots & Virtual Assistants** – with context memory and API access
    
* **Document Q&A** – retrieve answers from PDFs, docs, or knowledge bases
    
* **Code Generation** – build AI coding assistants
    
* **Workflow Automation** – LLM + tools for dynamic workflows
    
* **Customer Support Bots** – integrate with CRM and ticketing systems
    

# Best Practices

* **Prompt Engineering** – Define clear, structured prompts.
    
* **Control Costs** – Use smaller models where possible and cache results.
    
* **Security** – Validate and sanitize user input to avoid prompt injection.
    
* **Observability** – Log requests and responses for debugging.
    
* **Deploy with Edge Functions** – LangChain works well in serverless contexts like Vercel and Cloudflare Workers.
    

# Conclusion

LangChain is a powerful framework that helps JavaScript developers move beyond simple LLM calls to build **scalable, production-ready AI applications.** Whether you’re creating a chatbot, knowledge retrieval system, or autonomous agent, LangChain provides the abstractions and integrations you need.

With LangChain, JavaScript developers can transform LLMs from simple text generators into **intelligent, multi-functional applications.**

## **Next steps:**

* Explore LangChain.js docs
    
* Experiment with different chains and memory modules
    
* Try integrating with vector databases like Pinecone or Weaviate
    
* Build your own agent with custom tools
