Class: ActiveAgent::Providers::Anthropic

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

Constant Summary collapse

DEFAULT_URL =
'https://api.anthropic.com/v1/messages'

Instance Attribute Summary

Attributes inherited from Base

#api_key, #api_url, #model

Instance Method Summary collapse

Constructor Details

#initialize(model: 'claude-3-5-sonnet-20241022', api_key: ENV.fetch('ANTHROPIC_API_KEY', nil), api_url: nil) ⇒ Anthropic

Returns a new instance of Anthropic.

Raises:



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

def initialize(model: 'claude-3-5-sonnet-20241022', api_key: ENV.fetch('ANTHROPIC_API_KEY', nil), api_url: nil)
  url = api_url || DEFAULT_URL
  super(model: model, api_key: api_key, api_url: url)

  raise Error, 'ANTHROPIC_API_KEY is required for Anthropic provider' unless @api_key || ENV['MOCK_AGENT_RESPONSE']
end

Instance Method Details

#chat(messages:, tools: []) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/active_agent/providers/anthropic.rb', line 17

def chat(messages:, tools: [])
  headers = {
    'Content-Type' => 'application/json',
    'x-api-key' => @api_key,
    'anthropic-version' => '2023-06-01'
  }

  system_message = messages.find { |m| m[:role] == 'system' }&.fetch(:content, '')
  user_messages = messages.reject { |m| m[:role] == 'system' }

  payload = {
    model: @model,
    max_tokens: 4096,
    system: system_message,
    messages: user_messages,
    temperature: 0.2
  }

  data = http_post(@api_url, headers, payload)
  content = data.dig('content', 0, 'text')

  { content: content, tool_calls: nil }
end