Wiznet makers

simons

Published December 19, 2023 © MIT license (MIT)

30 UCC

11 WCC

3 VAR

0 Contests

0 Followers

0 Following

Using Google Gemini Pro with PICO

Build your application with free API calls

COMPONENTS Hardware components

WIZnet - W5100S-EVB-Pico

x 1

Software Apps and online services

micropython - MicroPython

x 1


PROJECT DESCRIPTION

Overview

Recently, LLM language models have been popping up in various places, and we've created an example using Google's recently announced Gemini Pro. I used Wiznet Scarlet's OpenAI as a reference for how to use it in pico. Currently, API calls to Gemini Pro are free. Take advantage of this opportunity to build your own simple application.

Refrence

Currently, Gemini Pro is free for up to 60 calls per minute. API pricing is as above. Considering that the performance is similar to GPT-3.5-turbo, isn't it better to use Gemini for the price and the fact that it's currently free?

Software environment

1.Download the Thonny microfiche environment.

https://thonny.org/

2. Download the Firmware

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

3. Google Gemini API key Settings

https://makersuite.google.com/

Log in to your Google account and go to the Google AI Studio site above, click new project under Developer Get API key to get a new API key.

# 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

Unlike GPT, the endpoint address contains an api_key, so you'll need to adapt your existing OpenAI code accordingly.

Since the form of response is different from GPT, you need to set the indexing code to get the text separately by referring to the docs.

Hardware enviroment

Connect the W5xx-EVB-Pico's Ethernet port and the micro5 pin USB(PC,Notebook).

Upload the downloaded firmware into 'boot mode' and disconnect and reconnect your USB.

Tool -> Interpreters

After connecting, set the interpreter to "Micro Python (Raspberry PI pico)" and the port to the port connected to the device manager earlier.

Source Code Setting

https://github.com/jh941213/Gemini_rp2040

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

Run send.py and the code will run.

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 

You can do this by typing gemini at the prompt in the console window. 

The loop exits when the exit prompt comes in.

 

Documents
Comments Write

Similar projects you might like

PCB that provides power and connectivity for the Raspberry Pi Pico, including Ethernet capabilities compatible with the W5100S or W5500.

Multifunctional power and distribution board for Raspberry Pi Pico and Wiznet W5100S/W5500

Benjamin
  • 847

  • 0

This is a demonstration of two Wiznet W5500s running a micropython script that sets one unit as a server, and the other as a client, with a small data packet go

Pico Pi Wiznet W5500 Two-way comms via Ethernet with Micropython

scarlet
  • 892

  • 0

RaspberryPi Zero W, W5100S-EVB-Pico, AWS IoT Core, MQTT

LTE CATM1 Mini Router with W5100S-EVB-Pico

taylor
  • 650

  • 0

Implementing IoT remote device control on Raspberry Pi's RP2040 + W5500

Implementing IoT remote device control on Raspberry Pi's RP2040 + W5500

simons
  • 438

  • 0

With your voice, you can control light, temperature, and bed gradient!!

[Recuration] Smart Bed System Using webOS

josephsr
  • 354

  • 0

일부 제조업체는 LLM Steak Classifier AIOT Bot 으로 알려진 Pi 기반 AI 고기 요리 모니터를 만든 개발자 Simon처럼 맛볼 수 있는 Raspberry Pi 프로젝트 를 만드는 방법을 확실히 알고 있습니다. 이 프로젝트는 실제 센서와 함께 ChatGPT를 사용하

Raspberry Pi 프로젝트가 잘 완료되었습니다. AI를 사용하여 고기를 완벽하게 요리합니다.

simons
  • 262

  • 0

This basic GPIO input/output testing provides foundational knowledge for using the Raspberry Pi Pico in various electronics projects.

[Recuration] Using Raspberry Pi Pico(W5100S-EVB-Pico) ADC

Benjamin
  • 578

  • 0

Do not Miss the IoT Module by Wiznet with RP2040 and Ethernet

Do not Miss the IoT Module by Wiznet with RP2040 and Ethernet

simons
  • 265

  • 0