LoginSignup
0
0

無料 AI API: PICOと一緒にGoogle Gemini Proを使用する

Posted at

最近、LLM言語モデルがあちこちで登場していますが、Googleが最近発表したGemini Proを活用して例を作ってみました。この機会を利用して、自分だけのシンプルなアプリケーションを構築してみてください

image.png

現在、Gemini Proは分あたり 最大60件の通話まで無料 です。APIの価格は上記の通りです。性能がGPT-3.5-ターボと似ている点を考慮すると、価格と現在無料である点を考慮すると、Geminiを使用する方が良いのではないでしょうか?
image.png

Software environment

Thonnyをダウンロードする。

image.png
他のマイクロPythonエディターを使用しても構いません。

W5100s-evb-picoファームウェアをダウンロードする。

https://micropython.org/download/W5100S_EVB_PICO/

image.png

Google Gemini API key Settings

https://makersuite.google.com/

Googleアカウントにログインし、上記のGoogle AI Studioサイトにアクセスして、Developerの下のNew Projectをクリックし、新しいAPIキーを取得します。

image.png

image.png

# Quickly test the API by running a cURL command
curl \
  -H 'Content-Type: application/json' \
  -d '{"contents":[{"parts":[{"text":"Write a story about a magic backpack"}]}]}' \
  -X POST https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=YOUR_API_KEY

GPTとは異なり、エンドポイントアドレスにはapi_keyが含まれているので、既存のOpenAIコードをそれに応じて適応させる必要があります。
image.png

GPTとは応答の形式が異なるため、ドキュメントを参照してテキストを個別に取得するためのインデックスコードを設定する必要があります。

Hardware enviroment

W5xx-EVB-Picoのイーサネットポートとマイクロ5ピンUSB(PC、ノートブック)を接続します。
MicroPythonファームウェアのダウンロードとThonnyの設定方法に関するチュートリアルは、以下のビデオを参照してください。

https://www.youtube.com/watch?v=8FcFhZRNNxE

Source Code Setting

https://github.com/jh941213/Gemini_rp2040

!git clone https://github.com/jh941213/Gemini_rp2040.git 

image.png
send.pyを実行すると、コードが実行されます。

Gemini.py

import json
import urequests


gemini_api_key = "your_api_key"
gemini_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={gemini_api_key}"

def send_prompt_to_gemini(prompt):
    headers = {"Content-Type": "application/json"}
    data = {
        "contents": [{
            "parts": [{"text": prompt}]
        }]
    }
    
    response = urequests.post(gemini_url, headers=headers, data=json.dumps(data))
    if response.status_code == 200:
        response_data = json.loads(response.text)
        return response_data["candidates"][0]["content"]["parts"][0]["text"]
    else:
        raise Exception(f"API error ({response.status_code}): {response.text}")

Send.py

from machine import Pin, SPI
import network
import utime
import gemini

#init Ethernet code
def init_ethernet(timeout=10):
    spi = SPI(0, 2_000_000, mosi=Pin(19), miso=Pin(16), sck=Pin(18))
    nic = network.WIZNET5K(spi, Pin(17), Pin(20))   # spi, cs, reset pin
    # DHCP
    nic.active(True)

    start_time = utime.ticks_ms()
    while not nic.isconnected():
        utime.sleep(1)
        if utime.ticks_ms() - start_time > timeout * 1000:
            raise Exception("Ethernet connection timed out.")
        print('Connecting ethernet...')

    print(f'Ethernet connected. IP: {nic.ifconfig()}')

def main():
    init_ethernet()

    while True:
        prompt = input("User: ")
        if prompt.lower() == "exit":  
            print("Exiting...")
            break

        try:
            response = gemini.send_prompt_to_gemini(prompt)  
            print("Gemini: ", response)
        except Exception as e:
            print("Error: ", e)

if __name__ == "__main__":
    main()

Result

コンソールウィンドウのプロンプトでgeminiと入力することで、これを行うことができます。

image.png

テキストウィンドウにexitと入力するとチャットが終了します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0