From aef9a03d4c3302afb1eb524da058092a88900b8a Mon Sep 17 00:00:00 2001 From: Rafael dos Santos Silva Date: Tue, 12 Nov 2024 15:52:46 -0300 Subject: [PATCH] FEATURE: Truncate AI Captions to a reasonable max size (#907) --- lib/ai_helper/assistant.rb | 4 +++- spec/requests/ai_helper/assistant_controller_spec.rb | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/ai_helper/assistant.rb b/lib/ai_helper/assistant.rb index b7014295..86d4b70b 100644 --- a/lib/ai_helper/assistant.rb +++ b/lib/ai_helper/assistant.rb @@ -3,6 +3,8 @@ module DiscourseAi module AiHelper class Assistant + IMAGE_CAPTION_MAX_WORDS = 50 + def self.prompt_cache @prompt_cache ||= ::DiscourseAi::MultisiteHash.new("prompt_cache") end @@ -164,7 +166,7 @@ module DiscourseAi feature_name: "image_caption", ) - raw_caption.delete("|").squish + raw_caption.delete("|").squish.truncate_words(IMAGE_CAPTION_MAX_WORDS) end private diff --git a/spec/requests/ai_helper/assistant_controller_spec.rb b/spec/requests/ai_helper/assistant_controller_spec.rb index ca78396b..4dd58ff1 100644 --- a/spec/requests/ai_helper/assistant_controller_spec.rb +++ b/spec/requests/ai_helper/assistant_controller_spec.rb @@ -163,6 +163,13 @@ RSpec.describe DiscourseAi::AiHelper::AssistantController do end end + it "truncates the caption from the LLM" do + request_caption({ image_url: image_url, image_url_type: "long_url" }, caption * 10) do |r| + expect(r.status).to eq(200) + expect(r.parsed_body["caption"].size).to be < caption.size * 10 + end + end + context "when the image_url is a short_url" do let(:image_url) { upload.short_url }