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,539 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaveAi
4
+ # Reserve-then-settle metering.
5
+ #
6
+ # Funds are HELD before the provider is called and settled against the real
7
+ # cost afterwards. The older shape checked "does this user have any credit"
8
+ # without a lock, called the provider, and only then tried to charge — so two
9
+ # concurrent requests could both spend the last credit, and an unaffordable
10
+ # request paid the vendor before failing.
11
+ #
12
+ # Every movement of funds runs in its own savepoint, so a failure part-way
13
+ # through settlement — even inside a host's transaction — undoes exactly
14
+ # that settlement and nothing is refunded twice.
15
+ class Spend
16
+ class BudgetExceeded < StandardError; end
17
+
18
+ # Who pays the vendor for an operation. :platform is every call made with
19
+ # our keys and is the only behaviour that existed before; :caller is a
20
+ # call made with the caller's own credential (PaveAi::Credential), which
21
+ # we record and never charge.
22
+ FUNDINGS = %i[platform caller].freeze
23
+ CALLER_FUNDING_SOURCE = "caller_key"
24
+
25
+ # Credits held from one place. The quota row is remembered so a refund
26
+ # returns to the month it came from, not to whatever month it is now.
27
+ Hold = Struct.new(:credits, :source, :quota_id, keyword_init: true)
28
+
29
+ # The price of one operation, fixed when its funds are held: editing an
30
+ # intent mid-flight cannot change a purchase already made. credits is nil when the host's cost policy prices it.
31
+ Price = Struct.new(:credits, :source, keyword_init: true)
32
+
33
+ class Budget
34
+ attr_reader :approved, :denial_reason, :estimated_cost_cents, :funding_source
35
+
36
+ def initialize(approved:, denial_reason: nil, estimated_cost_cents: 0, funding_source: nil,
37
+ holds: [], price: nil, log_attrs: {}, caller_funded: false)
38
+ @caller_funded = caller_funded
39
+ @approved = approved
40
+ @denial_reason = denial_reason
41
+ @estimated_cost_cents = estimated_cost_cents
42
+ @funding_source = funding_source
43
+ @holds = holds
44
+ @price = price
45
+ @log_attrs = log_attrs
46
+ @state = :open
47
+ end
48
+
49
+ def approved? = @approved
50
+ def recorded? = @state != :open
51
+ def settled? = @state == :settled
52
+
53
+ # Settle the held funds against what the operation really cost.
54
+ #
55
+ # Pass input_tokens/output_tokens (and cached_tokens) to be repriced
56
+ # from the model's real rates; actual_cost_cents overrides everything.
57
+ # Passing only actual_tokens records the count but cannot reprice — an
58
+ # input token and an output token do not cost the same.
59
+ def record!(actual_tokens: nil, actual_cost_cents: nil, input_tokens: nil, output_tokens: nil,
60
+ cached_tokens: nil, metadata: {})
61
+ return if recorded?
62
+
63
+ if @caller_funded
64
+ return record_caller_funded!(actual_tokens: actual_tokens, actual_cost_cents: actual_cost_cents,
65
+ input_tokens: input_tokens, output_tokens: output_tokens, cached_tokens: cached_tokens,
66
+ metadata: metadata)
67
+ end
68
+
69
+ reported = [ input_tokens, output_tokens, cached_tokens ]
70
+ # Usage reported as all zeros is usage missing, not a free call: settle at the estimate and say so.
71
+ usage_missing = actual_cost_cents.nil? && reported.any? && reported.sum(&:to_i).zero?
72
+ cost = actual_cost_cents ||
73
+ PaveAi::Spend.send(:reprice, @log_attrs, input_tokens, output_tokens, cached_tokens) ||
74
+ @estimated_cost_cents
75
+ # Never below zero: a negative cost or price must not refund more
76
+ # than was held.
77
+ cost = [ cost.to_i, 0 ].max
78
+ target = [ PaveAi::Spend.send(:credits_at, @price, cost).to_i, 0 ].max
79
+
80
+ merged_metadata = (@log_attrs[:metadata] || {}).merge(metadata.to_h)
81
+ merged_metadata["usage_missing"] = true if usage_missing
82
+
83
+ holds = @holds.map(&:dup)
84
+ ActiveRecord::Base.transaction(requires_new: true) do
85
+ notes = PaveAi::Spend.send(:settle_to!, user: @log_attrs[:user], holds: holds, target: target)
86
+
87
+ if cost > 0 && !PaveAi.config.budget_exempt_providers.include?(@log_attrs[:provider])
88
+ PaveAi.config.record_ai_usage(cost, provider: @log_attrs[:provider])
89
+ end
90
+
91
+ PaveAi::SpendLog.create!(
92
+ **@log_attrs,
93
+ funding_source: holds.first&.source || @funding_source,
94
+ actual_tokens: actual_tokens || reported.compact.sum.presence,
95
+ actual_cost_cents: cost,
96
+ credits_charged: holds.sum(&:credits),
97
+ success: true,
98
+ metadata: merged_metadata.merge(notes).merge(PaveAi::Spend.send(:charge_notes, holds, target))
99
+ )
100
+ end
101
+
102
+ @holds = holds
103
+ @state = :settled
104
+ end
105
+
106
+ # The caller's key paid the vendor. Usage is evidence, so the row is
107
+ # still written — with nothing charged, nothing held, and a cost to US
108
+ # of zero, so every existing total stays a total of our own spend. What
109
+ # the caller's account was billed goes in metadata, when the model is
110
+ # rated, and never touches the global budget.
111
+ def record_caller_funded!(actual_tokens:, actual_cost_cents:, input_tokens:, output_tokens:,
112
+ cached_tokens:, metadata:)
113
+ provider_cost = actual_cost_cents ||
114
+ PaveAi::Spend.send(:reprice, @log_attrs, input_tokens, output_tokens, cached_tokens)
115
+ merged_metadata = (@log_attrs[:metadata] || {}).merge(metadata.to_h)
116
+ merged_metadata = merged_metadata.merge("provider_cost_cents" => provider_cost) if provider_cost
117
+
118
+ PaveAi::SpendLog.create!(
119
+ **@log_attrs,
120
+ funding_source: CALLER_FUNDING_SOURCE,
121
+ actual_tokens: actual_tokens || [ input_tokens, output_tokens, cached_tokens ].compact.sum.presence,
122
+ actual_cost_cents: 0,
123
+ credits_charged: 0,
124
+ success: true,
125
+ metadata: merged_metadata
126
+ )
127
+ @state = :settled
128
+ end
129
+
130
+ # Give the held funds back — the operation produced no value.
131
+ def release!(reason:)
132
+ return if recorded?
133
+
134
+ write_failure!(reason: reason) { |holds, notes| [ holds.sum(&:credits), notes ] }
135
+ @state = :released
136
+ end
137
+
138
+ # The operation was settled, then failed before the caller got its
139
+ # result. Refund what was charged and write a
140
+ # reversal row: the settled row is evidence and is never rewritten,
141
+ # so the pair nets to what the customer actually paid.
142
+ def reverse!(reason:)
143
+ return unless settled? && !@caller_funded
144
+
145
+ charged = @holds.sum(&:credits)
146
+ write_failure!(reason: "reversed: #{reason}", reversal: true) do |holds, notes|
147
+ [ holds.sum(&:credits) - charged, notes ]
148
+ end
149
+ @state = :reversed
150
+ end
151
+
152
+ private
153
+
154
+ def write_failure!(reason:, reversal: false)
155
+ holds = @holds.map(&:dup)
156
+ ActiveRecord::Base.transaction(requires_new: true) do
157
+ notes = PaveAi::Spend.send(:settle_to!, user: @log_attrs[:user], holds: holds, target: 0)
158
+ credits, notes = yield holds, notes
159
+ metadata = (@log_attrs[:metadata] || {}).merge(notes)
160
+ metadata["reversal"] = true if reversal
161
+
162
+ PaveAi::SpendLog.create!(
163
+ **@log_attrs,
164
+ funding_source: @holds.first&.source || @funding_source,
165
+ approved: true,
166
+ success: false,
167
+ credits_charged: credits,
168
+ denial_reason: reason.to_s.truncate(255),
169
+ metadata: metadata
170
+ )
171
+ end
172
+ @holds = holds
173
+ end
174
+ end
175
+
176
+ class << self
177
+ def request(intent:, spend_type:, provider:, model: nil, user: nil, billable: nil,
178
+ estimated_tokens: nil, estimated_input_tokens: nil, metadata: {},
179
+ skip_budget_check: false, funding: :platform, &block)
180
+ # A symbol the caller wrote, not a string that happened to match: who
181
+ # pays is never something to read out of params or a column.
182
+ raise ArgumentError, "Unknown funding: #{funding.inspect}" unless FUNDINGS.include?(funding)
183
+
184
+ if funding == :caller
185
+ return request_caller_funded(intent: intent, spend_type: spend_type, provider: provider, model: model,
186
+ user: user, billable: billable, estimated_tokens: estimated_tokens, metadata: metadata, &block)
187
+ end
188
+
189
+ price = price_for(intent)
190
+ estimated_cost = estimate_cost(provider, spend_type, estimated_tokens, model, estimated_input_tokens)
191
+ estimated_credits = [ credits_at(price, estimated_cost).to_i, 0 ].max
192
+
193
+ log_attrs = {
194
+ user: user,
195
+ billable: billable,
196
+ intent: intent.to_s,
197
+ spend_type: spend_type.to_s,
198
+ provider: provider.to_s,
199
+ model: model&.to_s,
200
+ estimated_tokens: estimated_tokens,
201
+ estimated_cost_cents: estimated_cost,
202
+ approved: true,
203
+ # Which price applied, so a typo'd intent falling back to the cost
204
+ # policy is visible in the log.
205
+ metadata: (metadata || {}).to_h.merge("price_source" => price.source)
206
+ }
207
+
208
+ unless skip_budget_check
209
+ denial = check_budgets(provider: provider, user: user, estimated_cost: estimated_cost,
210
+ estimated_credits: estimated_credits)
211
+ if denial
212
+ PaveAi::SpendLog.create!(**log_attrs, approved: false, success: false,
213
+ credits_charged: 0, denial_reason: denial)
214
+ raise BudgetExceeded, denial
215
+ end
216
+ end
217
+
218
+ # Hold the funds BEFORE the provider is called, under a row lock, so a
219
+ # concurrent request cannot spend the same credit.
220
+ hold = reserve!(user: user, credits: estimated_credits,
221
+ allow_unfunded: skip_budget_check, log_attrs: log_attrs)
222
+
223
+ # Let through unheld by skip_budget_check: say so, rather than name a
224
+ # source that paid nothing.
225
+ unfunded = hold.nil? && skip_budget_check && user && !veto?(user) && estimated_credits.positive?
226
+ budget = Budget.new(
227
+ approved: true,
228
+ estimated_cost_cents: estimated_cost,
229
+ funding_source: hold&.source || (unfunded ? "unfunded" : determine_funding_source(user)),
230
+ holds: [ hold ].compact,
231
+ price: price,
232
+ log_attrs: log_attrs
233
+ )
234
+
235
+ run_metered(budget, &block)
236
+ end
237
+
238
+ # True while a metered block is running on this thread. Lets
239
+ # Client#chat_with_usage meter itself only when nothing else is.
240
+ def metering? = metering_depth.positive?
241
+
242
+ def remaining(scope:, user: nil)
243
+ case scope.to_sym
244
+ when :global then PaveAi.config.ai_budget_remaining
245
+ when :user
246
+ return 0 unless user
247
+ user_total_remaining(user)
248
+ else 0
249
+ end
250
+ end
251
+
252
+ def exceeded?(scope:, user: nil)
253
+ case scope.to_sym
254
+ when :global then PaveAi.config.ai_budget_remaining <= 0
255
+ when :user
256
+ return false unless user
257
+ return false if veto?(user)
258
+ user_total_remaining(user) <= 0
259
+ else false
260
+ end
261
+ end
262
+
263
+ private
264
+
265
+ # Run the caller's block and make sure the budget ends in exactly one
266
+ # recorded state, however the block leaves:
267
+ # - returns: settle (at the estimate if record! was forgotten)
268
+ # - raises: release the hold, or reverse a settled charge
269
+ # - break / throw: settle, like a forgotten record!
270
+ # - killed / Interrupt: release
271
+ def run_metered(budget)
272
+ finished = false
273
+ result = metering { yield budget }
274
+ budget.record! unless budget.recorded?
275
+ finished = true
276
+ result
277
+ rescue => e
278
+ finished = true
279
+ reason = "error: #{e.message.truncate(200)}"
280
+ budget.settled? ? budget.reverse!(reason: reason) : budget.release!(reason: reason)
281
+ raise
282
+ ensure
283
+ unless finished
284
+ if $!
285
+ budget.release!(reason: "interrupted: #{$!.class}") unless budget.recorded?
286
+ else
287
+ budget.record! unless budget.recorded?
288
+ end
289
+ end
290
+ end
291
+
292
+ def metering
293
+ Thread.current[:pave_ai_metering_depth] = metering_depth + 1
294
+ yield
295
+ ensure
296
+ Thread.current[:pave_ai_metering_depth] = metering_depth - 1
297
+ end
298
+
299
+ def metering_depth = Thread.current[:pave_ai_metering_depth].to_i
300
+
301
+ # No budget gate, no affordability check, no reservation: there is
302
+ # nothing of ours to protect. The lifecycle is otherwise the same — a
303
+ # forgotten record! still writes the row, a failure still writes one.
304
+ def request_caller_funded(intent:, spend_type:, provider:, model:, user:, billable:,
305
+ estimated_tokens:, metadata:, &block)
306
+ log_attrs = {
307
+ user: user,
308
+ billable: billable,
309
+ intent: intent.to_s,
310
+ spend_type: spend_type.to_s,
311
+ provider: provider.to_s,
312
+ model: model&.to_s,
313
+ estimated_tokens: estimated_tokens,
314
+ estimated_cost_cents: 0,
315
+ approved: true,
316
+ metadata: (metadata || {}).to_h.merge("credential_source" => "caller")
317
+ }
318
+ budget = Budget.new(approved: true, estimated_cost_cents: 0, funding_source: CALLER_FUNDING_SOURCE,
319
+ log_attrs: log_attrs, caller_funded: true)
320
+
321
+ run_metered(budget, &block)
322
+ end
323
+
324
+ def veto?(user)
325
+ user.respond_to?(:ai_veto?) && user.ai_veto?
326
+ end
327
+
328
+ # What we CHARGE, in credits. The intent (the feature) prices itself —
329
+ # a price is a property of the feature, never of the provider. Falls
330
+ # back to the host's cost-based policy when the intent is unpriced,
331
+ # unless the host requires every intent to carry a price.
332
+ def price_for(intent)
333
+ credits = PaveAi::Intent.credit_cost_for(intent)
334
+ return Price.new(credits: credits, source: "intent") if credits
335
+
336
+ if PaveAi.config.require_priced_intents
337
+ raise PaveAi::Client::HostSettingMissing,
338
+ "PaveAi intent #{intent.to_s.inspect} has no credit_cost and require_priced_intents is set"
339
+ end
340
+
341
+ Price.new(credits: nil, source: "cost_policy")
342
+ end
343
+
344
+ def credits_at(price, cost_cents)
345
+ price.credits || PaveAi.config.credits_for_cost(cost_cents)
346
+ end
347
+
348
+ # Kept for callers that ask for a price by intent name.
349
+ def credits_for(intent, cost_cents)
350
+ credits_at(price_for(intent), cost_cents)
351
+ end
352
+
353
+ # Real cost from the tokens actually used, when the model is rated.
354
+ # Nil when usage is absent or all zero — that is missing usage, and
355
+ # pricing it as zero would make the call free.
356
+ def reprice(log_attrs, input_tokens, output_tokens, cached_tokens = nil)
357
+ tokens = [ input_tokens, output_tokens, cached_tokens ]
358
+ return nil if tokens.all?(&:nil?) || tokens.sum(&:to_i).zero?
359
+ return nil unless log_attrs[:model]
360
+
361
+ PaveAi::Rates.text_cost_cents(
362
+ model: log_attrs[:model], provider: log_attrs[:provider],
363
+ input_tokens: input_tokens.to_i, output_tokens: output_tokens.to_i, cached_tokens: cached_tokens.to_i
364
+ )
365
+ end
366
+
367
+ # Hold `credits` for this operation. Quota first, then the purchased
368
+ # wallet — both under a lock, and the wallet re-checked INSIDE its lock
369
+ # so a concurrent host-side spend cannot be overdrawn. Returns the Hold,
370
+ # or nil when nothing needed holding (or allow_unfunded let it through).
371
+ def reserve!(user:, credits:, allow_unfunded:, log_attrs:)
372
+ return nil if credits <= 0 || user.nil? || veto?(user)
373
+
374
+ hold = ActiveRecord::Base.transaction(requires_new: true) do
375
+ quota = PaveAi::Quota.current_for(user)
376
+ quota.lock!
377
+ if quota.credits_remaining >= credits
378
+ quota.increment!(:credits_used, credits)
379
+ next Hold.new(credits: credits, source: "quota", quota_id: quota.id)
380
+ end
381
+
382
+ held = nil
383
+ if user.respond_to?(:with_lock)
384
+ user.with_lock do
385
+ if user.respond_to?(:sufficient_tool_credits?) && user.sufficient_tool_credits?(credits)
386
+ user.spend_tool_credits!(credits, source: "ai_usage", description: "AI credit (overflow)")
387
+ held = Hold.new(credits: credits, source: "purchased")
388
+ end
389
+ end
390
+ end
391
+ held
392
+ end
393
+ return hold if hold || allow_unfunded
394
+
395
+ # Written outside the reservation's transaction: a denial must keep
396
+ # its row.
397
+ message = PaveAi.config.denial_message(:credits_exhausted)
398
+ PaveAi::SpendLog.create!(**log_attrs, approved: false, success: false,
399
+ credits_charged: 0, denial_reason: message)
400
+ raise BudgetExceeded, message
401
+ end
402
+
403
+ # Move the holds to `target` credits in total. Tops up from quota then
404
+ # wallet, or refunds newest-first to where each hold came from. Mutates
405
+ # `holds` and returns notes for the log. A vetoed or anonymous user is
406
+ # never topped up and never in debt.
407
+ def settle_to!(user:, holds:, target:)
408
+ notes = {}
409
+ held = holds.sum(&:credits)
410
+
411
+ if target > held
412
+ return notes if user.nil? || veto?(user)
413
+
414
+ extra = reserve!(user: user, credits: target - held, allow_unfunded: true,
415
+ log_attrs: { user: user, intent: "settlement", spend_type: "text", provider: "settlement" })
416
+ extra ? holds << extra : notes["underfunded_credits"] = target - held
417
+ elsif target < held
418
+ excess = held - target
419
+ holds.reverse_each do |hold|
420
+ break if excess.zero?
421
+
422
+ take = [ hold.credits, excess ].min
423
+ next if take.zero?
424
+
425
+ excess -= take
426
+ if refund(user: user, hold: hold, credits: take)
427
+ hold.credits -= take
428
+ else
429
+ # Never silently keep the difference: make the debt visible.
430
+ notes["refund_owed_credits"] = notes.fetch("refund_owed_credits", 0) + take
431
+ end
432
+ end
433
+ end
434
+
435
+ notes
436
+ end
437
+
438
+ # Returns true when the credits went back, false when the host cannot
439
+ # take them back (no refund hook).
440
+ def refund(user:, hold:, credits:)
441
+ case hold.source
442
+ when "quota"
443
+ quota = PaveAi::Quota.lock.find_by(id: hold.quota_id)
444
+ quota&.update!(credits_used: [ quota.credits_used - credits, 0 ].max)
445
+ true
446
+ when "purchased"
447
+ return false unless user.respond_to?(:refund_tool_credits!)
448
+
449
+ if user.respond_to?(:with_lock)
450
+ user.with_lock { user.refund_tool_credits!(credits, source: "ai_usage_refund") }
451
+ else
452
+ user.refund_tool_credits!(credits, source: "ai_usage_refund")
453
+ end
454
+ true
455
+ else
456
+ true
457
+ end
458
+ end
459
+
460
+ # What the log needs to say about the charge beyond its total: the
461
+ # price when it differs from what was deducted, and the split when more
462
+ # than one place paid.
463
+ def charge_notes(holds, target)
464
+ notes = {}
465
+ charged = holds.sum(&:credits)
466
+ notes["credits_priced"] = target if target != charged
467
+ by_source = holds.select { |h| h.credits.positive? }.group_by(&:source).transform_values { |hs| hs.sum(&:credits) }
468
+ notes["credits_by_source"] = by_source if by_source.size > 1
469
+ notes
470
+ end
471
+
472
+ def check_budgets(provider:, user:, estimated_cost:, estimated_credits:)
473
+ # A vetoed user is never charged and never blocked — including by the
474
+ # global gate, which used to run first.
475
+ return nil if user && veto?(user)
476
+
477
+ unless PaveAi.config.budget_exempt_providers.include?(provider.to_s)
478
+ if PaveAi.config.ai_budget_remaining < estimated_cost
479
+ return PaveAi.config.denial_message(:budget_reached, provider: provider)
480
+ end
481
+ end
482
+
483
+ # Affordability, not "is anything left": a 5-credit operation with 1
484
+ # credit remaining used to pass here, call the provider, and fail at
485
+ # settlement — we paid the vendor and the customer got an error.
486
+ if user && estimated_credits.positive? && user_total_remaining(user) < estimated_credits
487
+ return PaveAi.config.denial_message(:credits_exhausted)
488
+ end
489
+
490
+ nil
491
+ end
492
+
493
+ def user_total_remaining(user)
494
+ quota = PaveAi::Quota.current_for(user)
495
+ quota_remaining = [ quota.credits_remaining, 0 ].max
496
+ purchased = user.respond_to?(:tool_credits_balance) ? user.tool_credits_balance : 0
497
+ quota_remaining + purchased
498
+ end
499
+
500
+ # What the operation cost US, in cents. Prices the model actually
501
+ # invoked when it is rated; the host's proc is the fallback for unrated
502
+ # models. Never scaled by a provider's legacy credit_cost — that is a
503
+ # price, not a cost.
504
+ #
505
+ # Text holds price the prompt as well as the output; embeddings are input-only.
506
+ def estimate_cost(provider, spend_type, estimated_tokens, model = nil, estimated_input_tokens = nil)
507
+ return 0 if provider.to_s == "ollama"
508
+
509
+ case spend_type.to_s
510
+ when "text"
511
+ output = estimated_tokens || 500
512
+ input = estimated_input_tokens.to_i
513
+ rated = model && PaveAi::Rates.text_cost_cents(
514
+ model: model, provider: provider, input_tokens: input, output_tokens: output
515
+ )
516
+ rated || PaveAi.config.estimate_text_cost(provider, output + input)
517
+ when "embedding"
518
+ tokens = estimated_tokens || 500
519
+ rated = model && PaveAi::Rates.text_cost_cents(model: model, provider: provider, input_tokens: tokens)
520
+ rated || PaveAi.config.estimate_text_cost(provider, tokens)
521
+ when "image" then PaveAi.config.estimate_image_cost(provider)
522
+ else 0
523
+ end
524
+ end
525
+
526
+ def determine_funding_source(user)
527
+ return "global" unless user
528
+ quota = PaveAi::Quota.current_for(user)
529
+ if quota.credits_remaining > 0
530
+ "quota"
531
+ elsif user.respond_to?(:tool_credits_balance) && user.tool_credits_balance > 0
532
+ "purchased"
533
+ else
534
+ "global"
535
+ end
536
+ end
537
+ end
538
+ end
539
+ end
@@ -0,0 +1,17 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Pave ai</title>
5
+ <%= csrf_meta_tags %>
6
+ <%= csp_meta_tag %>
7
+
8
+ <%= yield :head %>
9
+
10
+ <%= stylesheet_link_tag "pave_ai/application", media: "all" %>
11
+ </head>
12
+ <body>
13
+
14
+ <%= yield %>
15
+
16
+ </body>
17
+ </html>
@@ -0,0 +1,20 @@
1
+ # PaveAI Content Policy
2
+
3
+ ## Always
4
+ - Be helpful, accurate, and constructive
5
+ - Credit original creators and sources
6
+ - Respect user privacy and data
7
+ - Be transparent about AI-generated content
8
+
9
+ ## Never
10
+ - Generate harmful, misleading, or deceptive content
11
+ - Impersonate real people without consent
12
+ - Create spam or manipulative content
13
+ - Produce content that violates applicable laws
14
+ - Generate content promoting violence or discrimination
15
+
16
+ ## Guidelines
17
+ - When uncertain, err on the side of caution
18
+ - Provide balanced perspectives on controversial topics
19
+ - Acknowledge limitations of AI-generated content
20
+ - Respect intellectual property rights
data/config/routes.rb ADDED
@@ -0,0 +1,2 @@
1
+ PaveAi::Engine.routes.draw do
2
+ end
@@ -0,0 +1,102 @@
1
+ class CreatePaveAiTables < ActiveRecord::Migration[8.0]
2
+ def change
3
+ create_table :pave_ai_personas do |t|
4
+ t.references :user, polymorphic: true, index: { unique: true }
5
+ t.text :content, null: false
6
+ t.timestamps
7
+ end
8
+
9
+ create_table :pave_ai_intents do |t|
10
+ t.string :name, null: false
11
+ t.string :display_name, null: false
12
+ t.string :content_type, null: false, default: "custom"
13
+ t.text :description
14
+ t.text :rules
15
+ t.text :output_format
16
+ t.text :topic_keywords
17
+ t.text :internal_sources
18
+ t.boolean :preset, null: false, default: false
19
+ t.boolean :user_accessible, null: false, default: false
20
+ t.boolean :active, null: false, default: true
21
+ t.integer :position
22
+ t.references :user, polymorphic: true, index: true
23
+ t.references :persona, foreign_key: { to_table: :pave_ai_personas }, index: true
24
+ t.timestamps
25
+ end
26
+ add_index :pave_ai_intents, :name, unique: true
27
+ add_index :pave_ai_intents, :content_type
28
+ add_index :pave_ai_intents, :active
29
+
30
+ create_table :pave_ai_persona_documents do |t|
31
+ t.string :name, null: false
32
+ t.string :slug, null: false
33
+ t.text :content, null: false
34
+ t.string :category, null: false
35
+ t.integer :position, null: false, default: 0
36
+ t.boolean :active, null: false, default: true
37
+ t.timestamps
38
+ end
39
+ add_index :pave_ai_persona_documents, :slug, unique: true
40
+ add_index :pave_ai_persona_documents, :category
41
+ add_index :pave_ai_persona_documents, [ :active, :position ]
42
+
43
+ create_table :pave_ai_chats do |t|
44
+ t.references :user, polymorphic: true, null: false, index: true
45
+ t.references :intent, foreign_key: { to_table: :pave_ai_intents }, null: false, index: true
46
+ t.string :title
47
+ t.string :status, null: false, default: "active"
48
+ t.public_send(metadata_column_type, :metadata, null: false, default: {})
49
+ t.timestamps
50
+ end
51
+ add_index :pave_ai_chats, [ :user_id, :user_type, :status ]
52
+
53
+ create_table :pave_ai_chat_messages do |t|
54
+ t.references :pave_ai_chat, null: false, foreign_key: true, index: true
55
+ t.string :role, null: false
56
+ t.text :content, null: false
57
+ t.public_send(metadata_column_type, :metadata, null: false, default: {})
58
+ t.timestamps
59
+ end
60
+ add_index :pave_ai_chat_messages, [ :pave_ai_chat_id, :created_at ]
61
+
62
+ create_table :pave_ai_quotas do |t|
63
+ t.references :user, polymorphic: true, null: false
64
+ t.string :period, null: false
65
+ t.integer :generations_used, null: false, default: 0
66
+ t.integer :generations_limit, null: false, default: 50
67
+ t.integer :exports_used, null: false, default: 0
68
+ t.integer :exports_limit, null: false, default: 20
69
+ t.integer :credits_used, null: false, default: 0
70
+ t.integer :credits_limit, null: false, default: 20
71
+ t.timestamps
72
+ end
73
+ add_index :pave_ai_quotas, [ :user_id, :user_type, :period ], unique: true
74
+
75
+ create_table :pave_ai_spend_logs do |t|
76
+ t.references :user, polymorphic: true, index: true
77
+ t.string :intent, null: false
78
+ t.string :spend_type, null: false
79
+ t.string :provider, null: false
80
+ t.integer :estimated_tokens
81
+ t.integer :actual_tokens
82
+ t.integer :estimated_cost_cents, default: 0
83
+ t.integer :actual_cost_cents, default: 0
84
+ t.boolean :approved, null: false, default: false
85
+ t.boolean :success, null: false, default: false
86
+ t.string :funding_source
87
+ t.string :denial_reason
88
+ t.public_send(metadata_column_type, :metadata, null: false, default: {})
89
+ t.datetime :created_at, null: false
90
+ end
91
+ add_index :pave_ai_spend_logs, :created_at
92
+ add_index :pave_ai_spend_logs, :intent
93
+ add_index :pave_ai_spend_logs, :provider
94
+ add_index :pave_ai_spend_logs, :approved
95
+ end
96
+
97
+ private
98
+
99
+ def metadata_column_type
100
+ connection.adapter_name.to_s.downcase.include?("postgres") ? :jsonb : :json
101
+ end
102
+ end
@@ -0,0 +1,5 @@
1
+ class AddBillableToPaveAiSpendLogs < ActiveRecord::Migration[8.0]
2
+ def change
3
+ add_reference :pave_ai_spend_logs, :billable, polymorphic: true, index: true
4
+ end
5
+ end