برنامج تعليمي: بدء استخدام Gemini API


العرض على تكنولوجيات الذكاء الاصطناعي من Google التنفيذ في Google Colab عرض المصدر على GitHub

تشرح هذه المقالة للبدء السريع كيفية استخدام حزمة Python API الخاصة بواجهة Gemini API، ما يتيح لك الوصول إلى نماذج Gemini اللغوية الكبيرة من Google. في هذه البداية السريعة، ستتعلم كيفية:

  1. لاستخدام Gemini، يُرجى إعداد بيئة التطوير وإمكانية الوصول إلى واجهة برمجة التطبيقات.
  2. إنشاء ردود نصية من الإدخالات النصية
  3. إنشاء ردود نصية من مدخلات متعددة الوسائط (النصوص والصور)
  4. استخدِم Gemini لإجراء محادثات متعددة الأدوار (الدردشة).
  5. يمكنك استخدام التضمينات للنماذج اللغوية الكبيرة.

المتطلّبات الأساسية

يمكنك بدء عملية التشغيل السريع هذه في Google Colab، الذي يشغِّل ورقة الملاحظات هذه مباشرةً في المتصفّح ولا يتطلّب أي إعدادات إضافية في البيئة.

بدلاً من ذلك، لإكمال هذا البدء السريع محليًا، تأكَّد من أنّ بيئة التطوير تستوفي المتطلبات التالية:

  • Python 3.9+
  • يجب تثبيت jupyter لتشغيل ورقة الملاحظات.

ضبط إعدادات الجهاز

تثبيت حزمة Python SDK

يتضمّن حزمة google-generativeai حزمة Python الخاصة بواجهة برمجة التطبيقات Gemini API. تثبيت التبعية باستخدام pip:

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، أضِف المفتاح إلى مدير السرّات ضمن "🔑" في اللوحة اليمنى. أدخِل الاسم 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. يمكنك استخدام "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)

أثار السؤال عن الغرض من الحياة حيرة لدى الأشخاص عبر القرون والثقافات والقارات. على الرغم من عدم وجود رد معترف به عالميًا، تم طرح العديد من الأفكار، وتعتمد الإجابة بشكل متكرر على الأفكار والمعتقدات والتجارب الفردية.

  1. السعادة والرفاهية: يعتقد الكثير من الأفراد أنّ الهدف من الحياة هو تحقيق السعادة والرفاهية الشخصية. وقد يستلزم هذا تحديد أماكن السعي وراء السعادة، وبناء علاقات وثيقة، والاهتمام بصحته الجسدية والعقلية، ومتابعة الأهداف والاهتمامات الشخصية.

  2. المساهمة الهادفة: يعتقد البعض أنّ الغرض من الحياة هو تقديم مساهمة هادفة للعالم. وقد يستلزم هذا ممارسة مهنة تفيد الآخرين، أو الانخراط في أنشطة تطوعية أو خيرية، أو إنشاء أعمال فنية أو أدب، أو اختراع.

  3. تحقيق الذات وتطوير الذات: إنّ السعي نحو تحقيق الذات وتطوير الذات هو هدف شائع آخر في الحياة. وهذا قد ينطوي على تعلم مهارات جديدة، وتجاوز الحدود، ومواجهة العقبات الشخصية، والتطور كشخص.

  4. السلوك الأخلاقي والأخلاقي:يعتقد البعض أنّ الهدف من الحياة هو التصرف على نحو أخلاقي وأخلاقي. وقد يستلزم هذا الالتزام بالمبادئ الأخلاقية للمرء، وفعل الشيء الصحيح حتى عندما يكون صعبًا ومحاولة جعل العالم مكانًا أفضل.

  5. تحقيق الإقبال الروحي: يرتبط هدف الحياة بالمعتقدات الروحانية أو الدينية لدى بعض الأشخاص. وقد يستلزم هذا السعي إلى تحقيق صلة بسلطة أعلى أو ممارسة طقوس دينية أو اتّباع تعاليم روحية.

  6. تحقيق أقصى استفادة من الحياة اليومية، يعتقد بعض الأفراد أنّ الهدف من الحياة هو تجربة كل مزاياه. وقد يتضمن ذلك السفر وتجربة أشياء جديدة والمخاطرة وتقبّل مواجهات جديدة.

  7. إرث وتأثير: يعتقد آخرون أن الهدف من الحياة هو ترك إرث دائم وتأثير دائم في العالم. وقد يستلزم ذلك إنجاز شيء جدير بالاهتمام أو تذكر مساهمات الشخص أو إلهام الآخرين وتحفيزهم.

  8. تحقيق التوازن والانسجام: بالنسبة إلى بعض الأشخاص، يكون الهدف من الحياة هو تحقيق التوازن والتناغم في جميع جوانب حياتهم. وقد يستلزم هذا التوفيق بين الالتزامات الشخصية والمهنية والاجتماعية، والسعي وراء سلام داخلي ورضا عالٍ، وعيش حياة تتوافق مع قيم الشخص ومعتقداته.

في نهاية المطاف، معنى الحياة هو رحلة شخصية، وقد يكتشف الأفراد المختلفون هدفهم الفريد من خلال تجاربهم وأفكارهم وتفاعلاتهم مع العالم من حولهم.

إذا لم تعرض واجهة برمجة التطبيقات نتيجة، يمكنك استخدام 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)

أطباق دجاج ترياكي التحضيرية مع أرز بني وبروكلي مشوي وفلفل حلو

لتقديم كل من النص والصور في الطلب، أدخِل قائمة تحتوي على السلاسل والصور:

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)

إنّ تحضير الوجبات هو طريقة رائعة لتوفير الوقت والمال، ويمكن أن يساعدك أيضًا في تناول طعام صحي. هذه الوجبة هي مثال رائع على وجبة صحية ولذيذة يمكن تحضيرها بسهولة في وقت مُسبق.

وتشمل هذه الوجبة الأرز البني والخضار المشوية والدجاج التيرياكي. الأرز البني هو حبة كاملة غنية بالألياف والمغذيات. الخضروات المشوية هي طريقة رائعة للحصول على جرعة يومية من الفيتامينات والمعادن. ويُعتبر ترياكي الدجاج مصدر بروتين خالٍ من الدهون والسكر والملح ومليء بالنكهات أيضًا.

من السهل إعداد هذه الوجبة مسبقًا. ما عليك سوى طهي الأرز البني وحمّص الخضار وطهي الدجاج التيرياكي. بعد ذلك، قسِّم الوجبة إلى حاويات فردية واحتفِظ بها في الثلاجة. عندما تكون جاهزًا لتناول الطعام، ما عليك سوى جلب وعاء لتسخينه.

تعد هذه الوجبة خيارًا رائعًا للأشخاص المشغولين الذين يبحثون عن طريقة تناول طعام صحية ولذيذة. وهو أيضًا وجبة رائعة للأشخاص الذين يحاولون إنقاص الوزن أو الحفاظ على وزنهم الصحي.

إذا كنت تبحث عن وجبة صحية ولذيذة يمكن تحضيرها بسهولة في وقت مُسبق، ستشكّل هذه الوجبة خيارًا رائعًا. ننصحك بتجربة الميزة اليوم.

محادثات Chat

يتيح لك 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)

يشبه الكمبيوتر الجهاز الذكي جدًا الذي يمكنه فهم تعليماتنا واتّباعها، ومساعدتك في إنجاز المهام، وحتى اللعب معنا.

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}'))

المستخدم: في جملة واحدة، اشرح آلية عمل الكمبيوتر بالنسبة إلى طفل صغير.

model: يشبه الكمبيوتر جهازًا ذكيًا جدًا يمكنه فهم تعليماتنا واتّباعها، ومساعدتك في إنجاز المهام، وحتى اللعب معنا.

المستخدم: حسنًا، ما رأيك بتقديم شرح أكثر تفصيلاً لأحد طلاب المرحلة الثانوية؟

model: يعمل الكمبيوتر وفقًا للتعليمات التي تُسمى البرنامج، والتي تخبره بما يجب تنفيذه. تمت كتابة هذه التعليمات بلغة خاصة يمكن للكمبيوتر فهمها، ويتم تخزينها في ذاكرة الكمبيوتر. يقرأ معالج الكمبيوتر، أو وحدة المعالجة المركزية (CPU)، التعليمات من الذاكرة وينفّذها، ويُجري العمليات الحسابية، ويتّخذ القرارات بناءً على منطق البرنامج. بعد ذلك يتم عرض نتائج هذه الحسابات والقرارات على شاشة الكمبيوتر أو يتم تخزينها في الذاكرة لاستخدامها لاحقًا.

للحصول على تشبيه بسيط، تخيل أن جهاز كمبيوتر كطاه يتبع وصفة طعام. تشبه الوصفة البرنامج، وإجراءات الطاهي تشبه التعليمات التي يتبعها الكمبيوتر. يقرأ الطاهي الوصفة (البرنامج) وينفذ إجراءات مثل جمع المكونات (جلب البيانات من الذاكرة)، ومزجها معًا (إجراء العمليات الحسابية)، وطهيها (معالجة البيانات). يتم بعد ذلك تقديم الطبق الأخير (الإخراج) على طبق (شاشة الكمبيوتر).

باختصار، يعمل الكمبيوتر عن طريق تنفيذ سلسلة من التعليمات، مخزنة في ذاكرته، لإجراء العمليات الحسابية، واتخاذ القرارات، وعرض النتائج أو تخزينها.

عدد الرموز المميّزة

تحتوي النماذج اللغوية الكبيرة على نافذة للسياق، وغالبًا ما يتم قياس طول السياق من حيث عدد الرموز المميّزة. باستخدام Gemini API، يمكنك تحديد عدد الرموز المميّزة لكلّ عنصر من عناصر genai.protos.Content. في أبسط الحالات، يمكنك تمرير سلسلة طلب بحث إلى الطريقة GenerativeModel.count_tokens على النحو التالي:

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

بالمثل، يمكنك التحقّق من token_count لجهاز ChatSession:

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...

حالات الاستخدام المتقدّمة

تناقش الأقسام التالية حالات الاستخدام المتقدّمة والتفاصيل الأدنى الخاصة بحزمة Python SDK الخاصة بـ Gemini API.

إعدادات الأمان

تتيح لك الوسيطة 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] ...")

إنّ تحضير الوجبات هو طريقة رائعة لتوفير الوقت والمال، ويمكن أن يساعدك أيضًا في تناول طعام صحي. بواسطة ... [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)

تخيّل جهاز الكمبيوتر كصديق ذكي يمكنه مساعدتك في العديد من الأمور. تمامًا مثل العقل للتفكير والتعلم، فإن جهاز الكمبيوتر لديه عقل أيضًا، يسمى المعالج. الأمر أشبه بمدير الكمبيوتر عندما يخبره بما يجب عليه فعله.

يوجد داخل الكمبيوتر مكان خاص يسمى الذاكرة، والذي يشبه صندوق تخزين كبير. يتذكّر التطبيق كل الطلبات التي تطلبها منه، مثل فتح الألعاب أو تشغيل الفيديوهات.

عند الضغط على أزرار لوحة المفاتيح أو النقر على العناصر المعروضة على الشاشة بالماوس، يتم إرسال رسائل إلى جهاز الكمبيوتر. تنتقل هذه الرسائل عبر أسلاك خاصة تُعرف باسم الكابلات إلى المعالج.

يقرأ المعالج الرسائل ويخبر الكمبيوتر بما يجب فعله. ويمكنه فتح البرامج أو عرض الصور أو حتى تشغيل الموسيقى لك.

يتم إنشاء جميع الأشياء التي تراها على الشاشة بواسطة بطاقة الرسومات، والتي تشبه الفنان السحري داخل جهاز الكمبيوتر. فهو يستخدم تعليمات معالج البيانات ويحولها إلى صور ومقاطع فيديو ملونة.

لحفظ الألعاب أو الفيديوهات أو الصور المفضلة لديك، يستخدم الكمبيوتر مساحة تخزين خاصة تُعرف باسم محرك الأقراص الثابتة. فالأمر يشبه مكتبة عملاقة حيث يمكن للكمبيوتر الاحتفاظ بجميع أشيائك الثمينة بأمان.

وعندما تريد الاتصال بالإنترنت لتشغيل الألعاب مع الأصدقاء أو مشاهدة فيديوهات مضحكة، يستخدم الكمبيوتر ما يُعرف باسم بطاقة الشبكة لإرسال الرسائل واستلامها عبر كابلات الإنترنت أو إشارات Wi-Fi.

لذا، مثلما يساعدك عقلك على التعلم واللعب، يعمل معالج الكمبيوتر والذاكرة وبطاقة الرسومات ومحرك الأقراص الثابتة وبطاقة الشبكة معًا لجعل جهاز الكمبيوتر صديقًا ذكيًا للغاية يمكنه مساعدتك في تنفيذ أشياء مدهشة!

لمتابعة المحادثة، أضِف الردّ ورسالة أخرى.

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)

الكمبيوتر في جوهره عبارة عن آلة يمكن برمجتها لتنفيذ مجموعة من التعليمات. وهي تتألف من العديد من المكونات الأساسية التي تعمل معًا لمعالجة المعلومات وتخزينها وعرضها:

‫1. معالِج البيانات (CPU): - عقل الكمبيوتر. - تنفيذ التعليمات وإجراء العمليات الحسابية. - يتم قياس السرعة بالغيغاهرتز (غيغاهرتز). - تعني زيادة غيغا هرتز بشكل عام معالجة أسرع.

2. الذاكرة (ذاكرة الوصول العشوائي): - مساحة تخزين مؤقتة للبيانات التي تتم معالجتها. - يتضمن التعليمات والبيانات أثناء تشغيل البرنامج. - يتم قياسه بالغيغابايت (GB). - المزيد من ذاكرة الوصول العشوائي (RAM) تسمح بتشغيل المزيد من البرامج في وقت واحد.

‫3. مساحة التخزين (HDD/SSD): - تخزين دائم للبيانات - تخزين ملفات نظام التشغيل والبرامج وملفات المستخدم - يتم قياسه بالجيجابايت (GB) أو تيرابايت (TB). - تعد محركات الأقراص الثابتة (HDD) تقليدية وأبطأ وأرخص. - محركات الأقراص ذات الحالة الصلبة (SSD) هي أحدث وأسرع وأكثر تكلفة.

‫4. بطاقة الرسومات (GPU): - لمعالجة الصور وعرضها. - إنها ضرورية للألعاب وتعديل الفيديوهات وغيرها من المهام التي تتطلب رسومات كثيفة. - يتم قياسها من خلال ذاكرة الوصول العشوائي للفيديو (VRAM) وسرعة الساعة.

‫5. اللوحة الأم: - تربط جميع المكوّنات. - يوفر مسارات القوة والتواصل.

‫6. أجهزة الإدخال/الإخراج (I/O): - تسمح للمستخدم بالتفاعل مع جهاز الكمبيوتر. - أمثلة: لوحة المفاتيح، والماوس، والشاشة، والطابعة.

‫7. نظام التشغيل (OS): - برنامج يدير موارد الكمبيوتر. - توفر واجهة مستخدم ووظائف أساسية. - أمثلة: Windows وmacOS وLinux.

عند تشغيل برنامج على الكمبيوتر، يحدث ما يلي:

  1. يتم تحميل تعليمات البرنامج من مساحة التخزين إلى الذاكرة.
  2. يقرأ المعالج التعليمات من الذاكرة وينفّذها واحدة تلو الأخرى.
  3. إذا كانت التعليمات تتضمن عمليات حسابية، فسينفذها المعالج باستخدام وحدة المنطق الحسابية (ALU).
  4. إذا كانت التعليمات تتضمن بيانات، فإن المعالج يقرأ أو يكتب في الذاكرة.
  5. يتم تخزين نتائج العمليات الحسابية أو معالجة البيانات في الذاكرة.
  6. إذا احتاج البرنامج إلى عرض شيء ما على الشاشة، فسيرسل البيانات الضرورية إلى بطاقة الرسومات.
  7. تعالج بطاقة الرسومات البيانات وترسلها إلى الشاشة التي يتم عرضها.

وتستمر هذه العملية حتى يكمل البرنامج مهمته أو ينهيها المستخدم.

إعدادات الإنشاء

تسمح لك الوسيطة 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)

في قديم الزمان، في بلدة صغيرة تقع وسط تلال خضراء غنّاء، عاشت فتاة صغيرة اسمها...

الخطوات التالية

  • التصميم الفوري هو عملية إنشاء الطلبات التي تستخلص الاستجابة المطلوبة من النماذج اللغوية. كتابة طلبات منظَّمة بشكل جيّد هي جزء أساسي من ضمان تقديم ردود دقيقة وعالية الجودة باستخدام نموذج لغوي. تعرَّف على أفضل الممارسات لكتابة الطلب.
  • يوفّر Gemini عدّة نماذج مختلفة لتلبية احتياجات حالات الاستخدام المختلفة، مثل أنواع الإدخال ومستويات التعقيد وعمليات التنفيذ للمحادثات أو المهام الأخرى الخاصة بلغة الحوار وقيود الحجم. نماذج Gemini المتاحة المتاحة