Class: Raif::Llm

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Model, Concerns::Llms::MessageFormatting
Defined in:
app/models/raif/llm.rb

Constant Summary collapse

VALID_RESPONSE_FORMATS =
[:text, :json, :html].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key:, api_name:, display_name: nil, model_provider_settings: {}, supported_provider_managed_tools: [], supports_native_tool_use: true, temperature: nil, max_completion_tokens: nil, input_token_cost: nil, output_token_cost: nil, deprecated: false, retirement_date: nil, replacement_key: nil, migration_note: nil, lifecycle: {}, pricing: {}, capabilities: {}) ⇒ Llm

Returns a new instance of Llm.



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
60
61
62
63
64
65
66
67
68
69
70
71
# File 'app/models/raif/llm.rb', line 35

def initialize(
  key:,
  api_name:,
  display_name: nil,
  model_provider_settings: {},
  supported_provider_managed_tools: [],
  supports_native_tool_use: true,
  temperature: nil,
  max_completion_tokens: nil,
  input_token_cost: nil,
  output_token_cost: nil,
  deprecated: false,
  retirement_date: nil,
  replacement_key: nil,
  migration_note: nil,
  lifecycle: {},
  pricing: {},
  capabilities: {}
)
  @key = key
  @api_name = api_name
  @display_name = display_name
  @provider_settings = model_provider_settings
  @supports_native_tool_use = supports_native_tool_use
  @default_temperature = temperature || 0.7
  @default_max_completion_tokens = max_completion_tokens
  @input_token_cost = input_token_cost
  @output_token_cost = output_token_cost
  @supported_provider_managed_tools = supported_provider_managed_tools.map(&:to_s)
  @deprecated = deprecated
  @retirement_date = retirement_date
  @replacement_key = replacement_key
  @migration_note = migration_note
  @lifecycle = lifecycle
  @pricing = pricing
  @capabilities = capabilities
end

Instance Attribute Details

#api_name ⇒ Object

Returns the value of attribute api_name.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def api_name
  @api_name
end

#capabilities ⇒ Object (readonly)

capabilities is the manifest's claim for this endpoint, not the behavioral switch: supports_structured_outputs? and streaming_supported? consult provider settings and Raif.config.streaming_unsupported_model_keys, so read those to decide behavior.



26
27
28
# File 'app/models/raif/llm.rb', line 26

def capabilities
  @capabilities
end

#default_max_completion_tokens ⇒ Object

Returns the value of attribute default_max_completion_tokens.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def default_max_completion_tokens
  @default_max_completion_tokens
end

#default_temperature ⇒ Object

Returns the value of attribute default_temperature.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def default_temperature
  @default_temperature
end

#deprecated ⇒ Object

Returns the value of attribute deprecated.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def deprecated
  @deprecated
end

#display_name ⇒ Object

Returns the value of attribute display_name.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def display_name
  @display_name
end

#input_token_cost ⇒ Object

Returns the value of attribute input_token_cost.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def input_token_cost
  @input_token_cost
end

#key ⇒ Object

Returns the value of attribute key.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def key
  @key
end

#lifecycle ⇒ Object (readonly)

capabilities is the manifest's claim for this endpoint, not the behavioral switch: supports_structured_outputs? and streaming_supported? consult provider settings and Raif.config.streaming_unsupported_model_keys, so read those to decide behavior.



26
27
28
# File 'app/models/raif/llm.rb', line 26

def lifecycle
  @lifecycle
end

#migration_note ⇒ Object

Returns the value of attribute migration_note.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def migration_note
  @migration_note
end

#output_token_cost ⇒ Object

Returns the value of attribute output_token_cost.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def output_token_cost
  @output_token_cost
end

#pricing ⇒ Object (readonly)

capabilities is the manifest's claim for this endpoint, not the behavioral switch: supports_structured_outputs? and streaming_supported? consult provider settings and Raif.config.streaming_unsupported_model_keys, so read those to decide behavior.



26
27
28
# File 'app/models/raif/llm.rb', line 26

def pricing
  @pricing
end

#provider_settings ⇒ Object

Returns the value of attribute provider_settings.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def provider_settings
  @provider_settings
end

#replacement_key ⇒ Object

Returns the value of attribute replacement_key.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def replacement_key
  @replacement_key
end

#retirement_date ⇒ Object

Returns the value of attribute retirement_date.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def retirement_date
  @retirement_date
end

#supported_provider_managed_tools ⇒ Object

Returns the value of attribute supported_provider_managed_tools.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def supported_provider_managed_tools
  @supported_provider_managed_tools
end

#supports_native_tool_use ⇒ Object Also known as: supports_native_tool_use?

Returns the value of attribute supports_native_tool_use.



8
9
10
# File 'app/models/raif/llm.rb', line 8

def supports_native_tool_use
  @supports_native_tool_use
end

Class Method Details

.batch_inference_cost_multiplier ⇒ Object

Multiplier applied to per-token costs when a model completion was resolved through this provider's Batch API. Defaults to 0.5 (50% discount), which is what both Anthropic and OpenAI charge for batch requests today.



338
339
340
# File 'app/models/raif/llm.rb', line 338

def self.batch_inference_cost_multiplier
  0.5
end

.cache_creation_input_token_cost_multiplier ⇒ Object

Multiplier applied to the base input_token_cost to derive the per-token cost for cache creation writes. Return nil when there is no write surcharge.



313
314
315
# File 'app/models/raif/llm.rb', line 313

def self.cache_creation_input_token_cost_multiplier
  nil
end

.cache_read_input_token_cost_multiplier ⇒ Object

Multiplier applied to the base input_token_cost to derive the per-token cost for cache reads. Return nil when the provider has no cache pricing.



307
308
309
# File 'app/models/raif/llm.rb', line 307

def self.cache_read_input_token_cost_multiplier
  nil
end

.prompt_tokens_include_cached_tokens? ⇒ Boolean

Override in subclasses to indicate whether prompt_tokens reported by the provider already include cached tokens as a subset (OpenAI, Google, OpenRouter) or whether cached tokens are reported separately and are additive to prompt_tokens (Anthropic, Bedrock).

Returns:

  • (Boolean)


301
302
303
# File 'app/models/raif/llm.rb', line 301

def self.prompt_tokens_include_cached_tokens?
  true
end

.streaming_supported_for_key?(model_key) ⇒ Boolean

Whether streaming is supported for the given Raif model key. A model key is considered unsupported if it matches any entry in Raif.config.streaming_unsupported_model_keys (each entry may be a String, Symbol, or Regexp). Used by #chat to transparently fall back to the non-streaming path for models with known-broken streaming endpoints.

Returns:

  • (Boolean)


116
117
118
119
120
121
122
123
124
125
# File 'app/models/raif/llm.rb', line 116

def self.streaming_supported_for_key?(model_key)
  entries = Array(Raif.config.streaming_unsupported_model_keys)
  key_str = model_key.to_s
  entries.none? do |entry|
    case entry
    when Regexp then entry.match?(key_str)
    else entry.to_s == key_str
    end
  end
end

.supports_batch_inference? ⇒ Boolean

Whether this provider supports submitting model completions via a Batch API. Override in subclasses by including Raif::Concerns::Llms::SupportsBatchInference, which sets this to true.

Returns:

  • (Boolean)


320
321
322
# File 'app/models/raif/llm.rb', line 320

def self.supports_batch_inference?
  false
end

.valid_response_formats ⇒ Object



293
294
295
# File 'app/models/raif/llm.rb', line 293

def self.valid_response_formats
  VALID_RESPONSE_FORMATS
end

Instance Method Details

#added_on ⇒ Object



87
88
89
# File 'app/models/raif/llm.rb', line 87

def added_on
  lifecycle[:added_on]
end

#build_forced_tool_choice(tool_name) ⇒ Hash

Build the tool_choice parameter to force a specific tool to be called. Each provider implements this to return the correct format.

Parameters:

  • tool_name (String) —

    The name of the tool to force

Returns:

  • (Hash) —

    The tool_choice parameter for the provider's API

Raises:

  • (NotImplementedError)


350
351
352
# File 'app/models/raif/llm.rb', line 350

def build_forced_tool_choice(tool_name)
  raise NotImplementedError, "#{self.class.name} must implement #build_forced_tool_choice"
end

#build_pending_model_completion(messages:, response_format: :text, available_model_tools: [], source: nil, system_prompt: nil, temperature: nil, max_completion_tokens: nil, tool_choice: nil, stream_response: false, allow_parallel_tool_calls: false, anthropic_prompt_caching_enabled: false, bedrock_prompt_caching_enabled: false, open_ai_store_responses: nil, open_router_data_collection: nil, open_router_zdr: nil, raif_model_completion_batch: nil, batch_custom_id: nil) ⇒ Raif::ModelCompletion

Builds and persists a Raif::ModelCompletion without performing the request. Used by #chat (which then calls perform_model_completion!) and by callers that want to defer execution -- e.g. submitting through a provider Batch API via Raif::Task.build_for_batch / Raif::Task#prepare_for_batch!.

Returns:



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'app/models/raif/llm.rb', line 258

def build_pending_model_completion(messages:, response_format: :text, available_model_tools: [], source: nil,
  system_prompt: nil, temperature: nil, max_completion_tokens: nil, tool_choice: nil,
  stream_response: false, allow_parallel_tool_calls: false, anthropic_prompt_caching_enabled: false,
  bedrock_prompt_caching_enabled: false, open_ai_store_responses: nil, open_router_data_collection: nil,
  open_router_zdr: nil, raif_model_completion_batch: nil, batch_custom_id: nil)
  temperature ||= default_temperature
  max_completion_tokens ||= default_max_completion_tokens

  model_completion = Raif::ModelCompletion.create!(
    messages: format_messages(messages),
    system_prompt: system_prompt,
    response_format: response_format,
    source: source,
    llm_model_key: key.to_s,
    model_api_name: api_name,
    temperature: temperature,
    max_completion_tokens: max_completion_tokens,
    available_model_tools: available_model_tools,
    tool_choice: tool_choice&.to_s,
    stream_response: stream_response,
    request_settings: {
      "open_ai_store_responses" => open_ai_store_responses,
      "open_router_data_collection" => open_router_data_collection&.to_s.presence,
      "open_router_zdr" => open_router_zdr
    }.compact,
    raif_model_completion_batch: raif_model_completion_batch,
    batch_custom_id: batch_custom_id
  )

  model_completion.allow_parallel_tool_calls = allow_parallel_tool_calls
  model_completion.anthropic_prompt_caching_enabled = anthropic_prompt_caching_enabled
  model_completion.bedrock_prompt_caching_enabled = bedrock_prompt_caching_enabled
  model_completion
end

#build_required_tool_choice ⇒ Hash, String

Build the tool_choice parameter to require the model to call any tool (but not a specific one). Each provider implements this to return the correct format.

Returns:

  • (Hash, String) —

    The tool_choice parameter for the provider's API

Raises:

  • (NotImplementedError)


357
358
359
# File 'app/models/raif/llm.rb', line 357

def build_required_tool_choice
  raise NotImplementedError, "#{self.class.name} must implement #build_required_tool_choice"
end

#chat(message: nil, messages: nil, response_format: :text, available_model_tools: [], source: nil, system_prompt: nil, temperature: nil, max_completion_tokens: nil, tool_choice: nil, allow_parallel_tool_calls: false, anthropic_prompt_caching_enabled: false, bedrock_prompt_caching_enabled: false, open_ai_store_responses: nil, open_router_data_collection: nil, open_router_zdr: nil, &block) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'app/models/raif/llm.rb', line 131

def chat(message: nil, messages: nil, response_format: :text, available_model_tools: [], source: nil, system_prompt: nil, temperature: nil,
  max_completion_tokens: nil, tool_choice: nil, allow_parallel_tool_calls: false, anthropic_prompt_caching_enabled: false,
  bedrock_prompt_caching_enabled: false, open_ai_store_responses: nil, open_router_data_collection: nil,
  open_router_zdr: nil, &block)
  unless response_format.is_a?(Symbol)
    raise ArgumentError,
      "Raif::Llm#chat - Invalid response format: #{response_format}. Must be a symbol (you passed #{response_format.class}) and be one of: #{VALID_RESPONSE_FORMATS.join(", ")}" # rubocop:disable Layout/LineLength
  end

  unless VALID_RESPONSE_FORMATS.include?(response_format)
    raise ArgumentError, "Raif::Llm#chat - Invalid response format: #{response_format}. Must be one of: #{VALID_RESPONSE_FORMATS.join(", ")}"
  end

  unless message.present? || messages.present?
    raise ArgumentError, "Raif::Llm#chat - You must provide either a message: or messages: argument"
  end

  if message.present? && messages.present?
    raise ArgumentError, "Raif::Llm#chat - You must provide either a message: or messages: argument, not both"
  end

  # Normalize :required / "required" to the symbol form for validation
  tool_choice = :required if tool_choice.to_s == "required"

  # The adapters' build_*_tool_choice methods validate support again for callers that
  # bypass chat; checking here keeps the failure ahead of the ModelCompletion record
  # and the authorizer call.
  if tool_choice == :required
    if available_model_tools.blank?
      raise ArgumentError,
        "Raif::Llm#chat - tool_choice: :required requires at least one available model tool"
    end

    validate_tool_choice_support!(:required)
  elsif tool_choice.present?
    unless available_model_tools.map(&:to_s).include?(tool_choice.to_s)
      raise ArgumentError,
        "Raif::Llm#chat - Invalid tool choice: #{tool_choice} is not included in the available model tools: #{available_model_tools.join(", ")}"
    end

    validate_tool_choice_support!(:forced)
  end

  # Runs before the ModelCompletion is created or any provider call is made,
  # and before the llm_api_requests_enabled guard so authorization applies
  # even when API requests are disabled. Vetoes by raising. Any raised
  # exception is tagged with Raif::Errors::ModelCompletionAuthorizationError
  # so wrapped flows (Raif::Task.run, Raif::Conversation) re-raise it to the
  # caller instead of swallowing it as an ordinary model failure.
  if Raif.config.model_completion_authorizer
    begin
      Raif.config.model_completion_authorizer.call(llm: self, source: source)
    rescue StandardError => e
      e.extend(Raif::Errors::ModelCompletionAuthorizationError) unless e.is_a?(Raif::Errors::ModelCompletionAuthorizationError)
      raise
    end
  end

  unless Raif.config.llm_api_requests_enabled
    Raif.logger.warn("LLM API requests are disabled. Skipping request to #{api_name}.")
    return
  end

  messages = [{ "role" => "user", "content" => message }] if message.present?

  temperature ||= default_temperature
  max_completion_tokens ||= default_max_completion_tokens

  stream_response = block_given? && streaming_supported?
  if block_given? && !stream_response
    Raif.logger.info(
      "Raif::Llm#chat: streaming requested but disabled for model key #{key.inspect} " \
        "via Raif.config.streaming_unsupported_model_keys; falling back to non-streaming."
    )
  end

  model_completion = build_pending_model_completion(
    messages: messages,
    response_format: response_format,
    available_model_tools: available_model_tools,
    source: source,
    system_prompt: system_prompt,
    temperature: temperature,
    max_completion_tokens: max_completion_tokens,
    tool_choice: tool_choice,
    stream_response: stream_response,
    allow_parallel_tool_calls: allow_parallel_tool_calls,
    anthropic_prompt_caching_enabled: anthropic_prompt_caching_enabled,
    bedrock_prompt_caching_enabled: bedrock_prompt_caching_enabled,
    open_ai_store_responses: open_ai_store_responses,
    open_router_data_collection: open_router_data_collection,
    open_router_zdr: open_router_zdr
  )

  model_completion.started!

  retry_with_backoff(model_completion) do
    perform_model_completion!(model_completion, &block)
    ensure_model_completion_present!(model_completion)
  end

  model_completion.completed!
  model_completion
rescue Raif::Errors::StreamingError => e
  Rails.logger.error("Raif streaming error -- code: #{e.code} -- type: #{e.type} -- message: #{e.message} -- event: #{e.event}")
  model_completion&.record_failure!(e) unless model_completion&.failed?
  raise e
rescue Faraday::Error => e
  Raif.logger.error("LLM API request failed (status: #{e.response_status}): #{e.message}")
  Raif.logger.error(e.response_body)
  model_completion&.record_failure!(e) unless model_completion&.failed?
  raise e
rescue StandardError => e
  model_completion&.record_failure!(e) unless model_completion&.failed?
  raise e
end

#deprecated? ⇒ Boolean

Returns:

  • (Boolean)


73
74
75
# File 'app/models/raif/llm.rb', line 73

def deprecated?
  !!deprecated
end

#deprecated_on ⇒ Object



91
92
93
# File 'app/models/raif/llm.rb', line 91

def deprecated_on
  lifecycle[:deprecated_on]
end

#deprecation_message ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
# File 'app/models/raif/llm.rb', line 95

def deprecation_message
  message = +"Raif model :#{key} is deprecated"
  message << " and will be removed after #{retirement_date}" if retirement_date
  message << "."
  if replacement_key
    message << " Use :#{replacement_key} instead."
  elsif migration_note
    message << " #{migration_note}"
  end
  message
end

#lifecycle_status ⇒ Object

Manifest lifecycle conveniences. status is :active or :deprecated for models Raif ships (retired entries are never registered) and nil for a model a host app registered itself. The flat deprecated/retirement_date/ replacement_key/migration_note keyword arguments are what deprecated? and the warnings read; lifecycle is the manifest record and can be empty for a host-registered model.



83
84
85
# File 'app/models/raif/llm.rb', line 83

def lifecycle_status
  lifecycle[:status]
end

#name ⇒ Object



107
108
109
# File 'app/models/raif/llm.rb', line 107

def name
  I18n.t("raif.model_names.#{key}", default: display_name || key.to_s.humanize)
end

#perform_model_completion!(model_completion, &block) ⇒ Object

Raises:

  • (NotImplementedError)


248
249
250
# File 'app/models/raif/llm.rb', line 248

def perform_model_completion!(model_completion, &block)
  raise NotImplementedError, "#{self.class.name} must implement #perform_model_completion!"
end

#streaming_supported? ⇒ Boolean

Returns:

  • (Boolean)


127
128
129
# File 'app/models/raif/llm.rb', line 127

def streaming_supported?
  self.class.streaming_supported_for_key?(key)
end

#supports_batch_inference? ⇒ Boolean

Whether this model can be submitted through its provider's Batch API. Batch support is not uniformly provider-wide: xAI serves grok-4.5 on the synchronous endpoint but rejects it at batch-file validation, so the registry entry needs to be able to opt a single model out of a provider that otherwise supports batching. Defaults to the provider's capability.

Returns:

  • (Boolean)


329
330
331
332
333
# File 'app/models/raif/llm.rb', line 329

def supports_batch_inference?
  return provider_settings[:supports_batch_inference] if provider_settings.key?(:supports_batch_inference)

  self.class.supports_batch_inference?
end

#supports_faithful_required_tool_choice?(available_model_tools) ⇒ Boolean

Whether the provider can faithfully enforce tool_choice: :required for the given tool set. Override in subclasses when a provider can only enforce required tool use for some tool types.

Returns:

  • (Boolean)


391
392
393
# File 'app/models/raif/llm.rb', line 391

def supports_faithful_required_tool_choice?(available_model_tools)
  supports_required_tool_choice? && available_model_tools.present?
end

#supports_forced_tool_choice? ⇒ Boolean

Returns:

  • (Boolean)


361
362
363
# File 'app/models/raif/llm.rb', line 361

def supports_forced_tool_choice?
  supports_native_tool_use? && provider_settings.fetch(:supports_forced_tool_choice, true)
end

#supports_parallel_tool_calls? ⇒ Boolean

Whether this model can handle being asked to make multiple tool calls in a single response. Override (per provider or per model key) to return false for models that reject the parallel-tool-call request parameter or that produce worse results when allowed to batch. Agents consult this before enabling parallel tool calls; when false they fall back to one tool call per step.

Returns:

  • (Boolean)


400
401
402
# File 'app/models/raif/llm.rb', line 400

def supports_parallel_tool_calls?
  true
end

#supports_provider_managed_tool?(tool_klass) ⇒ Boolean

Returns:

  • (Boolean)


342
343
344
# File 'app/models/raif/llm.rb', line 342

def supports_provider_managed_tool?(tool_klass)
  supported_provider_managed_tools&.include?(tool_klass.to_s)
end

#supports_required_tool_choice? ⇒ Boolean

Returns:

  • (Boolean)


365
366
367
# File 'app/models/raif/llm.rb', line 365

def supports_required_tool_choice?
  supports_native_tool_use? && provider_settings.fetch(:supports_required_tool_choice, true)
end

#supports_structured_outputs? ⇒ Boolean

Returns:

  • (Boolean)


377
378
379
# File 'app/models/raif/llm.rb', line 377

def supports_structured_outputs?
  provider_settings.fetch(:supports_structured_outputs, true)
end

#supports_temperature? ⇒ Boolean

Provider settings come from the manifest (model_provider_settings) or a host's register_llm call. Without a setting a model is assumed to accept a temperature and native structured outputs. Adapters override these when the answer depends on more than settings (Anthropic and Bedrock default structured outputs to false).

Returns:

  • (Boolean)


373
374
375
# File 'app/models/raif/llm.rb', line 373

def supports_temperature?
  provider_settings.fetch(:supports_temperature, true)
end

#validate_provider_managed_tool_support!(tool) ⇒ Object



404
405
406
407
408
409
# File 'app/models/raif/llm.rb', line 404

def validate_provider_managed_tool_support!(tool)
  unless supports_provider_managed_tool?(tool)
    raise Raif::Errors::UnsupportedFeatureError,
      "Invalid provider-managed tool: #{tool.name} for #{key}"
  end
end

#validate_tool_choice_support!(choice) ⇒ Object



381
382
383
384
385
386
# File 'app/models/raif/llm.rb', line 381

def validate_tool_choice_support!(choice)
  supported = choice == :required ? supports_required_tool_choice? : supports_forced_tool_choice?
  return if supported

  raise Raif::Errors::UnsupportedFeatureError, "#{name} does not support #{choice} tool choice."
end