Class: RagRuby::Generators::Anthropic

Inherits:
Base
  • Object
show all
Defined in:
lib/rag_ruby/generators/anthropic.rb

Constant Summary collapse

ENDPOINT =
"https://api.anthropic.com/v1/messages"

Instance Method Summary collapse

Constructor Details

#initialize(model: "claude-sonnet-4-20250514", api_key: nil, max_tokens: 4096) ⇒ Anthropic

Returns a new instance of Anthropic.

Raises:

  • (ArgumentError)


12
13
14
15
16
17
# File 'lib/rag_ruby/generators/anthropic.rb', line 12

def initialize(model: "claude-sonnet-4-20250514", api_key: nil, max_tokens: 4096)
  @model = model
  @api_key = api_key || ENV["ANTHROPIC_API_KEY"]
  @max_tokens = max_tokens
  raise ArgumentError, "Anthropic API key is required (set ANTHROPIC_API_KEY or pass api_key:)" unless @api_key
end

Instance Method Details

#generate(prompt:, system_prompt: nil, temperature: 0.7) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rag_ruby/generators/anthropic.rb', line 19

def generate(prompt:, system_prompt: nil, temperature: 0.7)
  body = {
    model: @model,
    max_tokens: @max_tokens,
    messages: [{ role: "user", content: prompt }],
    temperature: temperature
  }
  body[:system] = system_prompt if system_prompt

  request_with_retry do
    uri = URI.parse(ENDPOINT)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.open_timeout = 30
    http.read_timeout = 120

    req = Net::HTTP::Post.new(uri)
    req["x-api-key"] = @api_key
    req["anthropic-version"] = "2023-06-01"
    req["Content-Type"] = "application/json"
    req.body = JSON.generate(body)

    response = http.request(req)

    unless response.is_a?(Net::HTTPSuccess)
      raise RagRuby::Error, "Anthropic API error (#{response.code}): #{response.body}"
    end

    data = JSON.parse(response.body)
    text = data.dig("content", 0, "text")
    raise RagRuby::Error, "Empty response from Anthropic" if text.nil?
    usage = data["usage"] || {}

    {
      text: text,
      tokens_used: {
        prompt: usage["input_tokens"],
        completion: usage["output_tokens"]
      }
    }
  end
end