Class: Zwischen::AI::AnthropicClient
- Inherits:
-
BaseClient
- Object
- BaseClient
- Zwischen::AI::AnthropicClient
- Defined in:
- lib/zwischen/ai/anthropic_client.rb
Constant Summary collapse
- API_BASE_URL =
"https://api.anthropic.com/v1/"- API_VERSION =
"2023-06-01"
Instance Attribute Summary
Attributes inherited from BaseClient
Instance Method Summary collapse
- #analyze(prompt) ⇒ Object
-
#initialize(api_key: nil, config: {}) ⇒ AnthropicClient
constructor
A new instance of AnthropicClient.
Constructor Details
#initialize(api_key: nil, config: {}) ⇒ AnthropicClient
Returns a new instance of AnthropicClient.
13 14 15 16 17 18 19 20 21 22 |
# File 'lib/zwischen/ai/anthropic_client.rb', line 13 def initialize(api_key: nil, config: {}) super raise Error, "Claude API key not found." unless @api_key @client = Faraday.new(url: API_BASE_URL) do |conn| conn.request :json conn.response :json, content_type: /\bjson$/ conn.adapter Faraday.default_adapter end end |
Instance Method Details
#analyze(prompt) ⇒ Object
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 |
# File 'lib/zwischen/ai/anthropic_client.rb', line 24 def analyze(prompt) model = @config["model"] || "claude-3-5-sonnet-20241022" # Relative path: a leading slash would discard the /v1 prefix of the base URL response = @client.post("messages") do |req| req.headers["x-api-key"] = @api_key req.headers["anthropic-version"] = API_VERSION req.body = { model: model, max_tokens: 4096, messages: [ { role: "user", content: prompt } ] } end body = response.body body = JSON.parse(body) if body.is_a?(String) if response.success? body.dig("content", 0, "text") else = body.dig("error", "message") rescue body raise Error, "Claude API error: #{}" end rescue Faraday::Error => e raise Error, "Network error: #{e.}" rescue JSON::ParserError => e raise Error, "Invalid JSON response: #{e.}" end |