Last active
May 15, 2024 20:30
-
-
Save alexschreyer/870b2637b8051e25d36ef80eb13c83bc to your computer and use it in GitHub Desktop.
This code queries OpenAI's API for valid SketchUp Ruby code and then executes it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'uri' | |
require 'json' | |
# Set the endpoint and API key for the OpenAI API | |
endpoint = "https://api.openai.com/v1/chat/completions" | |
api_key = "<YOUR API KEY>" | |
# Set up the system message for the code completion | |
sys_message = "Generate only valid SketchUp Ruby code." | |
# Ask the actual prompt | |
prompt = "Draw a box" | |
# Set up the HTTP request with the API key and prompt | |
uri = URI(endpoint) | |
req = Net::HTTP::Post.new(uri) | |
req["Content-Type"] = "application/json" | |
req["Authorization"] = "Bearer #{api_key}" | |
req.body = JSON.dump({ | |
# Enter the AI model here | |
"model" => "gpt-3.5-turbo", | |
"messages" => [ | |
{ "role" => "system", "content" => "#{sys_message}" }, | |
{ "role" => "user", "content" => "#{prompt}" } | |
], | |
"max_tokens" => 1024, | |
"top_p" => 1, | |
"n" => 1, | |
"temperature" => 0.1, | |
"stream" => false | |
}) | |
# Make the HTTP request to the OpenAI API and parse the response | |
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| | |
http.request(req) | |
end | |
response_body = JSON.parse(res.body) | |
# Get the generated code from the API response and clean it up a bit | |
generated_code = response_body["choices"][0]["message"]["content"] | |
generated_code.strip! | |
generated_code = generated_code[/```ruby(.*?)```/m, 1].strip! if generated_code.include? "```" | |
# Display the generated code in the Ruby console | |
p generated_code | |
# Run the generated code - fingers crossed! | |
eval generated_code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment