Module: Legion::Extensions::Llm::Ledger::Writers::OfficialRecordWriter
- Defined in:
- lib/legion/extensions/llm/ledger/writers/official_record_writer.rb
Class Method Summary collapse
- .billing(body) ⇒ Object
- .classification_level(body) ⇒ Object
- .contains_phi?(body) ⇒ Boolean
- .contains_pii?(body) ⇒ Boolean
- .correlation_id(body) ⇒ Object
- .cost_usd(body) ⇒ Object
- .deep_symbolize(value) ⇒ Object
- .find_or_create_conversation(db, body) ⇒ Object
- .find_or_create_metric(db, request, response, body) ⇒ Object
- .find_or_create_request(db, conversation, latest_message, body) ⇒ Object
- .find_or_create_response(db, request, response_message, body) ⇒ Object
- .find_or_create_response_message(db, conversation, request, body) ⇒ Object
- .find_or_create_user_message(db, conversation, body) ⇒ Object
- .finish_reason(body) ⇒ Object
- .insert_row(db, table, attributes, operation:) ⇒ Object
- .integer(value, default: 0) ⇒ Object
- .json_dump(value) ⇒ Object
- .link_response_message!(db, response_message, response) ⇒ Object
- .model_id(body) ⇒ Object
- .next_message_seq(db, conversation) ⇒ Object
- .operation(body) ⇒ Object
- .present?(value) ⇒ Boolean
- .provider(body) ⇒ Object
- .provider_instance(body) ⇒ Object
- .recorded_at(body) ⇒ Object
- .reference(body, *keys) ⇒ Object
- .request_content(body) ⇒ Object
- .request_payload(body) ⇒ Object
- .request_ref(body) ⇒ Object
- .response_content(body) ⇒ Object
- .stable_uuid(value) ⇒ Object
- .stringify_content(content) ⇒ Object
- .thinking_response(body) ⇒ Object
- .tier(body) ⇒ Object
- .tokens(body) ⇒ Object
- .visible_response(body) ⇒ Object
- .write_metering(payload) ⇒ Object
- .write_prompt(payload) ⇒ Object
Class Method Details
.billing(body) ⇒ Object
260 261 262 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 260 def billing(body) body[:billing] || body[:cost] || {} end |
.classification_level(body) ⇒ Object
304 305 306 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 304 def classification_level(body) body[:classification_level] || body.dig(:classification, :level) end |
.contains_phi?(body) ⇒ Boolean
308 309 310 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 308 def contains_phi?(body) body[:contains_phi] || body.dig(:classification, :contains_phi) || false end |
.contains_pii?(body) ⇒ Boolean
312 313 314 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 312 def contains_pii?(body) body[:contains_pii] || body.dig(:classification, :contains_pii) || false end |
.correlation_id(body) ⇒ Object
225 226 227 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 225 def correlation_id(body) reference(body, :correlation_id, :correlation_ref) || body.dig(:tracing, :correlation_id) end |
.cost_usd(body) ⇒ Object
264 265 266 267 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 264 def cost_usd(body) raw = body[:cost_usd] || body.dig(:cost, :estimated_usd) || body.dig(:cost, :usd) raw.to_f end |
.deep_symbolize(value) ⇒ Object
353 354 355 356 357 358 359 360 361 362 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 353 def deep_symbolize(value) case value when Hash value.each_with_object({}) { |(key, item), memo| memo[key.to_sym] = deep_symbolize(item) } when Array value.map { |item| deep_symbolize(item) } else value end end |
.find_or_create_conversation(db, body) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 52 def find_or_create_conversation(db, body) uuid = stable_uuid(reference(body, :conversation_id, :conversation_ref) || 'default-conversation') existing = db[:llm_conversations].where(uuid: uuid).first return existing if existing id = insert_row(db, :llm_conversations, { uuid: uuid, title: body[:title] || body[:conversation_title], classification_level: classification_level(body), contains_phi: contains_phi?(body), contains_pii: contains_pii?(body), retention_policy: body[:retention_policy] || 'default', expires_at: body[:expires_at], recorded_at: recorded_at(body), inserted_at: Time.now.utc, created_at: Time.now.utc, updated_at: Time.now.utc }, operation: 'official_record_writer.conversation') db[:llm_conversations][id: id] end |
.find_or_create_metric(db, request, response, body) ⇒ Object
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 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 179 def find_or_create_metric(db, request, response, body) metric_uuid = stable_uuid(reference(body, :message_id) || "metric:#{request_ref(body)}") existing = db[:llm_message_inference_metrics].where(uuid: metric_uuid).first return existing if existing token_values = tokens(body) id = insert_row(db, :llm_message_inference_metrics, { uuid: metric_uuid, message_inference_request_id: request[:id], message_inference_response_id: response[:id], provider: provider(body), model_key: model_id(body), tier: tier(body), input_tokens: token_values[:input_tokens], output_tokens: token_values[:output_tokens], thinking_tokens: token_values[:thinking_tokens], total_tokens: token_values[:total_tokens], latency_ms: integer(body[:latency_ms]), wall_clock_ms: integer(body[:wall_clock_ms]), cost_usd: cost_usd(body), currency: body[:currency] || 'USD', cost_center: billing(body)[:cost_center], budget_key: billing(body)[:budget_id] || billing(body)[:budget_key], recorded_at: recorded_at(body), inserted_at: Time.now.utc }, operation: 'official_record_writer.inference_metric') db[:llm_message_inference_metrics][id: id] end |
.find_or_create_request(db, conversation, latest_message, body) ⇒ Object
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 94 def find_or_create_request(db, conversation, , body) request_id = request_ref(body) existing = db[:llm_message_inference_requests].where(request_ref: request_id).first return existing if existing operation = operation(body) id = insert_row(db, :llm_message_inference_requests, { uuid: stable_uuid(request_id), conversation_id: conversation[:id], latest_message_id: [:id], caller_principal_id: body[:caller_principal_id], caller_identity_id: body[:caller_identity_id], runtime_caller_type: body[:caller_type], request_ref: request_id, correlation_ref: correlation_id(body), correlation_id: correlation_id(body), exchange_ref: body[:exchange_id], request_type: operation, operation: operation, idempotency_key: body[:idempotency_key] || request_id, status: 'responded', context_message_count: Array(body.dig(:request, :messages) || body[:messages]).size, request_capture_mode: 'full', request_json: json_dump(request_payload(body)), classification_level: classification_level(body), cost_center: billing(body)[:cost_center], budget_key: billing(body)[:budget_id] || billing(body)[:budget_key], requested_at: recorded_at(body), inserted_at: Time.now.utc }, operation: 'official_record_writer.inference_request') db[:llm_message_inference_requests][id: id] end |
.find_or_create_response(db, request, response_message, body) ⇒ Object
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 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 150 def find_or_create_response(db, request, , body) response_uuid = stable_uuid(reference(body, :provider_response_ref) || "response:#{request_ref(body)}") existing = db[:llm_message_inference_responses].where(uuid: response_uuid).first return existing if existing id = insert_row(db, :llm_message_inference_responses, { uuid: response_uuid, message_inference_request_id: request[:id], response_message_id: &.dig(:id), provider: provider(body), provider_instance: provider_instance(body), model_key: model_id(body), tier: tier(body), runner_ref: body[:worker_id] || body[:runner_ref], provider_response_ref: body[:provider_response_ref], status: body[:error] ? 'error' : 'success', finish_reason: finish_reason(body), latency_ms: integer(body[:latency_ms]), wall_clock_ms: integer(body[:wall_clock_ms]), response_capture_mode: 'full', response_json: json_dump(visible_response(body)), response_thinking_json: json_dump(thinking_response(body)), dispatch_path: body[:dispatch_path] || body[:tier], responded_at: recorded_at(body), inserted_at: Time.now.utc }, operation: 'official_record_writer.inference_response') db[:llm_message_inference_responses][id: id] end |
.find_or_create_response_message(db, conversation, request, body) ⇒ Object
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 127 def (db, conversation, request, body) uuid = stable_uuid(reference(body, :response_message_id) || "response-message:#{request_ref(body)}") existing = db[:llm_messages].where(uuid: uuid).first return existing if existing latest = db[:llm_messages][id: request[:latest_message_id]] id = insert_row(db, :llm_messages, { uuid: uuid, conversation_id: conversation[:id], parent_message_id: latest&.dig(:id), message_inference_request_id: request[:id], seq: (latest&.dig(:seq) || 1) + 1, role: 'assistant', content_type: 'text', content: response_content(body), input_tokens: 0, output_tokens: tokens(body)[:output_tokens], created_at: recorded_at(body), inserted_at: Time.now.utc }, operation: 'official_record_writer.response_message') db[:llm_messages][id: id] end |
.find_or_create_user_message(db, conversation, body) ⇒ Object
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 73 def (db, conversation, body) uuid = stable_uuid(reference(body, :message_id, :message_id_ctx) || "request-message:#{request_ref(body)}") existing = db[:llm_messages].where(uuid: uuid).first return existing if existing seq = body[:message_seq] ? integer(body[:message_seq]) : (db, conversation) id = insert_row(db, :llm_messages, { uuid: uuid, conversation_id: conversation[:id], seq: seq, role: 'user', content_type: 'text', content: request_content(body), input_tokens: tokens(body)[:input_tokens], output_tokens: 0, created_at: recorded_at(body), inserted_at: Time.now.utc }, operation: 'official_record_writer.user_message') db[:llm_messages][id: id] end |
.finish_reason(body) ⇒ Object
300 301 302 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 300 def finish_reason(body) body[:finish_reason] || body.dig(:response, :finish_reason) || body.dig(:response, :stop, :reason) end |
.insert_row(db, table, attributes, operation:) ⇒ Object
208 209 210 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 208 def insert_row(db, table, attributes, operation:) Helpers::PersistenceLogging.insert_row(db, table, attributes, operation: operation) end |
.integer(value, default: 0) ⇒ Object
336 337 338 339 340 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 336 def integer(value, default: 0) return default if value.nil? value.to_i end |
.json_dump(value) ⇒ Object
349 350 351 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 349 def json_dump(value) Helpers::Json.dump(value) end |
.link_response_message!(db, response_message, response) ⇒ Object
218 219 220 221 222 223 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 218 def (db, , response) return unless && response return if [:message_inference_response_id] == response[:id] db[:llm_messages].where(id: [:id]).update(message_inference_response_id: response[:id]) end |
.model_id(body) ⇒ Object
242 243 244 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 242 def model_id(body) body[:model_id] || body[:model_key] || body.dig(:routing, :model) end |
.next_message_seq(db, conversation) ⇒ Object
332 333 334 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 332 def (db, conversation) db[:llm_messages].where(conversation_id: conversation[:id]).max(:seq).to_i + 1 end |
.operation(body) ⇒ Object
229 230 231 232 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 229 def operation(body) (body[:operation] || body[:request_type] || body.dig(:routing, :operation) || body.dig(:headers, :'x-legion-llm-request-type') || 'chat').to_s end |
.present?(value) ⇒ Boolean
364 365 366 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 364 def present?(value) !value.nil? && !(value.respond_to?(:empty?) && value.empty?) end |
.provider(body) ⇒ Object
234 235 236 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 234 def provider(body) (body[:provider] || body.dig(:routing, :provider)).to_s end |
.provider_instance(body) ⇒ Object
238 239 240 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 238 def provider_instance(body) body[:provider_instance] || body.dig(:routing, :provider_instance) || body.dig(:routing, :instance) end |
.recorded_at(body) ⇒ Object
316 317 318 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 316 def recorded_at(body) body[:recorded_at] || body[:timestamp] || body.dig(:timestamps, :returned) || body.dig(:timestamps, :provider_end) || Time.now.utc end |
.reference(body, *keys) ⇒ Object
320 321 322 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 320 def reference(body, *keys) keys.lazy.map { |key| body[key] }.find { |value| present?(value) }&.to_s end |
.request_content(body) ⇒ Object
273 274 275 276 277 278 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 273 def request_content(body) = body.dig(:request, :messages) || body[:messages] = Array().reverse.find { |item| item[:role].to_s == 'user' } || Array().last content = &.dig(:content) || body[:prompt] || body[:text] stringify_content(content) end |
.request_payload(body) ⇒ Object
269 270 271 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 269 def request_payload(body) body[:request] || body[:messages] || {} end |
.request_ref(body) ⇒ Object
212 213 214 215 216 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 212 def request_ref(body) body[:__ledger_request_ref] ||= reference(body, :request_id, :request_ref) || correlation_id(body) || stable_uuid(SecureRandom.uuid) end |
.response_content(body) ⇒ Object
296 297 298 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 296 def response_content(body) stringify_content(visible_response(body)[:content] || visible_response(body).dig(:message, :content)) end |
.stable_uuid(value) ⇒ Object
324 325 326 327 328 329 330 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 324 def stable_uuid(value) raw = value.to_s return raw if raw.length <= 36 hex = Digest::SHA256.hexdigest(raw)[0, 32] "#{hex[0, 8]}-#{hex[8, 4]}-#{hex[12, 4]}-#{hex[16, 4]}-#{hex[20, 12]}" end |
.stringify_content(content) ⇒ Object
342 343 344 345 346 347 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 342 def stringify_content(content) return nil if content.nil? return content if content.is_a?(String) json_dump(content) end |
.thinking_response(body) ⇒ Object
288 289 290 291 292 293 294 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 288 def thinking_response(body) thinking = body[:response_thinking] || body[:thinking] || body.dig(:response, :thinking) return {} if thinking.nil? return { content: thinking } if thinking.is_a?(String) thinking end |
.tier(body) ⇒ Object
246 247 248 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 246 def tier(body) body[:tier] || body.dig(:routing, :tier) end |
.tokens(body) ⇒ Object
250 251 252 253 254 255 256 257 258 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 250 def tokens(body) raw = body[:tokens] || body input = integer(raw[:input_tokens] || raw[:input]) output = integer(raw[:output_tokens] || raw[:output]) thinking = integer(raw[:thinking_tokens] || raw[:thinking]) total = integer(raw[:total_tokens] || raw[:total], default: input + output + thinking) { input_tokens: input, output_tokens: output, thinking_tokens: thinking, total_tokens: total } end |
.visible_response(body) ⇒ Object
280 281 282 283 284 285 286 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 280 def visible_response(body) response = body[:response] || body[:response_content] || body[:content] || {} return { content: response } if response.is_a?(String) return { content: response[:content] } if response.is_a?(Hash) && response.key?(:content) response.is_a?(Hash) ? response.except(:thinking) : { content: response.to_s } end |
.write_metering(payload) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 35 def write_metering(payload) body = deep_symbolize(payload) db = ::Legion::Data.connection result = nil db.transaction do conversation = find_or_create_conversation(db, body) = (db, conversation, body) request = find_or_create_request(db, conversation, , body) response = find_or_create_response(db, request, nil, body) metric = find_or_create_metric(db, request, response, body) result = { result: :ok, request_id: request[:id], response_id: response[:id], metric_id: metric[:id] } end result end |
.write_prompt(payload) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/legion/extensions/llm/ledger/writers/official_record_writer.rb', line 16 def write_prompt(payload) body = deep_symbolize(payload) db = ::Legion::Data.connection result = nil db.transaction do conversation = find_or_create_conversation(db, body) = (db, conversation, body) request = find_or_create_request(db, conversation, , body) = (db, conversation, request, body) response = find_or_create_response(db, request, , body) (db, , response) metric = find_or_create_metric(db, request, response, body) result = { result: :ok, request_id: request[:id], response_id: response[:id], metric_id: metric[:id] } end result end |