Class: TranslationAPI::Provider::OpenAI

Inherits:
Object
  • Object
show all
Defined in:
lib/translation_api/provider/openai.rb,
lib/translation_api/provider/openai/log.rb,
lib/translation_api/provider/openai/cost.rb

Defined Under Namespace

Classes: Cost, Log

Constant Summary collapse

SYSTEM_PROMPT_BASE =
<<~TEXT
  Translate only.
  Return result only, no extra info
  Keep symbols
TEXT
API_KEY_ERROR_MESSAGE =
"API key is not found."
MODEL_ERROR_MESSAGE =
"Specified model is not supported. Please check the model name."

Instance Method Summary collapse

Constructor Details

#initialize(output_logs:, except_words:, language:) ⇒ OpenAI

Returns a new instance of OpenAI.



20
21
22
23
24
25
26
27
# File 'lib/translation_api/provider/openai.rb', line 20

def initialize(output_logs:, except_words:, language:)
  validate_api_key!

  @client = init_client
  @output_logs   = output_logs
  @system_prompt = SYSTEM_PROMPT_BASE + except_option_text(except_words)
  @user_prompt   = user_prompt_text(language)
end

Instance Method Details

#dig_used_tokens(type:) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/translation_api/provider/openai.rb', line 46

def dig_used_tokens(type:)
  case type
  when :input
    @response["usage"]["prompt_tokens"]
  when :output
    @response["usage"]["completion_tokens"]
  else
    raise ArgumentError, "Invalid token type: #{type}"
  end
end

#translate(text) ⇒ Object



29
30
31
32
33
34
35
36
# File 'lib/translation_api/provider/openai.rb', line 29

def translate(text)
  return text if text.strip.empty?

  @response = chat_to_api(text)
  Log.new(self).write if @output_logs

  translated_text
end

#translated_textObject



38
39
40
# File 'lib/translation_api/provider/openai.rb', line 38

def translated_text
  @response["choices"][0]["message"]["content"]
end

#using_modelObject



42
43
44
# File 'lib/translation_api/provider/openai.rb', line 42

def using_model
  ENV["OPENAI_MODEL"] || "gpt-5-mini"
end