From 596f09d42d5a4d3251c6d97743f06f0b9bb518de Mon Sep 17 00:00:00 2001 From: Owens Ehimen Date: Wed, 15 Jan 2025 16:52:00 -0500 Subject: [PATCH] fix(openai_translator): Enforce JSON Response format --- .../tasks/translators/openai_translator.rb | 38 +++++++++++-------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/lib/i18n/tasks/translators/openai_translator.rb b/lib/i18n/tasks/translators/openai_translator.rb index 02d9de51..50f51cd8 100644 --- a/lib/i18n/tasks/translators/openai_translator.rb +++ b/lib/i18n/tasks/translators/openai_translator.rb @@ -18,6 +18,7 @@ class OpenAiTranslator < BaseTranslator Variables (starting with %%{ and ending with }) must not be changed under any circumstance. Keep in mind the context of all the strings for a more accurate translation. + It is CRITICAL you output only the result, without any additional information, code block syntax or comments. PROMPT def initialize(*) @@ -86,7 +87,27 @@ def translate_values(list, from:, to:) end def translate(values, from, to) - messages = [ + response = translator.chat( + parameters: { + model: model, + messages: build_messages(values, from, to), + temperature: 0.0, + response_format: { type: 'json_object' } + } + ) + + translations = response.dig('choices', 0, 'message', 'content') + error = response['error'] + + fail "AI error: #{error}" if error.present? + + # Extract the array from the JSON object response + result = JSON.parse(translations) + result['translations'].to_json + end + + def build_messages(values, from, to) + [ { role: 'system', content: format(system_prompt, from: from, to: to) @@ -100,21 +121,6 @@ def translate(values, from, to) content: values.to_json } ] - - response = translator.chat( - parameters: { - model: model, - messages: messages, - temperature: 0.0 - } - ) - - translations = response.dig('choices', 0, 'message', 'content') - error = response['error'] - - fail "AI error: #{error}" if error.present? - - translations end end end