Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(insights): narrate LLM insight bodies in the family's locale (#3533)

Radoslaw Dabrowski659a0ab8d737
diff --git a/app/models/insight/body_writer.rb b/app/models/insight/body_writer.rb
index 76587af4b3..0987aa2d6d 100644
--- a/app/models/insight/body_writer.rb
+++ b/app/models/insight/body_writer.rb
@@ -26,6 +26,14 @@ class Insight::BodyWriter
private
attr_reader :family
+ # The system prompt is written in English, so without an explicit instruction the
+ # model narrates in English even when the family uses another locale. The template
+ # fallback already follows I18n, so this keeps both paths in the same language.
+ def language_instruction
+ locale = family.locale.presence || I18n.default_locale.to_s
+ "- Write in the user's language (BCP 47 locale: #{locale}).\n"
+ end
+
def template_body(generated_insight)
I18n.t(
"insights.templates.#{generated_insight.template_key}",
@@ -44,7 +52,7 @@ class Insight::BodyWriter
response = provider.chat_response(
prompt,
model: provider.class.effective_model,
- instructions: SYSTEM_PROMPT,
+ instructions: SYSTEM_PROMPT + language_instruction,
family: family
)
return nil unless response.success?
diff --git a/test/models/insight/body_writer_test.rb b/test/models/insight/body_writer_test.rb
index 20c6390ffb..ae26294c6d 100644
--- a/test/models/insight/body_writer_test.rb
+++ b/test/models/insight/body_writer_test.rb
@@ -23,6 +23,19 @@ class Insight::BodyWriterTest < ActiveSupport::TestCase
assert_equal "Narrated body.", body
end
+ test "tells the LLM to write in the family's full locale tag" do
+ @family.update!(locale: "pt-BR")
+ provider = FakeLlmProvider.new("Narrated body.")
+ captured = nil
+ provider.stubs(:chat_response).with { |*, **kwargs| captured = kwargs[:instructions]; true }
+ .returns(OpenStruct.new(success?: true, data: OpenStruct.new(messages: [ OpenStruct.new(id: "1", output_text: "Narrated body.") ])))
+ Provider::Registry.stubs(:preferred_llm_provider).returns(provider)
+
+ Insight::BodyWriter.new(@family).write(generated_insight)
+
+ assert_includes captured, "BCP 47 locale: pt-BR"
+ end
+
test "falls back to the template and captures a debug log when the LLM call fails" do
provider = FakeLlmProvider.new("unused")
provider.stubs(:chat_response).raises(StandardError.new("boom"))