Class: Spacy::AnthropicHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-spacy/anthropic_helper.rb

Overview

A helper class for Anthropic (Claude) API interactions, designed to work with spaCy's linguistic analysis via the block-based Language#with_llm API.

Provides the same chat interface as OpenAIHelper, so code written against one provider works with the other. Anthropic does not offer an embeddings API; use the :openai or :ollama provider for embeddings.

Examples:

Basic usage with linguistic_summary

nlp = Spacy::Language.new("en_core_web_sm")
nlp.with_llm(provider: :anthropic) do |ai|
  doc = nlp.read("Apple Inc. was founded by Steve Jobs.")
  ai.chat(system: "Analyze the linguistic data.", user: doc.linguistic_summary)
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(access_token: nil, model: AnthropicClient::DEFAULT_MODEL, max_tokens: 1000, temperature: nil, base_url: nil) ⇒ AnthropicHelper

Creates a new AnthropicHelper instance.

Parameters:

  • access_token (String, nil) (defaults to: nil)

    Anthropic API key (defaults to ANTHROPIC_API_KEY env var)

  • model (String) (defaults to: AnthropicClient::DEFAULT_MODEL)

    the default model for chat requests

  • max_tokens (Integer) (defaults to: 1000)

    default maximum tokens in responses

  • temperature (Float, nil) (defaults to: nil)

    default sampling temperature (omitted from requests when nil; models that reject it are retried without it)

  • base_url (String, nil) (defaults to: nil)

    API endpoint override



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/ruby-spacy/anthropic_helper.rb', line 28

def initialize(access_token: nil, model: AnthropicClient::DEFAULT_MODEL,
               max_tokens: 1000, temperature: nil, base_url: nil)
  @access_token = access_token || ENV["ANTHROPIC_API_KEY"]
  raise "Error: ANTHROPIC_API_KEY is not set" unless @access_token

  @model = model
  @default_max_tokens = max_tokens
  @default_temperature = temperature
  @client = AnthropicClient.new(access_token: @access_token,
                                base_url: base_url || AnthropicClient::API_ENDPOINT)
end

Instance Attribute Details

#modelString (readonly)

Returns the default model for chat requests.

Returns:

  • (String)

    the default model for chat requests



19
20
21
# File 'lib/ruby-spacy/anthropic_helper.rb', line 19

def model
  @model
end

Instance Method Details

#chat(system: nil, user: nil, messages: nil, model: nil, max_tokens: nil, temperature: nil, schema: nil, raw: false) ⇒ String, ...

Sends a Messages API request.

Provides convenient system: and user: keyword arguments as shortcuts. For multi-turn conversations, pass a full messages: array directly (the system prompt stays a separate system: argument — Anthropic takes it as a top-level parameter, not a message role).

Parameters:

  • system (String, nil) (defaults to: nil)

    system prompt

  • user (String, nil) (defaults to: nil)

    user message content (shortcut)

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

    full message array (overrides user:)

  • model (String, nil) (defaults to: nil)

    model override (defaults to instance model)

  • max_tokens (Integer, nil) (defaults to: nil)

    token limit override

  • temperature (Float, nil) (defaults to: nil)

    temperature override

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

    JSON Schema for structured outputs; when given, the model output is constrained to the schema and the parsed Hash is returned. Objects in the schema must set additionalProperties: false.

  • raw (Boolean) (defaults to: false)

    if true, returns the full API response Hash instead of text

Returns:

  • (String, Hash, nil)

    the response text, parsed Hash (if schema:), full response Hash (if raw:), or nil on API error, refusal, or when the schema output cannot be parsed as JSON (e.g., truncated by the token limit)



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/ruby-spacy/anthropic_helper.rb', line 61

def chat(system: nil, user: nil, messages: nil,
         model: nil, max_tokens: nil, temperature: nil,
         schema: nil, raw: false)
  msgs = messages || (user ? [{ role: "user", content: user }] : [])
  raise ArgumentError, "No messages provided. Use user:/messages:" if msgs.empty?

  output_config = schema ? { format: { type: "json_schema", schema: schema } } : nil

  response = @client.messages(
    model: model || @model,
    messages: msgs,
    system: system,
    max_tokens: max_tokens || @default_max_tokens,
    temperature: temperature || @default_temperature,
    output_config: output_config
  )

  return response if raw

  # Safety classifiers can decline a request with HTTP 200 and an empty
  # or partial content array.
  if response["stop_reason"] == "refusal"
    warn "Error: Anthropic API declined the request (stop_reason: refusal)"
    return nil
  end

  if response["stop_reason"] == "max_tokens"
    warn "Warning: response was truncated (stop_reason: max_tokens); consider increasing max_tokens"
  end

  text = Array(response["content"])
         .select { |block| block["type"] == "text" }
         .map { |block| block["text"] }
         .join
  schema ? parse_json_content(text) : text
rescue AnthropicClient::APIError => e
  warn "Error: Anthropic API call failed - #{e.message}"
  nil
end

#embeddingsObject

Anthropic does not provide an embeddings API.

Raises:

  • (NotImplementedError)

    always



103
104
105
106
107
# File 'lib/ruby-spacy/anthropic_helper.rb', line 103

def embeddings(*)
  raise NotImplementedError,
        "Anthropic does not provide an embeddings API. " \
        "Use with_llm(provider: :openai) or a local OpenAI-compatible server for embeddings."
end