17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# File 'lib/polylingo_chat/translator/anthropic_client.rb', line 17
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?
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 = anthropic_message(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
end
end
translated
end
|