Skip to content

Commit c2bb89f

Browse files
committed
improve guide code
1 parent 78ba3de commit c2bb89f

File tree

1 file changed

+46
-29
lines changed
  • CircuitPython_GetSuperpower_PicoW_OpenAI

1 file changed

+46
-29
lines changed

CircuitPython_GetSuperpower_PicoW_OpenAI/code.py

Lines changed: 46 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@
33
import json
44
import os
55
import ssl
6+
import traceback
67

78
import board
89
import displayio
910
import digitalio
1011
import keypad
1112
import socketpool
13+
import supervisor
1214
from wifi import radio
1315

1416
import adafruit_requests
@@ -26,7 +28,7 @@
2628
# MY_PROMPT="Give me an idea for a gluten free, keto dinner. Write one sentence"
2729
# PLEASE_WAIT="Cooking something up just for you"
2830
#
29-
# Experiementation is best to figure out what works. Usually you'll want to ask
31+
# Experimentation is best to figure out what works. Usually you'll want to ask
3032
# for just one sentence or paragraph, since the 128x32 pixel screen can't hold
3133
# much text!
3234

@@ -116,7 +118,7 @@ def add_text(self, new_text):
116118
self.scroll_to_end()
117119

118120
def set_text(self, text):
119-
print("\033[H\033[2J", end=text)
121+
print("\n\n", end=text)
120122
self.text = text
121123
self.lines = wrap_text_to_pixels(text, display.width, nice_font)
122124
self.offset = 0
@@ -161,6 +163,7 @@ def refresh(self):
161163

162164
def wait_button_scroll_text():
163165
led.switch_to_output(True)
166+
keys.events.clear()
164167
deadline = ticks_add(ticks_ms(),
165168
5000 if wrapped_text.on_last_line() else 1000)
166169
while True:
@@ -194,32 +197,46 @@ def iter_lines(resp):
194197
]
195198

196199
keys = keypad.Keys((board.GP14,), value_when_pressed=False)
197-
led = digitalio.DigitalInOut(board.LED)
200+
led = digitalio.DigitalInOut(board.GP10)
201+
led.switch_to_output(False)
198202

199-
while True:
200-
wrapped_text.show(please_wait)
201-
202-
with requests.post("https://api.openai.com/v1/chat/completions",
203-
json={"model": "gpt-3.5-turbo", "messages": full_prompt, "stream": True},
204-
headers={
205-
"Authorization": f"Bearer {openai_api_key}",
206-
},
207-
) as response:
203+
try:
204+
while True:
205+
wrapped_text.show(please_wait)
206+
207+
with requests.post("https://api.openai.com/v1/chat/completions",
208+
json={"model": "gpt-3.5-turbo", "messages": full_prompt, "stream": True},
209+
headers={
210+
"Authorization": f"Bearer {openai_api_key}",
211+
},
212+
) as response:
213+
214+
wrapped_text.set_text("")
215+
if response.status_code != 200:
216+
wrapped_text.show(f"Uh oh! {response.status_code}: {response.reason}")
217+
else:
218+
wrapped_text.show("")
219+
for line in iter_lines(response):
220+
led.switch_to_output(True)
221+
if line.startswith("data: [DONE]"):
222+
break
223+
if line.startswith("data:"):
224+
content = json.loads(line[5:])
225+
try:
226+
token = content['choices'][0]['delta'].get('content', '')
227+
except (KeyError, IndexError) as e:
228+
token = None
229+
led.value = False
230+
if token:
231+
wrapped_text.add_show(token)
232+
wait_button_scroll_text()
233+
except Exception as e:
234+
traceback.print_exception(e) # pylint: disable=no-value-for-parameter
235+
print(end="\n\n\nAn error occurred\n\nPress button\nto reload")
236+
display.root_group = displayio.CIRCUITPYTHON_TERMINAL
237+
display.auto_refresh = True
238+
while True:
239+
if (event := keys.events.get()) and event.pressed:
240+
break
241+
supervisor.reload()
208242

209-
wrapped_text.set_text("")
210-
if response.status_code != 200:
211-
wrapped_text.show(f"Uh oh! {response.status_code}: {response.reason}")
212-
else:
213-
wrapped_text.show("")
214-
for line in iter_lines(response):
215-
if line.startswith("data: [DONE]"):
216-
break
217-
if line.startswith("data:"):
218-
content = json.loads(line[5:])
219-
try:
220-
token = content['choices'][0]['delta'].get('content', '')
221-
except (KeyError, IndexError) as e:
222-
token = None
223-
if token:
224-
wrapped_text.add_show(token)
225-
wait_button_scroll_text()

0 commit comments

Comments
 (0)