Class: Legion::LLM::API::ClientTranslators::OpenAIResponses
- Inherits:
-
Object
- Object
- Legion::LLM::API::ClientTranslators::OpenAIResponses
- Extended by:
- Legion::Logging::Helper
- Includes:
- SharedExtractors, Legion::Logging::Helper
- Defined in:
- lib/legion/llm/api/client_translators/openai_responses.rb
Overview
OpenAI /v1/responses (Responses API) client translator.
Per Phase 5:
- parse_request(body, env) -> Canonical::Request (handles
input/instructions/reasoning/tools shapes specific to /v1/responses)
- format_response(canonical_or_pipeline_response) -> Hash with output[]
containing {thinking, function_call, message} items
- format_error(error, status_code:, type:)
- events_emitter(out, ...) -> Events emitter conforming to the
StreamAssembler contract.
Defined Under Namespace
Classes: Events
Constant Summary collapse
- Canonical =
Legion::Extensions::Llm::Canonical
Constants included from SharedExtractors
SharedExtractors::PARAM_SPELLINGS
Instance Method Summary collapse
- #build_inference_request(canonical_request, request_id:, server_caller:, modality: nil) ⇒ Object
-
#build_tool_choice(raw) ⇒ Object
OpenAI Responses tool_choice shapes: "auto" / "none" / "required" → corresponding sym 'function', name: 'X' → 'function', name: 'X' 'function', function: {name:} → flatten to 'function', name: 'X'.
-
#ensure_reasoning_summary(body) ⇒ Object
When the caller asks for reasoning (
reasoning.effortset) but didn't pin a summary mode, default tosummary: 'auto'. - #events_emitter(out, request_id:, model:, conv_id: nil) ⇒ Object
-
#format_chunk(canonical_chunk) ⇒ Object
Format a single Canonical::Chunk to a /v1/responses SSE event hash.
- #format_error(error, status_code: 500, type: 'server_error') ⇒ Object
- #format_response(pipeline_response, model:, request_id:) ⇒ Object
-
#format_response_status(pipeline_response) ⇒ Object
One stop-state → Responses status policy (M7).
-
#format_tool_call_delta_chunk(canonical_chunk) ⇒ Object
G24 — server-executed tool chunks surface as completed function_call output items so the client sees the call name AND result inline.
-
#g24_format ⇒ Object
G24 — declares which execution-proxy contract shape this translator surfaces.
- #parse_request(body, env = {}) ⇒ Object
- #server_tool_chunk?(tool_call) ⇒ Boolean
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
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 123 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 85 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] extra[:tier] = tier.to_sym if tier routing_explicit = canonical_request.[:routing_explicit] extra[:routing_explicit] = routing_explicit if routing_explicit # N x N law: the executor receives canonical messages end-to-end. = canonical_request. request_kwargs = { id: request_id, 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, stream: canonical_request.stream == true, modality: modality, # N2: shared execution carries the canonical Thinking::Config # (or nil) — the client dialect is re-shaped by the PROVIDER # translator at the provider edge, never in the pipeline. thinking: canonical_request.thinking, cache: { strategy: :default, cacheable: true }, extra: extra, metadata: canonical_request. } apply_canonical_params_to_inference(request_kwargs, canonical_request.params) Legion::LLM::Inference::Request.build(**request_kwargs) end |
#build_tool_choice(raw) ⇒ Object
OpenAI Responses tool_choice shapes:
"auto" / "none" / "required" → corresponding sym
{type: 'function', name: 'X'} → {type: 'function', name: 'X'}
{type: 'function', function: {name:}} → flatten to {type: 'function', name: 'X'}
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 129 def build_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 any].include?(type) ? type.to_sym : symbolized end when String, Symbol raw.to_sym end end |
#ensure_reasoning_summary(body) ⇒ Object
When the caller asks for reasoning (reasoning.effort set) but
didn't pin a summary mode, default to summary: 'auto'. OpenAI's
/v1/responses lane omits reasoning summary content unless the
request opts in — without this, codex→openai cells return only
the message item (no reasoning), and the e2e validator
reports "reasoning never produced" (P5-final-cells.md B3).
74 75 76 77 78 79 80 81 82 83 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 74 def ensure_reasoning_summary(body) reasoning = body[:reasoning] return body unless reasoning.is_a?(Hash) normalized = reasoning.transform_keys { |k| k.respond_to?(:to_sym) ? k.to_sym : k } return body.merge(reasoning: normalized) if normalized.key?(:summary) return body unless normalized[:effort] body.merge(reasoning: normalized.merge(summary: 'auto')) end |
#events_emitter(out, request_id:, model:, conv_id: nil) ⇒ Object
214 215 216 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 214 def events_emitter(out, request_id:, model:, conv_id: nil) Events.new(out: out, request_id: request_id, model: model.to_s, conv_id: conv_id) end |
#format_chunk(canonical_chunk) ⇒ Object
Format a single Canonical::Chunk to a /v1/responses SSE event hash.
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 219 def format_chunk(canonical_chunk) return nil if canonical_chunk.nil? case canonical_chunk.type when :text_delta { type: 'response.output_text.delta', delta: extract_content_text(canonical_chunk.delta), output_index: canonical_chunk.block_index || 0 } when :thinking_delta { type: 'response.thinking.delta', delta: canonical_chunk.delta.to_s, output_index: canonical_chunk.block_index || 0 } when :tool_call_delta format_tool_call_delta_chunk(canonical_chunk) when :done { type: 'response.completed' } end end |
#format_error(error, status_code: 500, type: 'server_error') ⇒ Object
210 211 212 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 210 def format_error(error, status_code: 500, type: 'server_error') [status_code, { error: { message: error.respond_to?(:message) ? error. : error.to_s, type: type } }] end |
#format_response(pipeline_response, model:, request_id:) ⇒ 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 150 def format_response(pipeline_response, model:, request_id:) 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. : nil content = extract_content_text(raw_msg) resolved_model = (routing[:model] || routing['model'] || model).to_s actionable_tool_calls = build_output_tool_calls(pipeline_response) server_tool_items = build_output_server_tool_items(pipeline_response) reasoning = build_output_reasoning(pipeline_response) output = [*reasoning, *server_tool_items, *actionable_tool_calls] unless content.to_s.strip.empty? && (actionable_tool_calls.any? || server_tool_items.any?) output << { type: 'message', id: "msg_#{SecureRandom.hex(12)}", role: 'assistant', content: [{ type: 'output_text', text: content }], status: 'completed' } end # M7: the response status is the stop state's dialect rendering — # a provider-declared completion stop is 'completed', an explicit # truncation (max_tokens) is 'incomplete', and an :error or an # absent/unmapped stop state is 'failed'. Never a hardcoded # 'completed': the client must be able to tell a clean turn from # a turn the daemon could not confirm completed. (Output items # that did complete keep their own 'completed' item status — the # response-level status is the turn's state.) Client-callable # calls and LegionIO-run results ride in output[]; requires_action # / action_required are Assistants API concepts that real # Responses clients (Codex) reject. { id: request_id, object: 'response', created_at: Time.now.to_i, model: resolved_model, output: output, usage: build_usage(tokens), status: format_response_status(pipeline_response) } end |
#format_response_status(pipeline_response) ⇒ Object
One stop-state → Responses status policy (M7). The envelope's stop member is the { reason: } Hash (G3: one shape); the reason is the canonical stop enum or nil (absent).
197 198 199 200 201 202 203 204 205 206 207 208 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 197 def format_response_status(pipeline_response) stop = pipeline_response.respond_to?(:stop) ? pipeline_response.stop : nil reason = stop.is_a?(Hash) ? (stop[:reason] || stop['reason']) : nil case reason&.to_sym when :max_tokens 'incomplete' when :end_turn, :stop_sequence, :tool_use, :pause_turn, :content_filter 'completed' else 'failed' end end |
#format_tool_call_delta_chunk(canonical_chunk) ⇒ Object
G24 — server-executed tool chunks surface as completed function_call output items so the client sees the call name AND result inline. Plain client-callable chunks remain plain function_call_arguments.delta events.
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 240 def format_tool_call_delta_chunk(canonical_chunk) tc = canonical_chunk.tool_call args = tool_fragment_field(tc, :arguments) || {} output_index = canonical_chunk.block_index || 0 if server_tool_chunk?(tc) { type: 'response.output_item.done', output_index: output_index, item: { type: 'function_call', id: "fc_#{SecureRandom.hex(12)}", call_id: tool_fragment_field(tc, :id), name: tool_fragment_field(tc, :name).to_s, arguments: args_as_json_string(args), status: 'completed' } } else { type: 'response.function_call_arguments.delta', output_index: output_index, delta: args_as_json_string(args) } end end |
#g24_format ⇒ Object
G24 — declares which execution-proxy contract shape this translator surfaces. Consumed by the lex-llm conformance shared examples.
34 35 36 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 34 def g24_format :openai_responses end |
#parse_request(body, env = {}) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 38 def parse_request(body, env = {}) log.debug('[llm][client_translator][openai_responses] action=parse_request') body = symbolize(body) system, = (body[:input], body[:instructions]) tools = build_tools(body[:tools]) params = build_params(body) thinking = build_thinking(body[:reasoning]) tool_choice = build_tool_choice(body[:tool_choice]) Canonical::Request.build( id: env['HTTP_X_CLIENT_REQUEST_ID'] || "resp_#{SecureRandom.hex(16)}", system: system, messages: , tools: tools, tool_choice: tool_choice, params: params, thinking: thinking, stream: body[:stream] == true, conversation_id: env['HTTP_X_LEGION_CONVERSATION_ID'] || env['HTTP_THREAD_ID'] || body[:conversation], routing: legion_routing_from_env(env), metadata: { client_model: body[:model], tier: env['HTTP_X_LEGION_TIER'], routing_explicit: legion_routing_explicit_from_env(env), external_refs: external_refs(body, env) }.compact ) end |
#server_tool_chunk?(tool_call) ⇒ Boolean
265 266 267 268 269 270 271 272 273 |
# File 'lib/legion/llm/api/client_translators/openai_responses.rb', line 265 def server_tool_chunk?(tool_call) # The chunk fragment's source is the closed dispatch-type enum # (R4 fragment contract) — server-executed tools are the # registry/special/extension/mcp set (G24). source = tool_fragment_field(tool_call, :source) return false if source.nil? %i[special registry extension mcp].include?(source.to_sym) end |