Skip to content

ClasCat® AI Research

クラスキャット – 生成 AI, AI エージェント, MCP

Menu
  • ホーム
    • ClassCat® AI Research ホーム
    • クラスキャット・ホーム
  • OpenAI API
    • OpenAI Python ライブラリ 1.x : 概要
    • OpenAI ブログ
      • GPT の紹介
      • GPT ストアの紹介
      • ChatGPT Team の紹介
    • OpenAI platform 1.x
      • Get Started : イントロダクション
      • Get Started : クイックスタート (Python)
      • Get Started : クイックスタート (Node.js)
      • Get Started : モデル
      • 機能 : 埋め込み
      • 機能 : 埋め込み (ユースケース)
      • ChatGPT : アクション – イントロダクション
      • ChatGPT : アクション – Getting started
      • ChatGPT : アクション – アクション認証
    • OpenAI ヘルプ : ChatGPT
      • ChatGPTとは何ですか?
      • ChatGPT は真実を語っていますか?
      • GPT の作成
      • GPT FAQ
      • GPT vs アシスタント
      • GPT ビルダー
    • OpenAI ヘルプ : ChatGPT > メモリ
      • FAQ
    • OpenAI ヘルプ : GPT ストア
      • 貴方の GPT をフィーチャーする
    • OpenAI Python ライブラリ 0.27 : 概要
    • OpenAI platform
      • Get Started : イントロダクション
      • Get Started : クイックスタート
      • Get Started : モデル
      • ガイド : GPT モデル
      • ガイド : 画像生成 (DALL·E)
      • ガイド : GPT-3.5 Turbo 対応 微調整
      • ガイド : 微調整 1.イントロダクション
      • ガイド : 微調整 2. データセットの準備 / ケーススタディ
      • ガイド : 埋め込み
      • ガイド : 音声テキスト変換
      • ガイド : モデレーション
      • ChatGPT プラグイン : イントロダクション
    • OpenAI Cookbook
      • 概要
      • API 使用方法 : レート制限の操作
      • API 使用方法 : tiktoken でトークンを数える方法
      • GPT : ChatGPT モデルへの入力をフォーマットする方法
      • GPT : 補完をストリームする方法
      • GPT : 大規模言語モデルを扱う方法
      • 埋め込み : 埋め込みの取得
      • GPT-3 の微調整 : 分類サンプルの微調整
      • DALL-E : DALL·E で 画像を生成して編集する方法
      • DALL·E と Segment Anything で動的マスクを作成する方法
      • Whisper プロンプティング・ガイド
  • Gemini API
    • Tutorials : クイックスタート with Python (1) テキスト-to-テキスト生成
    • (2) マルチモーダル入力 / 日本語チャット
    • (3) 埋め込みの使用
    • (4) 高度なユースケース
    • クイックスタート with Node.js
    • クイックスタート with Dart or Flutter (1) 日本語動作確認
    • Gemma
      • 概要 (README)
      • Tutorials : サンプリング
      • Tutorials : KerasNLP による Getting Started
  • Keras 3
    • 新しいマルチバックエンド Keras
    • Keras 3 について
    • Getting Started : エンジニアのための Keras 入門
    • Google Colab 上のインストールと Stable Diffusion デモ
    • コンピュータビジョン – ゼロからの画像分類
    • コンピュータビジョン – 単純な MNIST convnet
    • コンピュータビジョン – EfficientNet を使用した微調整による画像分類
    • コンピュータビジョン – Vision Transformer による画像分類
    • コンピュータビジョン – 最新の MLPモデルによる画像分類
    • コンピュータビジョン – コンパクトな畳込み Transformer
    • Keras Core
      • Keras Core 0.1
        • 新しいマルチバックエンド Keras (README)
        • Keras for TensorFlow, JAX, & PyTorch
        • 開発者ガイド : Getting started with Keras Core
        • 開発者ガイド : 関数型 API
        • 開発者ガイド : シーケンシャル・モデル
        • 開発者ガイド : サブクラス化で新しい層とモデルを作成する
        • 開発者ガイド : 独自のコールバックを書く
      • Keras Core 0.1.1 & 0.1.2 : リリースノート
      • 開発者ガイド
      • Code examples
      • Keras Stable Diffusion
        • 概要
        • 基本的な使い方 (テキスト-to-画像 / 画像-to-画像変換)
        • 混合精度のパフォーマンス
        • インペインティングの簡易アプリケーション
        • (参考) KerasCV – Stable Diffusion を使用した高性能画像生成
  • TensorFlow
    • TF 2 : 初級チュートリアル
    • TF 2 : 上級チュートリアル
    • TF 2 : ガイド
    • TF 1 : チュートリアル
    • TF 1 : ガイド
  • その他
    • 🦜️🔗 LangChain ドキュメント / ユースケース
    • Stable Diffusion WebUI
      • Google Colab で Stable Diffusion WebUI 入門
      • HuggingFace モデル / VAE の導入
      • LoRA の利用
    • Diffusion Models / 拡散モデル
  • クラスキャット
    • 会社案内
    • お問合せ
    • Facebook
    • ClassCat® Blog
Menu

Gemini API : Tutorials : クイックスタート with Python (4) 高度なユースケース

Posted on 03/15/2024 by Sales Information

Gemini API : Tutorials : クイックスタート with Python (4) 高度なユースケース

翻訳 : クラスキャット セールスインフォメーション
作成日時 : 03/15/2024

* 本ページは、ai.google.dev の以下のページを参考にしてまとめ直し、適宜、補足説明したものです :

  • Gemini API: Quickstart with Python

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

クラスキャット 人工知能 研究開発支援サービス

◆ クラスキャット は人工知能・テレワークに関する各種サービスを提供しています。お気軽にご相談ください :

ClassCat Chatbot

  • 人工知能研究開発支援
    1. 人工知能研修サービス(経営者層向けオンサイト研修)
    2. テクニカルコンサルティングサービス
    3. 実証実験(プロトタイプ構築)
    4. アプリケーションへの実装

  • 人工知能研修サービス

  • PoC(概念実証)を失敗させないための支援
◆ 人工知能とビジネスをテーマに WEB セミナーを定期的に開催しています。スケジュール。
  • お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。

◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。

  • クラスキャット セールス・マーケティング本部 セールス・インフォメーション
  • sales-info@classcat.com  ;  Website: www.classcat.com  ;   ClassCatJP

 

Gemini API : Tutorials : クイックスタート with Python (4) 高度なユースケース

以下のセクションは Gemini API 用の Python SDK の高度なユースケースと低位な詳細を説明します。

 

セーフティ設定

safety_settings 引数は、プロンプトと応答の両方でモデルが何をブロックし許可するかを構成設定できます。デフォルトでは、セーフティ設定はすべての次元に渡り安全でないコンテンツである確率が中程度 and/or 高いコンテンツをブロックします。セーフティ設定 について更に学習してください。

疑わしいプロンプトを入力してモデルをデフォルトのセーフティ設定で実行すると、候補を返しません :

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 に依存していました。このセクションは fully-typed な、前の例と同等なものを提供しますので、SDK がメッセージをエンコードする方法に関して低位の詳細をより良く理解できます。

Python SDK の基礎となるものは google.ai.generativelanguage クライアント・ライブラリです :

import google.ai.generativelanguage as glm

SDK は貴方のメッセージを glm.Content オブジェクトへの変換を試みます、これは各々が以下のいずれかを含む glm.Part オブジェクトのリストを含みます。

  1. テキスト (文字列)

  2. inline_data (glm.Blob), ここで blob はバイナリデータと mime_type を含みます。

これらの任意のクラスを同等な辞書として渡すこともできます。

⭐️ Note : 唯一の受け入れられる mime タイプは幾つかの画像タイプ, images/* です。

したがって、fully-typed である、前の例と同等のものは :

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] ...")
Meal prepping is a great way to save time and money, and it can also help you to eat healthier. By ... [TRIMMED] ...

 

マルチターン会話

前に示された genai.ChatSession クラスが多くのユースケースを処理できる一方で、それは幾つかの仮定をしています。貴方のユースケースがこのチャット実装に適合しない場合は、genai.ChatSession は GenerativeModel.generate_content 周りの単なるラッパーであることを覚えておくのと良いでしょう。単一のリクエストに加えて、それはマルチターン会話を処理できます。

前のセクションで見たように、個々のメッセージは 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)
Imagine a computer as a really smart friend who can help you with many things. Just like you have a brain to think and learn, a computer has a brain too, called a processor. It's like the boss of the computer, telling it what to do.

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

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

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

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

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

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

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

会話を続けるには、応答と別のメッセージを追加します。

⭐️ Note : マルチターン会話については、各リクエストで会話履歴全体を送信する必要があります。API はステートレスです。

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

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

response = model.generate_content(messages)

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

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

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

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

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

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

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

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

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

The program instructions are loaded from storage into memory.
The processor reads the instructions from memory and executes them one by one.
If the instruction involves calculations, the processor performs them using its arithmetic logic unit (ALU).
If the instruction involves data, the processor reads or writes to memory.
The results of the calculations or data manipulation are stored in memory.
If the program needs to display something on the screen, it sends the necessary data to the graphics card.
The graphics card processes the data and sends it to the monitor, which displays it.
This process continues until the program has completed its task or the user terminates it.

 

生成 configuration

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)
Once upon a time, in a small town nestled amidst lush green hills, lived a young girl named...

 

以上



クラスキャット

最近の投稿

  • LangGraph 0.5 on Colab : Get started : Tavily Web 検索ツールの追加
  • LangGraph 0.5 on Colab : Get started : カスタム・ワークフローの構築
  • LangGraph 0.5 on Colab : Get started : クイックスタート
  • LangGraph on Colab : SQL エージェントの構築
  • LangGraph on Colab : マルチエージェント・スーパーバイザー

タグ

AutoGen (13) ClassCat Press Release (20) ClassCat TF/ONNX Hub (11) DGL 0.5 (14) Eager Execution (7) Edward (17) FLUX.1 (16) Gemini (20) HuggingFace Transformers 4.5 (10) HuggingFace Transformers 4.6 (7) HuggingFace Transformers 4.29 (9) Keras 2 Examples (98) Keras 2 Guide (16) Keras 3 (10) Keras Release Note (17) Kubeflow 1.0 (10) LangChain (45) LangGraph (24) MediaPipe 0.8 (11) Model Context Protocol (16) NNI 1.5 (16) OpenAI Agents SDK (8) OpenAI Cookbook (13) OpenAI platform (10) OpenAI platform 1.x (10) OpenAI ヘルプ (8) TensorFlow 2.0 Advanced Tutorials (33) TensorFlow 2.0 Advanced Tutorials (Alpha) (15) TensorFlow 2.0 Advanced Tutorials (Beta) (16) TensorFlow 2.0 Guide (10) TensorFlow 2.0 Guide (Alpha) (16) TensorFlow 2.0 Guide (Beta) (9) TensorFlow 2.0 Release Note (12) TensorFlow 2.0 Tutorials (20) TensorFlow 2.0 Tutorials (Alpha) (14) TensorFlow 2.0 Tutorials (Beta) (12) TensorFlow 2.4 Guide (24) TensorFlow Deploy (8) TensorFlow Get Started (7) TensorFlow Graphics (7) TensorFlow Probability (9) TensorFlow Programmer's Guide (22) TensorFlow Release Note (18) TensorFlow Tutorials (33) TF-Agents 0.4 (11)
2024年3月
月 火 水 木 金 土 日
 123
45678910
11121314151617
18192021222324
25262728293031
« 2月   4月 »
© 2025 ClasCat® AI Research | Powered by Minimalist Blog WordPress Theme