Class: Legion::LLM::API::ClientTranslators::OpenAIChat

Inherits:
Object
  • Object
show all
Extended by:
Legion::Logging::Helper
Includes:
SharedExtractors, Legion::Logging::Helper
Defined in:
lib/legion/llm/api/client_translators/openai_chat.rb

Overview

OpenAI /v1/chat/completions client translator.

Per Phase 5: parse_request → Canonical::Request, format_response → chat.completion shape, format_error, events emitter for the chat completion SSE format (data: chunk\n\n + data: [DONE]).

Defined Under Namespace

Classes: Events

Constant Summary collapse

Canonical =
Legion::Extensions::Llm::Canonical
FINISH_REASON_MAP =

M7/N8: a provider :error stop is an error state, not a clean completion — it renders as 'error', never 'stop'. An absent or unmapped stop state surfaces the same way (see on_done / map_finish_reason): the client must be able to tell a provider-declared stop from a stop the daemon did not observe.

{
  end_turn:       'stop',
  tool_use:       'tool_calls',
  max_tokens:     'length',
  stop_sequence:  'stop',
  content_filter: 'content_filter',
  error:          'error',
  pause_turn:     'tool_calls'
}.freeze

Constants included from SharedExtractors

SharedExtractors::PARAM_SPELLINGS

Instance Method Summary collapse

Methods included from SharedExtractors

#apply_canonical_params_to_inference, #args_as_json_string, #args_as_object, #canonical_content_block, #canonical_image_block, #canonicalize_content_parts, #extract_content_text, #extract_thinking_text, #legion_routing_explicit_from_env, #legion_routing_from_env, #normalize_canonical_params, #normalize_response_format, #normalize_stop_sequences, #param_spelling, #text_content_type?, #token_value, #tool_fragment_field

Instance Method Details

#build_inference_request(canonical_request, request_id:, server_caller:, modality: nil) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
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
# File 'lib/legion/llm/api/client_translators/openai_chat.rb', line 82

def build_inference_request(canonical_request, request_id:, server_caller:, modality: nil)
  tool_defs = build_tool_definitions(canonical_request.tools)

  extra = {}
  tier = canonical_request.[:tier]
  cwd = canonical_request.[:cwd]
  extra[:tier] = tier.to_sym if tier
  extra[:cwd] = cwd if cwd
  routing_explicit = canonical_request.[:routing_explicit]
  extra[:routing_explicit] = routing_explicit if routing_explicit

   = { requested_tools: canonical_request.[:requested_tools] || [] }
  [:client_tool_passthrough] = canonical_request.[:client_tool_passthrough] unless canonical_request.[:client_tool_passthrough].nil?
  [:client_tool_request_count] = canonical_request.tools&.size if canonical_request.tools&.any?

  # N x N law: the executor receives canonical messages end-to-end.
  messages = canonical_request.messages
  request_kwargs = {
    id:              request_id,
    messages:        messages,
    system:          canonical_request.system,
    routing:         canonical_request.routing,
    # Body-model routing hint (SSOT v3 D19): the sole input to
    # BodyModelHintPolicy. The trusted X-Legion-Model pin in
    # `routing` supersedes it — RequestRequirements keeps that order.
    client_model:    canonical_request.[:client_model],
    tools:           tool_defs,
    tool_choice:     canonical_request.tool_choice,
    caller:          server_caller,
    conversation_id: canonical_request.conversation_id,
    metadata:        .compact,
    stream:          canonical_request.stream == true,
    modality:        modality,
    cache:           { strategy: :default, cacheable: true },
    extra:           extra.empty? ? {} : extra
  }

  apply_canonical_params_to_inference(request_kwargs, canonical_request.params)

  Legion::LLM::Inference::Request.build(**request_kwargs)
end

#events_emitter(out, request_id:, model:, conv_id: nil, include_reasoning: true) ⇒ Object



198
199
200
# File 'lib/legion/llm/api/client_translators/openai_chat.rb', line 198

def events_emitter(out, request_id:, model:, conv_id: nil, include_reasoning: true)
  Events.new(out: out, request_id: request_id, model: model.to_s, conv_id: conv_id, include_reasoning: include_reasoning)
end

#extract_tool_choice(raw) ⇒ Object

OpenAI chat-completions tool_choice shapes:

"auto" / "none" / "required"                       → sym
{type: 'function', function: {name: 'X'}}          → {type: 'function', name: 'X'}
{type: 'function', name: 'X'} (lenient passthrough)→ {type: 'function', name: 'X'}


128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/legion/llm/api/client_translators/openai_chat.rb', line 128

def extract_tool_choice(raw)
  return nil if raw.nil?

  case raw
  when Hash
    symbolized = raw.transform_keys(&:to_sym)
    type = symbolized[:type].to_s
    if type == 'function'
      fn = symbolized[:function].is_a?(Hash) ? symbolized[:function].transform_keys(&:to_sym) : nil
      name = symbolized[:name] || fn&.[](:name)
      return { type: :function, name: name.to_s } if name

      symbolized
    else
      %w[auto none required].include?(type) ? type.to_sym : symbolized
    end
  when String, Symbol
    raw.to_sym
  end
end

#format_chunk(canonical_chunk) ⇒ Object



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
# File 'lib/legion/llm/api/client_translators/openai_chat.rb', line 202

def format_chunk(canonical_chunk)
  return nil if canonical_chunk.nil?

  case canonical_chunk.type
  when :text_delta
    chunk_envelope({ content: canonical_chunk.delta.to_s })
  when :thinking_delta
    chunk_envelope({ reasoning_content: canonical_chunk.delta.to_s })
  when :tool_call_delta
    tc = canonical_chunk.tool_call
    args = tool_fragment_field(tc, :arguments) || {}
    chunk_envelope({
                     tool_calls: [{
                       index:    canonical_chunk.block_index || 0,
                       id:       tool_fragment_field(tc, :id),
                       type:     'function',
                       function: {
                         name:      tool_fragment_field(tc, :name).to_s,
                         arguments: args_as_json_string(args)
                       }
                     }]
                   })
  when :done
    # M7/N8: the done chunk carries the provider's stop_reason —
    # map it with the same policy as the streaming/sync edges
    # (absent/unmapped → 'error', never a fabricated 'stop').
    finish_reason = FINISH_REASON_MAP[canonical_chunk.stop_reason] || 'error'
    { object: 'chat.completion.chunk', choices: [{ index: 0, delta: {}, finish_reason: finish_reason }] }
  end
end

#format_error(error, status_code: 500, type: 'server_error', code: nil) ⇒ Object



192
193
194
195
196
# File 'lib/legion/llm/api/client_translators/openai_chat.rb', line 192

def format_error(error, status_code: 500, type: 'server_error', code: nil)
  body = { error: { message: error.respond_to?(:message) ? error.message : error.to_s, type: type } }
  body[:error][:code] = code if code
  [status_code, body]
end

#format_response(pipeline_response, model:, request_id:, include_reasoning: false) ⇒ Object



149
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
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/legion/llm/api/client_translators/openai_chat.rb', line 149

def format_response(pipeline_response, model:, request_id:, include_reasoning: false)
  request_id ||= SecureRandom.uuid
  routing = pipeline_response.respond_to?(:routing) ? pipeline_response.routing || {} : {}
  tokens = pipeline_response.respond_to?(:tokens) ? pipeline_response.tokens || {} : {}
  raw_msg = pipeline_response.respond_to?(:message) ? pipeline_response.message : nil
  content = extract_content_text(raw_msg)
  content = server_tool_results_text(pipeline_response) if content.empty?
  stop_reason = pipeline_response.respond_to?(:stop) ? pipeline_response.stop&.dig(:reason)&.to_s : nil

  actionable_tool_calls = build_tool_calls(pipeline_response)
  resolved_model = (routing[:model] || routing['model'] || model).to_s

  # G24 — server-executed tools are not actionable. When all tool
  # calls were server-resolved, finish_reason is 'stop' (not
  # 'tool_calls') and the model's text content is the only
  # client-visible turn. The server-resolved exchange is recorded
  # in the conversation history (via the executor's tool loop),
  # not on this response.
  finish_reason = actionable_tool_calls.empty? ? map_finish_reason(stop_reason) : 'tool_calls'

  content = nil if actionable_tool_calls.any? && content_looks_like_tool_json?(content)

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

  if include_reasoning && pipeline_response.respond_to?(:thinking) && pipeline_response.thinking
    text = extract_thinking_text(pipeline_response.thinking)
    message_body[:reasoning_content] = text unless text.empty?
  end

  input = token_value(tokens, :input, :input_tokens).to_i
  output = token_value(tokens, :output, :output_tokens).to_i

  {
    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: input, completion_tokens: output, total_tokens: input + output }
  }
end

#g24_formatObject

G24 — declares which execution-proxy contract shape this translator surfaces. Consumed by the lex-llm conformance shared examples.



44
45
46
# File 'lib/legion/llm/api/client_translators/openai_chat.rb', line 44

def g24_format
  :openai_chat
end

#parse_request(body, env = {}) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/legion/llm/api/client_translators/openai_chat.rb', line 48

def parse_request(body, env = {})
  log.debug('[llm][client_translator][openai_chat] action=parse_request')
  body = symbolize(body)

  messages, system = extract_messages_and_system(body[:messages] || [])
  tools = build_tools(body[:tools])
  params = extract_params(body)
  tool_choice = extract_tool_choice(body[:tool_choice])
  external = external_refs(body, env)

  Canonical::Request.build(
    id:              body[:request_id] || env['HTTP_X_CLIENT_REQUEST_ID'] || SecureRandom.uuid,
    messages:        messages,
    system:          system,
    tools:           tools,
    tool_choice:     tool_choice,
    params:          params,
    stream:          body[:stream] == true,
    conversation_id: env['HTTP_X_LEGION_CONVERSATION_ID'] || body[:conversation_id],
    routing:         legion_routing_from_env(env),
    metadata:        {
      client_model:            body[:model],
      tier:                    env['HTTP_X_LEGION_TIER'] || body[:tier],
      routing_explicit:        legion_routing_explicit_from_env(env),
      cwd:                     env['HTTP_X_LEGION_CWD'] || body[:cwd],
      requested_tools:         body[:requested_tools] || [],
      client_tool_passthrough: extract_client_tool_passthrough(body, env),
      caller_context:          body[:caller],
      include_reasoning:       body[:include_reasoning] != false && body[:include_thinking] != false,
      external_refs:           external
    }.compact
  )
end