Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟣 ML + AI  ·  Lesson 35

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 करना।

पारंपरिक MLGenerative 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 जल्दी भरते हैं।

Python – tokens.py
# 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")
tokens: ['the', 'shop', 'sells', 'fresh', 'sweets', 'and', 'the', 'shop', 'opens', 'early'] ids : [0, 1, 2, 3, 4, 5, 0, 1, 6, 7] vocabulary size: 8 'sweet': 5 characters, 5 UTF-8 bytes 'मिठाई': 5 characters, 15 UTF-8 bytes

Step 2: अगला शब्द predict करना

सबसे सरल language model गिनता है कि कौन सा शब्द किसके बाद आता है। यह bigram model sweet shop के 7 वाक्यों से सीखकर नया text लिखता है। असली LLMs भी यही विचार इस्तेमाल करते हैं पर neural network (Transformer) से हज़ारों पिछले tokens देखते हैं और खरबों tokens पर trained होते हैं।

Python – tiny_language_model.py
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))
after 'fresh': {'sweets': 2, 'kaju': 1} after 'the' : {'shop': 4, 'owner': 1} → the shop . customers buy fresh sweets are made every morning → the owner makes kaju katli . customers love the shop closes → the shop closes at nine at nine . customers buy fresh

देखिए यह ऐसे वाक्य बनाता है जो training text में कभी नहीं थे। सुनने में सही पर कभी-कभी ग़लत text ही कारण है कि LLMs hallucinate कर सकते हैं।

Step 3: temperature – रचनात्मक या अनुमानित

Model हर संभव अगले token के लिए score देता है। Softmax scores को probabilities में बदलता है, और temperature sampling से पहले उन्हें तेज़ या सपाट करता है।

Python – temperature.py
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.2: sweets=98% kaju=2% snacks=0% flowers=0% temperature 1.0: sweets=62% kaju=28% snacks=8% flowers=1% temperature 2.0: sweets=46% kaju=31% snacks=17% flowers=6%
Temperatureव्यवहारकिसके लिए
0 – 0.3लगभग हमेशा सबसे ऊपर वाला; एक जैसाFacts, code, data निकालना, grading
0.7 – 1.0संतुलितChat, explanations, emails
> 1चौंकाने वाला, कभी बेतुकाBrainstorming, कविताएँ, नाम

LLM कैसे बनता है

  1. Pre-training: बहुत बड़ी मात्रा में public text और code पढ़कर अगला token predict करना सीखना। इससे ज्ञान और भाषा आती है।
  2. Fine-tuning: अच्छे निर्देशों और जवाबों के उदाहरणों पर आगे training, ताकि requests माने।
  3. Feedback training (जैसे RLHF): लोग जवाबों को rate करते हैं और model ज़्यादा मददगार और सुरक्षित बनना सीखता है।
  4. इस्तेमाल: आप prompt भेजते हैं; model रुकने तक एक-एक token बनाता है।
शब्दअर्थ
ParametersNetwork के अंदर सीखी गई संख्याएँ (आधुनिक LLMs में अरबों)
Context windowModel एक बार में कितने tokens देख सकता है (prompt + जवाब)
EmbeddingToken या वाक्य के अर्थ को दर्शाने वाला vector
Hallucinationआत्मविश्वास भरा पर ग़लत output
RAGRetrieval-Augmented Generation: अपने documents ढूँढकर सवाल के साथ model को देना

Step 4: 20 lines में RAG का विचार

LLMs आपके school के fee नियम या दुकान की prices नहीं जानते। RAG पहले आपके अपने documents में सबसे relevant text ढूँढकर prompt में डालता है। यह retrieval वाला हिस्सा है, साधारण शब्द-मिलान scoring के साथ (असली systems embeddings इस्तेमाल करते हैं)।

Python – rag_retrieval.py
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)
Answer using ONLY the context. If the answer is not there, say you don't know. Context: School fees are due on the 10th of every month. A late fee of Rs 100 applies after the 15th. Question: What is the late fee if I pay after the 15th?

यह 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 से लें।

Python – call_llm.py (needs your own API key)
# 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)
⚠️ LLMs के साथ बनाने से पहले

API calls के पैसे प्रति token लगते हैं – खर्च की सीमा तय करें। Passwords, Aadhaar numbers या students का निजी data कभी न भेजें। ज़रूरी तथ्य जाँचें, और users को बताएँ कि content AI से बना है।

ताक़त और सीमाएँ

LLMs इनमें अच्छेLLMs को इनमें कठिनाई
समझाना, सार लिखना, अनुवादलंबी संख्याओं का सटीक गणित (code/tools लें)
Emails, notes, code का draftTraining के बाद की ताज़ा घटनाएँ
बिखरे text को structured data में बदलनानिजी तथ्य जो उन्होंने कभी नहीं देखे (RAG लें)
तेज़ी से कई ideasग़लत होने पर भी पक्का लगना

आगे: Prompt Engineering में बेहतर निर्देश लिखना सीखें, और असली users के लिए कुछ बनाने से पहले AI Ethics पढ़ें।

अभ्यास

  1. Bigram model को अपने school के 10 वाक्यों पर train करके 5 lines बनाएँ।
  2. Temperature बदलकर पता करें कि कब “sweets” 50% से नीचे जाता है।
  3. RAG उदाहरण में दो और documents जोड़कर transport document वाला सवाल पूछें।
  4. तीन ऐसे सवाल लिखें जिन पर 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 बचाएँ; ज़रूरी जवाब हमेशा जाँचें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या LLM इंसान की तरह समझता है?
इसने भाषा और ज्ञान के बहुत समृद्ध patterns सीखे हैं, जिससे यह कई समस्याओं पर तर्क कर पाता है, पर इसका कोई निजी अनुभव नहीं और यह आत्मविश्वास से ग़लत हो सकता है। इसे शक्तिशाली सहायक मानें जिसका काम आप जाँचें।
क्या मैं अपने laptop पर LLM चला सकता हूँ?
हाँ, छोटे open models (जैसे Llama, Mistral या Gemma families) Ollama या LM Studio जैसे tools से local चलते हैं। ये मुफ़्त और निजी हैं पर सबसे बड़े cloud models से कम सक्षम हैं और पर्याप्त RAM माँगते हैं।
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
अगला topicPrompt Engineering Basics आपकी प्रगति: 35 / 66 (53%) · Lesson 36 / 66 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें