Class: Anthemic::Providers::Anthropic

Inherits:
Base
  • Object
show all
Defined in:
lib/anthemic/providers/anthropic.rb

Constant Summary collapse

BASE_URL =
"https://api.anthropic.com/v1"
DEFAULT_MODEL =
"claude-3-opus-20240229"

Instance Method Summary collapse

Constructor Details

#initialize(model: nil, api_key: nil) ⇒ Anthropic

Returns a new instance of Anthropic.

Raises:



9
10
11
12
13
14
15
16
# File 'lib/anthemic/providers/anthropic.rb', line 9

def initialize(model: nil, api_key: nil)
  @model = model || DEFAULT_MODEL
  @api_key = api_key || Anthemic.configuration.api_keys[:anthropic]
  
  raise ConfigurationError, "Anthropic API key is required" unless @api_key
  
  @connection = create_connection(BASE_URL)
end

Instance Method Details

#embed(text) ⇒ Array<Float>

Create embeddings for a text (via OpenAI as Anthropic doesn’t have embeddings API) Requires OpenAI API key to be configured



60
61
62
63
64
65
66
67
68
# File 'lib/anthemic/providers/anthropic.rb', line 60

def embed(text)
  openai_key = Anthemic.configuration.api_keys[:openai]
  unless openai_key
    raise ConfigurationError, "OpenAI API key is required for embeddings with Anthropic provider"
  end
  
  openai = Openai.new(api_key: openai_key)
  openai.embed(text)
end

#generate(prompt, options = {}) ⇒ String

Generate a response from Anthropic Claude



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
# File 'lib/anthemic/providers/anthropic.rb', line 23

def generate(prompt, options = {})
  messages = []
  
  # Check if prompt is already formatted as messages
  if prompt.is_a?(Array) && prompt.all? { |p| p.is_a?(Hash) && p[:role] && p[:content] }
    messages = prompt
  else
    messages = [{ role: "user", content: prompt }]
  end
  
  response = @connection.post("messages") do |req|
    req.headers["x-api-key"] = @api_key
    req.headers["anthropic-version"] = "2023-06-01"
    
    req.body = {
      model: @model,
      messages: messages,
      max_tokens: options[:max_tokens] || 1000,
      temperature: options[:temperature] || 0.7,
      top_p: options[:top_p] || 1.0
    }
  end
  
  if response.status == 200
    response.body["content"][0]["text"]
  else
    raise ProviderError, "Anthropic API error: #{response.body["error"]["message"]}"
  end
rescue Faraday::Error => e
  raise ProviderError, "Anthropic connection error: #{e.message}"
end