ailiteracynepal 🇳🇵
पाठ आकार

अध्याय ३ · खण्ड III · 28 मिनेट

सरल नेपाली चाटबट बनाउने

अध्याय 1-3 का सबै कुरा एक कार्यरत परियोजनामा जोडिएको। System prompt, sliding-window memory, cost tracking, streaming output, र CLI सहितको नेपाली बोल्ने चाटबट। 150 भन्दा कम लाइन कोडमा।

तपाईंसँग वास्तविक chatbot निर्माण गर्न आवश्यक सबै छ। यो खण्डले यसलाई assemble गर्छ: chiya भन्ने नेपाली-बोल्ने सहायक — नेपाली मा दैनिक जीवन प्रश्नहरूका लागि मैत्रीपूर्ण, narrow-purpose bot। हामी ध्यानले लेखिएको system prompt, sliding-window memory, cost tracking, streaming output, र सानो command-line UI जोड्नेछौँ। अन्त्यसम्म तपाईंसँग वास्तवमै run गर्न र Devanagari मा च्याट गर्न सक्ने र यस पछि निर्माण गर्ने हरेक chatbot का लागि foundation हुनेछ।

हामी के निर्माण गर्दैछौँ

chiya हो:

  • Nepali-first: यसले user ले लेखेको उही भाषामा प्रतिक्रिया दिन्छ (नेपाली भए नेपाली, अंग्रेजी भए अंग्रेजी), र नेपाल-विशिष्ट context अलिकति जान्छ।
  • Narrow: यो दैनिक-जीवन सहायक हो, डाक्टर वा वकिल वा वित्तीय सल्लाहकार होइन। यदि user ले यसको scope बाहिर सोध्छ भने, यसले भद्रसँग भन्छ।
  • Careful: यो चिकित्सा, कानुनी, वा वित्तीय सल्लाह दिन अस्वीकार गर्छ। यसले तथ्यहरू आविष्कार गर्दैन।
  • Cheap: यसले Claude Haiku र sliding-window strategy प्रयोग गर्छ। Bounded प्रति-कुराकानी लागत।
  • Streaming: प्रतिक्रियाहरू token-token देखा पर्छन्, एकैचोटि सबै होइन — UX जीवित महसुस हुन्छ।

पूर्ण कोड एक फाइल हो। तल हामी यसलाई piece-by-piece हिँडाउँछौँ।

चरण 1 — system prompt

System prompt ले chiya को पहिचान परिभाषित गर्छ:

SYSTEM_PROMPT = """You are chiya (चिया), a friendly Nepali-speaking assistant
for everyday questions.

Your scope:
- Everyday-life questions: cooking, travel, festivals, general knowledge
  about Nepal, language questions, small explanations.
- Respond in the same language the user writes in. If the user writes
  in Devanagari Nepali, respond in Devanagari Nepali. If they write
  in Romanised Nepali, do the same. If they write in English, respond
  in English.

Your limits:
- Never give medical, legal, or financial advice. If asked, politely
  decline and suggest the user speak with a qualified professional.
- Never claim knowledge of events after your training cutoff, or of
  the user's private information beyond what they've shared in this
  chat.
- Never pretend to be a human. If asked if you're an AI, say yes.

Your style:
- Keep responses concise: 2-4 sentences unless the user asks for detail.
- Warm and friendly, but not saccharine. Use "तपाईं" for polite Nepali
  address, not "तिमी" or "तँ".
- Use plain language. If a user seems confused, offer a follow-up
  question to clarify.
"""

यसलाई पढ्नुहोस्। हरेक लाइन वास्तविक chatbot विफलताहरूबाट आएको नियम हो। Scope ले scope creep रोक्छ। Language rule ले “नेपाली मा सुरु भयो, अंग्रेजी मा drift भयो” bug रोक्छ। Limits ले liability रोक्छ। Style rules ले दुई सबैभन्दा सामान्य chatbot smells — over-formal र over-cheery — रोक्छन्।

चरण 2 — Conversation class

अघिल्लो खण्डमा हामीले निर्माण गरेको पुन: प्रयोग, streaming का लागि adapted:

import os
import time
from dataclasses import dataclass, field
from dotenv import load_dotenv
import anthropic

load_dotenv()
_client = anthropic.Anthropic()


HAIKU_INPUT_PER_M  = 0.25
HAIKU_OUTPUT_PER_M = 1.25


@dataclass
class Chiya:
    system_prompt: str = SYSTEM_PROMPT
    window: int = 12
    model: str = "claude-haiku-4-5-20251001"
    messages: list = field(default_factory=list)
    total_input_tokens: int = 0
    total_output_tokens: int = 0

    def _recent_messages(self) -> list:
        # Keep last `window` pairs of user+assistant messages
        return self.messages[-(self.window * 2):]

    def ask_streaming(self, user_message: str) -> str:
        self.messages.append({"role": "user", "content": user_message})

        full_text = ""
        with _client.messages.stream(
            model=self.model,
            max_tokens=800,
            temperature=0.7,
            system=self.system_prompt,
            messages=self._recent_messages(),
        ) as stream:
            for text_chunk in stream.text_stream:
                print(text_chunk, end="", flush=True)
                full_text += text_chunk
            print()

            # After stream completes, get usage
            final_message = stream.get_final_message()
            self.total_input_tokens  += final_message.usage.input_tokens
            self.total_output_tokens += final_message.usage.output_tokens

        self.messages.append({"role": "assistant", "content": full_text})
        return full_text

    def cost_so_far(self) -> float:
        return (
            self.total_input_tokens  / 1_000_000 * HAIKU_INPUT_PER_M +
            self.total_output_tokens / 1_000_000 * HAIKU_OUTPUT_PER_M
        )

पचास लाइन। प्रतिक्रिया stream गर्छ, tokens ट्र्याक गर्छ, अन्तिम 12 turns को sliding window राख्छ।

चरण 3 — CLI

एक मैत्रीपूर्ण command-line UI:

def run():
    print("चिया — तपाईंको दैनिक सहायक")
    print("(type 'quit' to exit, 'cost' to see running cost, 'reset' to start over)\n")

    chiya = Chiya()

    while True:
        try:
            user_input = input("You: ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            break

        if not user_input:
            continue
        if user_input.lower() in {"quit", "exit", "bye"}:
            print(f"Bye! Total cost: ${chiya.cost_so_far():.5f}")
            break
        if user_input.lower() == "cost":
            print(f"[cost so far: ${chiya.cost_so_far():.5f} "
                  f"| tokens: {chiya.total_input_tokens} in / "
                  f"{chiya.total_output_tokens} out]\n")
            continue
        if user_input.lower() == "reset":
            chiya = Chiya()
            print("[Conversation reset.]\n")
            continue

        print("chiya: ", end="", flush=True)
        chiya.ask_streaming(user_input)
        print()


if __name__ == "__main__":
    run()

पचीस थप लाइन। पूर्ण सहायक।

पूर्ण फाइल, सँगै राखिएको

# chiya.py
import os
from dataclasses import dataclass, field
from dotenv import load_dotenv
import anthropic

load_dotenv()
_client = anthropic.Anthropic()


SYSTEM_PROMPT = """You are chiya (चिया), a friendly Nepali-speaking assistant
for everyday questions.

Your scope:
- Everyday-life questions: cooking, travel, festivals, general knowledge
  about Nepal, language questions, small explanations.
- Respond in the same language the user writes in.

Your limits:
- Never give medical, legal, or financial advice. Politely decline.
- Never claim knowledge of events after your training cutoff.
- Never pretend to be a human. If asked, say you are an AI.

Your style:
- Keep responses concise: 2-4 sentences unless asked otherwise.
- Warm and friendly, not saccharine.
- Use "तपाईं" for polite Nepali address.
"""


HAIKU_INPUT_PER_M  = 0.25
HAIKU_OUTPUT_PER_M = 1.25


@dataclass
class Chiya:
    system_prompt: str = SYSTEM_PROMPT
    window: int = 12
    model: str = "claude-haiku-4-5-20251001"
    messages: list = field(default_factory=list)
    total_input_tokens: int = 0
    total_output_tokens: int = 0

    def _recent_messages(self) -> list:
        return self.messages[-(self.window * 2):]

    def ask_streaming(self, user_message: str) -> str:
        self.messages.append({"role": "user", "content": user_message})

        full_text = ""
        with _client.messages.stream(
            model=self.model,
            max_tokens=800,
            temperature=0.7,
            system=self.system_prompt,
            messages=self._recent_messages(),
        ) as stream:
            for chunk in stream.text_stream:
                print(chunk, end="", flush=True)
                full_text += chunk
            print()

            final = stream.get_final_message()
            self.total_input_tokens  += final.usage.input_tokens
            self.total_output_tokens += final.usage.output_tokens

        self.messages.append({"role": "assistant", "content": full_text})
        return full_text

    def cost_so_far(self) -> float:
        return (
            self.total_input_tokens  / 1_000_000 * HAIKU_INPUT_PER_M +
            self.total_output_tokens / 1_000_000 * HAIKU_OUTPUT_PER_M
        )


def run():
    print("चिया — तपाईंको दैनिक सहायक")
    print("(type 'quit', 'cost', or 'reset')\n")

    chiya = Chiya()

    while True:
        try:
            user_input = input("You: ").strip()
        except (KeyboardInterrupt, EOFError):
            print()
            break

        if not user_input:
            continue
        if user_input.lower() in {"quit", "exit", "bye"}:
            print(f"Bye! Total cost: ${chiya.cost_so_far():.5f}")
            break
        if user_input.lower() == "cost":
            print(f"[cost: ${chiya.cost_so_far():.5f}]\n")
            continue
        if user_input.lower() == "reset":
            chiya = Chiya()
            print("[Reset.]\n")
            continue

        print("chiya: ", end="", flush=True)
        chiya.ask_streaming(user_input)
        print()


if __name__ == "__main__":
    run()

150 लाइन मुनि। Terminal बाट चल्छ। Stream गर्छ। Cost ट्र्याक गर्छ। Sliding window स्वचालित रूपमा सम्हाल्छ। यो पूर्ण, इमानदार chatbot हो।

यसलाई कोसिस गर्ने

python chiya.py

एक नमुना session:

चिया — तपाईंको दैनिक सहायक
(type 'quit', 'cost', or 'reset')

You: नमस्ते! मलाई नेपाली चियाको सबैभन्दा राम्रो रेसिपी भन्नुहोस्।
chiya: नमस्ते! मेरो साथी। दूध चियाका लागि — पानीमा अदुवा, इलायची, र सुकेको
सक्खर हालेर एक मिनेट उमाल्नुहोस्, अनि चियापत्ती हालेर छिटो उमाल्नुहोस्, र
अन्तमा दूध मिसाएर छान्नुहोस्।

You: मीठो कति हुनुपर्छ?
chiya: तपाईंको स्वादमा भर पर्छ। एक कप चियाका लागि करिब आधा चम्चा चिनी वा
सुकेको सक्खर मिठाइको लागि उपयुक्त हुन्छ। कम मीठो मन पर्ने मानिसका लागि
घटाउनुहोस्।

You: cost
[cost: $0.00087]

You: मलाई डिप्रेसनको औषधि दिनुहोस्।
chiya: मलाई माफ गर्नुहोस्, तर म चिकित्सा सल्लाह दिन सक्दिनँ। कृपया कुनै
मानसिक स्वास्थ्य विशेषज्ञ वा मनोचिकित्सकसँग सल्लाह लिनुहोस्। यदि तपाईंलाई
तत्काल सहयोग चाहिन्छ भने, नेपालको Suicide Prevention Helpline
(1166) सम्पर्क गर्नुहोस्।

You: quit
Bye! Total cost: $0.00201

तीन कुरा ध्यान दिनुहोस्:

  • यसले चिया रेसिपीलाई n्यानो र नेपालीमा उत्तर दियो।
  • यो scope भित्र रह्यो: दैनिक प्रश्नहरूमा मैत्रीपूर्ण।
  • यसले चिकित्सा प्रश्न अस्वीकार गर्‍यो र वास्तविक नेपाली helpline नम्बर प्रस्ताव गर्‍यो। यो ठ्याक्कै त्यो behaviour हो जुन system prompt ले उत्पादन गर्न designed थियो।

के छुटेको छ (र के अर्को छ)

chiya वास्तविक, कार्यरत chatbot हो। यो जानीजानी अपूर्ण पनि छ:

  • कुनै RAG छैन। यसले तपाईंले दिनुभएको विशिष्ट कागजातहरू बारे प्रश्नहरूको उत्तर दिन सक्दैन। अध्याय 4-5 ले त्यो थप्छ।
  • कुनै औजारहरू छैनन्। यसले आजको मौसम, वा तपाईंको bank balance, वा कुनै real-time कुरा ल्याउन सक्दैन। अध्याय 6 ले त्यो सम्बोधन गर्छ।
  • कुनै per-user persistence छैन। Sessions एक-अर्कालाई सम्झँदैनन्। User database थप्नु सजिलो छ तर यहाँको scope बाहिर हो।
  • कुनै मूल्याङ्कन छैन। हामीले chiya ले users लाई वास्तवमै मद्दत गर्छ कि मापन गरेका छैनौँ। अध्याय 6 ले मूल्याङ्कन ओगट्छ।

Course 04 का तीन थप अध्यायहरू यीनै कारणले छन्।

आफ्नो बुझाइ जाँच्नुहोस्

Quick check

एक जुनियर developer ले chiya लाई विस्तार गरेर medical diagnoses पनि दिन चाहन्छन् किनकि 'LLM ले medicine जान्छ।' यो खण्डको आत्मामा professional प्रतिक्रिया के हो?

Quick check

एक साथीले सोध्छिन् चिया का chat responses (जस्तै extraction का लागि) temperature=0.0 प्रयोग गर्ने कि। सही उत्तर के हो?

अब के आउँछ

अध्याय 3 सकियो। तपाईंसँग कार्यरत chatbot छ। अध्याय 4 र 5 यो पाठ्यक्रममा सबैभन्दा ठूलो architectural छलाङ हुन्: embeddings र retrieval-augmented generation — त्यो ढाँचा जुनले LLMs लाई तपाईंले दिनुभएको कागजातहरूबाट प्रश्नहरूको उत्तर दिन दिन्छ, hallucinate नगरी। यो चिया जस्तो general-purpose chatbot लाई “customer support for our company” वा “answer questions about our government’s circulars” जस्तो विशिष्ट-उद्देश्य सहायकमा बदल्छ। यो आधुनिक निर्माताको सबैभन्दा-प्रयोग हुने प्रविधि हो।