Back to blog
Guides & Tutorials

Basics of Langchain

Basics of Langchain blog cover image
Large Language Model
GenAI
Langchain
Burhanuddin Nahargarwala
Key takeaways
  • The blog contains the journey of ChatGPT, and what are the limitations of ChatGPT, due to which Langchain came into the picture to overcome the limitations and help us to create applications that can solve our real-time queries

I asked ChatGPT a business-specific question, and unfortunately, it couldn’t provide a satisfactory answer. Wondering why?

Let’s pose a question to ChatGPT: “List all products with limited stocks.“

The response is vague and unsatisfactory. But why is that? What other options do we have other than ChatGPT that can help us? Let’s explore all possibilities, starting with understanding ChatGPT:

The GenAI Revolution and ChatGPT: A Prelude

In the dynamic realm of GenAI, one name stands out: ChatGPT. A familiar companion in our digital interactions, ChatGPT is where we turn with our lots of questions, expecting precise and informed answers. Its understanding of context became unparalleled, enabling it to seamlessly navigate complex conversations with users. It could effortlessly switch between topics, understand humor, and adapt its tone to match the preferences of its questioner. So don’t underestimate the power of common GPT, I mean ChatGpt.

When we ask a question to ChatGPT, instead of directly passing it to ChatGPT, it is first converted into tokens via a tokenizer.

Large Language Models receive a text as input and generate a text as output. However, being statistical models, they work much better with numbers than text sequences. That’s why every input to the model is processed by a tokenizer, before being used by the core model.

A token is a chunk of text consisting of a variable number of characters, so the tokenizer’s main task is splitting the input into an array of tokens. Then, each token is mapped to a token index, which is the integer encoding of the original text chunk. Click here to see how the text gets converted into tokens.

Challenges come in the situation when the inquiries are not just general but deeply rooted in specific contexts, like queries related to an e-commerce business, real-time queries, etc.

Imagine you’ve launched an e-commerce venture. Your goal is to offer an unparalleled customer experience with instant query resolution. But can ChatGPT, a generalist in its intelligence, be able to handle the business-specific questions that come its way?

We just saw that it’s not that efficient. Why? ChatGPT, despite its brilliance, is a general-purpose model. It’s designed for broad queries and not context-specific questions critical to your business. This is where LangChain enters, a superhero with the powers to solve specialized queries 🤽.

Introduction to LangChain

LangChain is the bridge that connects ChatGPT’s general intelligence with the specific needs of your context. It empowers ChatGPT to access external tools, from Wikipedia and search engines to databases, CSV files, and documents.

With LangChain, you can feed ChatGPT the context it needs. Imagine ChatGPT, now equipped with LangChain, being able to pull data from your business database or analyze customer trends from a CSV file. Suddenly, the answers become tailored, precise, and contextually aware.

Developers around the globe have harnessed the power of LangChain and Streamlit to build exceptional chatbots. Take a look at this remarkable example and see how LangChain elevates ChatGPT to new heights.

LangChain is not just a tool; it’s a revolutionary framework transforming the way we interact with Large Language models (LLMs). At its heart, LangChain allows us to orchestrate complex AI tasks with remarkable simplicity and efficiency. Let’s unpack the key components that make LangChain a game-changer in the world of AI.

Imagine LangChain as a sophisticated puzzle, where each piece is a component that, when connected, forms a more powerful and complex AI application. This “chaining” is what gives LangChain its unique ability to handle advanced use cases involving LLMs. Chains may consist of multiple components from several modules:

  1. Prompt Templates: Prompt templates are templates for different types of prompts. Like “chatbot” style templates, ELI5 (Explain Like I’m 5) question-answering, etc
  2. LLMs: Large language models like GPT-3, Google PaLM 2, Llama 2, etc
  3. Chains: Chains in LangChain are used to execute a sequence of commands that involves LLMs.
  4. Agents: Agents use LLMs to decide what actions should be taken. Tools like web search or calculators can be used, and all are packaged into a logical loop of operations.
  5. Memory: Short-term memory, long-term memory.

LLMs:

In LangChain, there are broadly two types of large language models (LLMs). Let’s understand it via the given image:

  1. The first model is LLM, which is designed to process and generate language based on string inputs and outputs.
  2. ChatModels in LangChain are more complex and designed to handle conversational contexts. The input for a ChatModel is a list of ChatMessages, not just a single string. The output of a ChatModel is a single ChatMessage, which is the model’s response to the ongoing conversation.

A chat message has two required components:

  1. content: This is the content of the message.
  2. role: This is the role of the entity from which the chat message is coming from.

Create an LLM object

Step 1: Install LangChain

First, you’ll need to install the LangChain library. You can do this by running the following command in your Python environment:

!pip install langchain

Using LangChain will usually require integrations with one or more model providers, data stores, APIs, etc. For this example, we’ll use OpenAI’s model APIs. You can go with other models also, such as HuggingFace, Llama, etc.

Step 2: Install OpenAI Python Package

Next, install the OpenAI Python package, which will allow you to interact with OpenAI’s API:

! pip install openai==0.27.9

Step 3: Obtain OpenAI API Key

To use OpenAI’s models, you’ll need an API key. Follow these steps to get one:

  1. Create/Open OpenAI account:
  • If you don’t already have an OpenAI account, create one.
  • Visit OpenAI’s website and sign up or log in. 2. Generate API Key:
  1. Once logged in, navigate to the API section, where you can generate a new API key.
  2. Follow the on-screen instructions to create a key.
  3. Free Credit for New Users:
  4. As a new user, you’ll typically receive free credits to get started. This allows you to experiment with the API without incurring an initial cost.

After setting up LangChain and obtaining your OpenAI API key, you can start using LangChain with OpenAI’s LLMs.

Let’s import the OpenAI class from the langchain package:

from langchain.llms import OpenAI
import os

# First export the OPENAI_API_KEY in environment variable
Os.environ["OPENAI_API_KEY"] = " sk-XXXX"

# Create LLM model
llm = OpenAI()
llm('Python is founded by whom and in which year?')

o/p: '\n\nPython was founded by Guido van Rossum in 1991.'

This is how it worked. The input that we passed is a single string, and as an output, we got a string.

OpenAI has two important parameters that are:

  1. temperature: It controls the randomness and creativity of the model’s output. Its value ranges from 0 to 1.
  2. The low temperature (close to 0) results in more deterministic, predictable, and conservative outputs, suitable for tasks where consistency and accuracy are more important than creativity. Example: A temperature of 0.1 might be used for factual data retrieval or business analytics.
  3. High temperatures lead to more varied, random, and creative outputs. Ideal for tasks requiring innovation, such as creative writing, brainstorming, or generating diverse ideas. Example: A temperature of 0.9 might be used for creative story writing or generating unique ideas.
  4. model_name: The model_name parameter allows you to specify which of OpenAI’s LLMs you want to use. Different models have varying capabilities, sizes, and computational requirements.
# Create LLM model
llm = OpenAI(temperature=0.5, model_name='gpt-3.5-turbo')

Similarly, we can create Chat models, for that import ChatOpenAI from langchain.chat_models:

# We can pass the list of messages, as
from langchain.chat_models import ChatOpenAI
from langchain.schema.messages import HumanMessage, SystemMessage

messages = [
    SystemMessage(content="You're a helpful assistant. In case if you don't know the answer then reply Sorry I don't know the answer!"),
    HumanMessage(content='What is object oriented programming?')
]

# Create LLM chat model
chat_llm = ChatOpenAI()
chat_llm.invoke(messages)

o/p: AIMessage(content='Object-oriented programming (OOP) is a programming…)

In addition to passing a list of HumanMessage and SystemMessage, you can also pass a simple string to the ChatOpenAI model. This is useful for simpler interactions where you don’t need the structure of HumanMessage or SystemMessage.

response = chat_llm.invoke("Who is the father of computer?")
print(response)

o/p: AIMessage(content='The father of computer is considered to be Alan Turing, an English mathematician, logician, and computer scientist who laid the foundations for modern computing.')

Conclusion:

LangChain is a key tool that makes advanced AI models like ChatGPT more useful for specific tasks. We’ve looked at how LangChain helps these models understand and respond better in different situations, by using various settings and approaches. Going forward, we’ll explore more about how LangChain works, including its use of templates, chains, and agents, to make AI interactions even smarter and more relevant. Essentially, LangChain is a powerful way to make AI more tailored and effective for our needs.

Future of Data?
Discover how Enqurious helps deliver an end-to-end learning experience
Curious how we're reshaping the future of data? Watch our story unfold
Get Free Snowpro Core Certification Skill Path

You Might Also Like

Mounting ADLS in Databricks? Here's What You're Missing blog cover image
Guides & Tutorials
July 20, 2026
Mounting ADLS in Databricks? Here's What You're Missing

Storage account keys and mount points give every user in a Databricks workspace the same shared access to ADLS, with no audit trail. Here's why teams are moving to Storage Credentials and External Locations instead.

Sayli Sr. Data Engineer
AI-Ready Data: Why Enterprise AI Pilots Fail in Production blog cover image
Guides & Tutorials
July 2, 2026
AI-Ready Data: Why Enterprise AI Pilots Fail in Production

89% of enterprise AI pilots never reach production. Data integration, governance gaps, and silos are why. See how Snowflake Cortex AI fixes the root cause.

Rohit Data Engineer
Snowflake Cortex AI in 2026: 59x Cost Difference Explained blog cover image
Guides & Tutorials
June 15, 2026
Snowflake Cortex AI in 2026: 59x Cost Difference Explained

A Snowflake Summit 2026 benchmark revealed a 59x cost gap — open-source models at 440 credits vs. frontier models at 26,000 credits for identical workloads. Learn how CoCo, CoWork, AI Credits, and Cortex Training change enterprise AI strategy.

Rohit Data Engineer
What Happens When Claude Meets Databricks? blog cover image
Guides & Tutorials
June 5, 2026
What Happens When Claude Meets Databricks?

How a data engineering team replaced manual pipeline work with natural language prompts, using Claude Code and the Databricks AI Dev Kit.

Sayli Sr. Data Engineer
6 Errors I Hit Connecting Databricks Apps to Genie AI blog cover image
Guides & Tutorials
June 3, 2026
6 Errors I Hit Connecting Databricks Apps to Genie AI

Six errors, 6 hours of debugging, and the permission checklist that finally made Databricks Apps + Genie work. The full lessons-learned guide.

Mansi AI & ML Engineer
Where Did My Claude Code Session Go? How to Find Any Lost Session blog cover image
Guides & Tutorials
June 2, 2026
Where Did My Claude Code Session Go? How to Find Any Lost Session

Your Claude Code session isn't lost. It's on disk, in a folder /resume isn't scanning. Here's how to find any session in 30 seconds, with the exact commands.

Mansi AI & ML Engineer
What is Scenario Based Learning for Data Teams? blog cover image
Guides & Tutorials
May 15, 2026
What is Scenario Based Learning for Data Teams?

Scenario based learning replaces tutorials with realistic operational scenarios where engineers develop the hands on judgment classroom instruction cannot produce. How it works and why it matters.

Mandar Sr. Data Analyst
Data Engineering Roadmap 2026: What Companies Actually Hire blog cover image
Guides & Tutorials
May 5, 2026
Data Engineering Roadmap 2026: What Companies Actually Hire

The 2026 data engineering roadmap. SQL, Python, cloud, Airflow, dbt, streaming. What companies actually hire for and how to build a portfolio that gets shortlisted.

Mandar Sr. Data Analyst
Medallion Architecture: Why Most Data Pipelines Break Without It blog cover image
Guides & Tutorials
April 30, 2026
Medallion Architecture: Why Most Data Pipelines Break Without It

Medallion Architecture splits your data pipeline into Bronze, Silver, and Gold layers so a small business change never forces a full rebuild. Here's why it works.

Divyanshi Data Engineer
An Advanced Git Tutorial: Lessons from a Real-World Versioning Crisis blog cover image
Guides & Tutorials
March 7, 2026
An Advanced Git Tutorial: Lessons from a Real-World Versioning Crisis

I was working on a large content repository on Windows, and I needed to version some new work — campaign assets, workshop content, LinkedIn job descriptions, and some file deletions. Simple enough, right? What followed was a two-day journey through some of Git's more obscure corners.

Amit Co-founder & CEO
The Docker Playground: Learning Without Fear blog cover image
Guides & Tutorials
January 29, 2026
The Docker Playground: Learning Without Fear

New engineers shouldn't learn Docker like they're defusing a bomb. Here's how we created a fear-free learning environment—and cut training time in half." (165 characters)

Burhanuddin DevOps Engineer
Data Quality Explained: Challenges, Best Practices, and Complete 2026 Guide blog cover image
Guides & Tutorials
January 23, 2026
Data Quality Explained: Challenges, Best Practices, and Complete 2026 Guide

A complete beginner’s guide to data quality, covering key challenges, real-world examples, and best practices for building trustworthy data.

Divyanshi Data Engineer
Data Lakehouse Demystified: Unlocking Databricks’ Hidden Powers in 2025 blog cover image
Guides & Tutorials
December 29, 2025
Data Lakehouse Demystified: Unlocking Databricks’ Hidden Powers in 2025

Explore the power of Databricks Lakehouse, Delta tables, and modern data engineering practices to build reliable, scalable, and high-quality data pipelines."

Divyanshi Data Engineer
My Three-Hour Terraform Task That Took Three Days (And Seven Errors) blog cover image
Guides & Tutorials
December 21, 2025
My Three-Hour Terraform Task That Took Three Days (And Seven Errors)

A real-world Terraform war story where a “simple” Azure SQL deployment spirals into seven hard-earned lessons, covering deprecated providers, breaking changes, hidden Azure policies, and why cloud tutorials age fast. A practical, honest read for anyone learning Infrastructure as Code the hard way.

Burhanuddin DevOps Engineer
Data Doesn’t Wait Anymore: A Guide to Streaming with Azure Databricks blog cover image
Guides & Tutorials
December 15, 2025
Data Doesn’t Wait Anymore: A Guide to Streaming with Azure Databricks

Data doesn’t wait - and neither should your insights. This blog breaks down streaming vs batch processing and shows, step by step, how to process real-time data using Azure Databricks.

Divyanshi Data Engineer
Unity Catalog Just Leveled Up: Meet your Data’s New Bodyguards blog cover image
Guides & Tutorials
December 8, 2025
Unity Catalog Just Leveled Up: Meet your Data’s New Bodyguards

This blog talks about Databricks’ Unity Catalog upgrades -like Governed Tags, Automated Data Classification, and ABAC which make data governance smarter, faster, and more automated.

Divyanshi Data Engineer
"Yeh Dosti" of AI: Claude & Nano Banana as Jai & Veeru! blog cover image
Guides & Tutorials
December 6, 2025
"Yeh Dosti" of AI: Claude & Nano Banana as Jai & Veeru!

Tired of boring images? Meet the 'Jai & Veeru' of AI! See how combining Claude and Nano Banana Pro creates mind-blowing results for comics, diagrams, and more.

Burhanuddin DevOps Engineer
A Week-Long Journey Through Deployment Errors and RBAC Implementation blog cover image
Guides & Tutorials
December 2, 2025
A Week-Long Journey Through Deployment Errors and RBAC Implementation

What I thought would be a simple RBAC implementation turned into a comprehensive lesson in Kubernetes deployment. Part 1: Fixing three critical deployment errors. Part 2: Implementing namespace-scoped RBAC security. Real terminal outputs and lessons learned included

Burhanuddin DevOps Engineer
The Day I Discovered Databricks Connect  blog cover image
Guides & Tutorials
December 1, 2025
The Day I Discovered Databricks Connect

This blog walks you through how Databricks Connect completely transforms PySpark development workflow by letting us run Databricks-backed Spark code directly from your local IDE. From setup to debugging to best practices this Blog covers it all.

Divyanshi Data Engineer
How a Simple ETL Job Turned Into a 5-Hour Kubernetes DNS Nightmare blog cover image
Guides & Tutorials
November 25, 2025
How a Simple ETL Job Turned Into a 5-Hour Kubernetes DNS Nightmare

A simple ETL job broke into a 5-hour Kubernetes DNS nightmare. This blog walks through the symptoms, the chase, and the surprisingly simple fix.

Burhanuddin DevOps Engineer
Building Bronze Layer: Using COPY INTO in Databricks blog cover image
Guides & Tutorials
September 12, 2025
Building Bronze Layer: Using COPY INTO in Databricks

Master the bronze layer foundation of medallion architecture with COPY INTO - the command that handles incremental ingestion and schema evolution automatically. No more duplicate data, no more broken pipelines when new columns arrive. Your complete guide to production-ready raw data ingestion

Sayli Sr. Data Engineer
Understanding the Power Law Distribution blog cover image
Guides & Tutorials
January 3, 2025
Understanding the Power Law Distribution

This blog talks about the Power Law statistical distribution and how it explains content virality

Amit Co-founder & CEO
How Apache Airflow Helps Manage Tasks, Just Like an Orchestra blog cover image
Guides & Tutorials
September 16, 2024
How Apache Airflow Helps Manage Tasks, Just Like an Orchestra

This blog explains how Apache Airflow orchestrates tasks like a conductor leading an orchestra, ensuring smooth and efficient workflow management. Using a fun Romeo and Juliet analogy, it shows how Airflow handles timing, dependencies, and errors.

Burhanuddin DevOps Engineer
An L&D Strategy to achieve 100% Certification clearance blog cover image
Guides & Tutorials
December 6, 2023
An L&D Strategy to achieve 100% Certification clearance

An account of experience gained by Enqurious team as a result of guiding our key clients in achieving a 100% success rate at certifications

Amit Co-founder & CEO
Calendar Events Automation: Streamline Your Life with App Script Automation blog cover image
Guides & Tutorials
October 10, 2023
Calendar Events Automation: Streamline Your Life with App Script Automation

This blog delves into the capabilities of Calendar Events Automation using App Script.

Burhanuddin DevOps Engineer
A Journey Through Extraction, Transformation, and Loading blog cover image
Guides & Tutorials
September 7, 2023
A Journey Through Extraction, Transformation, and Loading

Dive into the fundamental concepts and phases of ETL, learning how to extract valuable data, transform it into actionable insights, and load it seamlessly into your systems.

Burhanuddin DevOps Engineer