最近、LLM言語モデルがあちこちで登場していますが、Googleが最近発表したGemini Proを活用して例を作ってみました。この機会を利用して、自分だけのシンプルなアプリケーションを構築してみてください
現在、Gemini Proは分あたり 最大60件の通話まで無料 です。APIの価格は上記の通りです。性能がGPT-3.5-ターボと似ている点を考慮すると、価格と現在無料である点を考慮すると、Geminiを使用する方が良いのではないでしょうか?
Software environment
Thonnyをダウンロードする。
W5100s-evb-picoファームウェアをダウンロードする。
Google Gemini API key Settings
Googleアカウントにログインし、上記のGoogle AI Studioサイトにアクセスして、Developerの下のNew Projectをクリックし、新しいAPIキーを取得します。
# 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コードをそれに応じて適応させる必要があります。
GPTとは応答の形式が異なるため、ドキュメントを参照してテキストを個別に取得するためのインデックスコードを設定する必要があります。
Hardware enviroment
W5xx-EVB-Picoのイーサネットポートとマイクロ5ピンUSB(PC、ノートブック)を接続します。
MicroPythonファームウェアのダウンロードとThonnyの設定方法に関するチュートリアルは、以下のビデオを参照してください。
Source Code Setting
!git clone https://github.com/jh941213/Gemini_rp2040.git
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と入力することで、これを行うことができます。
テキストウィンドウにexit
と入力するとチャットが終了します。