
I Coded Working AI in Scratch!
Not just a bunch of ifs and say blocks - this is real AI.
----
Scratch Profile: scratch.mit.edu/users/charlesbel/
Email: contact@donutask.com
Website: donutask.com
----
I can't publish this extension because it requires an API key. Here are the resources you need to create it yourself. The OpenAI API, ironically, requires real money to use.
Scratch mod used: sheeptester.github.io/scratch-gui/
OpenAI Documentation: platform.openai.com/docs/api-reference/completions
Get API Key (requires account and billing details): platform.openai.com/account/api-keys
JavaScript Code (You need to provide an API key):
class AIBlock {
getInfo() {
//Metadata for block
return {
"id": "AI",
"name": "AI",
"blocks": [{
"opcode": "completePrompt",
"blockType": "reporter",
"text": "complete prompt [string]",
"arguments": {
"string": {
"type": "string",
"defaultValue": "Explain quantum computing in simple terms"
}
}
}],
//don't worry about it
"menus": {}
};
}
async completePrompt({ string }) {
//Remove trailing spaces, required for model to work properly
const text = string.trim();
//Request text completion using Davinci3
const url = `api.openai.com/v1/engines/text-davinci-003/complet…`;
const options = {
//Has to be post for some reason
method: "POST",
//Input prompt and a decent length
body: JSON.stringify({
prompt: text,
max_tokens: 300,
}),
//API key, and JSON content type
headers: {
Authorization: "Bearer " + API_KEY,
"Content-type": "application/json; charset=UTF-8"
},
};
console.log("REQUEST:" + url);
//Fetch and await promise.
const response = await fetch(url, options);
//Get JSON data
const jsonData = await response.json();
//The ai response will be the first (and only) choices text
const output = jsonData.choices[0].text;
return output;
}
}
//Register block with Scratch
Scratch.extensions.register(new AIBlock());
---
Sound effects from ZapSplat.com
Some images generated by DALL-E
Images and videos from Unsplash.com and Pexels.com
Music by Kevin MacLeod (incompetech.com)
Licensed under Creative Commons: By Attribution 4.0 License
creativecommons.org/licenses/by/4.0/
Subscribe!
Oh, and if you want to support me financially, consider becoming a member :)
youtube.com/channel/UC0OBisfM_ZRwf0sfDJ1Q0YQ/join
コメント