pave_ai 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +195 -0
  4. data/app/assets/stylesheets/pave_ai/application.css +15 -0
  5. data/app/controllers/pave_ai/application_controller.rb +4 -0
  6. data/app/helpers/pave_ai/application_helper.rb +4 -0
  7. data/app/jobs/pave_ai/application_job.rb +4 -0
  8. data/app/mailers/pave_ai/application_mailer.rb +6 -0
  9. data/app/models/pave_ai/application_record.rb +5 -0
  10. data/app/models/pave_ai/chat.rb +49 -0
  11. data/app/models/pave_ai/chat_message.rb +28 -0
  12. data/app/models/pave_ai/intent.rb +34 -0
  13. data/app/models/pave_ai/persona.rb +34 -0
  14. data/app/models/pave_ai/persona_document.rb +35 -0
  15. data/app/models/pave_ai/quota.rb +77 -0
  16. data/app/models/pave_ai/spend_log.rb +47 -0
  17. data/app/services/pave_ai/client/provider.rb +50 -0
  18. data/app/services/pave_ai/client/providers/anthropic.rb +15 -0
  19. data/app/services/pave_ai/client/providers/gemini.rb +15 -0
  20. data/app/services/pave_ai/client/providers/ollama.rb +16 -0
  21. data/app/services/pave_ai/client/providers/openai.rb +14 -0
  22. data/app/services/pave_ai/client/providers/openai_compatible.rb +18 -0
  23. data/app/services/pave_ai/client/providers/xai.rb +14 -0
  24. data/app/services/pave_ai/client/providers/zai.rb +13 -0
  25. data/app/services/pave_ai/client/providers/zen.rb +12 -0
  26. data/app/services/pave_ai/client.rb +683 -0
  27. data/app/services/pave_ai/credential.rb +66 -0
  28. data/app/services/pave_ai/governance.rb +70 -0
  29. data/app/services/pave_ai/rates.rb +101 -0
  30. data/app/services/pave_ai/spend.rb +539 -0
  31. data/app/views/layouts/pave_ai/application.html.erb +17 -0
  32. data/config/ai_governance/ETHICS.md +20 -0
  33. data/config/routes.rb +2 -0
  34. data/db/migrate/20260404000001_create_pave_ai_tables.rb +102 -0
  35. data/db/migrate/20260820000002_add_billable_to_pave_ai_spend_logs.rb +5 -0
  36. data/db/migrate/20260827000001_add_model_to_pave_ai_spend_logs.rb +8 -0
  37. data/db/migrate/20260828000001_add_intent_credit_cost_and_log_credits.rb +10 -0
  38. data/db/migrate/20261123000001_remove_quota_limit_defaults.rb +9 -0
  39. data/lib/generators/pave_ai/install/install_generator.rb +61 -0
  40. data/lib/pave_ai/engine.rb +23 -0
  41. data/lib/pave_ai/middleware/request_cleanup.rb +17 -0
  42. data/lib/pave_ai/version.rb +3 -0
  43. data/lib/pave_ai.rb +247 -0
  44. data/lib/tasks/pave_ai_tasks.rake +4 -0
  45. metadata +127 -0
@@ -0,0 +1,683 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "json"
5
+
6
+ module PaveAi
7
+ class Client
8
+ class AiError < StandardError; end
9
+ class ConfigurationError < AiError; end
10
+ # A plan or price the host has not set. Never wrapped or swallowed: a
11
+ # host that has not priced its features must find out, not meter wrong.
12
+ class HostSettingMissing < ConfigurationError; end
13
+ class ApiError < AiError; end
14
+ class TimeoutError < AiError; end
15
+ class ConnectionError < AiError; end
16
+ class BudgetExceededError < AiError; end
17
+ class UnavailableError < AiError; end
18
+
19
+ MAX_INPUT_CHARS = 100_000
20
+ MAX_IMAGE_PROMPT_CHARS = 4_000
21
+
22
+ DEFAULT_MODELS = {
23
+ "ollama" => "llama3.1:8b",
24
+ "openai" => "gpt-4o-mini",
25
+ "xai" => "grok-4-1-fast-non-reasoning",
26
+ "zai" => "glm-4.7-flash",
27
+ "zen" => "kimi-k2.5"
28
+ }.freeze
29
+
30
+ DEFAULT_IMAGE_MODELS = {
31
+ "openai" => "dall-e-3",
32
+ "xai" => "grok-imagine-image",
33
+ "zai" => "cogview-4"
34
+ }.freeze
35
+
36
+ # The historical default for the Chat Completions providers. A native
37
+ # provider gets no sampling parameter unless the caller passes one: newer
38
+ # Anthropic models reject a temperature nobody asked for.
39
+ DEFAULT_TEMPERATURE = 0.7
40
+ TEMPERATURE_UNSET = Object.new.freeze
41
+ private_constant :TEMPERATURE_UNSET
42
+
43
+ attr_reader :provider, :model
44
+
45
+ # credential: a caller's own PaveAi::Credential for this client's calls.
46
+ # Without one, nothing changes: keys come from PaveAi.configure. With one,
47
+ # the caller's key is the ONLY key used, the call is caller-funded, and an
48
+ # exhausted platform budget never reroutes it onto a provider we pay for.
49
+ def initialize(provider: nil, model: nil, credential: nil)
50
+ # nil or a Credential, nothing else: `credential: user.own_key? && cred`
51
+ # must not build a client that sends OUR key and meters it as theirs.
52
+ unless credential.nil? || credential.is_a?(PaveAi::Credential)
53
+ raise ArgumentError, "credential must be a PaveAi::Credential or nil"
54
+ end
55
+
56
+ @credential = credential
57
+ requested = provider || PaveAi.config.default_provider
58
+ @provider, @model = credential ? [ requested.to_s, model ] : apply_budget_fallback(requested, model)
59
+ @adapter = PaveAi::Client::Provider.for(@provider)
60
+ @model ||= @adapter.default_model
61
+ validate_configuration!
62
+ end
63
+
64
+ def caller_funded? = !@credential.nil?
65
+ def funding = caller_funded? ? :caller : :platform
66
+
67
+ # Meter a block against THIS client: provider, model and funding are taken
68
+ # from the client, so what the till records cannot disagree with the
69
+ # credential the call actually used. Hosts that wrap chat_with_usage use
70
+ # this instead of calling Spend.request with a hand-copied provider.
71
+ def meter(intent:, spend_type: :text, user: nil, billable: nil, estimated_tokens: nil,
72
+ estimated_input_tokens: nil, metadata: {}, skip_budget_check: false)
73
+ PaveAi::Spend.request(
74
+ intent: intent, spend_type: spend_type, provider: @provider, model: @model,
75
+ user: user, billable: billable, estimated_tokens: estimated_tokens,
76
+ estimated_input_tokens: estimated_input_tokens, metadata: metadata,
77
+ skip_budget_check: skip_budget_check, funding: funding
78
+ ) do |budget|
79
+ yield budget
80
+ rescue StandardError => e
81
+ # The till writes a failed row from this error's message. Whatever the
82
+ # host's own block raised, the caller's key does not go into that row.
83
+ raise unless caller_funded? && key_exposed_by?(e)
84
+
85
+ raise ApiError, redact(e.message), cause: nil
86
+ end
87
+ end
88
+
89
+ def self.for_images
90
+ new(provider: PaveAi.config.ai_image_provider)
91
+ end
92
+
93
+ def self.for_purpose(purpose)
94
+ new(
95
+ provider: PaveAi.config.provider_for(purpose),
96
+ model: PaveAi.config.model_for(purpose)
97
+ )
98
+ end
99
+
100
+ def self.test_connection(provider)
101
+ adapter = PaveAi::Client::Provider.for(provider)
102
+
103
+ if provider.to_s == "ollama"
104
+ test_ollama_connection
105
+ elsif adapter.openai_compatible? && adapter.chat_url
106
+ models_url = adapter.chat_url.sub("/chat/completions", "/models")
107
+ test_openai_compatible(models_url, adapter.api_key, provider)
108
+ else
109
+ { success: false, message: "No connection test for #{provider}", provider: provider }
110
+ end
111
+ rescue ConfigurationError => e
112
+ { success: false, message: e.message, provider: provider }
113
+ rescue => e
114
+ { success: false, message: e.message, provider: provider }
115
+ end
116
+
117
+ # --- Embeddings ---
118
+
119
+ EMBEDDING_MODEL = "text-embedding-3-small"
120
+
121
+ # Generate embedding vector for text. Returns array of floats, or nil on failure.
122
+ def self.embed(text, model: EMBEDDING_MODEL, user: nil, billable: nil)
123
+ return nil if text.blank?
124
+
125
+ tokens = (text.length / 4.0).ceil
126
+ result = nil
127
+
128
+ PaveAi::Spend.request(intent: "embedding", spend_type: :embedding, provider: "openai", model: model, estimated_tokens: tokens, user: user, billable: billable) do |budget|
129
+ response = RubyLLM.embed(text, model: model)
130
+ result = response.vectors
131
+ record_embedding_usage(budget, response, estimate: tokens)
132
+ end
133
+
134
+ result
135
+ rescue PaveAi::Spend::BudgetExceeded, HostSettingMissing
136
+ raise
137
+ rescue => e
138
+ Rails.logger.error "[PaveAi::Client] Embedding failed: #{e.message}"
139
+ nil
140
+ end
141
+
142
+ # Batch embed multiple texts. Returns array of vectors.
143
+ def self.embed_batch(texts, model: EMBEDDING_MODEL, user: nil, billable: nil)
144
+ return [] if texts.blank?
145
+
146
+ combined = texts.join(" ")
147
+ tokens = (combined.length / 4.0).ceil
148
+ results = nil
149
+
150
+ PaveAi::Spend.request(intent: "embedding", spend_type: :embedding, provider: "openai", model: model, estimated_tokens: tokens, user: user, billable: billable) do |budget|
151
+ response = RubyLLM.embed(texts, model: model)
152
+ results = response.vectors
153
+ record_embedding_usage(budget, response, estimate: tokens)
154
+ end
155
+
156
+ results || []
157
+ rescue PaveAi::Spend::BudgetExceeded, HostSettingMissing
158
+ raise
159
+ rescue => e
160
+ Rails.logger.error "[PaveAi::Client] Batch embedding failed: #{e.message}"
161
+ []
162
+ end
163
+
164
+ # The provider's own input-token count when it reports one, so the
165
+ # settlement reprices from real usage rather than a character guess. Without one, settle at the estimate.
166
+ def self.record_embedding_usage(budget, response, estimate:)
167
+ input = response.respond_to?(:tokens) ? response.tokens&.input : nil
168
+ if input.to_i.positive?
169
+ budget.record!(actual_tokens: input, input_tokens: input, output_tokens: 0)
170
+ else
171
+ budget.record!(actual_tokens: estimate)
172
+ end
173
+ end
174
+ private_class_method :record_embedding_usage
175
+
176
+ # --- Text generation ---
177
+
178
+ def generate(prompt, temperature: TEMPERATURE_UNSET, max_tokens: 500, skip_budget_check: false, user: nil, intent: "pave_ai", context: nil)
179
+ messages = [ { role: "user", content: prompt } ]
180
+ chat(
181
+ messages,
182
+ temperature: temperature,
183
+ max_tokens: max_tokens,
184
+ skip_budget_check: skip_budget_check,
185
+ user: user,
186
+ intent: intent,
187
+ context: context
188
+ )
189
+ end
190
+
191
+ # Returns { content:, usage_tokens:, input_tokens:, output_tokens:, cached_tokens: }
192
+ # for a host that meters the call itself, inside Spend.request or #meter.
193
+ # Called outside any meter, it meters itself: a call can never go
194
+ # unmetered.
195
+ def chat_with_usage(messages, temperature: TEMPERATURE_UNSET, max_tokens: 500, intent: "pave_ai", user: nil, context: nil)
196
+ validate_input_length!(messages)
197
+ enforce_request_policy!(intent: intent, kind: :text, user: user, context: context)
198
+ return raw_chat(messages, temperature: temperature, max_tokens: max_tokens) if PaveAi::Spend.metering?
199
+
200
+ response = nil
201
+ meter(intent: intent, user: user, estimated_tokens: max_tokens,
202
+ estimated_input_tokens: estimated_prompt_tokens(messages)) do |budget|
203
+ response = raw_chat(messages, temperature: temperature, max_tokens: max_tokens)
204
+ record_chat_usage(budget, response)
205
+ end
206
+ response
207
+ rescue PaveAi::Spend::BudgetExceeded => e
208
+ raise BudgetExceededError, e.message
209
+ end
210
+
211
+ def chat(messages, temperature: TEMPERATURE_UNSET, max_tokens: 500, skip_budget_check: false, intent: "pave_ai", user: nil, context: nil)
212
+ validate_input_length!(messages)
213
+ enforce_request_policy!(intent: intent, kind: :text, user: user, context: context)
214
+
215
+ # skip_budget_check skips the REFUSAL, never the meter: the operation is
216
+ # still priced, still charged when funds exist, and always logged.
217
+ # It used to return early and escape metering entirely.
218
+ result = nil
219
+ PaveAi::Spend.request(
220
+ intent: intent,
221
+ spend_type: :text,
222
+ provider: @provider,
223
+ model: @model,
224
+ estimated_tokens: max_tokens,
225
+ estimated_input_tokens: estimated_prompt_tokens(messages),
226
+ user: user,
227
+ skip_budget_check: skip_budget_check,
228
+ funding: funding
229
+ ) do |budget|
230
+ response = raw_chat(messages, temperature: temperature, max_tokens: max_tokens)
231
+ result = response[:content]
232
+ record_chat_usage(budget, response)
233
+ end
234
+ result
235
+ rescue PaveAi::Spend::BudgetExceeded => e
236
+ raise BudgetExceededError, e.message
237
+ rescue UnavailableError, BudgetExceededError, TimeoutError, ConnectionError, HostSettingMissing
238
+ raise
239
+ rescue Net::OpenTimeout, Net::ReadTimeout => e
240
+ Rails.logger.error "[PaveAi::Client] #{@provider} timed out: #{redact(e.message)}"
241
+ fail_as TimeoutError, "AI provider timed out — please try again"
242
+ rescue Errno::ECONNREFUSED, SocketError => e
243
+ Rails.logger.error "[PaveAi::Client] #{@provider} not reachable: #{redact(e.message)}"
244
+ fail_as ConnectionError, "AI provider not reachable — check configuration"
245
+ rescue => e
246
+ Rails.logger.error "[PaveAi::Client] #{@provider} failed: #{redact(e.message)}"
247
+ fail_as ApiError, "AI generation failed: #{e.message}"
248
+ end
249
+
250
+ def available?
251
+ caller_funded? || @adapter.configured?
252
+ end
253
+
254
+ def image_available?
255
+ !caller_funded? && @adapter.image_available? && available?
256
+ end
257
+
258
+ def info
259
+ {
260
+ provider: @provider,
261
+ model: @model,
262
+ image_model: @adapter.default_image_model,
263
+ configured: available?,
264
+ image_available: image_available?
265
+ }
266
+ end
267
+
268
+ def generate_image(prompt, size: "1024x1024", quality: "standard", format: :url, skip_budget_check: false, intent: "image_generation", user: nil, context: nil)
269
+ if prompt.to_s.length > MAX_IMAGE_PROMPT_CHARS
270
+ raise AiError, "Image prompt too long (max #{MAX_IMAGE_PROMPT_CHARS} characters)"
271
+ end
272
+
273
+ enforce_request_policy!(intent: intent, kind: :image, user: user, context: context)
274
+
275
+ # Text only for now: the image paths still post with platform keys, so a
276
+ # caller credential here would be metered as one thing and paid as another.
277
+ if caller_funded?
278
+ raise ConfigurationError, "Image generation is not available with a caller credential"
279
+ end
280
+
281
+ unless image_available?
282
+ raise ConfigurationError, "Image generation not available for #{@provider}"
283
+ end
284
+
285
+ result = nil
286
+ PaveAi::Spend.request(
287
+ intent: intent,
288
+ spend_type: :image,
289
+ provider: @provider,
290
+ model: DEFAULT_IMAGE_MODELS[@provider],
291
+ skip_budget_check: skip_budget_check,
292
+ user: user
293
+ ) do |budget|
294
+ result = case @provider
295
+ when "openai"
296
+ quality == "standard" ? ruby_llm_image(prompt, size: size, format: format) : openai_image(prompt, size: size, quality: quality, format: format)
297
+ when "xai"
298
+ ruby_llm_image(prompt, size: size, format: format)
299
+ when "zai"
300
+ zai_image(prompt, size: size, format: format)
301
+ else
302
+ raise ConfigurationError, "Image generation not supported for #{@provider}"
303
+ end
304
+ budget.record!
305
+ end
306
+ result
307
+ rescue PaveAi::Spend::BudgetExceeded => e
308
+ raise BudgetExceededError, e.message
309
+ rescue UnavailableError, BudgetExceededError, TimeoutError, ConnectionError, ApiError, HostSettingMissing
310
+ raise
311
+ rescue Net::OpenTimeout, Net::ReadTimeout => e
312
+ Rails.logger.error "[PaveAi::Client] Image generation timed out: #{e.message}"
313
+ raise TimeoutError, "Image generation timed out — please try again"
314
+ rescue Faraday::TimeoutError => e
315
+ Rails.logger.error "[PaveAi::Client] Image generation timed out: #{e.message}"
316
+ raise TimeoutError, "Image generation timed out — please try again"
317
+ rescue Errno::ECONNREFUSED, SocketError => e
318
+ Rails.logger.error "[PaveAi::Client] Image provider not reachable: #{e.message}"
319
+ raise ConnectionError, "AI provider not reachable — check configuration"
320
+ rescue Faraday::ConnectionFailed => e
321
+ Rails.logger.error "[PaveAi::Client] Image provider not reachable: #{e.message}"
322
+ raise ConnectionError, "AI provider not reachable — check configuration"
323
+ rescue RubyLLM::ConnectionError => e
324
+ Rails.logger.error "[PaveAi::Client] Image provider #{e.timeout? ? "timed out" : "not reachable"}: #{e.message}"
325
+ raise(e.timeout? ? TimeoutError : ConnectionError,
326
+ e.timeout? ? "AI provider timed out — please try again" : "AI provider not reachable — check configuration")
327
+ rescue RubyLLM::Error => e
328
+ Rails.logger.error "[PaveAi::Client] Image generation failed: #{e.message}"
329
+ raise ApiError, e.message
330
+ rescue => e
331
+ Rails.logger.error "[PaveAi::Client] Image generation failed: #{e.message}"
332
+ raise ApiError, "Image generation failed: #{e.message}"
333
+ end
334
+
335
+ private
336
+
337
+ def self.test_ollama_connection
338
+ uri = URI("#{PaveAi.config.ollama_url}/api/tags")
339
+ http = Net::HTTP.new(uri.host, uri.port)
340
+ http.use_ssl = uri.scheme == "https"
341
+ http.open_timeout = 5
342
+ http.read_timeout = 5
343
+
344
+ response = http.request(Net::HTTP::Get.new(uri))
345
+ if response.is_a?(Net::HTTPSuccess)
346
+ data = JSON.parse(response.body)
347
+ models = data["models"]&.map { |m| m["name"] } || []
348
+ { success: true, message: "Connected. #{models.size} model(s) available.", provider: "ollama" }
349
+ else
350
+ { success: false, message: "Ollama returned #{response.code}", provider: "ollama" }
351
+ end
352
+ end
353
+ private_class_method :test_ollama_connection
354
+
355
+ def self.test_openai_compatible(url, api_key, provider_name)
356
+ label = { "openai" => "OpenAI", "xai" => "x.ai", "zai" => "z.ai", "zen" => "Zen" }[provider_name] || provider_name
357
+ unless api_key.present?
358
+ return { success: false, message: "#{label} API key not configured", provider: provider_name }
359
+ end
360
+
361
+ uri = URI(url)
362
+ http = Net::HTTP.new(uri.host, uri.port)
363
+ http.use_ssl = true
364
+ http.open_timeout = 5
365
+ http.read_timeout = 5
366
+
367
+ request = Net::HTTP::Get.new(uri)
368
+ request["Authorization"] = "Bearer #{api_key}"
369
+
370
+ response = http.request(request)
371
+ if response.is_a?(Net::HTTPSuccess)
372
+ { success: true, message: "#{label} connected successfully.", provider: provider_name }
373
+ else
374
+ error = JSON.parse(response.body).dig("error", "message") rescue response.body.to_s.truncate(100)
375
+ { success: false, message: "#{label}: #{error}", provider: provider_name }
376
+ end
377
+ end
378
+ private_class_method :test_openai_compatible
379
+
380
+ def raw_chat(messages, temperature: TEMPERATURE_UNSET, max_tokens: 500)
381
+ ruby_llm_chat(messages, temperature: temperature, max_tokens: max_tokens)
382
+ rescue Net::OpenTimeout, Net::ReadTimeout => e
383
+ Rails.logger.error "[PaveAi::Client] #{@provider} timed out: #{redact(e.message)}"
384
+ fail_as TimeoutError, "AI provider timed out — please try again"
385
+ rescue Faraday::TimeoutError => e
386
+ Rails.logger.error "[PaveAi::Client] #{@provider} timed out: #{redact(e.message)}"
387
+ fail_as TimeoutError, "AI provider timed out — please try again"
388
+ rescue Errno::ECONNREFUSED, SocketError => e
389
+ Rails.logger.error "[PaveAi::Client] #{@provider} not reachable: #{redact(e.message)}"
390
+ fail_as ConnectionError, "AI provider not reachable — check configuration"
391
+ rescue Faraday::ConnectionFailed => e
392
+ Rails.logger.error "[PaveAi::Client] #{@provider} not reachable: #{redact(e.message)}"
393
+ fail_as ConnectionError, "AI provider not reachable — check configuration"
394
+ rescue BudgetExceededError, UnavailableError, TimeoutError, ConnectionError, ApiError
395
+ raise
396
+ rescue RubyLLM::ConnectionError => e
397
+ # RubyLLM 2.2+ wraps Faraday timeouts and refused connections in its own
398
+ # error (after its retries); keep reporting them as ours.
399
+ Rails.logger.error "[PaveAi::Client] #{@provider} #{e.timeout? ? "timed out" : "not reachable"}: #{redact(e.message)}"
400
+ if e.timeout?
401
+ fail_as TimeoutError, "AI provider timed out — please try again"
402
+ else
403
+ fail_as ConnectionError, "AI provider not reachable — check configuration"
404
+ end
405
+ rescue RubyLLM::Error => e
406
+ Rails.logger.error "[PaveAi::Client] #{@provider} failed: #{redact(e.message)}"
407
+ fail_as ApiError, e.message
408
+ rescue => e
409
+ Rails.logger.error "[PaveAi::Client] #{@provider} failed: #{redact(e.message)}"
410
+ fail_as ApiError, "AI generation failed: #{e.message}"
411
+ end
412
+
413
+ # A vendor error can echo the key it was sent. With a caller credential,
414
+ # nothing this client raises or logs carries it.
415
+ def redact(text) = @credential ? @credential.redact(text) : text.to_s
416
+
417
+ # Raise our own error for the one being rescued. With a caller credential
418
+ # the original is dropped rather than kept as `cause`: its message, and
419
+ # the request headers on a vendor error, still hold the key, and error
420
+ # reporters walk the cause chain.
421
+ def fail_as(error_class, message)
422
+ raise error_class, redact(message), cause: (caller_funded? ? nil : $!)
423
+ end
424
+
425
+ def key_exposed_by?(error)
426
+ seen = []
427
+ while error && !seen.include?(error)
428
+ return true if @credential.exposed_in?(error.message)
429
+
430
+ seen << error
431
+ error = error.cause
432
+ end
433
+ false
434
+ end
435
+
436
+ # The one key this client's calls carry: the caller's, or else ours.
437
+ def api_key = @credential ? @credential.api_key : @adapter.api_key
438
+
439
+ # When the paid budget is exhausted, downgrade to the configured
440
+ # cheaper provider/model rather than fail. Exempt providers are
441
+ # never rerouted — they are the destination, not the problem.
442
+ def apply_budget_fallback(provider, model)
443
+ fallback = PaveAi.config.budget_fallback
444
+ return [ provider, model ] unless fallback
445
+ return [ provider, model ] if PaveAi.config.budget_exempt_providers.include?(provider.to_s)
446
+ return [ provider, model ] unless PaveAi::Spend.exceeded?(scope: :global)
447
+
448
+ [ fallback[:provider], fallback[:model] ]
449
+ end
450
+
451
+ def validate_input_length!(messages)
452
+ total = messages.sum { |m| m[:content].to_s.length }
453
+ if total > MAX_INPUT_CHARS
454
+ raise AiError, "Input too long (#{total} chars, max #{MAX_INPUT_CHARS})"
455
+ end
456
+ end
457
+
458
+ def enforce_request_policy!(intent:, kind:, user:, context:)
459
+ decision = PaveAi.config.request_policy(
460
+ provider: @provider,
461
+ intent: intent,
462
+ kind: kind,
463
+ user: user,
464
+ context: context
465
+ )
466
+
467
+ return if decision.nil? || decision == true
468
+
469
+ message = decision.is_a?(String) ? decision : "This AI request is not available in the current host context."
470
+ raise UnavailableError, message
471
+ end
472
+
473
+ PROVIDER_LABELS = {
474
+ "anthropic" => "Anthropic", "gemini" => "Gemini", "openai" => "OpenAI",
475
+ "openai_compatible" => "OpenAI-compatible endpoint", "xai" => "x.ai", "zai" => "z.ai",
476
+ "zen" => "OpenCode Zen"
477
+ }.freeze
478
+
479
+ def validate_configuration!
480
+ label = PROVIDER_LABELS[@provider.to_s] || @provider
481
+ # No default pin exists for a provider we have not live-smoked. (A blank
482
+ # model on a provider that HAS a default constructs as it always did.)
483
+ if @model.blank? && @adapter.default_model.nil?
484
+ raise ConfigurationError, "#{label} needs an explicit model"
485
+ end
486
+ return validate_caller_credential!(label) if @credential
487
+
488
+ raise ConfigurationError, "#{label} needs a caller credential" if @adapter.requires_caller_credential?
489
+ return if @provider == "ollama"
490
+ return if @adapter.configured?
491
+
492
+ raise ConfigurationError, "#{label} API key not configured"
493
+ end
494
+
495
+ def validate_caller_credential!(label)
496
+ unless @adapter.accepts_caller_credential?
497
+ raise ConfigurationError, "#{label} does not take a caller credential"
498
+ end
499
+
500
+ if @adapter.accepts_api_base?
501
+ raise ConfigurationError, "#{label} needs a base URL on the caller credential" if @credential.api_base.nil?
502
+ elsif @credential.api_base
503
+ raise ConfigurationError, "#{label} does not take a caller base URL"
504
+ end
505
+ end
506
+
507
+ def ruby_llm_chat(messages, temperature:, max_tokens:)
508
+ # Preserve the endpoint and max_tokens wire format used by our compatible
509
+ # vendors. A native provider (Anthropic, Gemini) speaks its own protocol,
510
+ # where the limit is RubyLLM's own max-output setting.
511
+ native = @adapter.native_protocol?
512
+ chat = ruby_llm_context.chat(model: @model, provider: ruby_llm_provider,
513
+ protocol: (native ? nil : :chat_completions), assume_model_exists: true)
514
+ temperature = (native ? nil : DEFAULT_TEMPERATURE) if temperature.equal?(TEMPERATURE_UNSET)
515
+ chat.with_temperature(temperature) unless native && temperature.nil?
516
+ native ? chat.with_max_output_tokens(max_tokens) : chat.with_provider_options(max_tokens: max_tokens)
517
+ messages.each { |message| chat.add_message(role: message[:role].to_sym, content: message[:content]) }
518
+
519
+ response = chat.complete
520
+ {
521
+ content: response.content.to_s.strip,
522
+ usage_tokens: total_usage_tokens(response, fallback: max_tokens),
523
+ # Kept separate: input and output tokens do not cost the same, so a
524
+ # single total cannot reprice the charge.
525
+ # nil, not 0, when the provider reports no usage: missing usage
526
+ # settles at the estimate instead of pricing the call at zero.
527
+ input_tokens: response.tokens.input,
528
+ output_tokens: response.tokens.output,
529
+ # Prompt-cache reads are billed apart from standard input (10).
530
+ cached_tokens: response.tokens.cache_read
531
+ }
532
+ end
533
+
534
+ def ruby_llm_image(prompt, size:, format:)
535
+ image = ruby_llm_context.paint(
536
+ prompt,
537
+ model: DEFAULT_IMAGE_MODELS[@provider],
538
+ provider: ruby_llm_provider,
539
+ assume_model_exists: true,
540
+ size: size
541
+ )
542
+
543
+ format == :binary ? image.to_blob : image.url
544
+ end
545
+
546
+ # OpenAI-compatible vendors RubyLLM has no first-class provider for.
547
+ OPENAI_COMPAT_BASES = {
548
+ "zai" => "https://open.bigmodel.cn/api/paas/v4",
549
+ "zen" => "https://opencode.ai/zen/v1"
550
+ }.freeze
551
+
552
+ def ruby_llm_provider
553
+ case @provider
554
+ when "openai", "xai", "anthropic", "gemini" then @provider.to_sym
555
+ when "zai", "zen", "openai_compatible" then :openai
556
+ when "ollama" then :ollama
557
+ else
558
+ raise ConfigurationError, "Unsupported provider: #{@provider}"
559
+ end
560
+ end
561
+
562
+ def ruby_llm_context
563
+ RubyLLM.context do |config|
564
+ detach_from_host_vendor_settings(config) if caller_funded?
565
+
566
+ case @provider
567
+ when "openai"
568
+ config.openai_api_key = api_key
569
+ when "xai"
570
+ config.xai_api_key = api_key
571
+ when "anthropic"
572
+ config.anthropic_api_key = api_key
573
+ when "gemini"
574
+ config.gemini_api_key = api_key
575
+ when "zai", "zen"
576
+ config.openai_api_base = OPENAI_COMPAT_BASES[@provider]
577
+ config.openai_api_key = api_key
578
+ when "openai_compatible"
579
+ config.openai_api_base = @credential.api_base
580
+ config.openai_api_key = api_key
581
+ when "ollama"
582
+ config.ollama_api_base = "#{PaveAi.config.ollama_url}/v1"
583
+ else
584
+ raise ConfigurationError, "Unsupported provider: #{@provider}"
585
+ end
586
+ end
587
+ end
588
+
589
+ # The context starts as a copy of the host's RubyLLM configuration. A
590
+ # caller's key must go to the vendor it belongs to, as the caller's own
591
+ # account: not through a proxy base the host configured, and not tagged
592
+ # with the host's organization or project.
593
+ HOST_VENDOR_SETTINGS = %i[
594
+ openai_api_base openai_organization_id openai_project_id
595
+ xai_api_base anthropic_api_base gemini_api_base
596
+ ].freeze
597
+
598
+ def detach_from_host_vendor_settings(config)
599
+ HOST_VENDOR_SETTINGS.each do |name|
600
+ config.public_send("#{name}=", nil) if config.respond_to?("#{name}=")
601
+ end
602
+ end
603
+
604
+ def record_chat_usage(budget, response)
605
+ budget.record!(
606
+ actual_tokens: response[:usage_tokens],
607
+ input_tokens: response[:input_tokens],
608
+ output_tokens: response[:output_tokens],
609
+ cached_tokens: response[:cached_tokens]
610
+ )
611
+ end
612
+
613
+ # A rough count of the prompt about to be sent (4 characters a token), so
614
+ # the hold covers input as well as output.
615
+ def estimated_prompt_tokens(messages)
616
+ (Array(messages).sum { |message| message[:content].to_s.length } / 4.0).ceil
617
+ end
618
+
619
+ def total_usage_tokens(response, fallback:)
620
+ input = response.tokens.input.to_i
621
+ output = response.tokens.output.to_i
622
+ total = input + output
623
+ total.positive? ? total : fallback
624
+ end
625
+
626
+ def openai_image(prompt, size:, quality:, format:)
627
+ uri = URI("https://api.openai.com/v1/images/generations")
628
+ http = Net::HTTP.new(uri.host, uri.port)
629
+ http.use_ssl = true
630
+ http.read_timeout = 120
631
+ http.open_timeout = 10
632
+
633
+ request = Net::HTTP::Post.new(uri)
634
+ request["Content-Type"] = "application/json"
635
+ request["Authorization"] = "Bearer #{PaveAi.config.openai_api_key}"
636
+ request.body = {
637
+ model: DEFAULT_IMAGE_MODELS["openai"],
638
+ prompt: prompt, n: 1, size: size, quality: quality,
639
+ response_format: format == :binary ? "b64_json" : "url"
640
+ }.to_json
641
+
642
+ response = http.request(request)
643
+ handle_image_response(response, format)
644
+ end
645
+
646
+ def zai_image(prompt, size:, format:)
647
+ uri = URI("https://open.bigmodel.cn/api/paas/v4/images/generations")
648
+ http = Net::HTTP.new(uri.host, uri.port)
649
+ http.use_ssl = true
650
+ http.read_timeout = 120
651
+ http.open_timeout = 10
652
+
653
+ request = Net::HTTP::Post.new(uri)
654
+ request["Content-Type"] = "application/json"
655
+ request["Authorization"] = "Bearer #{PaveAi.config.zai_api_key}"
656
+ request.body = {
657
+ model: DEFAULT_IMAGE_MODELS["zai"],
658
+ prompt: prompt, n: 1, size: size
659
+ }.to_json
660
+
661
+ response = http.request(request)
662
+ handle_image_response(response, format)
663
+ end
664
+
665
+ def handle_image_response(response, format)
666
+ if response.is_a?(Net::HTTPSuccess)
667
+ data = JSON.parse(response.body)
668
+ image_data = data.dig("data", 0)
669
+
670
+ if format == :binary && image_data["b64_json"]
671
+ Base64.decode64(image_data["b64_json"])
672
+ else
673
+ image_data["url"]
674
+ end
675
+ else
676
+ error_body = JSON.parse(response.body) rescue { "error" => response.body }
677
+ error_obj = error_body["error"]
678
+ error_msg = error_obj.is_a?(Hash) ? error_obj["message"] : (error_obj || response.body)
679
+ raise ApiError, "Image generation error: #{response.code} - #{error_msg}"
680
+ end
681
+ end
682
+ end
683
+ end