Module: Legion::LLM::API::Translators::OpenAIResponse

Extended by:
Legion::Logging::Helper
Defined in:
lib/legion/llm/api/translators/openai_response.rb

Constant Summary collapse

FINISH_REASON_MAP =
{
  'stop'           => 'stop',
  'length'         => 'length',
  'tool_calls'     => 'tool_calls',
  'content_filter' => 'content_filter'
}.freeze

Class Method Summary collapse

Class Method Details

.build_tool_calls(pipeline_response) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/legion/llm/api/translators/openai_response.rb', line 147

def build_tool_calls(pipeline_response)
  tools_data = pipeline_response.respond_to?(:tools) ? pipeline_response.tools : nil
  return [] unless tools_data.is_a?(Array) && !tools_data.empty?

  tools_data.each_with_index.filter_map do |tc, idx|
    name = tc.respond_to?(:name) ? tc.name : (tc[:name] || tc['name'])
    args = tc.respond_to?(:arguments) ? tc.arguments : (tc[:arguments] || tc['arguments'] || {})
    tc_id = tc.respond_to?(:id) ? tc.id : (tc[:id] || tc['id'] || "call_#{SecureRandom.hex(8)}")
    next unless name

    {
      id:       tc_id,
      type:     'function',
      index:    idx,
      function: {
        name:      name.to_s,
        arguments: args.is_a?(String) ? args : Legion::JSON.dump(args)
      }
    }
  end
end

.embedding_token_count(usage, input_text) ⇒ Object



183
184
185
186
187
188
189
190
191
# File 'lib/legion/llm/api/translators/openai_response.rb', line 183

def embedding_token_count(usage, input_text)
  usage_hash = usage.respond_to?(:key?) ? usage : {}
  token_count = usage_hash[:prompt_tokens] || usage_hash['prompt_tokens'] ||
                usage_hash[:input_tokens] || usage_hash['input_tokens'] ||
                usage_hash[:total_tokens] || usage_hash['total_tokens']
  return token_count.to_i if token_count

  input_text.to_s.split.size
end

.extract_token_count(tokens, key) ⇒ Object



173
174
175
176
177
178
179
180
181
# File 'lib/legion/llm/api/translators/openai_response.rb', line 173

def extract_token_count(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 }[key]
  return tokens.public_send(method_name) if method_name && tokens.respond_to?(method_name)

  nil
end

.format_chat_completion(pipeline_response, model:, request_id: nil) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/legion/llm/api/translators/openai_response.rb', line 23

def format_chat_completion(pipeline_response, model:, request_id: nil)
  request_id ||= SecureRandom.uuid
  routing = pipeline_response.routing || {}
  tokens = pipeline_response.tokens || {}
  raw_msg = pipeline_response.message
  content = raw_msg.is_a?(Hash) ? (raw_msg[:content] || raw_msg['content']) : raw_msg.to_s
  stop_reason = pipeline_response.stop&.dig(:reason)&.to_s
  tool_calls = build_tool_calls(pipeline_response)
  resolved_model = (routing[:model] || routing['model'] || model).to_s

  log.debug("[llm][translator][openai_response] action=format_chat_completion request_id=#{request_id} model=#{resolved_model}")

  finish_reason = tool_calls.empty? ? map_finish_reason(stop_reason) : 'tool_calls'

  message_body = { role: 'assistant', content: content }
  message_body[:tool_calls] = tool_calls unless tool_calls.empty?

  {
    id:      "chatcmpl-#{request_id.delete('-')}",
    object:  'chat.completion',
    created: Time.now.to_i,
    model:   resolved_model,
    choices: [
      {
        index:         0,
        message:       message_body,
        finish_reason: finish_reason
      }
    ],
    usage:   {
      prompt_tokens:     extract_token_count(tokens, :input),
      completion_tokens: extract_token_count(tokens, :output),
      total_tokens:      (extract_token_count(tokens, :input).to_i + extract_token_count(tokens, :output).to_i)
    }
  }
end

.format_embeddings(vector, model:, input_text:, usage: nil) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/legion/llm/api/translators/openai_response.rb', line 118

def format_embeddings(vector, model:, input_text:, usage: nil)
  tokens = embedding_token_count(usage, input_text)

  {
    object: 'list',
    data:   [
      {
        object:    'embedding',
        embedding: vector,
        index:     0
      }
    ],
    model:  model.to_s,
    usage:  {
      prompt_tokens: tokens,
      total_tokens:  tokens
    }
  }
end

.format_model_object(id, created: nil, owned_by: 'legion') ⇒ Object



138
139
140
141
142
143
144
145
# File 'lib/legion/llm/api/translators/openai_response.rb', line 138

def format_model_object(id, created: nil, owned_by: 'legion')
  {
    id:       id.to_s,
    object:   'model',
    created:  created || Time.now.to_i,
    owned_by: owned_by
  }
end

.format_stream_chunk(delta_text, model:, request_id:, finish_reason: nil) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/legion/llm/api/translators/openai_response.rb', line 60

def format_stream_chunk(delta_text, model:, request_id:, finish_reason: nil)
  choice = { index: 0, delta: {}, finish_reason: finish_reason }
  choice[:delta][:content] = delta_text if delta_text && !delta_text.empty?

  {
    id:      "chatcmpl-#{request_id.delete('-')}",
    object:  'chat.completion.chunk',
    created: Time.now.to_i,
    model:   model.to_s,
    choices: [choice]
  }
end

.format_stream_delta_chunk(delta, model:, request_id:, finish_reason: nil) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/legion/llm/api/translators/openai_response.rb', line 102

def format_stream_delta_chunk(delta, model:, request_id:, finish_reason: nil)
  {
    id:      "chatcmpl-#{request_id.delete('-')}",
    object:  'chat.completion.chunk',
    created: Time.now.to_i,
    model:   model.to_s,
    choices: [
      {
        index:         0,
        delta:         delta,
        finish_reason: finish_reason
      }
    ]
  }
end

.format_stream_tool_call_chunk(tool_call, model:, request_id:, index:) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/legion/llm/api/translators/openai_response.rb', line 73

def format_stream_tool_call_chunk(tool_call, model:, request_id:, index:)
  fn = tool_call.is_a?(Hash) ? (tool_call[:function] || tool_call['function'] || {}) : {}
  name = tool_call.respond_to?(:name) ? tool_call.name : (tool_call[:name] || tool_call['name'] || fn[:name] || fn['name'])
  args = if tool_call.respond_to?(:arguments)
           tool_call.arguments
         else
           tool_call[:arguments] || tool_call['arguments'] || fn[:arguments] || fn['arguments'] || {}
         end
  tc_id = tool_call.respond_to?(:id) ? tool_call.id : (tool_call[:id] || tool_call['id'] || "call_#{SecureRandom.hex(8)}")

  format_stream_delta_chunk(
    {
      tool_calls: [
        {
          index:    index,
          id:       tc_id,
          type:     'function',
          function: {
            name:      name.to_s,
            arguments: args.is_a?(String) ? args : Legion::JSON.dump(args)
          }
        }
      ]
    },
    model:      model,
    request_id: request_id
  )
end

.map_finish_reason(stop_reason) ⇒ Object



169
170
171
# File 'lib/legion/llm/api/translators/openai_response.rb', line 169

def map_finish_reason(stop_reason)
  FINISH_REASON_MAP.fetch(stop_reason.to_s, 'stop')
end