10. Build a chatbot for the Indian Penal Code. We’ll start by downloading the official Indian Penal Code document, and then we’ll create a chatbot that can interact with it. Users will be able to ask questions about the Indian Penal Code and have a conversation with it.
NOTE: Please add your Cohere API key before running the program (COHERE_API_KEY variable).
PROGRAM:
# Module or library install command (run this in terminal before running the script)
# pip install langchain langchain-core langchain-community langchain-cohere langchain-text-splitters cohere pypdf faiss-cpu tiktoken sentence-transformers
import os
import warnings
warnings.filterwarnings("ignore")
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_core.prompts import PromptTemplate
from langchain_cohere import ChatCohere
# =========================
# CONFIG
# =========================
COHERE_API_KEY = "Enter your Cohere API key here"
PDF_PATH = "./IPC.pdf"
os.environ["COHERE_API_KEY"] = COHERE_API_KEY
# =========================
# LOAD PDF
# =========================
print(f"✅ PDF ready → {PDF_PATH}")
loader = PyPDFLoader(PDF_PATH)
pages = loader.load()
splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
chunks = splitter.split_documents(pages)
print(f"✅ {len(pages)} pages → {len(chunks)} chunks")
# =========================
# EMBEDDINGS + VECTOR STORE
# =========================
print("🔢 Creating embeddings — using free HuggingFace model ...")
print(" First run downloads the model ~90MB, takes 1-2 min ...")
embeddings = HuggingFaceEmbeddings(
model_name="all-MiniLM-L6-v2"
)
vector_store = FAISS.from_documents(chunks, embeddings)
print("✅ Vector store ready")
# =========================
# PROMPT
# =========================
prompt = PromptTemplate(
input_variables=["context", "question", "chat_history"],
template="""
You are an Indian Penal Code legal assistant.
Answer the user's question only from the given context.
Use this format:
Section:
Mention the IPC section if available.
Explanation:
Explain the meaning in simple language.
Punishment:
Mention punishment if available.
If the answer is not available in the context, say:
"I could not find this clearly in the provided IPC PDF."
Context:
{context}
Question:
{question}
Chat History:
{chat_history}
Answer:
"""
)
# =========================
# LLM + RETRIEVER
# =========================
llm = ChatCohere(
model="command-a-03-2025",
temperature=0.2
)
retriever = vector_store.as_retriever(
search_kwargs={"k": 4}
)
chain = prompt | llm
# =========================
# CHAT FUNCTION
# =========================
def chat(question):
docs = retriever.invoke(question)
context = "\n\n".join([doc.page_content for doc in docs])
result = chain.invoke({
"context": context,
"question": question,
"chat_history": ""
})
print("\nBot:")
print(result.content)
print()
# =========================
# START CHAT
# =========================
print("✅ Chatbot ready!")
print("Type 'exit' to stop.\n")
while True:
question = input("You: ")
if question.lower() == "exit":
break
chat(question)OUTPUT:
✅ PDF ready → ./IPC.pdf
✅ 89 pages → 248 chunks
🔢 Creating embeddings — using free HuggingFace model ...
First run downloads the model ~90MB, takes 1-2 min ...
C:\Users\braun\OneDrive\Desktop\progrma\main.py:50: LangChainDeprecationWarning: The class `HuggingFaceEmbeddings` was deprecated in LangChain 0.2.2 and will be removed in 1.0. An updated version of the class exists in the `langchain-huggingface package and should be used instead. To use it run `pip install -U `langchain-huggingface` and import as `from `langchain_huggingface import HuggingFaceEmbeddings``.
embeddings = HuggingFaceEmbeddings(
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
Loading weights: 100%|████████████████████████████████████████████████████████████████████████████████████████████████| 103/103 [00:00<00:00, 9682.92it/s]
✅ Vector store ready
✅ Chatbot ready!
Type 'exit' to stop.
You: What is theft?
Bot:
Section: 378
Explanation: Theft is defined as the act of dishonestly taking any movable property out of the possession of any person without their consent, and moving that property with the intention of taking it. It is important to note that the property must be movable, and the act of moving the property is essential to constitute theft. If an item is attached to the earth, it is not considered movable property and cannot be stolen until it is severed from the earth.
Punishment: The specific punishment for theft is not mentioned in the provided context, but it is mentioned that theft in a dwelling house is punishable under Section 380. However, the general punishment for theft would depend on the specific circumstances and the value of the property stolen, which is not detailed in the given context.
You: who is the owner of Vtucircle?
Bot:
I could not find this clearly in the provided IPC PDF.
You: 