Generative AI और LLM Basics
Generative AI क्या है?
Generative AI सिर्फ़ classify या संख्या predict करने की जगह नया content बनाता है – text, images, code, audio। Large Language Model (LLM) text के लिए generative model है: ChatGPT, Claude, Gemini और Llama LLMs हैं। अंदर से LLM एक साधारण काम बार-बार करता है: text का अगला टुकड़ा predict करना।
| पारंपरिक ML | Generative AI |
|---|---|
| यह email spam है? → हाँ/नहीं | इस email का विनम्र जवाब लिखो |
| घर की कीमत predict → ₹48 लाख | Property ad के लिए इस घर का वर्णन लिखो |
| एक काम के लिए trained | एक model prompts से कई काम करता है |
Step 1: text tokens बनता है
Models अक्षर या पूरे शब्द नहीं पढ़ते; वे tokens पढ़ते हैं – शब्दों के आम टुकड़े। “unbelievable” “un”, “believ”, “able” बन सकता है। हर token एक संख्या (id) और फिर vector बनता है। एक ही वाक्य के लिए Hindi को अक्सर English से ज़्यादा tokens लगते हैं, इसलिए Hindi prompts महँगे पड़ सकते हैं और context जल्दी भरते हैं।
# a toy tokenizer: split into words and give each new word an id
sentence = "the shop sells fresh sweets and the shop opens early"
vocab = {}
ids = []
for word in sentence.split():
if word not in vocab:
vocab[word] = len(vocab)
ids.append(vocab[word])
print("tokens:", sentence.split())
print("ids :", ids)
print("vocabulary size:", len(vocab))
# bytes show why non-English text is “longer” for machines
for text in ["sweet", "मिठाई"]:
print(f"{text!r}: {len(text)} characters, {len(text.encode('utf-8'))} UTF-8 bytes")Step 2: अगला शब्द predict करना
सबसे सरल language model गिनता है कि कौन सा शब्द किसके बाद आता है। यह bigram model sweet shop के 7 वाक्यों से सीखकर नया text लिखता है। असली LLMs भी यही विचार इस्तेमाल करते हैं पर neural network (Transformer) से हज़ारों पिछले tokens देखते हैं और खरबों tokens पर trained होते हैं।
import random
from collections import Counter, defaultdict
corpus = "the shop opens at nine . the shop sells fresh sweets . fresh sweets are made every morning . the owner makes kaju katli every morning . customers buy fresh kaju katli . the shop closes at nine at night . customers love the shop ."
words = corpus.split()
# 1. TRAINING: count next-word frequencies
next_counts = defaultdict(Counter)
for current, nxt in zip(words, words[1:]):
next_counts[current][nxt] += 1
print("after 'fresh':", dict(next_counts["fresh"]))
print("after 'the' :", dict(next_counts["the"]))
# 2. GENERATION: repeatedly sample the next word
def generate(start, length=10, seed=1):
rng = random.Random(seed)
out = [start]
for _ in range(length):
options = next_counts[out[-1]]
if not options:
break
out.append(rng.choices(list(options), weights=options.values())[0])
return " ".join(out)
for seed in (1, 2, 3):
print("→", generate("the", seed=seed))देखिए यह ऐसे वाक्य बनाता है जो training text में कभी नहीं थे। सुनने में सही पर कभी-कभी ग़लत text ही कारण है कि LLMs hallucinate कर सकते हैं।
Step 3: temperature – रचनात्मक या अनुमानित
Model हर संभव अगले token के लिए score देता है। Softmax scores को probabilities में बदलता है, और temperature sampling से पहले उन्हें तेज़ या सपाट करता है।
import math
next_words = ["sweets", "kaju", "snacks", "flowers"]
scores = [3.0, 2.2, 1.0, -1.0] # model scores (logits) after "the shop sells fresh"
def softmax(values, temperature):
exps = [math.exp(v / temperature) for v in values]
total = sum(exps)
return [e / total for e in exps]
for t in (0.2, 1.0, 2.0):
probs = softmax(scores, t)
row = " ".join(f"{w}={p:.0%}" for w, p in zip(next_words, probs))
print(f"temperature {t}: {row}")| Temperature | व्यवहार | किसके लिए |
|---|---|---|
| 0 – 0.3 | लगभग हमेशा सबसे ऊपर वाला; एक जैसा | Facts, code, data निकालना, grading |
| 0.7 – 1.0 | संतुलित | Chat, explanations, emails |
| > 1 | चौंकाने वाला, कभी बेतुका | Brainstorming, कविताएँ, नाम |
LLM कैसे बनता है
- Pre-training: बहुत बड़ी मात्रा में public text और code पढ़कर अगला token predict करना सीखना। इससे ज्ञान और भाषा आती है।
- Fine-tuning: अच्छे निर्देशों और जवाबों के उदाहरणों पर आगे training, ताकि requests माने।
- Feedback training (जैसे RLHF): लोग जवाबों को rate करते हैं और model ज़्यादा मददगार और सुरक्षित बनना सीखता है।
- इस्तेमाल: आप prompt भेजते हैं; model रुकने तक एक-एक token बनाता है।
| शब्द | अर्थ |
|---|---|
| Parameters | Network के अंदर सीखी गई संख्याएँ (आधुनिक LLMs में अरबों) |
| Context window | Model एक बार में कितने tokens देख सकता है (prompt + जवाब) |
| Embedding | Token या वाक्य के अर्थ को दर्शाने वाला vector |
| Hallucination | आत्मविश्वास भरा पर ग़लत output |
| RAG | Retrieval-Augmented Generation: अपने documents ढूँढकर सवाल के साथ model को देना |
Step 4: 20 lines में RAG का विचार
LLMs आपके school के fee नियम या दुकान की prices नहीं जानते। RAG पहले आपके अपने documents में सबसे relevant text ढूँढकर prompt में डालता है। यह retrieval वाला हिस्सा है, साधारण शब्द-मिलान scoring के साथ (असली systems embeddings इस्तेमाल करते हैं)।
documents = {
"fees": "School fees are due on the 10th of every month. A late fee of Rs 100 applies after the 15th.",
"timing": "Classes run from 8:00 am to 2:00 pm, Monday to Saturday.",
"transport": "Bus service is available for Khurja and Bulandshahr routes at Rs 900 per month.",
}
def retrieve(question, k=1):
q = set(question.lower().replace("?", "").split())
scored = sorted(documents.items(), key=lambda d: -len(q & set(d[1].lower().split())))
return [text for _, text in scored[:k]]
question = "What is the late fee if I pay after the 15th?"
context = retrieve(question)[0]
prompt = f"""Answer using ONLY the context. If the answer is not there, say you don't know.
Context: {context}
Question: {question}"""
print(prompt)यह prompt फिर LLM को भेजा जाता है। जवाब context में है, इसलिए model सही जवाब दे सकता है और आप user को source दिखा सकते हैं।
Python से असली LLM बुलाना
हर provider (Anthropic, OpenAI, Google) का Python SDK है। Pattern एक जैसा है: SDK install करें, API key environment variable में रखें, messages भेजें, text जवाब पढ़ें। Model के नाम अक्सर बदलते हैं – मौजूदा नाम provider के documentation से लें।
# pip install anthropic (set ANTHROPIC_API_KEY and LLM_MODEL in your environment)
import os
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY automatically
reply = client.messages.create(
model=os.environ["LLM_MODEL"], # e.g. the current model name from the docs
max_tokens=300,
temperature=0.3,
system="You are a patient tutor for Class 10 students. Answer in simple Hindi and English.",
messages=[{"role": "user", "content": "Explain photosynthesis in 5 short points."}],
)
print(reply.content[0].text)API calls के पैसे प्रति token लगते हैं – खर्च की सीमा तय करें। Passwords, Aadhaar numbers या students का निजी data कभी न भेजें। ज़रूरी तथ्य जाँचें, और users को बताएँ कि content AI से बना है।
ताक़त और सीमाएँ
| LLMs इनमें अच्छे | LLMs को इनमें कठिनाई |
|---|---|
| समझाना, सार लिखना, अनुवाद | लंबी संख्याओं का सटीक गणित (code/tools लें) |
| Emails, notes, code का draft | Training के बाद की ताज़ा घटनाएँ |
| बिखरे text को structured data में बदलना | निजी तथ्य जो उन्होंने कभी नहीं देखे (RAG लें) |
| तेज़ी से कई ideas | ग़लत होने पर भी पक्का लगना |
आगे: Prompt Engineering में बेहतर निर्देश लिखना सीखें, और असली users के लिए कुछ बनाने से पहले AI Ethics पढ़ें।
अभ्यास
- Bigram model को अपने school के 10 वाक्यों पर train करके 5 lines बनाएँ।
- Temperature बदलकर पता करें कि कब “sweets” 50% से नीचे जाता है।
- RAG उदाहरण में दो और documents जोड़कर transport document वाला सवाल पूछें।
- तीन ऐसे सवाल लिखें जिन पर LLM hallucinate कर सकता है, और क्यों।
सारांश
- LLMs text को tokens में बदलकर बार-बार अगला token predict करते हैं।
- Training = विशाल text पर pre-training + fine-tuning + human feedback।
- Temperature randomness तय करता है; facts के लिए कम, ideas के लिए ज़्यादा।
- RAG hallucinations कम करने के लिए आपके documents prompt में जोड़ता है।
- Keys, खर्च और निजी data बचाएँ; ज़रूरी जवाब हमेशा जाँचें।
