Module: Legion::LLM::API::Native::Helpers
- Extended by:
- Legion::Logging::Helper
- Defined in:
- lib/legion/llm/api/native/helpers.rb
Class Method Summary collapse
-
.registered(app) ⇒ Object
rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity.
Class Method Details
.registered(app) ⇒ Object
rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
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 247 248 249 250 251 252 253 254 255 256 257 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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 |
# File 'lib/legion/llm/api/native/helpers.rb', line 177 def self.registered(app) # rubocop:disable Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity log.debug('[llm][api][helpers] registering shared helpers') app.helpers do # rubocop:disable Metrics/BlockLength include Legion::Logging::Helper include ::Legion::Cache::Helper unless method_defined?(:parse_request_body) define_method(:parse_request_body) do log.debug('[llm][api][helpers] parse_request_body action=parsing') raw = request.body.read return {} if raw.nil? || raw.empty? parsed = begin Legion::JSON.load(raw) rescue StandardError => e handle_exception(e, level: :warn, handled: true, operation: 'llm.api.parse_request_body') halt 400, { 'Content-Type' => 'application/json' }, Legion::JSON.dump({ error: { code: 'invalid_json', message: 'request body is not valid JSON' } }) end unless parsed.respond_to?(:transform_keys) halt 400, { 'Content-Type' => 'application/json' }, Legion::JSON.dump({ error: { code: 'invalid_request_body', message: 'request body must be a JSON object' } }) end parsed.transform_keys(&:to_sym) end end unless method_defined?(:validate_required!) define_method(:validate_required!) do |body, *keys| missing = keys.select { |k| body[k].nil? || (body[k].respond_to?(:empty?) && body[k].empty?) } return if missing.empty? log.debug("[llm][api][helpers] validate_required! missing=#{missing.join(',')}") halt 400, { 'Content-Type' => 'application/json' }, Legion::JSON.dump({ error: { code: 'missing_fields', message: "required: #{missing.join(', ')}" } }) end end unless method_defined?(:json_response) define_method(:json_response) do |data, status_code: 200| content_type :json status status_code Legion::JSON.dump({ data: data }) end end unless method_defined?(:json_error) define_method(:json_error) do |code, , status_code: 400| content_type :json status status_code Legion::JSON.dump({ error: { code: code, message: } }) end end unless method_defined?(:require_llm!) define_method(:require_llm!) do return if defined?(Legion::LLM) && Legion::LLM.respond_to?(:started?) && Legion::LLM.started? log.debug('[llm][api][helpers] require_llm! action=halting reason=not_started') halt 503, { 'Content-Type' => 'application/json' }, Legion::JSON.dump({ error: { code: 'llm_unavailable', message: 'LLM subsystem is not available' } }) end end unless method_defined?(:cache_available?) define_method(:cache_available?) do cache_connected? || local_cache_connected? end end unless method_defined?(:validate_tools!) define_method(:validate_tools!) do |tool_list| unless tool_list.is_a?(Array) && tool_list.all? { |t| t.respond_to?(:transform_keys) } halt 400, { 'Content-Type' => 'application/json' }, Legion::JSON.dump({ error: { code: 'invalid_tools', message: 'tools must be an array of objects' } }) end invalid = tool_list.any? do |t| ts = t.transform_keys(&:to_sym) ts[:name].to_s.empty? end return unless invalid halt 400, { 'Content-Type' => 'application/json' }, Legion::JSON.dump({ error: { code: 'invalid_tools', message: 'each tool must have a non-empty name' } }) end end unless method_defined?(:validate_messages!) define_method(:validate_messages!) do |msg_list| valid = msg_list.all? do |m| next false unless m.respond_to?(:key?) && m.respond_to?(:[]) role = m[:role] || m['role'] content_value = m[:content] || m['content'] !role.to_s.empty? && (m.key?(:content) || m.key?('content')) && !content_value.nil? && !(content_value.respond_to?(:empty?) && content_value.empty?) end return if valid halt 400, { 'Content-Type' => 'application/json' }, Legion::JSON.dump({ error: { code: 'invalid_messages', message: 'each message must be an object with non-empty role and content' } }) end end define_method(:build_client_tool_class) do |tname, tdesc, tschema| log.debug("[llm][api][helpers] build_client_tool_class name=#{tname}") Legion::LLM::Types::ToolDefinition.build( name: tname, description: tdesc, parameters: tschema || {}, source: { type: :client, executable: true } ) rescue StandardError => e handle_exception(e, level: :warn, handled: true, operation: "llm.api.build_client_tool_class.#{tname}") nil end define_method(:extract_tool_calls) do |pipeline_response| tools_data = pipeline_response.tools return [] unless tools_data.is_a?(Array) && !tools_data.empty? tools_data.map do |tc| { id: tc.respond_to?(:id) ? tc.id : (tc[:id] || tc['id']), name: tc.respond_to?(:name) ? tc.name : (tc[:name] || tc['name'] || tc.to_s), arguments: tc.respond_to?(:arguments) ? tc.arguments : (tc[:arguments] || tc['arguments'] || {}) } end end define_method(:extract_text_content) do |content| case content when nil '' when String content when Array content.filter_map { |entry| extract_text_content(entry) }.join when Hash type = content[:type] || content['type'] return '' unless type.nil? || type.to_s == 'text' text = content.key?(:text) || content.key?('text') ? (content[:text] || content['text']) : (content[:content] || content['content']) extract_text_content(text) else content.to_s end end define_method(:emit_sse_event) do |stream, event_name, payload| level = event_name == 'text-delta' ? :debug : :info log.send(level, "[sse][emit] event=#{event_name} keys=#{payload.is_a?(Hash) ? payload.keys.join(',') : 'n/a'}") stream << "event: #{event_name}\ndata: #{Legion::JSON.dump(payload)}\n\n" end define_method(:emit_timeline_tool_events) do |stream, pipeline_response, skip_tool_results: false| timeline = Array(pipeline_response.timeline) log.debug("[llm][api][helpers] emit_timeline_tool_events count=#{timeline.size} skip_tool_results=#{skip_tool_results}") timeline.each do |event| key = event[:key].to_s detail = event[:detail] data = event[:data].is_a?(Hash) ? event[:data] : {} name = key.split(':', 3).last next if name.to_s.empty? if key.start_with?('tool:result:') next if skip_tool_results event_name = data[:status].to_s == 'error' ? 'tool-error' : 'tool-result' emit_sse_event(stream, event_name, { toolCallId: data[:tool_call_id], toolName: name, result: data[:result] || detail, status: data[:status], timestamp: Time.now.utc.iso8601 }) elsif key.start_with?('tool:execute:') emit_sse_event(stream, 'tool-progress', { toolCallId: data[:tool_call_id], toolName: name, type: 'execution_complete', args: data[:arguments] || {}, source: data[:source], status: detail, timestamp: Time.now.utc.iso8601 }) end end end define_method(:identity_request_from_env) do |rack_env| return nil unless defined?(Legion::Identity::Request) return nil unless Legion::Identity::Request.respond_to?(:from_env) Legion::Identity::Request.from_env(rack_env) end define_method(:identity_canonical_name) do |rack_env| request_identity = identity_request_from_env(rack_env) name = request_identity&.canonical_name if request_identity.respond_to?(:canonical_name) return name if name && name.to_s != '' if defined?(Legion::Identity::Process) && Legion::Identity::Process.respond_to?(:canonical_name) process_name = Legion::Identity::Process.canonical_name return process_name if process_name && process_name.to_s != '' end raw = ENV.fetch('USER', nil) || ENV.fetch('LOGNAME', nil) || 'anonymous' raw.to_s.include?('@') ? raw.to_s.split('@').first : raw.to_s end define_method(:identity_caller_hash) do |rack_env| request_identity = identity_request_from_env(rack_env) if request_identity.respond_to?(:to_caller_hash) caller_hash = request_identity.to_caller_hash if caller_hash.is_a?(Hash) requested_by = caller_hash[:requested_by] || caller_hash['requested_by'] return { requested_by: requested_by } if requested_by end end { requested_by: { identity: identity_canonical_name(rack_env), type: :process, credential: :system } } end define_method(:build_server_caller) do |source:, path:, env:, caller_context: nil| normalized_caller = caller_context.respond_to?(:transform_keys) ? caller_context.transform_keys(&:to_sym) : {} safe_caller_fields = normalized_caller.slice(:context, :session_id, :trace_id) { source: source, path: path, requested_by: identity_caller_hash(env).fetch(:requested_by) }.merge(safe_caller_fields) end define_method(:token_value) do |tokens, key| return nil if tokens.nil? return tokens[key] || tokens[key.to_s] if tokens.is_a?(Hash) method_name = { input: :input_tokens, output: :output_tokens, total: :total_tokens }[key] return tokens.public_send(method_name) if method_name && tokens.respond_to?(method_name) nil end end log.debug('[llm][api][helpers] shared helpers registered') end |