Module: Legion::LLM::API::Translators::OpenAIRequest
- Extended by:
- Legion::Logging::Helper
- Defined in:
- lib/legion/llm/api/translators/openai_request.rb
Class Method Summary collapse
- .extract_content(content) ⇒ Object
- .extract_messages_and_system(raw_messages) ⇒ Object
- .normalize(body) ⇒ Object
- .normalize_tools(raw_tools) ⇒ Object
Class Method Details
.extract_content(content) ⇒ Object
56 57 58 59 60 61 62 63 64 |
# File 'lib/legion/llm/api/translators/openai_request.rb', line 56 def extract_content(content) return content if content.is_a?(String) return content unless content.is_a?(Array) content.filter_map do |block| b = block.respond_to?(:transform_keys) ? block.transform_keys(&:to_sym) : block b[:text] if b[:type].to_s == 'text' end.join end |
.extract_messages_and_system(raw_messages) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/legion/llm/api/translators/openai_request.rb', line 37 def () system_content = nil = [] .each do |msg| m = msg.respond_to?(:transform_keys) ? msg.transform_keys(&:to_sym) : msg role = m[:role].to_s if role == 'system' system_content = extract_content(m[:content]) log.debug('[llm][translator][openai_request] action=extracted_system') else << { role: role, content: extract_content(m[:content]) } end end [, system_content] end |
.normalize(body) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/legion/llm/api/translators/openai_request.rb', line 14 def normalize(body) log.debug('[llm][translator][openai_request] action=normalize') , system = (body[:messages] || body['messages'] || []) tools = normalize_tools(body[:tools] || body['tools']) model = body[:model] || body['model'] stream = body[:stream] || body['stream'] max_tokens = body[:max_tokens] || body['max_tokens'] temperature = body[:temperature] || body['temperature'] result = { messages: , model: model, stream: stream == true, max_tokens: max_tokens, temperature: temperature, tools: tools } result[:system] = system if system log.debug("[llm][translator][openai_request] action=normalized messages=#{.size} has_system=#{!system.nil?} tools=#{tools&.size || 0}") result.compact end |
.normalize_tools(raw_tools) ⇒ Object
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/legion/llm/api/translators/openai_request.rb', line 66 def normalize_tools(raw_tools) return nil if raw_tools.nil? || !raw_tools.is_a?(Array) || raw_tools.empty? raw_tools.filter_map do |tool| t = tool.respond_to?(:transform_keys) ? tool.transform_keys(&:to_sym) : tool next unless t[:type].to_s == 'function' fn = t[:function] fn = fn.transform_keys(&:to_sym) if fn.respond_to?(:transform_keys) next unless fn.is_a?(Hash) { name: fn[:name].to_s, description: fn[:description].to_s, parameters: fn[:parameters] || {} } end end |