Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(openai_translator): Enforce JSON Response format #611

Merged
merged 1 commit into from
Jan 15, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 22 additions & 16 deletions lib/i18n/tasks/translators/openai_translator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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(*)
Expand Down Expand Up @@ -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)
Expand All @@ -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
Loading