जेमा के साथ चैटबॉट बनाएं

ai.google.dev पर देखें Google Colab में चलाएं Vertex AI में खोलें GitHub पर सोर्स देखें

Gemma जैसे बड़े लैंग्वेज मॉडल (एलएलएम), जानकारी देने वाले जवाब जनरेट करने में माहिर होते हैं. इस मॉडल को वर्चुअल असिस्टेंट और चैटबॉट बनाने के लिए बेहतरीन माना जाता है.

परंपरागत तौर पर, एलएलएम स्टेटलेस तरीके से काम करते हैं. इसका मतलब है कि उनके पास पुरानी बातचीत को सेव करने के लिए मेमोरी नहीं होती है. हर सवाल या सवाल को, पहले के इंटरैक्शन पर ध्यान दिए बिना अलग से प्रोसेस किया जाता है. हालांकि, सामान्य बातचीत का एक अहम पहलू यह है कि पहले की बातचीत के संदर्भ को याद रखा जा सके. इस सीमा को पार करने और बातचीत के कॉन्टेक्स्ट को बनाए रखने के लिए, एलएलएम को हर नए प्रॉम्प्ट में साफ़ तौर पर ज़रूरी जानकारी देनी होगी. जैसे, बातचीत का इतिहास या ज़रूरी हिस्से.

इस ट्यूटोरियल में बताया गया है कि Gemma के निर्देशों वाले मॉडल वैरिएंट का इस्तेमाल करके, चैटबॉट कैसे बनाएं.

सेटअप

Gemma का सेटअप

इस ट्यूटोरियल को पूरा करने के लिए, आपको सबसे पहले Gemma सेटअप में दिए गए सेटअप के निर्देशों को पूरा करना होगा. Gemma के सेटअप से जुड़े निर्देशों में बताया गया है कि ये काम कैसे किए जा सकते हैं:

  • kaggle.com पर Gemma का ऐक्सेस पाएँ.
  • Gemma 2B मॉडल को चलाने के लिए, ज़रूरत के मुताबिक संसाधनों वाला Colab रनटाइम चुनें.
  • Kaggle उपयोगकर्ता नाम और एपीआई पासकोड को जनरेट और कॉन्फ़िगर करें.

Gemma का सेटअप पूरा करने के बाद, अगले सेक्शन पर जाएं. यहां अपने Colab एनवायरमेंट के लिए, एनवायरमेंट वैरिएबल सेट किए जा सकते हैं.

एनवायरमेंट वैरिएबल सेट करना

KAGGLE_USERNAME और KAGGLE_KEY के लिए, एनवायरमेंट वैरिएबल सेट करें.

import os
from google.colab import userdata

# Note: `userdata.get` is a Colab API. If you're not using Colab, set the env
# vars as appropriate for your system.
os.environ["KAGGLE_USERNAME"] = userdata.get('KAGGLE_USERNAME')
os.environ["KAGGLE_KEY"] = userdata.get('KAGGLE_KEY')

डिपेंडेंसी इंस्टॉल करें

Keras और KerasNLP इंस्टॉल करें.

# Install Keras 3 last. See https://keras.io/getting_started/ for more details.
pip install -q tensorflow-cpu
pip install -q -U keras-nlp tensorflow-hub
pip install -q -U keras>=3
pip install -q -U tensorflow-text

बैकएंड चुनें

Keras एक हाई-लेवल, मल्टी-फ़्रेमवर्क डीप लर्निंग एपीआई है. इसे सरलता और इस्तेमाल में आसानी के लिए डिज़ाइन किया गया है. Keras 3 की मदद से, बैकएंड में इनमें से कोई भी विकल्प चुना जा सकता है: TensorFlow, JAX या PyTorch. इस ट्यूटोरियल के लिए ये तीनों काम करेंगे.

import os

# Select JAX as the backend
os.environ["KERAS_BACKEND"] = "jax"

# Pre-allocate 100% of TPU memory to minimize memory fragmentation
os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "1.0"

पैकेज इंपोर्ट करें

Keras और KerasNLP इंपोर्ट करें.

import keras
import keras_nlp

# for reproducibility
keras.utils.set_random_seed(42)

मॉडल को इंस्टैंशिएट करना

KerasNLP कई लोकप्रिय मॉडल आर्किटेक्चर को लागू करने की सुविधा देता है. इस ट्यूटोरियल में, GemmaCausalLM का इस्तेमाल करके मॉडल को इंस्टैंशिएट किया जाएगा. यह टाइम-टू-एंड जेमा मॉडल है, जो किसी भाषा के सामान्य मॉडल के लिए इस्तेमाल किया जाता है. कॉज़ल लैंग्वेज मॉडल, पिछले टोकन के आधार पर अगले टोकन का अनुमान लगाता है.

from_preset तरीके का इस्तेमाल करके मॉडल को इंस्टैंशिएट करें:

gemma_lm = keras_nlp.models.GemmaCausalLM.from_preset("gemma_1.1_instruct_2b_en")
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'task.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'config.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'config.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'config.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'model.weights.h5' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'metadata.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'preprocessor.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'tokenizer.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'tokenizer.json' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...
Attaching 'assets/tokenizer/vocabulary.spm' from model 'keras/gemma/keras/gemma_1.1_instruct_2b_en/3' to your Colab notebook...

GemmaCausalLM.from_preset() फ़ंक्शन, मॉडल को प्रीसेट आर्किटेक्चर और वेट से इंस्टैंशिएट करता है. ऊपर दिए गए कोड में, "gemma_1.1_instruct_2b_en" स्ट्रिंग में 2 अरब पैरामीटर के साथ Gemma 2B मॉडल को पहले से सेट किया गया है. 7B, 9B, और 27B पैरामीटर वाले जेमा मॉडल भी उपलब्ध हैं. Gemma मॉडल के लिए कोड स्ट्रिंग, Kaggle पर उनकी मॉडल वैरिएशन लिस्टिंग में देखी जा सकती हैं.

मॉडल के बारे में ज़्यादा जानकारी पाने के लिए, summary तरीके का इस्तेमाल करें:

gemma_lm.summary()

खास जानकारी से साफ़ तौर पर पता चलता है कि मॉडल में ट्रेनिंग देने लायक 2.5 अरब पैरामीटर हैं.

फ़ॉर्मैटिंग हेल्पर फ़ंक्शन तय करना

from IPython.display import Markdown
import textwrap

def display_chat(prompt, text):
  formatted_prompt = "<font size='+1' color='brown'>🙋‍♂️<blockquote>" + prompt + "</blockquote></font>"
  text = text.replace('•', '  *')
  text = textwrap.indent(text, '> ', predicate=lambda _: True)
  formatted_text = "<font size='+1' color='teal'>🤖\n\n" + text + "\n</font>"
  return Markdown(formatted_prompt+formatted_text)

def to_markdown(text):
  text = text.replace('•', '  *')
  return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))

चैटबॉट बनाना

Gemma के निर्देशों वाले मॉडल gemma_1.1_instruct_2b_en को इन टर्न टोकन को समझने के लिए ऑप्टिमाइज़ किया गया है:

<start_of_turn>user\n  ... <end_of_turn>\n
<start_of_turn>model\n ... <end_of_turn>\n

इस ट्यूटोरियल में चैटबॉट बनाने के लिए इन टोकन का इस्तेमाल किया गया है. Gemma कंट्रोल टोकन के बारे में ज़्यादा जानने के लिए, फ़ॉर्मैटिंग और सिस्टम से जुड़े निर्देश देखें.

बातचीत की स्थिति मैनेज करने के लिए, चैट हेल्पर बनाएं

class ChatState():
  """
  Manages the conversation history for a turn-based chatbot
  Follows the turn-based conversation guidelines for the Gemma family of models
  documented at https://ai.google.dev/gemma/docs/formatting
  """

  __START_TURN_USER__ = "<start_of_turn>user\n"
  __START_TURN_MODEL__ = "<start_of_turn>model\n"
  __END_TURN__ = "<end_of_turn>\n"

  def __init__(self, model, system=""):
    """
    Initializes the chat state.

    Args:
        model: The language model to use for generating responses.
        system: (Optional) System instructions or bot description.
    """
    self.model = model
    self.system = system
    self.history = []

  def add_to_history_as_user(self, message):
      """
      Adds a user message to the history with start/end turn markers.
      """
      self.history.append(self.__START_TURN_USER__ + message + self.__END_TURN__)

  def add_to_history_as_model(self, message):
      """
      Adds a model response to the history with start/end turn markers.
      """
      self.history.append(self.__START_TURN_MODEL__ + message + self.__END_TURN__)

  def get_history(self):
      """
      Returns the entire chat history as a single string.
      """
      return "".join([*self.history])

  def get_full_prompt(self):
    """
    Builds the prompt for the language model, including history and system description.
    """
    prompt = self.get_history() + self.__START_TURN_MODEL__
    if len(self.system)>0:
      prompt = self.system + "\n" + prompt
    return prompt

  def send_message(self, message):
    """
    Handles sending a user message and getting a model response.

    Args:
        message: The user's message.

    Returns:
        The model's response.
    """
    self.add_to_history_as_user(message)
    prompt = self.get_full_prompt()
    response = self.model.generate(prompt, max_length=1024)
    result = response.replace(prompt, "")  # Extract only the new response
    self.add_to_history_as_model(result)
    return result

मॉडल के साथ चैट करें

मॉडल के साथ चैट करना शुरू करें.

chat = ChatState(gemma_lm)
message = "Tell me, in a few words,  how to compute all prime numbers up to 1000?"
display_chat(message, chat.send_message(message))

🙋‍♂️

मुझे कुछ शब्दों में बताएं कि 1,000 तक की सभी प्राइम संख्याओं का हिसाब कैसे लगाएं?
̋

किसी दी गई सीमा तक सभी प्राइम संख्याओं की गिनती के लिए, सिव ऑफ़ एराटोस्थीनिस का काफ़ी इस्तेमाल होता है. इसमें हर प्राइम नंबर के मल्टीपल को बार-बार मार्क करना शामिल है.

बातचीत जारी रखें.

message = "Now in Python! No numpy, please!"
display_chat(message, chat.send_message(message))

🙋‍♂️

अब Python में! कृपया हमारी जानकारी दें, ताकि आप हमसे संपर्क न करें!
🤖

def prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

message = "Thank you, it works! Can you explain the code in plain English?"
display_chat(message, chat.send_message(message))

🙋‍♂️

धन्यवाद, यह सही तरीके से काम कर रहा है! क्या आपको कोड को आसान अंग्रेज़ी में समझा जा सकता है?
🤖`

दिया गया कोड, prime फ़ंक्शन के बारे में बताता है. इससे यह पता चलता है कि दी गई संख्या, प्राइम है या नहीं.

यह सुविधा कैसे काम करती है:

  • फ़ंक्शन एक तर्क, n लेता है, जो वह संख्या है जिसकी जांच करनी है.

  • यह सबसे पहले यह पता लगाता है कि n, 1 से कम है या उसके बराबर है. अगर ऐसा है, तो संख्या प्राइम नहीं होती है, इसलिए फ़ंक्शन False दिखाता है.

  • इसके बाद यह एक लूप में पहुंचता है, जो 2 से लेकर n के वर्गमूल तक की संख्याओं के ज़रिए फिर से दोहराया जाता है.

  • हर i संख्या के लिए, यह जांच करता है कि n को i से बराबर तौर पर विभाजित किया जा सकता है या नहीं (यानी, n % i == 0).

  • अगर n को i से विभाजित किया जा सकता है, तो फ़ंक्शन False लौटाता है, क्योंकि अगर n का भाजक (डिवाइज़र) है, तो उसे प्राइम नहीं माना जा सकता.

  • अगर लूप, n के लिए कोई डिवाइज़र खोजे बिना पूरा होता है, तो फ़ंक्शन True दिखाता है कि n एक प्राइम नंबर है.

इस्तेमाल का उदाहरण:

>>> prime(2)
True
>>> prime(3)
True
>>> prime(4)
False
>>> prime(5)
True

इस कोड के फ़ायदे:

  • यह अभाज्य संख्याएं ढूंढने का आसान और कारगर एल्गोरिदम है.
  • इसका इस्तेमाल कई तरह के कंप्यूटर साइंस और गणित के ऐप्लिकेशन में किया जाता है.
message = "Great! Now add those explanations as comments in the code."
display_chat(message, chat.send_message(message))

🙋‍♂️

बढ़िया! अब उन एक्सप्लेनेशंस को कोड में टिप्पणियों के तौर पर जोड़ें.
🤖

def prime(n):
    """
    Checks whether a given number is prime or not.

    Args:
        n: The number to check.

    Returns:
        True if n is prime, False otherwise.
    """

    # Check if n is less than or equal to 1.
    if n <= 1:
        return False

    # Iterate through numbers from 2 to the square root of n.
    for i in range(2, int(n**0.5) + 1):
        # Check if n is divisible by i.
        if n % i == 0:
            return False

    # If the loop completes without finding any divisors for n, then n is prime.
    return True

जनरेट किया गया कोड चलाकर, जनरेट किए गए रिस्पॉन्स की जांच करें:

def is_prime(n):
  """
  Checks if a number is prime.

  Args:
    n: The number to check.

  Returns:
    True if n is prime, False otherwise.
  """

  # If n is less than or equal to 1, it is not prime.
  if n <= 1:
    return False

  # Iterate through all the numbers from 2 to the square root of n.
  for i in range(2, int(n**0.5) + 1):
    # If n is divisible by any of the numbers in the range from 2 to the square root of n, it is not prime.
    if n % i == 0:
      return False

  # If no divisors are found, n is prime.
  return True


# Initialize an empty list to store prime numbers.
primes = []

# Iterate through all the numbers from 2 to 1000.
for i in range(2, 1001):
  # If the number is prime, add it to the list.
  if is_prime(i):
    primes.append(i)

# Print the prime numbers.
print(primes)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]

get_history तरीके का इस्तेमाल करके देखें कि Chat क्लास ने पूरे कॉन्टेक्स्ट को कैसे बनाए रखा है.

print(chat.get_history())
<start_of_turn>user
Tell me, in a few words,  how to compute all prime numbers up to 1000?<end_of_turn>
<start_of_turn>model
The Sieve of Eratosthenes is a widely used method to compute all prime numbers up to a given limit. It involves iteratively marking out multiples of each prime number.<end_of_turn>
<start_of_turn>user
Now in Python! No numpy, please!<end_of_turn>
<start_of_turn>model

```python
def prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True
```<end_of_turn>
<start_of_turn>user
Thank you, it works! Can you explain the code in plain English?<end_of_turn>
<start_of_turn>model
The provided code defines a function `prime` that checks whether a given number is prime or not.

**How it works:**

- The function takes a single argument, `n`, which is the number to check.


- It first checks if `n` is less than or equal to 1. If it is, the number is not prime, so the function returns `False`.


- It then enters a loop that iterates through numbers from 2 to the square root of `n`.


- For each number `i`, it checks if `n` is divisible evenly by `i` (i.e., `n % i == 0`).


- If `n` is divisible by `i`, the function returns `False` because `n` cannot be prime if it has a divisor.


- If the loop completes without finding any divisors for `n`, the function returns `True`, indicating that `n` is a prime number.


**Example Usage:**

```python
>>> prime(2)
True
>>> prime(3)
True
>>> prime(4)
False
>>> prime(5)
True
```

**Benefits of this Code:**

- It is a simple and efficient algorithm for finding prime numbers.
- It is widely used in various computer science and mathematical applications.<end_of_turn>
<start_of_turn>user
Great! Now add those explanations as comments in the code.<end_of_turn>
<start_of_turn>model
```python
def prime(n):
    """
    Checks whether a given number is prime or not.

    Args:
        n: The number to check.

    Returns:
        True if n is prime, False otherwise.
    """

    # Check if n is less than or equal to 1.
    if n <= 1:
        return False

    # Iterate through numbers from 2 to the square root of n.
    for i in range(2, int(n**0.5) + 1):
        # Check if n is divisible by i.
        if n % i == 0:
            return False

    # If the loop completes without finding any divisors for n, then n is prime.
    return True
```<end_of_turn>

खास जानकारी और आगे का लेख

इस ट्यूटोरियल में, आपने JAX पर Keras का इस्तेमाल करके Gemma 2B निर्देश ट्यून किया गया मॉडल से चैट करने का तरीका सीखा.

जेमा के बारे में ज़्यादा जानने के लिए, ये गाइड और ट्यूटोरियल देखें: