チュートリアル: Gemini API のスタートガイド


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

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

  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-1.5-flash: Google の最速マルチモーダル モデル
  • gemini-1.5-pro: Google の最も高性能でインテリジェントなマルチモーダル モデル
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 アクセサがあれば十分です。書式設定されたマークダウン テキストを表示するには、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 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)

食事の準備は時間とお金を節約する優れた方法であるだけでなく、健康的な食生活にも役立ちます。この食事は、事前に簡単に準備できる健康的でおいしい食事の好例です。

玄米、焼いた野菜、チキンの照り焼き料理です。玄米は全粒穀物で、食物繊維と栄養素が豊富です。ローストした野菜は、ビタミンとミネラルを毎日摂取するのに最適な方法です。そして、鶏肉の照り焼きは、無駄のないたんぱく質のソースで、風味も味わえます。

この食事は事前に簡単に準備できます。玄米を焼いて、野菜を焼いて、チキン照り焼きを作るだけ。次に、食事を個々の容器に分けて冷蔵庫に保存します。食べたら、容器を取って加熱するだけです。

この食事は、ヘルシーで美味しい食事方法を探している多忙な人に最適なオプションです。体重を減らしたい、または健康的な体重を維持しようとしている人にも素晴らしい食事です。

事前に簡単に準備できるヘルシーで美味しい食事をお探しなら、この食事がおすすめです。ぜひお試しください。

チャットの会話

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 メソッドは、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.
________________________________________________________________________________

genai.protos.Content オブジェクトには、genai.protos.Part オブジェクトのリストが含まれ、それぞれにテキスト(文字列)または inline_data(genai.protos.Blob)のいずれかが含まれます。blob には、バイナリデータと mime_type が含まれます。チャットの履歴は、ChatSession.historygenai.protos.Content オブジェクトのリストとして表示されます。

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

ユーザー: 低年齢のお子様に対して、パソコンの仕組みを 1 文で説明してください。

model: コンピュータは、私たちの指示を理解して従うことができ、仕事を助けてくれたり、一緒にゲームをしたりできる、非常にスマートなマシンのようなものです。

ユーザー: わかりました。高校生に説明してもらいますか?

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

簡単に例えると、パソコンを料理人として、レシピに沿って操作しているところを想像してみてください。レシピはプログラムに似ており、シェフのアクションはコンピュータが従う指示のようなものです。シェフはレシピ(プログラム)を読み、材料を集める(メモリからデータを取得する)、それらを混ぜ合わせる(計算を行う)、調理する(データの処理)などのアクションを実行します。完成した料理(出力)が皿(パソコンの画面)に載ります。

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

トークンをカウントする

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

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

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

model.count_tokens(chat.history)
total_tokens: 501

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

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

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 など)を中心に構築されています。genai.protos.Content オブジェクトは、API の会話の主要な単位です。

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

同様に、チャットの履歴には genai.protos.Content オブジェクトのリストが含まれ、これを embed_content 関数に直接渡すことができます。

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

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

高度な用途

以降のセクションでは、Gemini API 用の Python SDK の高度なユースケースと下位レベルの詳細について説明します。

安全性設定

safety_settings 引数を使用すると、モデルがプロンプトとレスポンスの両方でブロックおよび許可するものを構成できます。デフォルトでは、安全性設定により、すべての要素において、安全でないコンテンツである確率が中程度または高いコンテンツがブロックされます。詳しくは、安全性設定についての説明をご覧ください。

質問できるプロンプトを入力し、デフォルトの安全性設定でモデルを実行すると、どの候補も返されません。

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

prompt_feedback には、プロンプトをブロックした安全フィルタが表示されます。

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

次に、新しく構成した安全性設定を使用して同じプロンプトをモデルに提供すると、レスポンスが得られます。

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

また、プロンプトに合格しても、個々のレスポンスが安全チェックに合格しなかった場合に備えて、各候補には独自の safety_ratings があることに注意してください。

メッセージのエンコード

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

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

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

  1. text(文字列)
  2. inline_datagenai.protos.Blob)。ここで、blob にはバイナリの datamime_type が含まれます。

これらのクラスのいずれかを同等の辞書として渡すこともできます。

したがって、前の例の完全型は次のようになります。

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] ...")

食事の準備は時間とお金を節約する優れた方法であるだけでなく、健康的な食生活にも役立ちます。作成者 ... [カット] ...

マルチターンの会話

前述の genai.ChatSession クラスは多くのユースケースを処理できますが、いくつかの前提があります。ユースケースがこのチャットの実装に当てはまらない場合は、genai.ChatSessionGenerativeModel.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)

コンピュータを、いろんなことをサポートしてくれる本当に賢い友だちだと想像してみてください。思考して学ぶ脳があるように、コンピュータにもプロセッサと呼ばれる脳があります。これは、コンピュータにタスクを指示する上司のようなものです。

コンピュータの中にはメモリという特別な場所があり、これは大きな収納ボックスのようなものです。ゲームの起動や動画の再生など、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. プロセッサ(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-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 モデルについて学習する。