Video Tutorial (Optional)
Watch first if you want to follow the full Raspberry Pi Pico W ChatGPT API setup in real time.
Project Overview
Raspberry Pi Pico W + ChatGPT API: In this tutorial, you use a Raspberry Pi Pico W to call the ChatGPT (OpenAI) API over WiFi, send prompts, and print the responses.
ChatGPT can be useful for building projects that accept natural language input. For example, with external microphones and speakers, you can build voice-controlled systems that respond to user queries or control appliances.
- Time: 20 to 40 minutes
- Skill level: Intermediate
- What you will build: A Pico W script that connects to WiFi, sends a prompt to the OpenAI API, and prints the completion text
Parts List
From ShillehTek
- Raspberry Pi Pico 2W - the WiFi microcontroller board used in this build
External
- WiFi network name (SSID) and password
- OpenAI account and API key (generated at https://platform.openai.com/account/api-keys)
- OpenAI API reference for completions: documentation
Note: This example uses the OpenAI Completions endpoint and the model text-davinci-003. You will also need billing set up once you exceed any free usage limits.
Step-by-Step Guide
Step 1 - Generate an API key
Goal: Create the OpenAI API key that your Raspberry Pi Pico W will use to authenticate API requests.
What to do: Generate an API key here: https://platform.openai.com/account/api-keys.
The API key is a unique code used to authenticate your requests and identify your account. This controls access and enables billing and security tracking. You will need it to make requests and receive responses from the language model.
Expected result: You have an API key ready to paste into your project constants.
Step 2 - Connect to WiFi and make an API call
Goal: Connect the Pico W to the internet and send a prompt to the OpenAI API so you can receive and print a response.
What to do: Use the following MicroPython code to connect to WiFi, format the request, send it to the API, and print the completion.
Code:
import json
import network
import time
import urequests
# Internal libs
import constants
def chat_gpt(ssid, password, endpoint, api_key, model, prompt, max_tokens):
"""
Description: This is a function to hit chat gpt api and get
a response.
Parameters:
ssid[str]: The name of your internet connection
password[str]: Password for your internet connection
endpoint[str]: API enpoint
api_key[str]: API key for access
model[str]: AI model (see openAI documentation)
prompt[str]: Input to the model
max_tokens[int]: The maximum number of tokens to
generate in the completion.
Returns: Simply prints the response
"""
# Just making our internet connection
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('waiting for connection...')
time.sleep(1)
# Handle connection error
if wlan.status() != 3:
print(wlan.status())
raise RuntimeError('network connection failed')
else:
print('connected')
print(wlan.status())
status = wlan.ifconfig()
## Begin formatting request
headers = {'Content-Type': 'application/json',
"Authorization": "Bearer " + api_key}
data = {"model": model,
"prompt": prompt,
"max_tokens": max_tokens}
print("Attempting to send Prompt")
r = urequests.post("https://api.openai.com/v1/{}".format(endpoint),
json=data,
headers=headers)
if r.status_code >= 300 or r.status_code < 200:
print("There was an error with your request \n" +
"Response Status: " + str(r.text))
else:
print("Success")
response_data = json.loads(r.text)
completion = response_data["choices"][0]["text"]
print(completion)
r.close()
chat_gpt(constants.INTERNET_NAME,
constants.INTERNET_PASSWORD,
"completions",
constants.CHAT_GPT_API_KEY,
"text-davinci-003",
"Write a tagline for an ice cream shop. ",
100)
What this code is doing:
- Connects to the internet because an active connection is required to access the API. Pass in your network name and password.
- Passes the API key, model, and max_tokens. See the API details in the documentation.
- Uses the completions API path. Other API paths exist for different purposes, including edits or embeddings.
- Notes that many other configurable variables can be passed in, and you can modify the function to incorporate additional parameters.
- Highlights the temperature parameter as an experiment: higher values like 0.8 are more random, while lower values like 0.2 are more focused and deterministic. It is generally recommended to alter this or top_p, but not both.
Expected result: The Pico W prints connection status, then prints either an error message with the API response text or a successful completion returned from the API.
Conclusion
You set up ChatGPT on a Raspberry Pi Pico W by connecting to WiFi, calling the OpenAI Completions API, and printing the response to your prompt. This is a solid starting point for natural language features in microcontroller projects.
Want parts for your next Pico build? Grab what you need from ShillehTek.com. If you want help tailoring this into a product prototype or a custom IoT solution, check out our IoT consulting services.


