xxxxxxxxxx
277
let serial; // variable to hold an instance of the serialport library
let portName = '/dev/tty.usbserial-02898BB7';
let inData;
// OPEN AI REQUEST
// var prompt;
// //choosing the prompt????
// function keyTyped() {
// if (key === 'a') {
// prompt = "tell me a story in less than 100 words about the history of Vermont through the point of view of a teddy bear";
// print('a');
// } else if (key === 'b') {
// prompt = "tell me a story in less than 50 words about Joey's morning routine through the perspective of his toaster. really anthropomorphize the toaster";
// }
// return false;
// }
let open_ai_access_token = "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";
let open_ai_complete_url = "https://api.openai.com/v1/completions";
let open_ai_post_data = {
"model": "text-davinci-003",
"prompt": "\"tell me a story in less than 100 words about the history of Vermont through the point of view of a teddy bear\"\n",
"temperature": 0.7,
"max_tokens": 256,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0
};
// SERIAL INFO
// variable to hold an instance of the p5.webserial library:
// HTML button object:
let portButton;
let outByte = 0; // for outgoing data
let isPortOpen = false;
function setup() {
createCanvas(400, 400);
// makeHTTPRequest();
// check to see if serial is available:
// if (!navigator.serial) {
// alert("WebSerial is not supported in this browser. Try Chrome or MS Edge.");
// }
// // if serial is available, add connect/disconnect listeners:
// navigator.serial.addEventListener("connect", portConnect);
// navigator.serial.addEventListener("disconnect", portDisconnect);
// // check for any ports that are available:
// serial.getPorts();
// // if there's no port chosen, choose one:
// serial.on("noport", makePortButton);
// // open whatever port is available:
// serial.on("portavailable", openPort);
// // handle serial errors:
// serial.on("requesterror", portError);
// // handle any incoming serial data:
// serial.on("data", handleIncomingSerialEvent);
// serial.on("close", makePortButton);
}
// this draws a small window
// on the screen...
function draw() {
background(220);
}
// read any incoming data as a string
// (assumes a newline at the end of it):
function handleIncomingSerialEvent()
{
inData = serial.readLine();
console.log(inData);
print(inData);
// Check to see if the incoming Serial data
// begins with 'ASK_OPENAI'
if( inData != null && inData.startsWith("2") ){
// make a request to the
// open AI api
makeHTTPRequest( );
print("madeHTTPRequest");
}
}
// This function will make a web request to the
// openAI complete API endpoint.
// The request will be sent as POST data
// it will create HTTP headers and include the
// authorization / API token to allow us access.
// finally it will pass the data for the request
// e.g. the prompt, and other parameters to
// generate the text output
function makeHTTPRequest( )
{
// display that we're making a reqest
// on the console
console.log( "-> MAKING REQUEST TO:");
console.log ( open_ai_complete_url );
httpRequestData = {
method: 'POST',
body: JSON.stringify(open_ai_post_data),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + open_ai_access_token
}
};
console.log ( httpRequestData );
// make the request...
httpDo(open_ai_complete_url , httpRequestData,
function(result) {
// when there's a result pass it to the
// processing function...
console.log( result );
print(result);
processHTTPResponse( result );
}, function(err){
// if theres an error display it
console.log("HTTP Error");
console.log(err.toString());
});
}
// A response will look like this
// {
// "id": "cmpl-6uLrjlDLLUivOGe0afYAZRbSnkbTb",
// "object": "text_completion",
// "created": 1678888439,
// "model": "text-davinci-003",
// "choices": [
// {
// "text": "\n\nYour hard work is about to pay off in the near future, so make sure to stay focused and don't lose sight of your goals. This is a great time to take risks and explore new opportunities. You will find that your creativity and ambition will be rewarded. Take some time to relax and revitalize your energy. Now is the time to enjoy the fruits of your labor.",
// "index": 0,
// "logprobs": null,
// "finish_reason": "stop"
// }
// ],
// "usage": {
// "prompt_tokens": 5,
// "completion_tokens": 78,
// "total_tokens": 83
// }
function processHTTPResponse( data ){
// convert the web request response to
// json data
jsonData = JSON.parse(data.toString());
// get the choices > 0 > text option
generatedText = jsonData["choices"][0]["text"];
// spit it out to the console to see what we got.
console.log(generatedText);
print(generatedText);
print("a");
// relay this to the arduino...
sendTextonSerial( generatedText.trim() )
}
function sendTextonSerial( text ){
// if the serial port is open and active
if( isPortOpen ){
// display that we're sending info
console.log( "-> SENDING TEXT TO ARDUINO");
// write the text via the serial connection
serial.write(text);
// send a link break character.
serial.write("\n");
}
}
/*-----------------------
SERIAL PORT MANAGEMENT
--------------------*/
// if there's no port selected,
// make a port select button appear:
function makePortButton() {
// create and position a port chooser button:
portButton = createButton("choose port");
portButton.position(10, 10);
// give the port button a mousepressed handler:
portButton.mousePressed(choosePort);
}
// make the port selector window appear:
function choosePort() {
if (portButton) portButton.show();
serial.requestPort();
}
// open the selected port, and make the port
// button invisible:
function openPort() {
// wait for the serial.open promise to return,
// then call the initiateSerial function
serial.open().then(initiateSerial);
// once the port opens, let the user know:
function initiateSerial() {
console.log("port open");
isPortOpen = true;
}
// hide the port button once a port is chosen:
if (portButton) portButton.hide();
}
// pop up an alert if there's a port error:
function portError(err) {
alert("Serial port error: " + err);
}
// read any incoming data as a string
// (assumes a newline at the end of it):
function serialEvent() {
//inData = Number(serial.read());
inData = serial.readLine();
console.log(inData);
}
// try to connect if a new serial port
// gets added (i.e. plugged in via USB):
function portConnect() {
console.log("port connected");
serial.getPorts();
}
// if a port is disconnected:
function portDisconnect() {
serial.close();
isPortOpen = false;
console.log("port disconnected");
}
function closePort() {
serial.close();
isPortOpen = false;
}