Class: LlmTranslate::AiClient

Inherits:
Object
  • Object
show all
Defined in:
lib/llm_translate/ai_client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, logger) ⇒ AiClient



10
11
12
13
14
# File 'lib/llm_translate/ai_client.rb', line 10

def initialize(config, logger)
  @config = config
  @logger = logger
  @client = initialize_client
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



8
9
10
# File 'lib/llm_translate/ai_client.rb', line 8

def config
  @config
end

#loggerObject (readonly)

Returns the value of attribute logger.



8
9
10
# File 'lib/llm_translate/ai_client.rb', line 8

def logger
  @logger
end

Instance Method Details

#test_connectionObject



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/llm_translate/ai_client.rb', line 41

def test_connection
  test_prompt = 'Hello, world!'

  begin
    response = make_request(test_prompt)
    !response.nil? && !response.empty?
  rescue StandardError => e
    logger.error "AI connection test failed: #{e.message}"
    false
  end
end

#translate(content, custom_prompt = nil) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/llm_translate/ai_client.rb', line 16

def translate(content, custom_prompt = nil)
  prompt = build_prompt(content, custom_prompt)

  logger.log_ai_request(prompt.length, config.ai_model)

  retries = 0
  begin
    response = make_request(prompt)

    raise TranslationError, 'Empty response from AI service' unless response && !response.empty?

    logger.log_ai_response(response.length)
    response.strip
  rescue StandardError => e
    retries += 1
    unless retries <= config.retry_attempts
      raise TranslationError, "AI translation failed after #{config.retry_attempts} attempts: #{e.message}"
    end

    logger.warn "AI request failed (attempt #{retries}/#{config.retry_attempts}): #{e.message}"
    sleep(config.retry_delay * retries) # Exponential backoff
    retry
  end
end