Skip to content

Commit 195ebc4

Browse files
committed
WIP: image generation with Dall-e
1 parent b56f1de commit 195ebc4

File tree

4 files changed

+53
-1
lines changed

4 files changed

+53
-1
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,6 @@
5656
/.idea/*
5757
/client/.idea/*
5858
vendor/bundle
59+
60+
# Ignore downloaded images
61+
/public/dalle_images

app/services/toolbox.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ def self.descendants
33
[
44
Toolbox::HelloWorld,
55
Toolbox::OpenMeteo,
6+
Toolbox::Dalle
67
]
78
end
89

app/services/toolbox/dalle.rb

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Toolbox::Dalle < Toolbox
2+
3+
describe :generate_an_image, <<~S
4+
Generate an image based on what the user asks you to generate. You will pass the user's prompt and will get back a URL to an image.
5+
S
6+
7+
def self.generate_an_image(image_generation_prompt_s:)
8+
9+
response = client.images.generate(
10+
parameters: {
11+
prompt: image_generation_prompt_s,
12+
model: "dall-e-3",
13+
size: "1024x1792",
14+
quality: "standard"
15+
}
16+
)
17+
18+
dalle_url = response.dig("data", 0, "url")
19+
download(dalle_url)
20+
21+
{
22+
url: dalle_url
23+
}
24+
end
25+
26+
class << self
27+
private
28+
29+
def download(image_url)
30+
filename = File.basename(URI.parse(image_url).path)
31+
file_path = Rails.root.join('public', 'dalle_images', filename)
32+
33+
FileUtils.mkdir_p(File.dirname(file_path))
34+
35+
File.open(file_path, 'wb') do |file|
36+
file << URI.open(image_url).read
37+
end
38+
39+
file_path
40+
end
41+
42+
def client
43+
OpenAI::Client.new(
44+
access_token: Current.user.openai_key,
45+
)
46+
end
47+
end
48+
end

test/services/toolbox_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
class ToolboxTest < ActiveSupport::TestCase
44
test "tools" do
5-
assert_equal 4, Toolbox.tools.length
5+
assert_equal 5, Toolbox.tools.length
66
assert Toolbox::OpenMeteo.tools.first[:function].values.all? { |value| value.present? }
77
assert Toolbox::OpenMeteo.tools.first[:function][:description].length > 100
88
tools = [

0 commit comments

Comments
 (0)