بدء استخدام Gemini API: Python

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

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

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

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

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

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

  • Python 3.9 أو إصدار أحدث
  • تثبيت jupyter لتشغيل دفتر الملاحظات.

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

تثبيت حزمة تطوير البرامج (SDK) للغة Python

تتوفّر حزمة Python SDK لـ Gemini API في الحزمة google-generativeai. تثبيت التبعية باستخدام 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، يجب أولاً الحصول على مفتاح واجهة برمجة التطبيقات. أنشِئ مفتاحًا بنقرة واحدة في "استوديو Google AI" إذا لم يكن لديك مفتاح.

الحصول على مفتاح واجهة برمجة التطبيقات

في 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 API. يمكنك استخدام list_models للاطّلاع على طُرز Gemini المتاحة:

  • gemini-pro: محسَّن للمطالبات النصية فقط.
  • gemini-pro-vision: محسَّن للمطالبات المتعلقة بالنصوص والصور
for m in genai.list_models():
  if 'generateContent' in m.supported_generation_methods:
    print(m.name)

تتوافق حزمة genai أيضًا مع مجموعة طُرز PaLM، ولكنّ طُرز Gemini فقط تتوافق مع الإمكانات العامة المتعدّدة الوسائط لطريقة generateContent.

إنشاء نص من إدخالات النص

بالنسبة إلى الطلبات النصية فقط، يمكنك استخدام نموذج gemini-pro:

model = genai.GenerativeModel('gemini-pro')

يمكن لطريقة 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-pro-vision) يقبل النصوص والصور والإدخالات. صُمِّمت واجهة برمجة التطبيقات 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-pro-vision وتمرير الصورة إلى النموذج باستخدام generate_content.

model = genai.GenerativeModel('gemini-pro-vision')
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)

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

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

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

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

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

محادثات الدردشة

يتيح لك Gemini إجراء محادثات حرة عبر منعطفات متعددة. تعمل الفئة ChatSession على تبسيط العملية من خلال إدارة حالة المحادثة، ولذلك لن تضطر، على عكس generate_content، إلى تخزين سجلّ المحادثات كقائمة.

إعداد المحادثة:

model = genai.GenerativeModel('gemini-pro')
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)، حيث يحتوي كائن ثنائي على بيانات ثنائية و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، يمكنك تحديد عدد الرموز المميّزة لكل عنصر glm.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 تقبل السلاسل البسيطة أو قوائم السلاسل، فإنها في الواقع تستند إلى النوع glm.Content (مثل GenerativeModel.generate_content). كائنات glm.Content هي الوحدات الأساسية للمحادثة في واجهة برمجة التطبيقات.

على الرغم من أنّ الكائن glm.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 ...

وبالمثل، يحتوي سجلّ المحادثات على قائمة بكائنات glm.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) للرسائل.

تشتمل حزمة Python SDK على مكتبة برامج google.ai.generativelanguage:

import google.ai.generativelanguage as glm

تحاول حزمة تطوير البرامج (SDK) تحويل رسالتك إلى عنصر glm.Content يحتوي على قائمة بعنصرَين (glm.Part) يحتوي كل منهما على أي مما يلي:

  1. text (سلسلة)
  2. inline_data (glm.Blob)، حيث يحتوي كائن ثنائي على رمز data ثنائي وmime_type.

ويمكنك أيضًا ضبط أي من هذه الفئات كقاموس مكافئ.

وبالتالي، فإن المكافئ المكتوب بالكامل للمثال السابق هو:

model = genai.GenerativeModel('gemini-pro-vision')
response = model.generate_content(
    glm.Content(
        parts = [
            glm.Part(text="Write a short, engaging blog post based on this picture."),
            glm.Part(
                inline_data=glm.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. بالإضافة إلى الطلبات الفردية، يمكنه التعامل مع المحادثات المتعددة الأدوار.

الرسائل الفردية هي كائنات glm.Content أو قواميس متوافقة، كما هو موضّح في الأقسام السابقة. تتطلّب الرسالة استخدام مفتاحَي role وparts كقاموس. يمكن أن يكون الحقل "role" في المحادثة هو user الذي يقدّم الطلبات أو model الذي يقدّم الردود.

تمرير قائمة من عناصر glm.Content وسيتم التعامل معها كمحادثة متعددة الأدوار:

model = genai.GenerativeModel('gemini-pro')

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

to_markdown(response.text)

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

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

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

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

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

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

وعندما تريد الاتصال بالإنترنت للعب الألعاب مع الأصدقاء أو مشاهدة مقاطع فيديو مضحكة، يستخدم الكمبيوتر شيئًا يُدعى بطاقة الشبكة لإرسال الرسائل وتلقيها عبر كابلات الإنترنت أو إشارات 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. المعالج (وحدة المعالجة المركزية): - دماغ الكمبيوتر. - ينفذ التعليمات ويجري العمليات الحسابية. - تُقاس السرعة بالغيغاهرتز (غيغاهيرتز). - كلما كانت الترددات أعلى، تتم معالجة البيانات بشكل أسرع.

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

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

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

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

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

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

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

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

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

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

تتيح لك الوسيطة generation_config تعديل معلمات الإنشاء. يتضمّن كل طلب ترسله إلى النموذج قيم مَعلمات تتحكّم في كيفية إنشاء النموذج للردود.

model = genai.GenerativeModel('gemini-pro')
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 المتوفّرة.
  • يوفّر Gemini خيارات لطلب زيادة الحدّ الأقصى للسعر. الحدّ الأقصى لمعدّل تحميل طُرز Gemini-Pro هو 60 طلبًا في الدقيقة (RPM).