Class: Ask::Providers::Anthropic

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

Overview

Anthropic Claude API provider.

Class Method Summary collapse

Instance Method Summary collapse

Methods included from LLM::SSEBuffer

#each_sse_event, #init_sse_buffer

Constructor Details

#initialize(config = {}) ⇒ Anthropic

Returns a new instance of Anthropic.



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

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

Class Method Details

.capabilitiesObject



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

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

.configuration_optionsObject



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

def configuration_options; %i[api_key api_base]; end

.configuration_requirementsObject



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

def configuration_requirements; %i[api_key]; end

.slugObject



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

def slug; "anthropic"; end

Instance Method Details

#api_baseObject



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

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



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

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)


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

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

#headersObject



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

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

#list_modelsObject



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

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



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

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