Class: RailsAIPromptable::Providers::AnthropicProvider

Inherits:
BaseProvider
  • Object
show all
Defined in:
lib/rails_ai_promptable/providers/anthropic_provider.rb

Constant Summary collapse

API_VERSION =
"2023-06-01"

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ AnthropicProvider

Returns a new instance of AnthropicProvider.



11
12
13
14
15
16
# File 'lib/rails_ai_promptable/providers/anthropic_provider.rb', line 11

def initialize(configuration)
  super
  @api_key = configuration.anthropic_api_key || configuration.api_key
  @base_url = configuration.anthropic_base_url || "https://api.anthropic.com/v1"
  @timeout = configuration.timeout
end

Instance Method Details

#generate(prompt:, model:, temperature:, format:) ⇒ Object



18
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
# File 'lib/rails_ai_promptable/providers/anthropic_provider.rb', line 18

def generate(prompt:, model:, temperature:, format:)
  uri = URI.parse("#{@base_url}/messages")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == "https"
  http.read_timeout = @timeout

  request = Net::HTTP::Post.new(uri.request_uri, {
                                  "Content-Type" => "application/json",
                                  "x-api-key" => @api_key,
                                  "anthropic-version" => API_VERSION
                                })

  body = {
    model: model,
    messages: [{ role: "user", content: prompt }],
    temperature: temperature,
    max_tokens: 4096
  }

  request.body = body.to_json

  response = http.request(request)
  parsed = JSON.parse(response.body)

  if response.code.to_i >= 400
    error_message = parsed.dig("error", "message") || "Unknown error"
    raise "Anthropic API error: #{error_message}"
  end

  # Extract content from Anthropic response
  parsed.dig("content", 0, "text")
rescue StandardError => e
  RailsAIPromptable.configuration.logger.error("[rails_ai_promptable] anthropic error: #{e.message}")
  nil
end