Class: Ask::Providers::Anthropic

Inherits:
Ask::Provider
  • Object
show all
Defined in:
lib/ask/provider/anthropic.rb

Overview

Anthropic Claude API provider.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Anthropic

Returns a new instance of Anthropic.



7
8
9
10
11
# File 'lib/ask/provider/anthropic.rb', line 7

def initialize(config = {})
  config = normalize_config(config)
  super(config)
  @http = build_http
end

Class Method Details

.capabilitiesObject



51
52
53
# File 'lib/ask/provider/anthropic.rb', line 51

def capabilities
  { chat: true, streaming: true, tool_calls: true, vision: true, thinking: true, prompt_caching: true, structured_output: true }
end

.configuration_optionsObject



54
# File 'lib/ask/provider/anthropic.rb', line 54

def configuration_options; %i[api_key api_base]; end

.configuration_requirementsObject



55
# File 'lib/ask/provider/anthropic.rb', line 55

def configuration_requirements; %i[api_key]; end

.slugObject



56
# File 'lib/ask/provider/anthropic.rb', line 56

def slug; "anthropic"; end

Instance Method Details

#api_baseObject



13
14
15
# File 'lib/ask/provider/anthropic.rb', line 13

def api_base
  @config.api_base || "https://api.anthropic.com"
end

#chat(messages, model:, tools: nil, temperature: nil, stream: nil, schema: nil, **params, &block) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/ask/provider/anthropic.rb', line 25

def chat(messages, model:, tools: nil, temperature: nil, stream: nil, schema: nil, **params, &block)
  msgs = messages.is_a?(Ask::Conversation) ? messages.to_a : messages
  payload = build_chat_payload(msgs, model, tools, temperature, stream, schema, **params)
  if stream
    chat_stream(payload, model, &block)
  else
    chat_nonstream(payload, model)
  end
end

#embed(_texts, model: nil) ⇒ Object

Raises:

  • (Ask::CapabilityNotSupported)


35
36
37
# File 'lib/ask/provider/anthropic.rb', line 35

def embed(_texts, model: nil)
  raise Ask::CapabilityNotSupported, "Anthropic does not support embeddings"
end

#headersObject



17
18
19
20
21
22
23
# File 'lib/ask/provider/anthropic.rb', line 17

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

#list_modelsObject



39
40
41
42
43
# File 'lib/ask/provider/anthropic.rb', line 39

def list_models
  response = @http.get("v1/models")
  return [] unless response.success?
  response.body["data"].map { |m| Ask::ModelInfo.new(id: m["id"], provider: slug) }
end

#parse_error(response) ⇒ Object



45
46
47
48
# File 'lib/ask/provider/anthropic.rb', line 45

def parse_error(response)
  body = response.body rescue nil
  body&.dig("error", "message") || body&.dig("error", "type")
end