ट्यूटोरियल: Gemini API का इस्तेमाल शुरू करना


Google के एआई पर देखें Google Colab में चलाएं GitHub पर सोर्स देखें

इस क्विकस्टार्ट में, Gemini API के लिए Python SDK टूल इस्तेमाल करने का तरीका बताया गया है. आपको Google के Gemini के लार्ज लैंग्वेज मॉडल का ऐक्सेस देता है. इस क्विकस्टार्ट में, आपको इनके बारे में जानकारी मिलेगी:

  1. Gemini का इस्तेमाल करने के लिए, अपने डेवलपमेंट एनवायरमेंट और एपीआई का ऐक्सेस सेट अप करें.
  2. टेक्स्ट इनपुट से टेक्स्ट रिस्पॉन्स जनरेट करें.
  3. मल्टीमोडल इनपुट (टेक्स्ट और इमेज) की मदद से टेक्स्ट रिस्पॉन्स जनरेट करें.
  4. कभी-कभी होने वाली बातचीत (चैट) के लिए, Gemini का इस्तेमाल करें.
  5. बड़े लैंग्वेज मॉडल के लिए एम्बेड करने की सुविधा का इस्तेमाल करना.

ज़रूरी शर्तें

आप इस क्विकस्टार्ट को Google में चला सकते हैं Colab, जो इस notebook को सीधे ब्राउज़र में चलाता है. साथ ही, इसके लिए अतिरिक्त एनवायरमेंट कॉन्फ़िगरेशन.

इसके अलावा, इस क्विकस्टार्ट को स्थानीय तौर पर पूरा करने के लिए, पक्का करें कि ये सुविधाएं इन ज़रूरी शर्तों को पूरा करती हैं:

  • Python 3.9 और उसके बाद के वर्शन
  • नोटबुक को चलाने के लिए jupyter को इंस्टॉल किया गया.

सेटअप

Python SDK टूल इंस्टॉल करें

Gemini API के लिए Python SDK टूल google-generativeai पैकेज. पीआईपी की मदद से, डिपेंडेंसी इंस्टॉल करें:

pip install -q -U google-generativeai

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

ज़रूरी पैकेज इंपोर्ट करें.

import pathlib
import textwrap

import google.generativeai as genai

from IPython.display import display
from IPython.display import Markdown

def to_markdown(text):
  text = text.replace('•', '  *')
  return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))
# Used to securely store your API key
from google.colab import userdata

एपीआई पासकोड सेट अप करना

Gemini API का इस्तेमाल करने से पहले, आपको एपीआई पासकोड हासिल करना होगा. अगर आपको पहले से कोई बटन नहीं है, तो Google AI Studio में बस एक क्लिक करके कुंजी बनाएं.

एपीआई पासकोड पाएं

Colab में, "GIF" में जाकर सीक्रेट मैनेजर में कुंजी जोड़ें क्लिक करें. इसे GOOGLE_API_KEY नाम दें.

एपीआई पासकोड मिलने के बाद, उसे SDK टूल को भेजें. आप इसे दो तरीकों से कर सकते हैं:

  • कुंजी को GOOGLE_API_KEY एनवायरमेंट वैरिएबल में रखें (SDK टूल वहां से अपने-आप पिक अप कर सकता है).
  • कुंजी को genai.configure(api_key=...) को पास करें
# Or use `os.getenv('GOOGLE_API_KEY')` to fetch an environment variable.
GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')

genai.configure(api_key=GOOGLE_API_KEY)

मॉडल की सूची बनाएं

अब Gemini API का इस्तेमाल किया जा सकता है. list_models का इस्तेमाल करके Gemini के मॉडल:

  • gemini-1.5-flash: हमारा सबसे तेज़ मल्टी-मॉडल मॉडल
  • gemini-1.5-pro: हमारा सबसे बेहतर और स्मार्ट मल्टी-मॉडल मॉडल
for m in genai.list_models():
  if 'generateContent' in m.supported_generation_methods:
    print(m.name)

टेक्स्ट इनपुट से टेक्स्ट जनरेट करें

सिर्फ़ टेक्स्ट प्रॉम्प्ट के लिए, Gemini 1.5 मॉडल या Gemini 1.0 Pro मॉडल का इस्तेमाल करें:

model = genai.GenerativeModel('gemini-1.5-flash')

generate_content तरीके से कई तरह के मामलों को हैंडल किया जा सकता है. इनमें ये शामिल हैं मल्टी-टर्न चैट और मल्टीमोडल इनपुट. यह इस बात पर निर्भर करता है कि मॉडल कौनसा है इस्तेमाल किया जा सकता है. उपलब्ध मॉडल में, इनपुट और टेक्स्ट के तौर पर सिर्फ़ टेक्स्ट और इमेज का इस्तेमाल किया जा सकता है एक आउटपुट के रूप में.

सबसे आसान मामले में, एक प्रॉम्प्ट स्ट्रिंग GenerativeModel.generate_content तरीका:

%%time
response = model.generate_content("What is the meaning of life?")
CPU times: user 110 ms, sys: 12.3 ms, total: 123 ms
Wall time: 8.25 s

कुछ मामलों में, आपको सिर्फ़ response.text ऐक्सेसर की ज़रूरत होगी. दिखाने के लिए फ़ॉर्मैट किए गए Markdown टेक्स्ट के लिए, to_markdown फ़ंक्शन का इस्तेमाल करें:

to_markdown(response.text)
The query of life's purpose has perplexed people across centuries, cultures, and continents. While there is no universally recognized response, many ideas have been put forth, and the response is frequently dependent on individual ideas, beliefs, and life experiences.

1.  **Happiness and Well-being:** Many individuals believe that the goal of life is to attain personal happiness and well-being. This might entail locating pursuits that provide joy, establishing significant connections, caring for one's physical and mental health, and pursuing personal goals and interests.

2.  **Meaningful Contribution:** Some believe that the purpose of life is to make a meaningful contribution to the world. This might entail pursuing a profession that benefits others, engaging in volunteer or charitable activities, generating art or literature, or inventing.

3.  **Self-realization and Personal Growth:** The pursuit of self-realization and personal development is another common goal in life. This might entail learning new skills, pushing one's boundaries, confronting personal obstacles, and evolving as a person.

4.  **Ethical and Moral Behavior:** Some believe that the goal of life is to act ethically and morally. This might entail adhering to one's moral principles, doing the right thing even when it is difficult, and attempting to make the world a better place.

5.  **Spiritual Fulfillment:** For some, the purpose of life is connected to spiritual or religious beliefs. This might entail seeking a connection with a higher power, practicing religious rituals, or following spiritual teachings.

6.  **Experiencing Life to the Fullest:** Some individuals believe that the goal of life is to experience all that it has to offer. This might entail traveling, trying new things, taking risks, and embracing new encounters.

7.  **Legacy and Impact:** Others believe that the purpose of life is to leave a lasting legacy and impact on the world. This might entail accomplishing something noteworthy, being remembered for one's contributions, or inspiring and motivating others.

8.  **Finding Balance and Harmony:** For some, the purpose of life is to find balance and harmony in all aspects of their lives. This might entail juggling personal, professional, and social obligations, seeking inner peace and contentment, and living a life that is in accordance with one's values and beliefs.

Ultimately, the meaning of life is a personal journey, and different individuals may discover their own unique purpose through their experiences, reflections, and interactions with the world around them.

अगर एपीआई से कोई नतीजा नहीं मिलता, तो GenerateContentResponse.prompt_feedback ताकि यह पता चल सके कि इस सवाल को सुरक्षा से जुड़ी किसी समस्या की वजह से ब्लॉक तो नहीं किया गया.

response.prompt_feedback
safety_ratings {
  category: HARM_CATEGORY_SEXUALLY_EXPLICIT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HATE_SPEECH
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HARASSMENT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_DANGEROUS_CONTENT
  probability: NEGLIGIBLE
}

Gemini, एक प्रॉम्प्ट के लिए कई जवाब जनरेट कर सकता है. ये संभावित जवाबों को candidates कहा जाता है. आपके पास इन्हें चुनने के लिए, जो जवाब के तौर पर सबसे सही हो.

इसके साथ जवाब उम्मीदवारों को देखें GenerateContentResponse.candidates:

response.candidates
[
  content {
    parts {
      text: "The query of life\'s purpose has perplexed people across centuries, cultures, and continents. While there is no universally recognized response, many ideas have been put forth, and the response is frequently dependent on individual ideas, beliefs, and life experiences.\n\n1. **Happiness and Well-being:** Many individuals believe that the goal of life is to attain personal happiness and well-being. This might entail locating pursuits that provide joy, establishing significant connections, caring for one\'s physical and mental health, and pursuing personal goals and interests.\n\n2. **Meaningful Contribution:** Some believe that the purpose of life is to make a meaningful contribution to the world. This might entail pursuing a profession that benefits others, engaging in volunteer or charitable activities, generating art or literature, or inventing.\n\n3. **Self-realization and Personal Growth:** The pursuit of self-realization and personal development is another common goal in life. This might entail learning new skills, pushing one\'s boundaries, confronting personal obstacles, and evolving as a person.\n\n4. **Ethical and Moral Behavior:** Some believe that the goal of life is to act ethically and morally. This might entail adhering to one\'s moral principles, doing the right thing even when it is difficult, and attempting to make the world a better place.\n\n5. **Spiritual Fulfillment:** For some, the purpose of life is connected to spiritual or religious beliefs. This might entail seeking a connection with a higher power, practicing religious rituals, or following spiritual teachings.\n\n6. **Experiencing Life to the Fullest:** Some individuals believe that the goal of life is to experience all that it has to offer. This might entail traveling, trying new things, taking risks, and embracing new encounters.\n\n7. **Legacy and Impact:** Others believe that the purpose of life is to leave a lasting legacy and impact on the world. This might entail accomplishing something noteworthy, being remembered for one\'s contributions, or inspiring and motivating others.\n\n8. **Finding Balance and Harmony:** For some, the purpose of life is to find balance and harmony in all aspects of their lives. This might entail juggling personal, professional, and social obligations, seeking inner peace and contentment, and living a life that is in accordance with one\'s values and beliefs.\n\nUltimately, the meaning of life is a personal journey, and different individuals may discover their own unique purpose through their experiences, reflections, and interactions with the world around them."
    }
    role: "model"
  }
  finish_reason: STOP
  index: 0
  safety_ratings {
    category: HARM_CATEGORY_SEXUALLY_EXPLICIT
    probability: NEGLIGIBLE
  }
  safety_ratings {
    category: HARM_CATEGORY_HATE_SPEECH
    probability: NEGLIGIBLE
  }
  safety_ratings {
    category: HARM_CATEGORY_HARASSMENT
    probability: NEGLIGIBLE
  }
  safety_ratings {
    category: HARM_CATEGORY_DANGEROUS_CONTENT
    probability: NEGLIGIBLE
  }
]

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

जवाबों को स्ट्रीम करने के लिए, GenerativeModel.generate_content(..., stream=True) का इस्तेमाल करें.

%%time
response = model.generate_content("What is the meaning of life?", stream=True)
CPU times: user 102 ms, sys: 25.1 ms, total: 128 ms
Wall time: 7.94 s
for chunk in response:
  print(chunk.text)
  print("_"*80)
The query of life's purpose has perplexed people across centuries, cultures, and
________________________________________________________________________________
 continents. While there is no universally recognized response, many ideas have been put forth, and the response is frequently dependent on individual ideas, beliefs, and life experiences
________________________________________________________________________________
.

1.  **Happiness and Well-being:** Many individuals believe that the goal of life is to attain personal happiness and well-being. This might entail locating pursuits that provide joy, establishing significant connections, caring for one's physical and mental health, and pursuing personal goals and aspirations.

2.  **Meaning
________________________________________________________________________________
ful Contribution:** Some believe that the purpose of life is to make a meaningful contribution to the world. This might entail pursuing a profession that benefits others, engaging in volunteer or charitable activities, generating art or literature, or inventing.

3.  **Self-realization and Personal Growth:** The pursuit of self-realization and personal development is another common goal in life. This might entail learning new skills, exploring one's interests and abilities, overcoming obstacles, and becoming the best version of oneself.

4.  **Connection and Relationships:** For many individuals, the purpose of life is found in their relationships with others. This might entail building
________________________________________________________________________________
 strong bonds with family and friends, fostering a sense of community, and contributing to the well-being of those around them.

5.  **Spiritual Fulfillment:** For those with religious or spiritual beliefs, the purpose of life may be centered on seeking spiritual fulfillment or enlightenment. This might entail following religious teachings, engaging in spiritual practices, or seeking a deeper understanding of the divine.

6.  **Experiencing the Journey:** Some believe that the purpose of life is simply to experience the journey itself, with all its joys and sorrows. This perspective emphasizes embracing the present moment, appreciating life's experiences, and finding meaning in the act of living itself.

7.  **Legacy and Impact:** For others, the goal of life is to leave a lasting legacy or impact on the world. This might entail making a significant contribution to a particular field, leaving a positive mark on future generations, or creating something that will be remembered and cherished long after one's lifetime.

Ultimately, the meaning of life is a personal and subjective question, and there is no single, universally accepted answer. It is about discovering what brings you fulfillment, purpose, and meaning in your own life, and living in accordance with those values.
________________________________________________________________________________

स्ट्रीम करते समय, रिस्पॉन्स से जुड़े कुछ एट्रिब्यूट तब तक उपलब्ध नहीं होते, जब तक कि उन्हें फिर से नहीं दोहराया जाता अलग-अलग जवाब दें. इसके बारे में यहां बताया गया है:

response = model.generate_content("What is the meaning of life?", stream=True)

prompt_feedback एट्रिब्यूट काम करता है:

response.prompt_feedback
safety_ratings {
  category: HARM_CATEGORY_SEXUALLY_EXPLICIT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HATE_SPEECH
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HARASSMENT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_DANGEROUS_CONTENT
  probability: NEGLIGIBLE
}

हालांकि, text जैसे एट्रिब्यूट से ऐसा नहीं होता:

try:
  response.text
except Exception as e:
  print(f'{type(e).__name__}: {e}')
IncompleteIterationError: Please let the response complete iteration before accessing the final accumulated
attributes (or call `response.resolve()`)

इमेज और टेक्स्ट इनपुट से टेक्स्ट जनरेट करें

Gemini कई तरह के मॉडल उपलब्ध कराता है, जो मल्टीमोडल इनपुट का इस्तेमाल कर सकते हैं (Gemini 1.5 मॉडल) ताकि आप टेक्स्ट और इमेज दोनों इनपुट कर सकें. कृपया प्रॉम्प्ट के लिए इमेज से जुड़ी ज़रूरी शर्तें.

अगर प्रॉम्प्ट इनपुट में टेक्स्ट और इमेज, दोनों शामिल हैं, तो Gemini 1.5 का इस्तेमाल टेक्स्ट आउटपुट जनरेट करने का GenerativeModel.generate_content तरीका:

आइए, एक इमेज शामिल करें:

curl -o image.jpg https://t0.gstatic.com/licensed-image?q=tbn:ANd9GcQ_Kevbk21QBRy-PgB4kQpS79brbmmEG7m3VOTShAn4PecDU5H5UxrJxE3Dw1JiaG17V88QIol19-3TM2wCHw
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100  405k  100  405k    0     0  6982k      0 --:--:-- --:--:-- --:--:-- 7106k
import PIL.Image

img = PIL.Image.open('image.jpg')
img

png

Gemini 1.5 मॉडल का इस्तेमाल करें और generate_content की मदद से, इस मॉडल को इमेज पास करें.

model = genai.GenerativeModel('gemini-1.5-flash')
response = model.generate_content(img)

to_markdown(response.text)
Chicken Teriyaki Meal Prep Bowls with brown rice, roasted broccoli and bell peppers.

किसी प्रॉम्प्ट में टेक्स्ट और इमेज, दोनों की जानकारी देने के लिए, स्ट्रिंग वाली सूची पास करें और इमेज:

response = model.generate_content(["Write a short, engaging blog post based on this picture. It should include a description of the meal in the photo and talk about my journey meal prepping.", img], stream=True)
response.resolve()
to_markdown(response.text)
Meal prepping is a great way to save time and money, and it can also help you to eat healthier. This meal is a great example of a healthy and delicious meal that can be easily prepped ahead of time.

This meal features brown rice, roasted vegetables, and chicken teriyaki. The brown rice is a whole grain that is high in fiber and nutrients. The roasted vegetables are a great way to get your daily dose of vitamins and minerals. And the chicken teriyaki is a lean protein source that is also packed with flavor.

This meal is easy to prepare ahead of time. Simply cook the brown rice, roast the vegetables, and cook the chicken teriyaki. Then, divide the meal into individual containers and store them in the refrigerator. When you're ready to eat, simply grab a container and heat it up.

This meal is a great option for busy people who are looking for a healthy and delicious way to eat. It's also a great meal for those who are trying to lose weight or maintain a healthy weight.

If you're looking for a healthy and delicious meal that can be easily prepped ahead of time, this meal is a great option. Give it a try today!

चैट पर की गई बातचीत

Gemini की मदद से, फ़्रीफ़ॉर्म तौर पर कई बार बातचीत की जा सकती है. कॉन्टेंट बनाने ChatSession क्लास, की तरह है, इसलिए generate_content के विपरीत, आपको बातचीत के इतिहास को सूची के तौर पर दिखाता है.

चैट शुरू करें:

model = genai.GenerativeModel('gemini-1.5-flash')
chat = model.start_chat(history=[])
chat
<google.generativeai.generative_models.ChatSession at 0x7b7b68250100>

कॉन्टेंट बनाने ChatSession.send_message तरीका, GenerateContentResponse टाइप से मिलता-जुलता है GenerativeModel.generate_content. इसमें आपका मैसेज और चैट के इतिहास में जवाब भी शामिल होता है:

response = chat.send_message("In one sentence, explain how a computer works to a young child.")
to_markdown(response.text)
A computer is like a very smart machine that can understand and follow our instructions, help us with our work, and even play games with us!
chat.history
[
  parts {
    text: "In one sentence, explain how a computer works to a young child."
  }
  role: "user",
  parts {
    text: "A computer is like a very smart machine that can understand and follow our instructions, help us with our work, and even play games with us!"
  }
  role: "model"
]

बातचीत जारी रखने के लिए, मैसेज भेजना जारी रखा जा सकता है. इसका इस्तेमाल करें चैट को स्ट्रीम करने के लिए stream=True आर्ग्युमेंट:

response = chat.send_message("Okay, how about a more detailed explanation to a high schooler?", stream=True)

for chunk in response:
  print(chunk.text)
  print("_"*80)
A computer works by following instructions, called a program, which tells it what to
________________________________________________________________________________
 do. These instructions are written in a special language that the computer can understand, and they are stored in the computer's memory. The computer's processor
________________________________________________________________________________
, or CPU, reads the instructions from memory and carries them out, performing calculations and making decisions based on the program's logic. The results of these calculations and decisions are then displayed on the computer's screen or stored in memory for later use.

To give you a simple analogy, imagine a computer as a
________________________________________________________________________________
 chef following a recipe. The recipe is like the program, and the chef's actions are like the instructions the computer follows. The chef reads the recipe (the program) and performs actions like gathering ingredients (fetching data from memory), mixing them together (performing calculations), and cooking them (processing data). The final dish (the output) is then presented on a plate (the computer screen).

In summary, a computer works by executing a series of instructions, stored in its memory, to perform calculations, make decisions, and display or store the results.
________________________________________________________________________________

glm.Content ऑब्जेक्ट में glm.Part ऑब्जेक्ट की एक सूची है. हर ऑब्जेक्ट में ये शामिल हैं टेक्स्ट (स्ट्रिंग) या inline_data (glm.Blob) में, जहां BLOB में बाइनरी हो डेटा और mime_type. चैट का इतिहास, glm.Content की सूची के तौर पर उपलब्ध है में मौजूद ऑब्जेक्ट ChatSession.history:

for message in chat.history:
  display(to_markdown(f'**{message.role}**: {message.parts[0].text}'))
**user**: In one sentence, explain how a computer works to a young child.

**model**: A computer is like a very smart machine that can understand and follow our instructions, help us with our work, and even play games with us!

**user**: Okay, how about a more detailed explanation to a high schooler?

**model**: A computer works by following instructions, called a program, which tells it what to do. These instructions are written in a special language that the computer can understand, and they are stored in the computer's memory. The computer's processor, or CPU, reads the instructions from memory and carries them out, performing calculations and making decisions based on the program's logic. The results of these calculations and decisions are then displayed on the computer's screen or stored in memory for later use.

To give you a simple analogy, imagine a computer as a chef following a recipe. The recipe is like the program, and the chef's actions are like the instructions the computer follows. The chef reads the recipe (the program) and performs actions like gathering ingredients (fetching data from memory), mixing them together (performing calculations), and cooking them (processing data). The final dish (the output) is then presented on a plate (the computer screen).

In summary, a computer works by executing a series of instructions, stored in its memory, to perform calculations, make decisions, and display or store the results.

टोकन गिनें

बड़े लैंग्वेज मॉडल में एक कॉन्टेक्स्ट विंडो होती है और कॉन्टेक्स्ट विंडो अक्सर को टोकन की संख्या के हिसाब से मापा जाता है. Gemini API का इस्तेमाल करके, ये काम किए जा सकते हैं किसी भी genai.protos.Content ऑब्जेक्ट के लिए टोकन की संख्या तय करें. इस सबसे आसान स्थिति में, आप GenerativeModel.count_tokens नीचे बताया गया है:

model.count_tokens("What is the meaning of life?")
total_tokens: 7

इसी तरह, अपने ChatSession के लिए, token_count की जांच करें:

model.count_tokens(chat.history)
total_tokens: 501

एम्बेड करने की सुविधा का इस्तेमाल करना

एम्बेड करना एक तकनीक है, जिसका इस्तेमाल जानकारी को फ़्लोटिंग पॉइंट नंबर की सूची के रूप में दिखाने के लिए किया जाता है होता है. Gemini की मदद से टेक्स्ट (शब्द, वाक्य, और ब्लॉक) दिखाया जा सकता है होता है. इससे लोगों के लिए, टेक्स्ट की तुलना करना और उनमें अंतर करना आसान हो जाता है. एम्बेड करना. उदाहरण के लिए, एक जैसे विषय वाले दो टेक्स्ट या भावनाओं को ज़ाहिर करने के लिए, कॉन्टेंट एक जैसा होना चाहिए. कोसाइन (कोसाइन) समानता जैसी गणित की तुलना करने की तकनीकें. यह जानने के लिए कि और आपको एम्बेड का इस्तेमाल क्यों करना चाहिए, इसके बारे में ज़्यादा जानने के लिए, एम्बेडिंग" गाइड देखें.

एम्बेड करने की सुविधा जनरेट करने के लिए, embed_content तरीके का इस्तेमाल करें. यह तरीका नीचे दिए गए टास्क (task_type) के लिए एम्बेड करना:

टास्क किस तरह का है ब्यौरा
RETRIEVAL_QUERY तय करता है कि दिया गया टेक्स्ट, खोज/वापस पाने की सेटिंग में क्वेरी है.
RETRIEVAL_DOCUMENT तय करता है कि दिया गया टेक्स्ट, खोज/वापस पाने की सेटिंग में मौजूद दस्तावेज़ है. इस टास्क टाइप का इस्तेमाल करने के लिए, title होना ज़रूरी है.
SEMANTIC_SIMILARITY इससे पता चलता है कि दिए गए टेक्स्ट का इस्तेमाल, सिमैंटिक टेक्स्ट वाली समानता (STS) के लिए किया जाएगा.
वर्गीकरण इससे पता चलता है कि एम्बेड करने की सुविधा का इस्तेमाल, कैटगरी तय करने के लिए किया जाएगा.
क्लस्टरिंग इससे पता चलता है कि एम्बेड करने की सुविधा का इस्तेमाल, क्लस्टर बनाने के लिए किया जाएगा.

यहां दी गई चीज़ें, दस्तावेज़ वापस पाने के लिए एक स्ट्रिंग के लिए एम्बेडिंग जनरेट करती हैं:

result = genai.embed_content(
    model="models/embedding-001",
    content="What is the meaning of life?",
    task_type="retrieval_document",
    title="Embedding of single string")

# 1 input > 1 vector output
print(str(result['embedding'])[:50], '... TRIMMED]')
[-0.003216741, -0.013358698, -0.017649598, -0.0091 ... TRIMMED]

स्ट्रिंग के बैच को मैनेज करने के लिए, content में स्ट्रिंग की सूची पास करें:

result = genai.embed_content(
    model="models/embedding-001",
    content=[
      'What is the meaning of life?',
      'How much wood would a woodchuck chuck?',
      'How does the brain work?'],
    task_type="retrieval_document",
    title="Embedding of list of strings")

# A list of inputs > A list of vectors output
for v in result['embedding']:
  print(str(v)[:50], '... TRIMMED ...')
[0.0040260437, 0.004124458, -0.014209415, -0.00183 ... TRIMMED ...
[-0.004049845, -0.0075574904, -0.0073463684, -0.03 ... TRIMMED ...
[0.025310587, -0.0080734305, -0.029902633, 0.01160 ... TRIMMED ...

जबकि genai.embed_content फ़ंक्शन स्ट्रिंग या स्ट्रिंग की सूचियों को स्वीकार करता है, यह असल में, इसे genai.protos.Content टाइप के आस-पास बनाया गया है (जैसे GenerativeModel.generate_content). glm.Content ऑब्जेक्ट, एपीआई में बातचीत की मुख्य इकाइयां हैं.

genai.protos.Content ऑब्जेक्ट मल्टीमोडल होने के दौरान, embed_content का तरीका सिर्फ़ टेक्स्ट एम्बेड करने की सुविधा देता है. यह डिज़ाइन एपीआई को संभावना बढ़ाएं.

response.candidates[0].content
parts {
  text: "A computer works by following instructions, called a program, which tells it what to do. These instructions are written in a special language that the computer can understand, and they are stored in the computer\'s memory. The computer\'s processor, or CPU, reads the instructions from memory and carries them out, performing calculations and making decisions based on the program\'s logic. The results of these calculations and decisions are then displayed on the computer\'s screen or stored in memory for later use.\n\nTo give you a simple analogy, imagine a computer as a chef following a recipe. The recipe is like the program, and the chef\'s actions are like the instructions the computer follows. The chef reads the recipe (the program) and performs actions like gathering ingredients (fetching data from memory), mixing them together (performing calculations), and cooking them (processing data). The final dish (the output) is then presented on a plate (the computer screen).\n\nIn summary, a computer works by executing a series of instructions, stored in its memory, to perform calculations, make decisions, and display or store the results."
}
role: "model"
result = genai.embed_content(
    model = 'models/embedding-001',
    content = response.candidates[0].content)

# 1 input > 1 vector output
print(str(result['embedding'])[:50], '... TRIMMED ...')
[-0.013921871, -0.03504407, -0.0051786783, 0.03113 ... TRIMMED ...

इसी तरह, चैट के इतिहास में genai.protos.Content ऑब्जेक्ट की सूची होती है, इसे सीधे embed_content फ़ंक्शन में पास किया जा सकता है:

chat.history
[
  parts {
    text: "In one sentence, explain how a computer works to a young child."
  }
  role: "user",
  parts {
    text: "A computer is like a very smart machine that can understand and follow our instructions, help us with our work, and even play games with us!"
  }
  role: "model",
  parts {
    text: "Okay, how about a more detailed explanation to a high schooler?"
  }
  role: "user",
  parts {
    text: "A computer works by following instructions, called a program, which tells it what to do. These instructions are written in a special language that the computer can understand, and they are stored in the computer\'s memory. The computer\'s processor, or CPU, reads the instructions from memory and carries them out, performing calculations and making decisions based on the program\'s logic. The results of these calculations and decisions are then displayed on the computer\'s screen or stored in memory for later use.\n\nTo give you a simple analogy, imagine a computer as a chef following a recipe. The recipe is like the program, and the chef\'s actions are like the instructions the computer follows. The chef reads the recipe (the program) and performs actions like gathering ingredients (fetching data from memory), mixing them together (performing calculations), and cooking them (processing data). The final dish (the output) is then presented on a plate (the computer screen).\n\nIn summary, a computer works by executing a series of instructions, stored in its memory, to perform calculations, make decisions, and display or store the results."
  }
  role: "model"
]
result = genai.embed_content(
    model = 'models/embedding-001',
    content = chat.history)

# 1 input > 1 vector output
for i,v in enumerate(result['embedding']):
  print(str(v)[:50], '... TRIMMED...')
[-0.014632266, -0.042202696, -0.015757175, 0.01548 ... TRIMMED...
[-0.010979066, -0.024494737, 0.0092659835, 0.00803 ... TRIMMED...
[-0.010055617, -0.07208932, -0.00011750793, -0.023 ... TRIMMED...
[-0.013921871, -0.03504407, -0.0051786783, 0.03113 ... TRIMMED...

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

यहां दिए गए सेक्शन में, Gemini API के लिए Python SDK.

सुरक्षा सेटिंग

safety_settings आर्ग्युमेंट की मदद से, यह कॉन्फ़िगर किया जा सकता है कि मॉडल क्या ब्लॉक करता है और प्रॉम्प्ट और रिस्पॉन्स, दोनों में अनुमति देता है. सुरक्षा सेटिंग, डिफ़ॉल्ट रूप से कॉन्टेंट को ब्लॉक करती हैं इन सभी में से असुरक्षित कॉन्टेंट होने की सामान्य और/या ज़्यादा संभावना होती है डाइमेंशन. सुरक्षा के बारे में ज़्यादा जानें सेटिंग पर टैप करें.

कोई सवाल डालें और मॉडल को डिफ़ॉल्ट सुरक्षा सेटिंग के साथ चलाएं, और इसका कोई जवाब नहीं मिलेगा:

response = model.generate_content('[Questionable prompt here]')
response.candidates
[
  content {
    parts {
      text: "I\'m sorry, but this prompt involves a sensitive topic and I\'m not allowed to generate responses that are potentially harmful or inappropriate."
    }
    role: "model"
  }
  finish_reason: STOP
  index: 0
  safety_ratings {
    category: HARM_CATEGORY_SEXUALLY_EXPLICIT
    probability: NEGLIGIBLE
  }
  safety_ratings {
    category: HARM_CATEGORY_HATE_SPEECH
    probability: NEGLIGIBLE
  }
  safety_ratings {
    category: HARM_CATEGORY_HARASSMENT
    probability: NEGLIGIBLE
  }
  safety_ratings {
    category: HARM_CATEGORY_DANGEROUS_CONTENT
    probability: NEGLIGIBLE
  }
]

prompt_feedback से आपको पता चलेगा कि किस सुरक्षा फ़िल्टर ने प्रॉम्प्ट को ब्लॉक किया है:

response.prompt_feedback
safety_ratings {
  category: HARM_CATEGORY_SEXUALLY_EXPLICIT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HATE_SPEECH
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HARASSMENT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_DANGEROUS_CONTENT
  probability: NEGLIGIBLE
}

अब कॉन्फ़िगर की गई नई सुरक्षा सेटिंग से, मॉडल को यही प्रॉम्प्ट दें, आपको जवाब मिल सकता है.

response = model.generate_content('[Questionable prompt here]',
                                  safety_settings={'HARASSMENT':'block_none'})
response.text

साथ ही, यह भी ध्यान रखें कि हर उम्मीदवार के पास उसका अपना safety_ratings होता है, पास हो जाता है, लेकिन सुरक्षा जांच में उस व्यक्ति के जवाब फ़ेल हो जाते हैं.

मैसेज को कोड में बदलें

पिछले सेक्शन में, SDK टूल की जानकारी दी गई थी, ताकि आसानी से प्रॉम्प्ट भेजे जा सकें को एपीआई में बदलें. यह सेक्शन, पिछले वर्शन के जैसा ही पूरी तरह टाइप करता है उदाहरण के लिए, ताकि आप इस बारे में निचले स्तर के विवरण को बेहतर ढंग से समझ सकें कि SDK टूल, मैसेज को कोड में बदल देता है.

SDK टूल आपके मैसेज को genai.protos.Content ऑब्जेक्ट में बदलने की कोशिश करता है, इस सूची में ऐसे genai.protos.Part ऑब्जेक्ट हैं जिनमें से हर एक में इनमें से कोई एक शामिल है:

  1. a text (स्ट्रिंग)
  2. inline_data (genai.protos.Blob), जहां BLOB में बाइनरी data और mime_type.
  3. या अन्य तरह का डेटा शामिल नहीं करते.

इनमें से किसी भी क्लास को समकक्ष शब्दकोश के रूप में भी पास किया जा सकता है.

इसलिए, पिछले उदाहरण की तरह पूरी तरह टाइप किया गया तरीका यह है:

model = genai.GenerativeModel('gemini-1.5-flash')
response = model.generate_content(
    genai.protos.Content(
        parts = [
            genai.protos.Part(text="Write a short, engaging blog post based on this picture."),
            genai.protos.Part(
                inline_data=genai.protos.Blob(
                    mime_type='image/jpeg',
                    data=pathlib.Path('image.jpg').read_bytes()
                )
            ),
        ],
    ),
    stream=True)
response.resolve()

to_markdown(response.text[:100] + "... [TRIMMED] ...")
Meal prepping is a great way to save time and money, and it can also help you to eat healthier. By ... [TRIMMED] ...

कई मोड़ वाली बातचीत

हालांकि, पहले दिखाई गई genai.ChatSession क्लास, इस्तेमाल के कई उदाहरणों को हैंडल कर सकती है, लेकिन यह कुछ अनुमान लगाता है. अगर आपके इस्तेमाल का उदाहरण इस चैट में नहीं आता है लागू करने पर, याद रखा जा सकता है कि genai.ChatSession सिर्फ़ एक रैपर है आस-पास GenerativeModel.generate_content. एक अनुरोध के अलावा, यह बहु-मोड़ बातचीत भी मैनेज कर सकता है.

अलग-अलग मैसेज genai.protos.Content ऑब्जेक्ट हैं या एक-दूसरे के साथ काम करते हैं डिक्शनरी, जैसा कि पिछले सेक्शन में दिया गया है. शब्दकोश के रूप में, role और parts कुंजियों की ज़रूरत है. बातचीत में मौजूद role user, जिससे प्रॉम्प्ट मिलते हैं या model से जवाब मिलते हैं.

genai.protos.Content ऑब्जेक्ट की सूची पास करें और इसे ऐसा माना जाएगा मल्टी-टर्न चैट

model = genai.GenerativeModel('gemini-1.5-flash')

messages = [
    {'role':'user',
     'parts': ["Briefly explain how a computer works to a young child."]}
]
response = model.generate_content(messages)

to_markdown(response.text)
Imagine a computer as a really smart friend who can help you with many things. Just like you have a brain to think and learn, a computer has a brain too, called a processor. It's like the boss of the computer, telling it what to do.

Inside the computer, there's a special place called memory, which is like a big storage box. It remembers all the things you tell it to do, like opening games or playing videos.

When you press buttons on the keyboard or click things on the screen with the mouse, you're sending messages to the computer. These messages travel through special wires, called cables, to the processor.

The processor reads the messages and tells the computer what to do. It can open programs, show you pictures, or even play music for you.

All the things you see on the screen are created by the graphics card, which is like a magic artist inside the computer. It takes the processor's instructions and turns them into colorful pictures and videos.

To save your favorite games, videos, or pictures, the computer uses a special storage space called a hard drive. It's like a giant library where the computer can keep all your precious things safe.

And when you want to connect to the internet to play games with friends or watch funny videos, the computer uses something called a network card to send and receive messages through the internet cables or Wi-Fi signals.

So, just like your brain helps you learn and play, the computer's processor, memory, graphics card, hard drive, and network card all work together to make your computer a super-smart friend that can help you do amazing things!

बातचीत जारी रखने के लिए, जवाब के साथ दूसरा मैसेज जोड़ें.

messages.append({'role':'model',
                 'parts':[response.text]})

messages.append({'role':'user',
                 'parts':["Okay, how about a more detailed explanation to a high school student?"]})

response = model.generate_content(messages)

to_markdown(response.text)
At its core, a computer is a machine that can be programmed to carry out a set of instructions. It consists of several essential components that work together to process, store, and display information:

**1. Processor (CPU):**
   -   The brain of the computer.
   -   Executes instructions and performs calculations.
   -   Speed measured in gigahertz (GHz).
   -   More GHz generally means faster processing.

**2. Memory (RAM):**
   -   Temporary storage for data being processed.
   -   Holds instructions and data while the program is running.
   -   Measured in gigabytes (GB).
   -   More GB of RAM allows for more programs to run simultaneously.

**3. Storage (HDD/SSD):**
   -   Permanent storage for data.
   -   Stores operating system, programs, and user files.
   -   Measured in gigabytes (GB) or terabytes (TB).
   -   Hard disk drives (HDDs) are traditional, slower, and cheaper.
   -   Solid-state drives (SSDs) are newer, faster, and more expensive.

**4. Graphics Card (GPU):**
   -   Processes and displays images.
   -   Essential for gaming, video editing, and other graphics-intensive tasks.
   -   Measured in video RAM (VRAM) and clock speed.

**5. Motherboard:**
   -   Connects all the components.
   -   Provides power and communication pathways.

**6. Input/Output (I/O) Devices:**
   -   Allow the user to interact with the computer.
   -   Examples: keyboard, mouse, monitor, printer.

**7. Operating System (OS):**
   -   Software that manages the computer's resources.
   -   Provides a user interface and basic functionality.
   -   Examples: Windows, macOS, Linux.

When you run a program on your computer, the following happens:

1.  The program instructions are loaded from storage into memory.
2.  The processor reads the instructions from memory and executes them one by one.
3.  If the instruction involves calculations, the processor performs them using its arithmetic logic unit (ALU).
4.  If the instruction involves data, the processor reads or writes to memory.
5.  The results of the calculations or data manipulation are stored in memory.
6.  If the program needs to display something on the screen, it sends the necessary data to the graphics card.
7.  The graphics card processes the data and sends it to the monitor, which displays it.

This process continues until the program has completed its task or the user terminates it.

जनरेशन कॉन्फ़िगरेशन

generation_config आर्ग्युमेंट की मदद से, जनरेशन पैरामीटर में बदलाव किया जा सकता है. मॉडल को भेजे जाने वाले हर प्रॉम्प्ट में पैरामीटर की वैल्यू शामिल होती हैं. इनकी मदद से, यह तय किया जाता है कि तो मॉडल जवाब जनरेट करता है.

model = genai.GenerativeModel('gemini-1.5-flash')
response = model.generate_content(
    'Tell me a story about a magic backpack.',
    generation_config=genai.types.GenerationConfig(
        # Only one candidate for now.
        candidate_count=1,
        stop_sequences=['x'],
        max_output_tokens=20,
        temperature=1.0)
)
text = response.text

if response.candidates[0].finish_reason.name == "MAX_TOKENS":
    text += '...'

to_markdown(text)
Once upon a time, in a small town nestled amidst lush green hills, lived a young girl named...

आगे क्या करना है

  • प्रॉम्प्ट डिज़ाइन, ऐसे प्रॉम्प्ट बनाने की प्रोसेस है जिनसे उपयोगकर्ता की पसंद के बारे में पता चलता है लैंग्वेज मॉडल से मिले रिस्पॉन्स. अच्छी तरह से स्ट्रक्चर किए गए प्रॉम्प्ट लिखना किसी भाषा से सटीक और अच्छी क्वालिटी वाले जवाब पाने का ज़रूरी हिस्सा मॉडल. प्रॉम्प्ट के लिए सबसे सही तरीकों के बारे में जानें लिखना.
  • अलग-अलग कामों की ज़रूरतों को पूरा करने के लिए, Gemini कई तरह के मॉडल उपलब्ध कराता है मामलों, जैसे इनपुट प्रकार और जटिलता, चैट या अन्य डायलॉग लैंग्वेज टास्क, और साइज़ कंस्ट्रेंट. उपलब्ध सुविधाओं के बारे में जानें Gemini के मॉडल.