Class: Claude::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/claude/client.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key, endpoint: nil, timeout: 60) ⇒ Client

Returns a new instance of Client.

Raises:

  • (ArgumentError)


29
30
31
32
33
34
35
# File 'lib/claude/client.rb', line 29

def initialize(api_key, endpoint: nil, timeout: 60)
  @api_key = api_key
  @endpoint = endpoint || anthropic_endpoint
  @timeout = timeout

  raise(ArgumentError, "api_key is required") if api_key.nil?
end

Class Method Details

.const_missing(const_name) ⇒ Object

for backwards compatibility with version 0.3.1



93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/claude/client.rb', line 93

def self.const_missing(const_name)
  if const_name.to_s.match(/^MODEL_(CLAUDE_.+)$/)
    new_const_name = $1
    if Claude::Model.constants.include?(new_const_name.to_sym)
      warn "[DEPRECATION] `#{const_name}` is deprecated. Please use `Claude::Model::#{new_const_name}` instead."
      Claude::Model.const_get(new_const_name)
    else
      super
    end
  else
    super
  end
end

Instance Method Details

#anthropic_endpointObject



41
42
43
# File 'lib/claude/client.rb', line 41

def anthropic_endpoint
  "https://api.anthropic.com/#{version}"
end

#headersObject



71
72
73
74
75
76
77
# File 'lib/claude/client.rb', line 71

def headers
  {
    'Content-Type' => 'application/json',
    'anthropic-version' => "2023-06-01",
    'x-api-key' => "#{@api_key}",
  }
end

#messages(messages, params = {}) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/claude/client.rb', line 49

def messages(messages, params = {})
  model = params[:model] || Model::CLAUDE_DEFAULT
  max_tokens = params[:max_tokens] || 4096
  system = params[:system] || "You are a helpful assistant."
  timeout = params[:timeout] || @timeout

  data = {
    model: model,
    messages: messages,
    system: system,
    max_tokens: max_tokens,
    metadata: params[:metadata],
    stop_sequences: params[:stop_sequences],
    stream: params[:stream],
    temperature: params[:temperature],
    top_p: params[:top_p],
    top_k: params[:top_k],
  }.compact

  post_api(messages_endpoint, data, timeout)
end

#messages_endpointObject



45
46
47
# File 'lib/claude/client.rb', line 45

def messages_endpoint
  "#{anthropic_endpoint}/messages"
end

#parse_response(response) ⇒ Object



88
89
90
# File 'lib/claude/client.rb', line 88

def parse_response(response)
  response['content'][0]['text']
end

#user_message(user_message) ⇒ Object



79
80
81
82
83
84
85
86
# File 'lib/claude/client.rb', line 79

def user_message(user_message)
  [
    {
      "role": "user",
      "content": user_message,
    }
  ]
end

#versionObject



37
38
39
# File 'lib/claude/client.rb', line 37

def version
  'v1'
end