RAG
নিজের data দিয়ে ChatGPT-style system বানানো।
LLM সব কিছু জানে — কিন্তু আপনার company এর internal document, আজকের news, আপনার project এর code? জানে না। সমাধান? RAG — Retrieval-Augmented Generation। নিজের data কে LLM এর সাথে combine করে ChatGPT-style assistant বানানো — modern AI app এর সবচেয়ে important pattern।
RAG = Retrieval + Generation। Workflow: (1) Document collection কে chunk করে embed করে vector DB তে store, (2) User query কে embed করে similar chunk retrieve, (3) Retrieved chunk + query কে LLM এ pass করে answer generate। ফলে LLM এর creativity + আপনার data এর accuracy + citation = hallucination-free, up-to-date answer।
ভাবুন একজন consultant — সে অনেক জানে, কিন্তু আপনার নির্দিষ্ট company এর data দিলে আরো ভালো answer দিতে পারবে। RAG ঠিক তাই — LLM consultant, vector DB হলো consultant এর সামনে রাখা reference book। Question এলে relevant page খুলে দেখায়, তারপর answer compose করে। Citation ও দিতে পারে — কোন source থেকে এসেছে।
import os
import numpy as np
from openai import OpenAI
client = OpenAI(
base_url="https://ai.gateway.lovable.dev/v1",
api_key=os.environ["LOVABLE_API_KEY"],
)
documents = [
"Our company offers a 30-day return policy on all electronics.",
"Free shipping is available for orders above $50 within the US.",
"Customer support is available Monday through Friday, 9 AM to 6 PM EST.",
"We accept Visa, Mastercard, American Express, and PayPal.",
"All products come with a 1-year manufacturer warranty.",
]
def embed(texts):
res = client.embeddings.create(model="google/gemini-embedding-001", input=texts)
return np.array([d.embedding for d in res.data])
def cosine(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
doc_vectors = embed(documents)
def rag_answer(question, k=2):
q_vec = embed([question])[0]
sims = [cosine(q_vec, dv) for dv in doc_vectors]
top_idx = np.argsort(sims)[-k:][::-1]
context = "\n".join(f"- {documents[i]}" for i in top_idx)
messages = [
{"role": "system", "content": "Answer using ONLY the provided context. If not in context, say 'I don't know'."},
{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
]
res = client.chat.completions.create(
model="google/gemini-2.5-flash",
messages=messages,
temperature=0.2,
)
return res.choices[0].message.content, [documents[i] for i in top_idx]
answer, sources = rag_answer("How long is the return period?")
print("Answer:", answer)
print("Sources:", sources)Minimal RAG: documents embed করে memory তে, query এলে embed + cosine similarity দিয়ে top-2 retrieve, context সহ LLM এ pass। Production এ vector DB (pgvector/Chroma) ব্যবহার করতে হবে, in-memory না।
একটি app যেখানে user PDF upload করে এবং সেই PDF এর content নিয়ে question করতে পারে। PyPDF2 দিয়ে text extract, chunk, embed (Gemini), pgvector এ store, query এলে retrieve + LLM answer with citation।