import json
import network
import time
import urequests
# Wokwi tiene problemas para realizar conexion a internet, por lo que no pude verificar el funcionamiento
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
"""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
ssid = "Wokwi-GUEST"
password = ""
wlan.connect(ssid, password)
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)
if wlan.status() != 3:
print(wlan.status())
raise RuntimeError('network connection failed')
else:
print('connected')
print(wlan.status())
status = wlan.ifconfig()
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)