Gemini API のスタートガイド: Python

Google AI で表示 Google Colab で実行 GitHub でソースを表示

このクイックスタートでは、Google の Gemini 大規模言語モデルにアクセスできる Gemini API 用の Python SDK の使用方法について説明します。このクイックスタートの学習内容は次のとおりです。

  1. Gemini を使用するには、開発環境と API アクセスを設定してください。
  2. テキスト入力からテキスト レスポンスを生成する。
  3. マルチモーダル入力(テキストと画像)からテキスト レスポンスを生成する。
  4. マルチターンの会話(チャット)には Gemini を使用します。
  5. 大規模言語モデルにエンベディングを使用する。

前提条件

このクイックスタートは Google Colab で実行できます。このノートブックはブラウザ内で直接実行され、追加の環境構成は必要ありません。

または、このクイックスタートをローカルで完了するには、開発環境が次の要件を満たしていることを確認してください。

  • Python 3.9 以降
  • ノートブックを実行するための jupyter のインストール。

設定

Python SDK をインストールする

Gemini API 用の Python SDK は、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

API キーを設定する

Gemini API を使用するには、まず API キーを取得する必要があります。まだ作成していない場合は、Google AI Studio でワンクリックでキーを作成できます。

API キーを取得する

Colab で、左側のパネルにある [↘] の下にあるシークレット マネージャーにキーを追加します。GOOGLE_API_KEY という名前を付けます。

API キーを取得したら、SDK に渡します。作成する方法は次の 2 つです。

  • キーを 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 ファミリーのモデルもサポートしていますが、generateContent メソッドの一般的なマルチモーダル機能をサポートしているのは Gemini モデルのみです。

テキスト入力からテキストを生成する

テキストのみのプロンプトの場合は、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 アクセサーがあれば十分です。書式設定されたマークダウン テキストを表示するには、to_markdown 関数を使用します。

to_markdown(response.text)

人生の目的を問うことが、何世紀にもわたって、文化や大陸を超えて人々を困惑させてきました。普遍的に認められた対応というものはありませんが、多くのアイデアが発表され、その対応はしばしば個人のアイデア、信念、人生経験に左右されます。

  1. 幸福と幸福: 多くの人は、人生の目標は個人の幸福と幸福を達成することだと考えています。これには、喜びをもたらす探求、重要なつながりの構築、心身の健康のケア、個人的な目標と興味の追求が含まれます。

  2. 有意義な貢献: 人生の目的は世界に有意義な貢献を行うことであると考える人もいます。たとえば、他の人の役に立つ職業訓練、ボランティアや慈善活動、芸術や文学の制作、発明などがこれに該当します。

  3. 自己実現と自己啓発: 自己実現や自己啓発の追求も、人生における共通の目標です。これには、新しいスキルの習得、限界を押し上げる、個人的な障害に立ち向かう、人間として進化していくことが必要となるかもしれません。

  4. 倫理的行動と道徳的行動: 人生の目標は倫理的かつ道徳的に行動することだと考える人もいます。そのためには、自分の道徳原則を守り、困難な状況でも正しいことをし、世界をより良い場所にしようと努める必要があるかもしれません。

  5. スピリチュアルな成熟: 人生の目的は、スピリチュアルな信念や宗教的な信念に関係している人もいます。これには、より高い権力とのつながりの追求、宗教的儀式、スピリチュアルな教えに従うことなどが含まれるかもしれません。

  6. 人生を最大限に楽しむ: 人生の目標は、人生で得られるすべてのものを経験することだと考える人もいます。そのためには、旅行をすること、新しいことに挑戦すること、リスクを負うこと、新しい出会いを受け入れることなどが伴います。

  7. レガシーと影響: 人生の目的は、永遠のレガシーと世界に影響を与えることであると考える人もいます。これには、注目すべきことを成し遂げる、自分の貢献が記憶に残る、他の人にインスピレーションややる気を起こさせる、といったことが含まれます。

  8. バランスと調和を見つける: 人生のあらゆる面でバランスと調和を見いだすことが人生の目的である人もいます。そのためには、個人的、職業的、社会的義務に対処し、内なる平和と満足を求めて、価値観や信念に沿った生活を送ることが必要となります。

結局のところ、人生の意味は個人的な旅であり、さまざまな人が自分の周りの世界での経験、振り返り、交流を通じて、独自の目的を見いだすかもしれません。

API が結果を返せなかった場合は、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 では、1 つのプロンプトに対して複数の回答候補を生成できます。こうした可能なレスポンスは 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 API は、マルチモーダル プロンプトを処理し、テキスト出力を返すように設計されています。

画像を追加しましょう。

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 メソッドは、GenerativeModel.generate_content と同じ GenerateContentResponse 型を返します。また、メッセージと返信がチャット履歴に追加されます。

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 オブジェクトには、それぞれテキスト(文字列)または inline_data(glm.Blob)のいずれかを含む glm.Part オブジェクトのリストが含まれ、blob にはバイナリデータと mime_type が含まれます。チャットの履歴は、ChatSession.historyglm.Content オブジェクトのリストとして利用できます。

for message in chat.history:
  display(to_markdown(f'**{message.role}**: {message.parts[0].text}'))

ユーザー: パソコンが幼い子どもに対してどのように機能するかを 1 文で説明します。

model: コンピュータは、指示を理解して従うことができ、作業を手伝ってくれるだけでなく、一緒にゲームをプレイすることもできる、非常にスマートなマシンのようなものです。

ユーザー: では、高校生にもっと詳しい説明をしてみませんか?

model: コンピュータは、プログラムと呼ばれる命令に従って動作し、命令します。これらの命令はコンピュータが理解できる特別な言語で記述され、コンピュータのメモリに保存されます。コンピュータのプロセッサ(CPU)は、メモリから命令を読み取って実行し、プログラムのロジックに基づいて計算を実行し、決定を行います。これらの計算や決定の結果は、コンピュータの画面上に表示されるか、後で使用するためにメモリに保存されます。

簡単に言えば、コンピュータがレシピに沿って料理人になっていると想像してみてください。レシピはプログラムに似ており、シェフの行動はコンピュータが従う指示に似ています。シェフはレシピ(プログラム)を読み、材料を集める(メモリからデータを取得する)、材料を混ぜる(計算を実行)、調理する(データを処理する)などのアクションを実行します。最後の料理(出力)は、皿(パソコンの画面)に提示されます。

要約すると、コンピュータは、メモリに保存されている一連の命令を実行し、計算を行い、決定を行い、結果を表示または保存することで機能します。

トークンをカウントする

大規模言語モデルにはコンテキスト ウィンドウがあり、多くの場合、コンテキストの長さはトークンの数で測定されます。Gemini API を使用すると、任意の glm.Content オブジェクトごとのトークンの数を判別できます。最も単純なケースでは、次のようにクエリ文字列を GenerativeModel.count_tokens メソッドに渡すことができます。

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

同様に、ChatSessiontoken_count を確認できます。

model.count_tokens(chat.history)
total_tokens: 501

エンベディングを使用する

エンベディングとは、配列内の浮動小数点数のリストとして情報を表現するために使用される手法です。Gemini では、テキスト(単語、文、テキスト ブロック)をベクトル化して表現できるため、エンベディングの比較や対比が容易になります。たとえば、類似した主題や感情を共有する 2 つのテキストは、エンベディングが類似しているはずです。エンベディングは、コサイン類似度などの数学的比較手法によって特定できます。エンベディングの使用方法と使用する理由について詳しくは、エンベディング ガイドをご覧ください。

embed_content メソッドを使用して、エンベディングを生成します。このメソッドは、次のタスク(task_type)の埋め込みを処理します。

タスクタイプ 説明
RETRIEVAL_QUERY 指定したテキストが検索 / 取得設定のクエリであることを指定します。
RETRIEVAL_DOCUMENT 指定したテキストが検索/取得設定のドキュメントであることを指定します。このタスクタイプを使用するには、title が必要です。
SEMANTIC_SIMILARITY 指定したテキストが意味論的テキスト類似性(STS)で使用されることを指定します。
分類 エンベディングを分類に使用することを指定します。
クラスタ化 エンベディングをクラスタリングに使用することを指定します。

以下は、ドキュメントを取得するための 1 つの文字列のエンベディングを生成します。

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 オブジェクトは、API での会話の基本単位です。

glm.Content オブジェクトはマルチモーダルですが、embed_content メソッドはテキスト エンベディングのみをサポートします。この設計により、API をマルチモーダル エンベディングに拡張する可能性が得られます。

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

高度な用途

以下のセクションでは、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 があります。

メッセージのエンコード

前のセクションでは、API にプロンプトを簡単に送信できるように SDK を使用していました。このセクションでは、前の例と同等の型の完全な型を提供しているため、SDK がメッセージをエンコードする方法に関する下位レベルの詳細について理解を深めることができます。

Python SDK の基盤となるのは、google.ai.generativelanguage クライアント ライブラリです。

import google.ai.generativelanguage as glm

SDK はメッセージを glm.Content オブジェクトに変換しようとします。このオブジェクトには、それぞれ以下のいずれかを含む glm.Part オブジェクトのリストが含まれています。

  1. text(文字列)
  2. inline_dataglm.Blob)。blob にはバイナリ datamime_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)

コンピュータが、さまざまなことを手助けしてくれる賢い友だちだと想像してみてください。考えて学習する頭脳があるように、コンピュータにもプロセッサと呼ばれる脳があります。何をすべきかを指示する、コンピュータの上司のようなものです。

コンピュータの中には、メモリと呼ばれる特別な場所があり、大きな収納ボックスのようなものです。ゲームの開始や動画の再生など、アシスタントに指示した操作はすべて保存されます。

キーボードのボタンを押すか、マウスで画面上の項目をクリックすると、パソコンにメッセージを送信します。これらのメッセージは、ケーブルと呼ばれる特殊なワイヤーを介してプロセッサに到達します。

プロセッサはメッセージを読み取り、コンピュータに何をすべきかを伝えます。プログラムを開いたり、画像を表示したり、音楽を再生したりできます。

画面に表示されるものはすべてグラフィック カードによって作成されます。これは、コンピュータの中の魔法の芸術家のようなものです。プロセッサの命令を受け取り、それをカラフルな画像や動画に変換します。

お気に入りのゲーム、動画、画像を保存するために、パソコンにはハードドライブと呼ばれる特別な保存容量が使用されます。コンピュータがあなたの大切なものをすべて安全に保管できる、巨大な図書館のようなものです。

インターネットに接続して友だちとゲームをしたり、面白い動画を見たりする場合は、パソコンはネットワーク カードと呼ばれるものを使用して、インターネット ケーブルまたは 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): - パソコンの頭脳。 - 命令を実行し、計算を行います。 - ギガヘルツ(GHz)単位で測定した速度。 - GHz が高いほど、一般的に処理が高速になります。

2. メモリ(RAM): - 処理されるデータ用の一時ストレージ。 - プログラムの実行中に命令とデータを保持します。 - ギガバイト(GB)単位で測定されます。 - RAM の容量が増えれば、より多くのプログラムを同時に実行できます。

3. ストレージ(HDD/SSD): - データ用の永続ストレージ。 - オペレーティング システム、プログラム、ユーザー ファイルを格納。 - ギガバイト(GB)またはテラバイト(TB)単位で測定。 - ハードディスク ドライブ(HDD)は従来より低速で、安価です。- ソリッド ステート ドライブ(SSD)は比較的新しく、高速かつ高価です。

4. グラフィック カード(GPU): - 画像を処理して表示します。 - ゲーム、動画編集、その他のグラフィックを多用するタスクに不可欠です。 - 動画 RAM(VRAM)とクロック速度で測定。

5. マザーボード: - すべてのコンポーネントを接続します。 - 電源と通信経路を提供します。

6. 入出力(I/O)デバイス: - ユーザーがパソコンを操作できるようにします。 - 例: キーボード、マウス、モニター、プリンタ。

7. オペレーティング システム(OS): - コンピュータのリソースを管理するソフトウェア。 - ユーザー インターフェースと基本機能を提供します。 - 例: Windows、macOS、Linux。

パソコンでプログラムを実行すると、次のようになります。

  1. プログラム命令はストレージからメモリにロードされます。
  2. プロセッサはメモリから命令を読み取り、1 つずつ実行します。
  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 モデルのレート制限は、1 分あたり 60 件のリクエスト(RPM)です。