Class: TranslationAPI::OpenAI
- Inherits:
-
Object
- Object
- TranslationAPI::OpenAI
- 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
-
.dig_used_tokens(response, token_type) ⇒ Integer
レスポンスから使用したトークン数を取得する.
Instance Method Summary collapse
-
#initialize(output_logs: true, except_words: [], language: "japanese") ⇒ void
constructor
OpenAI APIを使用してテキストを翻訳する.
-
#translate(text) ⇒ void
テキストを日本語に翻訳し、結果をファイルに書き込む.
Constructor Details
#initialize(output_logs: true, except_words: [], language: "japanese") ⇒ void
OpenAI APIを使用してテキストを翻訳する
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
レスポンスから使用したトークン数を取得する
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.
テキストを日本語に翻訳し、結果をファイルに書き込む
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 |