Class: PolylingoChat::Translator::OpenAIClient

Inherits:
Base
  • Object
show all
Defined in:
lib/polylingo_chat/translator/openai_client.rb

Class Method Summary collapse

Class Method Details

.detect_language(text) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/polylingo_chat/translator/openai_client.rb', line 9

def detect_language(text)
  return 'unknown' if text.nil? || text.strip.empty?
  prompt = "Detect language for the following text and return the ISO 639-1 code only:

#{text}"
  resp = openai_chat(prompt, system: 'You are a language detection assistant. Return only the lowercase ISO 639-1 code.')
  code = resp.to_s.strip[0,2]&.downcase
  code || 'unknown'
end

.translate(text:, from: nil, to:, context: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/polylingo_chat/translator/openai_client.rb', line 19

def translate(text:, from: nil, to:, context: nil)
  raise PolylingoChat::Error, 'target language required' if to.nil? || to.to_s.strip.empty?
  return '' if text.nil?

  # caching
  cache_key = "polylingo_chat:#{Digest::SHA1.hexdigest([text, from, to, context].join(':'))}"
  if (cache = PolylingoChat.config.cache_store)
    cached = cache.get(cache_key) rescue StandardError; nil
    return JSON.parse(cached)['translated'] if cached
  end

  prompt = build_prompt(text: text, from: from, to: to, context: context)
  translated = openai_chat(prompt, system: 'You are a translation assistant. Return only the translated text with no additional commentary.')

  if (cache = PolylingoChat.config.cache_store)
    begin
      cache.set(cache_key, { translated: translated }.to_json)
    rescue StandardError => e
      # ignore cache failures
    end
  end

  translated
end