Hackforge Academy

Category: python

What is LangChain and Why Use It with python

Published on 21 Oct 2026

Explanation

LangChain is an open-source framework for building applications powered by Large Language Models (LLMs). It helps developers connect language models with prompts, external tools, databases, APIs, and document retrieval systems. Without a framework, developers often write custom code to manage prompts,

Code:

# Install LangChain and the Ollama integration
# pip install langchain langchain-ollama

from langchain_ollama import ChatOllama

model = ChatOllama(
    model='qwen2.5:7b'
)

response = model.invoke(
    'Explain Python in two sentences.'
)

print(response.content)

# Make sure Ollama is running and the model is available.

Explanation

LangChain reduces the amount of custom integration code needed to build LLM applications. It provides components for creating prompts, invoking models, parsing structured outputs, connecting tools, and retrieving relevant information from documents. For example, a developer can build a coding assistant that accepts a question, retrieves relevant programming documentation, and generates an answer. LangChain is useful when an application requires several LLM-related components working together, although a simple application that only sends one prompt to a model may not need a framework.

Code:

# Install packages
# pip install langchain langchain-ollama

from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate

model = ChatOllama(model='qwen2.5:7b')

prompt = ChatPromptTemplate.from_messages([
    ('system', 'You are a Python programming tutor.'),
    ('human', 'Explain {topic} with a simple example.')
])

chain = prompt | model

response = chain.invoke({
    'topic': 'Python decorators'
})

print(response.content)

Explanation

Prompt templates allow developers to create reusable prompts containing dynamic values. Instead of writing a new prompt string for every request, a template defines placeholders that are filled at runtime. LangChain's Runnable interface allows components to be connected using the pipe operator. For example, a prompt template can pass its formatted messages to a language model, which generates a response. This pattern is useful for building reusable workflows such as code explanation, interview question generation, and content creation.

Code:

model = ChatOllama(model='qwen2.5:7b')

prompt = ChatPromptTemplate.from_template(
    'Create a beginner-friendly explanation of {topic} '
    'with one Python example.'
)

chain = prompt | model | StrOutputParser()

result = chain.invoke({
    'topic': 'list comprehension'
})

print(result)

Explanation

LLMs can generate text, but they do not automatically execute application functions or access live business data. Tools allow an AI application to interact with external systems, such as APIs, databases, calculators, and application services. LangChain supports defining tools that a compatible model can select when needed. For example, an educational assistant could use a tool to retrieve a student's course details or search a question bank. Tool execution should include validation and access controls, especially when tools can modify data or perform sensitive operations.

Code:

from langchain_core.tools import tool
from langchain_ollama import ChatOllama


@tool
def calculate_total(price: float, quantity: int) -> float:
    '''Calculate the total price for a quantity of items.'''
    return price * quantity


model = ChatOllama(
    model='qwen2.5:7b'
).bind_tools([calculate_total])

response = model.invoke(
    'Calculate the total for 3 books costing 250 each.'
)

print(response.content)
print(response.tool_calls)

# This example demonstrates tool-call generation.
# Your application must execute returned tool calls
# and send their results back to the model when required.

Explanation

LangChain can be used as one component in a complete AI application. For example, a Python coding tutor could accept questions through a FastAPI endpoint, use LangChain to construct prompts, call an LLM such as Qwen through Ollama, and return the generated explanation to the student. More advanced versions can use Retrieval-Augmented Generation (RAG) to retrieve relevant course material from a vector database such as Chroma. LangChain handles orchestration, while FastAPI exposes the API and the database stores application data. For complex, stateful, multi-step agent workflows, LangGraph is another option in the LangChain ecosystem.

Code:

# Install:
# pip install fastapi uvicorn langchain langchain-ollama

from fastapi import FastAPI
from pydantic import BaseModel
from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

app = FastAPI(title='AI Coding Tutor')

model = ChatOllama(model='qwen2.5:7b')
prompt = ChatPromptTemplate.from_template(
    'You are a coding tutor. Explain this topic clearly: {topic}'
)
chain = prompt | model | StrOutputParser()


class TutorRequest(BaseModel):
    topic: str


@app.post('/tutor/explain')
def explain_topic(request: TutorRequest):
    result = chain.invoke({
        'topic': request.topic
    })

    return {
        'topic': request.topic,
        'explanation': result
    }


# Run:
# uvicorn main:app --reload
# Test at http://localhost:8000/docs

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community