Class: TranslationAPI::OpenAI

Inherits:
Object
  • Object
show all
Defined in:
lib/translation_api/openai.rb

Constant Summary collapse

SYSTEM_CONTENT_BASE =
<<~TEXT
  Translate only.
  Return result only, no extra info
  Keep symbols
TEXT

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(output_logs: true, except_words: [], language: "japanese") ⇒ void

OpenAI APIを使用してテキストを翻訳する

Parameters:

  • output_logs (Boolean) (defaults to: true)

    ログを出力するかどうか

  • except_words (Array<String>) (defaults to: [])

    除外する単語のリスト

  • language (String) (defaults to: "japanese")

    翻訳先の言語



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/translation_api/openai.rb', line 21

def initialize(output_logs: true, except_words: [], language: "japanese")
  # 環境変数の読み込み
  Dotenv.load
  raise "API key is not found" unless ENV["OPENAI_API_KEY"]

  @client = ::OpenAI::Client.new(
    access_token: ENV["OPENAI_API_KEY"],
    log_errors: true # 好み
  )
  @output_logs = output_logs
  @system_content = SYSTEM_CONTENT_BASE + except_option_text(except_words)
  @language = language
end

Class Method Details

.dig_used_tokens(response, token_type) ⇒ Integer

レスポンスから使用したトークン数を取得する

Parameters:

  • response (Hash)

    OpenAI APIからのレスポンス

  • token_type (String)

    トークンの種類 (input or output)

Returns:

  • (Integer)

    使用したトークン数



54
55
56
57
58
59
60
# File 'lib/translation_api/openai.rb', line 54

def self.dig_used_tokens(response, token_type)
  if token_type == "input"
    response["usage"]["prompt_tokens"]
  elsif token_type == "output"
    response["usage"]["completion_tokens"]
  end
end

Instance Method Details

#translate(text) ⇒ void

This method returns an undefined value.

テキストを日本語に翻訳し、結果をファイルに書き込む

Parameters:

  • text (String)

    翻訳するテキスト



39
40
41
42
43
44
45
46
47
# File 'lib/translation_api/openai.rb', line 39

def translate(text)
  # 空白文字は翻訳する必要がない
  return text if text.strip.empty?

  response = chat_to_api(text)
  Writer.write_logs(self, response) if @output_logs

  response["choices"][0]["message"]["content"]
end