Class: AISpec::Core::Providers::Anthropic
- Defined in:
- lib/aispec/core/providers/anthropic.rb
Constant Summary collapse
- BASE_URI =
"https://api.anthropic.com/v1/messages"
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
- #generate(prompt, system_prompt: nil, temperature: 0.7, max_tokens: 1024, **_params) ⇒ Object
-
#initialize(model: "claude-3-5-sonnet-20241022", api_key: nil, **options) ⇒ Anthropic
constructor
A new instance of Anthropic.
Methods inherited from Base
Constructor Details
#initialize(model: "claude-3-5-sonnet-20241022", api_key: nil, **options) ⇒ Anthropic
Returns a new instance of Anthropic.
13 14 15 16 |
# File 'lib/aispec/core/providers/anthropic.rb', line 13 def initialize(model: "claude-3-5-sonnet-20241022", api_key: nil, **) super(model: model, **) @api_key = api_key || ENV["ANTHROPIC_API_KEY"] end |
Instance Method Details
#generate(prompt, system_prompt: nil, temperature: 0.7, max_tokens: 1024, **_params) ⇒ 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 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/aispec/core/providers/anthropic.rb', line 18 def generate(prompt, system_prompt: nil, temperature: 0.7, max_tokens: 1024, **_params) return fallback_mock_if_no_key(prompt) unless @api_key && !@api_key.empty? payload = { model: @model || "claude-3-5-sonnet-20241022", max_tokens: max_tokens, messages: [{ role: "user", content: prompt }], temperature: temperature } payload[:system] = system_prompt if system_prompt uri = URI.parse(BASE_URI) start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) req = Net::HTTP::Post.new(uri.path, { "Content-Type" => "application/json", "x-api-key" => @api_key, "anthropic-version" => "2023-06-01" }) req.body = JSON.generate(payload) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.read_timeout = AISpec.configuration.timeout res = http.request(req) elapsed_ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000.0 if res.is_a?(Net::HTTPSuccess) data = JSON.parse(res.body) output = data.dig("content", 0, "text") || "" input_tokens = data.dig("usage", "input_tokens") || 0 output_tokens = data.dig("usage", "output_tokens") || 0 total_tokens = input_tokens + output_tokens cost = (input_tokens * 0.000003) + (output_tokens * 0.000015) build_response( output: output, latency_ms: elapsed_ms, tokens: total_tokens, cost: cost, raw: data ) else raise "Anthropic API Error (#{res.code}): #{res.body}" end end |