Class: Spectre::Claude::Completions

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

Constant Summary collapse

API_URL =
'https://api.anthropic.com/v1/messages'
DEFAULT_MODEL =
'claude-opus-4-1'
DEFAULT_TIMEOUT =
60
ANTHROPIC_VERSION =
'2023-06-01'

Class Method Summary collapse

Class Method Details

.create(messages:, model: DEFAULT_MODEL, json_schema: nil, tools: nil, tool_choice: nil, **args) ⇒ Hash

Class method to generate a completion based on user messages and optional tools

Parameters:

  • messages (Array<Hash>)

    The conversation messages, each with a role and content

  • model (String) (defaults to: DEFAULT_MODEL)

    The model to be used for generating completions, defaults to DEFAULT_MODEL

  • json_schema (Hash, nil) (defaults to: nil)

    Optional JSON Schema; when provided, it will be converted into a tool with input_schema and forced via tool_choice unless overridden

  • tools (Array<Hash>, nil) (defaults to: nil)

    An optional array of tool definitions for function calling

  • tool_choice (Hash, nil) (defaults to: nil)

    Optional tool_choice to force a specific tool use (e.g., { type: ‘tool’, name: ‘record_summary’ })

  • args (Hash, nil)

    optional arguments like read_timeout and open_timeout. Provide max_tokens at the top level only.

Returns:

  • (Hash)

    The parsed response including any tool calls or content

Raises:

  • (APIKeyNotConfiguredError)

    If the API key is not set

  • (RuntimeError)

    For general API errors or unexpected issues



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
57
58
59
# File 'lib/spectre/claude/completions.rb', line 28

def self.create(messages:, model: DEFAULT_MODEL, json_schema: nil, tools: nil, tool_choice: nil, **args)
  api_key = Spectre.claude_configuration&.api_key
  raise APIKeyNotConfiguredError, "API key is not configured" unless api_key

  validate_messages!(messages)

  uri = URI(API_URL)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.read_timeout = args.fetch(:read_timeout, DEFAULT_TIMEOUT)
  http.open_timeout = args.fetch(:open_timeout, DEFAULT_TIMEOUT)

  request = Net::HTTP::Post.new(uri.path, {
    'Content-Type' => 'application/json',
    'x-api-key' => api_key,
    'anthropic-version' => ANTHROPIC_VERSION
  })

  max_tokens = args[:max_tokens] || 1024
  request.body = generate_body(messages, model, json_schema, max_tokens, tools, tool_choice).to_json
  response = http.request(request)

  unless response.is_a?(Net::HTTPSuccess)
    raise "Claude API Error: #{response.code} - #{response.message}: #{response.body}"
  end

  parsed_response = JSON.parse(response.body)

  handle_response(parsed_response, schema_used: !!json_schema)
rescue JSON::ParserError => e
  raise "JSON Parse Error: #{e.message}"
end