Concept #158Mediumpython-for-gen-ai

What is LangChain? What are all the use cases of LangChain? Is LangChain open-source? Can we use it for enterprise and do we need to pay? What is the pricing of LangChain?

#langchain#python#rag#agents#open-source#orchestration#langsmith#langgraph

Answer

What is LangChain?

LangChain is an open-source Python (and JavaScript) framework for building applications powered by Large Language Models. It provides a standardised interface to connect LLMs with external data sources, tools, memory, and other components — turning a raw LLM into a fully functional AI application.

Core idea: LLMs alone are stateless and isolated. LangChain gives them memory, data access, tool use, and the ability to chain reasoning steps together.

Originally created by Harrison Chase in October 2022, it quickly became the most popular LLM application framework in the world.


LangChain Ecosystem

LangChain is not one library — it is a suite of packages:

PackagePurpose
text
langchain-core
Base abstractions — runnables, prompts, messages
text
langchain
Chains, agents, and high-level components
text
langchain-community
700+ third-party integrations (vector stores, LLMs, tools)
text
langchain-openai
OpenAI-specific integration
text
langchain-anthropic
Anthropic Claude integration
text
langgraph
Stateful, graph-based agent workflows
text
langserve
Deploy LangChain apps as REST APIs
text
langsmith
Observability, tracing, and evaluation platform

What LangChain Is Used For

1. RAG (Retrieval-Augmented Generation)

The most common use case — connect LLMs to your own documents, databases, or knowledge bases.

python
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
from langchain.chains import RetrievalQA
from langchain_community.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter

# Load and chunk documents
loader = PyPDFLoader("company_handbook.pdf")
docs = loader.load()
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
chunks = splitter.split_documents(docs)

# Embed and store in vector DB
vectorstore = Chroma.from_documents(chunks, OpenAIEmbeddings())

# Build RAG chain
qa_chain = RetrievalQA.from_chain_type(
    llm=ChatOpenAI(model="gpt-4o"),
    retriever=vectorstore.as_retriever(search_kwargs={"k": 4})
)
answer = qa_chain.invoke("What is the vacation policy?")
print(answer["result"])

2. Prompt Management

Reusable, versioned prompt templates with variable injection.

python
from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate

# Structured prompt template
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are an expert {domain} engineer. Answer concisely."),
    ("human", "{question}")
])

chain = prompt | ChatOpenAI(model="gpt-4o")
response = chain.invoke({"domain": "Gen AI", "question": "What is LoRA?"})
print(response.content)

3. LLM Chains & Pipelines

Chain multiple LLM calls, transformations, and logic steps together using the LCEL (LangChain Expression Language) pipe syntax.

python
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o")

# Chain 1: generate a blog outline
outline_chain = (
    ChatPromptTemplate.from_template("Create a blog outline about: {topic}")
    | llm
    | StrOutputParser()
)

# Chain 2: write the blog from the outline
write_chain = (
    ChatPromptTemplate.from_template("Write a blog post from this outline:\n{outline}")
    | llm
    | StrOutputParser()
)

# Compose chains end-to-end
full_chain = {"outline": outline_chain} | write_chain
blog = full_chain.invoke({"topic": "Fine-tuning LLMs with LoRA"})

4. AI Agents with Tools

Give LLMs the ability to use tools (web search, calculators, APIs, code execution) and decide which tool to call.

python
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.prompts import ChatPromptTemplate

tools = [TavilySearchResults(max_results=3)]

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant with access to web search."),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}")
])

agent = create_tool_calling_agent(ChatOpenAI(model="gpt-4o"), tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
result = executor.invoke({"input": "What is the latest news about LLaMA 4?"})

5. Memory & Conversation History

Persist conversation context across multiple turns.

python
from langchain.memory import ConversationBufferWindowMemory
from langchain.chains import ConversationChain

memory = ConversationBufferWindowMemory(k=10)  # keep last 10 exchanges

conversation = ConversationChain(
    llm=ChatOpenAI(model="gpt-4o"),
    memory=memory,
    verbose=False
)

conversation.predict(input="My name is Alex.")
conversation.predict(input="What is RAG?")
response = conversation.predict(input="Can you remind me what my name is?")
print(response)  # "Your name is Alex."

6. Structured Output Parsing

Force LLMs to output structured data (JSON, Pydantic models).

python
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from pydantic import BaseModel, Field

class JobPosting(BaseModel):
    title: str = Field(description="Job title")
    skills: list[str] = Field(description="Required skills")
    experience_years: int = Field(description="Years of experience required")

llm = ChatOpenAI(model="gpt-4o").with_structured_output(JobPosting)

prompt = ChatPromptTemplate.from_template("Extract job info from: {job_description}")
chain = prompt | llm

result = chain.invoke({"job_description": "Senior Gen AI Engineer, 5 years exp, Python, LangChain..."})
print(result.title)      # "Senior Gen AI Engineer"
print(result.skills)     # ["Python", "LangChain", ...]

7. Document Loaders & Text Splitters

Load data from 100+ sources and prepare it for embedding.

python
from langchain_community.document_loaders import (
    PyPDFLoader,        # PDFs
    WebBaseLoader,      # Web pages
    CSVLoader,          # CSV files
    NotionDBLoader,     # Notion databases
    YoutubeLoader       # YouTube transcripts
)
from langchain.text_splitter import RecursiveCharacterTextSplitter

# Load from web
loader = WebBaseLoader("https://docs.langchain.com")
docs = loader.load()

# Smart chunking — respects sentence/paragraph boundaries
splitter = RecursiveCharacterTextSplitter(
    chunk_size=1000,
    chunk_overlap=100,
    separators=["\n\n", "\n", " ", ""]
)
chunks = splitter.split_documents(docs)

8. Multi-Modal Support

Process images, audio, and documents alongside text.

python
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
import base64

with open("diagram.png", "rb") as f:
    image_data = base64.b64encode(f.read()).decode()

llm = ChatOpenAI(model="gpt-4o")
response = llm.invoke([
    HumanMessage(content=[
        {"type": "text", "text": "Explain this architecture diagram."},
        {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_data}"}}
    ])
])

Is LangChain Open-Source?

Yes — LangChain is fully open-source.

ComponentLicenseSource
text
langchain
MIT Licensegithub.com/langchain-ai/langchain
text
langgraph
MIT Licensegithub.com/langchain-ai/langgraph
text
langchain-core
MIT LicensePart of the main monorepo
text
langsmith
SDK
MIT LicenseTracing SDK is open-source

MIT license means you can use it freely in personal, commercial, and enterprise projects with no restrictions.


Can LangChain Be Used for Enterprise?

Yes, absolutely. Since the framework is MIT-licensed, you can build and ship enterprise applications with zero licensing cost for the framework itself.

Large companies using LangChain in production include Elastic, Rakuten, Moody's, and many others.


LangChain Pricing

The framework (langchain, langgraph) is always free. Costs arise only from optional managed cloud products:

LangSmith (Observability & Evaluation)

PlanPriceTraces/MonthFeatures
DeveloperFree5,000Tracing, datasets, 1 user
Plus$39/month per user50,000Annotation queues, threads
EnterpriseCustom pricingUnlimitedSSO, RBAC, on-prem, SLA

LangGraph Platform (Hosted Agent Deployment)

PlanPriceWhat's Included
DeveloperFree1 deployment, community support
Plus$299/month3 deployments, autoscaling
EnterpriseCustomUnlimited deployments, SLA, VPC

Key point: You only pay if you use LangSmith or LangGraph Platform cloud. Self-hosting LangGraph or skipping LangSmith entirely means zero cost even at enterprise scale.


LangChain vs Alternatives

FrameworkOpen-SourceBest For
LangChainYes (MIT)General-purpose RAG, chains, agents
LlamaIndexYes (MIT)Document-heavy RAG pipelines
HaystackYes (Apache 2.0)Production NLP search pipelines
DSPyYes (MIT)Optimised prompt programs
LangGraphYes (MIT)Stateful, complex agent workflows

Summary

  • LangChain = free, open-source (MIT) framework — use it freely in any project
  • Provides RAG, chains, agents, memory, tools, document loading, structured output
  • No cost for the framework — you only pay for LLM API usage (OpenAI, Anthropic, etc.)
  • LangSmith (observability) and LangGraph Platform (hosted agents) are optional paid cloud products
  • Enterprise teams can self-host everything and pay nothing to LangChain Inc.

Learn more at LangChain Docs, LangSmith Pricing, and LangGraph Platform Pricing.