Class: Anthemic::Providers::Anthropic
- 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
-
#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.
-
#generate(prompt, options = {}) ⇒ String
Generate a response from Anthropic Claude.
-
#initialize(model: nil, api_key: nil) ⇒ Anthropic
constructor
A new instance of Anthropic.
Constructor Details
#initialize(model: nil, api_key: nil) ⇒ Anthropic
Returns a new instance of Anthropic.
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 (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.(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, = {}) = [] # Check if prompt is already formatted as messages if prompt.is_a?(Array) && prompt.all? { |p| p.is_a?(Hash) && p[:role] && p[:content] } = prompt else = [{ 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: , max_tokens: [:max_tokens] || 1000, temperature: [:temperature] || 0.7, top_p: [: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 |