xxxxxxxxxx
67
// Machine Learning for Artists and Designers
// NYUSH F24 - gohai
// Note: this sketch consists of additional JavaScript
// files. Make sure to duplicate it, rather than copying
// and pasting code :)
let openai_api_proxy = "https://zest-quiet-phalange.glitch.me/";
let lastSubject = '';
let customDraw = null;
function setup() {
createCanvas(400, 400);
background(255);
requestCode("car");
}
function requestCode(subject) {
messages = [{
role: "user",
content: "Draw a " + subject + " in p5.js. Return only the draw function. Do not prefix your response."
}];
let params = {
model: "gpt-4o",
messages: messages,
};
requestOAI("POST", "/v1/chat/completions", params, gotCode);
lastSubject = subject;
}
function gotCode(results) {
let code = results.choices[0].message.content;
// code responses from GPT are often prefixed with
// ```javascript or ``` - strip those
code = code.replaceAll('```javascript', '');
code = code.replaceAll('```', '');
// also remove the leading "function draw() {"
code = code.trim();
code = code.replaceAll('function draw() {', '');
// and the last character of the function,
// which we expect to be the closing curly brace
code = code.substring(0, code.length-1);
console.log(code);
// we can overwrite the draw function like so
try {
draw = new Function(code);
} catch (e) {
console.warn("Invalid code ;(");
}
// this uses try {} catch {} to gracefully
// handle the case when OpenAI returns code
// that doesn't run
requestCode(lastSubject);
}
function draw() {
}