Module: Kward::ModelStreamParser
- Defined in:
- lib/kward/model/stream_parser.rb
Overview
Parses streaming provider responses into Kward assistant messages.
ModelStreamParser is intentionally provider-shape focused and side-effect
light: it accumulates assistant text, reasoning summaries, tool calls, and
normalized usage from SSE events. Network IO, retries, credentials, and
telemetry stay in Client; frontend rendering stays in CLI/RPC event
handlers. Keep parser methods deterministic and easy to unit test with raw
response bodies.
Class Method Summary collapse
- .active_codex_item(state) ⇒ Object
- .active_or_known_codex_item(state, item) ⇒ Object
- .anthropic_sse_error(data, request_error_class: nil) ⇒ Object
- .anthropic_sse_message(state) ⇒ Object
- .anthropic_sse_state ⇒ Object
- .anthropic_tool_call(block_data) ⇒ Object
- .append_codex_raw_reasoning_text(state, text, on_reasoning_delta: nil) ⇒ Object
- .append_codex_reasoning_text(state, text, on_reasoning_delta: nil) ⇒ Object
- .codex_content_part_added(state, part) ⇒ Object
- .codex_item_has_stable_key?(item) ⇒ Boolean
- .codex_item_key(item) ⇒ Object
- .codex_message_phase(item) ⇒ Object
- .codex_output_item_added(state, item) ⇒ Object
- .codex_output_item_done(state, item, on_assistant_delta: nil, on_reasoning_delta: nil) ⇒ Object
- .codex_output_text_delta(state, delta, on_assistant_delta: nil) ⇒ Object
- .codex_raw_reasoning_delta(state, delta, on_reasoning_delta: nil) ⇒ Object
- .codex_raw_reasoning_done(state, text, on_reasoning_delta: nil) ⇒ Object
- .codex_reasoning_delta(state, delta, on_reasoning_delta: nil) ⇒ Object
- .codex_reasoning_part_done(state, on_reasoning_delta: nil) ⇒ Object
- .codex_reasoning_summary_part_added(state, part) ⇒ Object
- .codex_response_items(state) ⇒ Object
- .codex_sse_error(event, request_error_class: nil) ⇒ Object
- .codex_sse_message(state) ⇒ Object
- .codex_sse_state(show_raw_reasoning: false) ⇒ Object
- .codex_streamable_message_item?(item) ⇒ Boolean
- .codex_tool_arguments_delta(state, delta) ⇒ Object
- .codex_tool_arguments_done(state, arguments) ⇒ Object
- .codex_tool_call(item) ⇒ Object
- .codex_visible_content(state) ⇒ Object
- .codex_visible_reasoning_item(state, item) ⇒ Object
- .collect_codex_item_output(state, item, on_assistant_delta: nil, on_reasoning_delta: nil) ⇒ Object
- .compact_blank_codex_reasoning_lines(text) ⇒ Object
- .compact_codex_reasoning_delta_spacing(existing, text) ⇒ Object
- .deep_dup(value) ⇒ Object
- .deep_dup_hash(hash) ⇒ Object
- .finalized_streaming_tool_calls(tool_calls) ⇒ Object
- .flush_codex_reasoning_delta(state, on_reasoning_delta: nil) ⇒ Object
- .from_claude_code_tool_name(name) ⇒ Object
- .merge_codex_item(existing, update) ⇒ Object
- .merge_streaming_tool_call(tool_calls, delta) ⇒ Object
- .parse_anthropic_sse_stream(response, on_reasoning_delta: nil, on_assistant_delta: nil, cancellation: nil, usage_normalizer: nil, request_error_class: nil) ⇒ Object
- .parse_codex_sse(body, on_reasoning_delta: nil, on_assistant_delta: nil, show_raw_reasoning: false, usage_normalizer: nil, request_error_class: nil) ⇒ Object
-
.parse_codex_sse_stream(response, on_reasoning_delta: nil, on_assistant_delta: nil, cancellation: nil, show_raw_reasoning: false, usage_normalizer: nil, request_error_class: nil) ⇒ Object
Incrementally parses a Codex/Responses SSE HTTP response body.
- .parse_openai_chat_sse(body, on_assistant_delta: nil, usage_normalizer: nil) ⇒ Object
- .process_anthropic_sse_block(block, state, on_reasoning_delta: nil, on_assistant_delta: nil, usage_normalizer: nil, request_error_class: nil) ⇒ Object
- .process_codex_sse_block(block, state, on_reasoning_delta: nil, on_assistant_delta: nil, usage_normalizer: nil, request_error_class: nil) ⇒ Object
- .raw_reasoning_from_codex_items(items) ⇒ Object
- .reasoning_summary_from_codex_items(items) ⇒ Object
- .remember_codex_item(state, item) ⇒ Object
- .sanitize_codex_reasoning_summary_item(item) ⇒ Object
- .sanitize_codex_reasoning_text(text, keep_incomplete_comment: false) ⇒ Object
- .split_trailing_comment_prefix(text) ⇒ Object
- .text_from_codex_items(items) ⇒ Object
- .visible_codex_message_items(items, tool_calls: []) ⇒ Object
- .visible_codex_reasoning_delta(state, delta) ⇒ Object
Class Method Details
.active_codex_item(state) ⇒ Object
584 585 586 587 |
# File 'lib/kward/model/stream_parser.rb', line 584 def active_codex_item(state) key = state[:active_item_id] key ? state[:items_by_id][key] : nil end |
.active_or_known_codex_item(state, item) ⇒ Object
569 570 571 572 573 574 575 576 577 578 |
# File 'lib/kward/model/stream_parser.rb', line 569 def active_or_known_codex_item(state, item) key = codex_item_key(item) known = state[:items_by_id][key] return known if known active = active_codex_item(state) return active if active && (!codex_item_has_stable_key?(item) || codex_item_key(active) == key) nil end |
.anthropic_sse_error(data, request_error_class: nil) ⇒ Object
159 160 161 162 163 164 165 |
# File 'lib/kward/model/stream_parser.rb', line 159 def anthropic_sse_error(data, request_error_class: nil) if request_error_class request_error_class.new(provider: "Anthropic", code: 400, body: data) else data end end |
.anthropic_sse_message(state) ⇒ Object
181 182 183 184 185 186 187 |
# File 'lib/kward/model/stream_parser.rb', line 181 def (state) = { "role" => "assistant", "content" => state[:content] } ["reasoning_summary"] = state[:reasoning_summary] unless state[:reasoning_summary].empty? ["tool_calls"] = state[:tool_calls] unless state[:tool_calls].empty? ["usage"] = state[:usage] if state[:usage] end |
.anthropic_sse_state ⇒ Object
106 107 108 |
# File 'lib/kward/model/stream_parser.rb', line 106 def anthropic_sse_state { content: +"", reasoning_summary: +"", blocks: {}, tool_calls: [], usage: nil } end |
.anthropic_tool_call(block_data) ⇒ Object
167 168 169 170 171 172 173 174 175 176 177 178 179 |
# File 'lib/kward/model/stream_parser.rb', line 167 def anthropic_tool_call(block_data) return nil unless block_data.is_a?(Hash) && block_data["type"] == "tool_use" name = from_claude_code_tool_name(block_data["name"]) arguments = block_data["partial_json"].to_s arguments = JSON.dump(block_data["input"] || {}) if arguments.empty? arguments = "{}" if arguments.empty? { "id" => block_data["id"] || "call_#{name}", "type" => "function", "function" => { "name" => name, "arguments" => arguments } } end |
.append_codex_raw_reasoning_text(state, text, on_reasoning_delta: nil) ⇒ Object
420 421 422 423 424 425 426 427 |
# File 'lib/kward/model/stream_parser.rb', line 420 def append_codex_raw_reasoning_text(state, text, on_reasoning_delta: nil) text = compact_codex_reasoning_delta_spacing(state[:reasoning_summary], text) return if text.empty? state[:raw_reasoning_visible] << text state[:reasoning_summary] << text on_reasoning_delta&.call(text) end |
.append_codex_reasoning_text(state, text, on_reasoning_delta: nil) ⇒ Object
406 407 408 409 410 411 412 413 414 415 416 417 418 |
# File 'lib/kward/model/stream_parser.rb', line 406 def append_codex_reasoning_text(state, text, on_reasoning_delta: nil) text = compact_codex_reasoning_delta_spacing(state[:reasoning_summary], text) return if text.empty? item = active_codex_item(state) if item&.fetch("type", nil) == "reasoning" item["summary"] ||= [] item["summary"] << { "type" => "summary_text", "text" => +"" } if item["summary"].empty? item["summary"].last["text"] = item["summary"].last["text"].to_s + text end state[:reasoning_summary] << text on_reasoning_delta&.call(text) end |
.codex_content_part_added(state, part) ⇒ Object
313 314 315 316 317 318 319 320 321 |
# File 'lib/kward/model/stream_parser.rb', line 313 def codex_content_part_added(state, part) item = active_codex_item(state) return unless item&.fetch("type", nil) == "message" && part.is_a?(Hash) return unless ["output_text", "text", "refusal"].include?(part["type"]) item["content"] ||= [] item["content"] << deep_dup_hash(part) state[:current_text_content_part] = item["content"].last end |
.codex_item_has_stable_key?(item) ⇒ Boolean
580 581 582 |
# File 'lib/kward/model/stream_parser.rb', line 580 def codex_item_has_stable_key?(item) item.key?("id") || item.key?("call_id") end |
.codex_item_key(item) ⇒ Object
600 601 602 |
# File 'lib/kward/model/stream_parser.rb', line 600 def codex_item_key(item) item["id"] || item["call_id"] || "item_#{item.object_id}" end |
.codex_message_phase(item) ⇒ Object
675 676 677 |
# File 'lib/kward/model/stream_parser.rb', line 675 def (item) item["phase"].to_s end |
.codex_output_item_added(state, item) ⇒ Object
301 302 303 304 305 306 307 308 309 310 311 |
# File 'lib/kward/model/stream_parser.rb', line 301 def codex_output_item_added(state, item) return unless item.is_a?(Hash) item = deep_dup_hash(item) item["content"] = [] if item["type"] == "message" && !item["content"].is_a?(Array) item["summary"] = [] if item["type"] == "reasoning" && !item["summary"].is_a?(Array) remember_codex_item(state, item) state[:active_item_id] = codex_item_key(item) state[:current_text_content_part] = nil state[:current_reasoning_content_part] = nil end |
.codex_output_item_done(state, item, on_assistant_delta: nil, on_reasoning_delta: nil) ⇒ Object
505 506 507 508 509 510 511 512 513 514 515 |
# File 'lib/kward/model/stream_parser.rb', line 505 def codex_output_item_done(state, item, on_assistant_delta: nil, on_reasoning_delta: nil) return unless item.is_a?(Hash) item = merge_codex_item(active_or_known_codex_item(state, item), item) item = codex_visible_reasoning_item(state, item) remember_codex_item(state, item) collect_codex_item_output(state, item, on_assistant_delta: on_assistant_delta, on_reasoning_delta: on_reasoning_delta) state[:active_item_id] = nil if state[:active_item_id] == codex_item_key(item) state[:current_text_content_part] = nil state[:current_reasoning_content_part] = nil end |
.codex_output_text_delta(state, delta, on_assistant_delta: nil) ⇒ Object
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
# File 'lib/kward/model/stream_parser.rb', line 323 def codex_output_text_delta(state, delta, on_assistant_delta: nil) text = delta.to_s return if text.empty? item = active_codex_item(state) if item&.fetch("type", nil) == "message" item["content"] ||= [{ "type" => "output_text", "text" => +"" }] part = state[:current_text_content_part] || item["content"].last part = item["content"].last unless part.is_a?(Hash) part["type"] ||= "output_text" text_key = part["type"] == "refusal" ? "refusal" : "text" part[text_key] = part[text_key].to_s + text end state[:raw_content] << text end |
.codex_raw_reasoning_delta(state, delta, on_reasoning_delta: nil) ⇒ Object
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 |
# File 'lib/kward/model/stream_parser.rb', line 355 def codex_raw_reasoning_delta(state, delta, on_reasoning_delta: nil) text = delta.to_s return if text.empty? item = active_codex_item(state) if item&.fetch("type", nil) == "reasoning" && state[:show_raw_reasoning] item["content"] ||= [{ "type" => "reasoning_text", "text" => +"" }] part = state[:current_reasoning_content_part] || item["content"].last part = item["content"].last unless part.is_a?(Hash) part["type"] ||= "reasoning_text" part["text"] = part["text"].to_s + text state[:current_reasoning_content_part] = part end return unless state[:show_raw_reasoning] visible = visible_codex_reasoning_delta(state, text) append_codex_raw_reasoning_text(state, visible, on_reasoning_delta: on_reasoning_delta) unless visible.empty? end |
.codex_raw_reasoning_done(state, text, on_reasoning_delta: nil) ⇒ Object
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 |
# File 'lib/kward/model/stream_parser.rb', line 374 def codex_raw_reasoning_done(state, text, on_reasoning_delta: nil) item = active_codex_item(state) full_text = text.to_s if item&.fetch("type", nil) == "reasoning" && state[:show_raw_reasoning] item["content"] ||= [{ "type" => "reasoning_text", "text" => +"" }] part = state[:current_reasoning_content_part] || item["content"].last part = item["content"].last unless part.is_a?(Hash) part["type"] ||= "reasoning_text" part["text"] = full_text state[:current_reasoning_content_part] = part end return unless state[:show_raw_reasoning] flush_codex_reasoning_delta(state, on_reasoning_delta: on_reasoning_delta) visible = sanitize_codex_reasoning_text(full_text) emitted = state[:raw_reasoning_visible] text = visible.start_with?(emitted) ? visible[emitted.length..].to_s : (emitted.empty? ? visible : +"") append_codex_raw_reasoning_text(state, text, on_reasoning_delta: on_reasoning_delta) unless text.empty? end |
.codex_reasoning_delta(state, delta, on_reasoning_delta: nil) ⇒ Object
348 349 350 351 352 353 |
# File 'lib/kward/model/stream_parser.rb', line 348 def codex_reasoning_delta(state, delta, on_reasoning_delta: nil) text = visible_codex_reasoning_delta(state, delta) return if text.empty? append_codex_reasoning_text(state, text, on_reasoning_delta: on_reasoning_delta) end |
.codex_reasoning_part_done(state, on_reasoning_delta: nil) ⇒ Object
394 395 396 397 398 399 400 401 402 403 404 |
# File 'lib/kward/model/stream_parser.rb', line 394 def codex_reasoning_part_done(state, on_reasoning_delta: nil) item = active_codex_item(state) return unless item&.fetch("type", nil) == "reasoning" return if item["summary"].to_a.empty? flush_codex_reasoning_delta(state, on_reasoning_delta: on_reasoning_delta) text = "\n\n" item["summary"].last["text"] = item["summary"].last["text"].to_s + text state[:reasoning_summary] << text on_reasoning_delta&.call(text) end |
.codex_reasoning_summary_part_added(state, part) ⇒ Object
339 340 341 342 343 344 345 346 |
# File 'lib/kward/model/stream_parser.rb', line 339 def codex_reasoning_summary_part_added(state, part) item = active_codex_item(state) return unless item&.fetch("type", nil) == "reasoning" && part.is_a?(Hash) item["summary"] ||= [] item["summary"] << deep_dup_hash(part) state[:current_reasoning_content_part] = nil end |
.codex_response_items(state) ⇒ Object
679 680 681 |
# File 'lib/kward/model/stream_parser.rb', line 679 def codex_response_items(state) state[:response_item_keys].filter_map { |key| state[:items_by_id][key] } end |
.codex_sse_error(event, request_error_class: nil) ⇒ Object
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 |
# File 'lib/kward/model/stream_parser.rb', line 284 def codex_sse_error(event, request_error_class: nil) response = event["response"] error = event["error"] || (response["error"] if response.is_a?(Hash)) || {} = if error.is_a?(Hash) [error["code"], error["message"]].compact.join(": ") else error.to_s end = event["type"].to_s if .empty? code = error.is_a?(Hash) && error["code"].to_s == "server_error" ? 500 : 400 if request_error_class request_error_class.new(provider: "Codex", code: code, body: "#{event["type"]}: #{}") else "#{event["type"]}: #{}" end end |
.codex_sse_message(state) ⇒ Object
641 642 643 644 645 646 647 648 649 |
# File 'lib/kward/model/stream_parser.rb', line 641 def (state) = { "role" => "assistant", "content" => codex_visible_content(state) } ["reasoning_summary"] = state[:reasoning_summary] unless state[:reasoning_summary].empty? ["tool_calls"] = state[:tool_calls] unless state[:tool_calls].empty? response_items = codex_response_items(state) ["response_items"] = response_items unless response_items.empty? ["usage"] = state[:usage] if state[:usage] end |
.codex_sse_state(show_raw_reasoning: false) ⇒ Object
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 |
# File 'lib/kward/model/stream_parser.rb', line 223 def codex_sse_state(show_raw_reasoning: false) { content: +"", raw_content: +"", emitted_message_keys: [], reasoning_summary: +"", raw_reasoning_visible: +"", pending_reasoning_delta: +"", show_raw_reasoning: show_raw_reasoning, tool_calls: [], response_item_keys: [], items_by_id: {}, active_item_id: nil, current_text_content_part: nil, current_reasoning_content_part: nil, usage: nil } end |
.codex_streamable_message_item?(item) ⇒ Boolean
671 672 673 |
# File 'lib/kward/model/stream_parser.rb', line 671 def (item) (item) == "final_answer" end |
.codex_tool_arguments_delta(state, delta) ⇒ Object
490 491 492 493 494 495 496 |
# File 'lib/kward/model/stream_parser.rb', line 490 def codex_tool_arguments_delta(state, delta) item = active_codex_item(state) return unless item && ["function_call", "custom_tool_call"].include?(item["type"]) key = item["type"] == "custom_tool_call" ? "input" : "arguments" item[key] = item[key].to_s + delta.to_s end |
.codex_tool_arguments_done(state, arguments) ⇒ Object
498 499 500 501 502 503 |
# File 'lib/kward/model/stream_parser.rb', line 498 def codex_tool_arguments_done(state, arguments) item = active_codex_item(state) return unless item&.fetch("type", nil) == "function_call" item["arguments"] = arguments.to_s end |
.codex_tool_call(item) ⇒ Object
683 684 685 686 687 688 689 690 691 692 693 694 695 696 |
# File 'lib/kward/model/stream_parser.rb', line 683 def codex_tool_call(item) return nil unless item.is_a?(Hash) && ["function_call", "custom_tool_call"].include?(item["type"]) name = item["name"].to_s return nil if name.empty? arguments = item["arguments"] || item["input"] || "{}" arguments = JSON.dump(arguments) unless arguments.is_a?(String) { "id" => (item["call_id"] || item["id"] || "call_#{name}"), "type" => "function", "function" => { "name" => name, "arguments" => arguments } } end |
.codex_visible_content(state) ⇒ Object
651 652 653 654 655 656 657 658 659 660 |
# File 'lib/kward/model/stream_parser.rb', line 651 def codex_visible_content(state) return state[:content] unless state[:content].empty? response_items = codex_response_items(state) visible_text = text_from_codex_items((response_items, tool_calls: state[:tool_calls])) return visible_text unless visible_text.empty? return "" unless state[:tool_calls].empty? state[:raw_content] end |
.codex_visible_reasoning_item(state, item) ⇒ Object
517 518 519 520 521 522 523 524 525 526 527 528 529 |
# File 'lib/kward/model/stream_parser.rb', line 517 def codex_visible_reasoning_item(state, item) return item unless item.is_a?(Hash) && item["type"] == "reasoning" visible = deep_dup_hash(item) sanitize_codex_reasoning_summary_item(visible) visible.delete("content") unless state[:show_raw_reasoning] return visible unless state[:show_raw_reasoning] return visible if visible["summary"].is_a?(Array) && !visible["summary"].empty? text = sanitize_codex_reasoning_text(raw_reasoning_from_codex_items([visible])) visible["summary"] = [{ "type" => "summary_text", "text" => text }] unless text.empty? visible end |
.collect_codex_item_output(state, item, on_assistant_delta: nil, on_reasoning_delta: nil) ⇒ Object
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 |
# File 'lib/kward/model/stream_parser.rb', line 545 def collect_codex_item_output(state, item, on_assistant_delta: nil, on_reasoning_delta: nil) case item["type"] when "message" text = text_from_codex_items([item]) return if text.empty? || !(item) state[:content] << text key = codex_item_key(item) unless state[:emitted_message_keys].include?(key) on_assistant_delta&.call(text) state[:emitted_message_keys] << key end when "reasoning" text = sanitize_codex_reasoning_text(reasoning_summary_from_codex_items([item])) if state[:reasoning_summary].empty? && !text.empty? state[:reasoning_summary] << text on_reasoning_delta&.call(text) end when "function_call", "custom_tool_call" tool_call = codex_tool_call(item) state[:tool_calls] << tool_call if tool_call && !state[:tool_calls].any? { |call| call["id"] == tool_call["id"] } end end |
.compact_blank_codex_reasoning_lines(text) ⇒ Object
476 477 478 |
# File 'lib/kward/model/stream_parser.rb', line 476 def compact_blank_codex_reasoning_lines(text) text.to_s.gsub(/(?:[ \t]*\n){3,}/, "\n\n") end |
.compact_codex_reasoning_delta_spacing(existing, text) ⇒ Object
480 481 482 483 484 485 486 487 488 |
# File 'lib/kward/model/stream_parser.rb', line 480 def compact_codex_reasoning_delta_spacing(existing, text) text = compact_blank_codex_reasoning_lines(text) trailing_newlines = existing.to_s[/\n+\z/].to_s.length leading_newlines = text[/\A\n+/].to_s.length excess_newlines = trailing_newlines + leading_newlines - 2 return text unless excess_newlines.positive? && leading_newlines.positive? text[[excess_newlines, leading_newlines].min..].to_s end |
.deep_dup(value) ⇒ Object
628 629 630 631 632 633 634 635 636 637 638 639 |
# File 'lib/kward/model/stream_parser.rb', line 628 def deep_dup(value) case value when Hash value.each_with_object({}) { |(key, entry), result| result[key] = deep_dup(entry) } when Array value.map { |entry| deep_dup(entry) } when String value.dup else value end end |
.deep_dup_hash(hash) ⇒ Object
624 625 626 |
# File 'lib/kward/model/stream_parser.rb', line 624 def deep_dup_hash(hash) deep_dup(hash) end |
.finalized_streaming_tool_calls(tool_calls) ⇒ Object
213 214 215 216 217 218 219 220 221 |
# File 'lib/kward/model/stream_parser.rb', line 213 def finalized_streaming_tool_calls(tool_calls) tool_calls.compact.each_with_index.map do |tool_call, index| tool_call["id"] ||= "call_#{index}" tool_call["type"] ||= "function" tool_call["function"] ||= { "name" => "", "arguments" => "{}" } tool_call["function"]["arguments"] = "{}" if tool_call["function"]["arguments"].to_s.empty? tool_call end end |
.flush_codex_reasoning_delta(state, on_reasoning_delta: nil) ⇒ Object
437 438 439 440 441 442 |
# File 'lib/kward/model/stream_parser.rb', line 437 def flush_codex_reasoning_delta(state, on_reasoning_delta: nil) pending = state[:pending_reasoning_delta].to_s state[:pending_reasoning_delta].clear text = sanitize_codex_reasoning_text(pending) append_codex_raw_reasoning_text(state, text, on_reasoning_delta: on_reasoning_delta) unless text.empty? end |
.from_claude_code_tool_name(name) ⇒ Object
189 190 191 192 193 194 195 196 197 198 199 200 |
# File 'lib/kward/model/stream_parser.rb', line 189 def from_claude_code_tool_name(name) case name.to_s when "Read" then "read_file" when "Write" then "write_file" when "Edit" then "edit_file" when "Bash" then "run_shell_command" when "WebSearch" then "web_search" when "WebFetch" then "fetch_content" when "AskUserQuestion" then "ask_user_question" else name.to_s end end |
.merge_codex_item(existing, update) ⇒ Object
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 |
# File 'lib/kward/model/stream_parser.rb', line 604 def merge_codex_item(existing, update) return deep_dup_hash(update) unless existing.is_a?(Hash) merged = deep_dup_hash(existing) update.each do |key, value| next if value.nil? merged[key] = if key == "content" && merged[key].is_a?(Array) && value.is_a?(Array) value.empty? ? merged[key] : value elsif key == "summary" && merged[key].is_a?(Array) && value.is_a?(Array) value.empty? ? merged[key] : value elsif key == "arguments" && value.to_s.empty? && !merged[key].to_s.empty? merged[key] else deep_dup(value) end end merged end |
.merge_streaming_tool_call(tool_calls, delta) ⇒ Object
202 203 204 205 206 207 208 209 210 211 |
# File 'lib/kward/model/stream_parser.rb', line 202 def merge_streaming_tool_call(tool_calls, delta) index = (delta["index"] || tool_calls.length).to_i tool_calls[index] ||= { "id" => nil, "type" => "function", "function" => { "name" => "", "arguments" => "" } } current = tool_calls[index] current["id"] = delta["id"] if delta["id"] current["type"] = delta["type"] if delta["type"] function = delta["function"] || {} current["function"]["name"] << function["name"].to_s if function["name"] current["function"]["arguments"] << function["arguments"].to_s if function["arguments"] end |
.parse_anthropic_sse_stream(response, on_reasoning_delta: nil, on_assistant_delta: nil, cancellation: nil, usage_normalizer: nil, request_error_class: nil) ⇒ Object
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/kward/model/stream_parser.rb', line 86 def parse_anthropic_sse_stream(response, on_reasoning_delta: nil, on_assistant_delta: nil, cancellation: nil, usage_normalizer: nil, request_error_class: nil) state = anthropic_sse_state buffer = +"" response.read_body do |chunk| cancellation&.raise_if_cancelled! buffer << chunk while (index = buffer.index(/\r?\n\r?\n/)) delimiter = Regexp.last_match[0] block = buffer[0...index] buffer = buffer[(index + delimiter.length)..] || +"" process_anthropic_sse_block(block, state, on_reasoning_delta: on_reasoning_delta, on_assistant_delta: on_assistant_delta, usage_normalizer: usage_normalizer, request_error_class: request_error_class) end end cancellation&.raise_if_cancelled! process_anthropic_sse_block(buffer, state, on_reasoning_delta: on_reasoning_delta, on_assistant_delta: on_assistant_delta, usage_normalizer: usage_normalizer, request_error_class: request_error_class) unless buffer.empty? (state) rescue JSON::ParserError => e raise "Anthropic returned invalid SSE JSON: #{e.}" end |
.parse_codex_sse(body, on_reasoning_delta: nil, on_assistant_delta: nil, show_raw_reasoning: false, usage_normalizer: nil, request_error_class: nil) ⇒ Object
48 49 50 51 52 53 54 55 56 57 |
# File 'lib/kward/model/stream_parser.rb', line 48 def parse_codex_sse(body, on_reasoning_delta: nil, on_assistant_delta: nil, show_raw_reasoning: false, usage_normalizer: nil, request_error_class: nil) state = codex_sse_state(show_raw_reasoning: show_raw_reasoning) body.split(/\r?\n\r?\n/).each do |block| process_codex_sse_block(block, state, on_reasoning_delta: on_reasoning_delta, on_assistant_delta: on_assistant_delta, usage_normalizer: usage_normalizer, request_error_class: request_error_class) end flush_codex_reasoning_delta(state, on_reasoning_delta: on_reasoning_delta) (state) rescue JSON::ParserError => e raise "Codex OAuth returned invalid SSE JSON: #{e.}" end |
.parse_codex_sse_stream(response, on_reasoning_delta: nil, on_assistant_delta: nil, cancellation: nil, show_raw_reasoning: false, usage_normalizer: nil, request_error_class: nil) ⇒ Object
Incrementally parses a Codex/Responses SSE HTTP response body.
Deltas are yielded as soon as complete SSE blocks arrive so interactive frontends can render streamed assistant and reasoning text without waiting for the provider to close the response.
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/kward/model/stream_parser.rb', line 64 def parse_codex_sse_stream(response, on_reasoning_delta: nil, on_assistant_delta: nil, cancellation: nil, show_raw_reasoning: false, usage_normalizer: nil, request_error_class: nil) state = codex_sse_state(show_raw_reasoning: show_raw_reasoning) buffer = +"" response.read_body do |chunk| cancellation&.raise_if_cancelled! buffer << chunk while (index = buffer.index(/\r?\n\r?\n/)) delimiter = Regexp.last_match[0] block = buffer[0...index] buffer = buffer[(index + delimiter.length)..] || +"" process_codex_sse_block(block, state, on_reasoning_delta: on_reasoning_delta, on_assistant_delta: on_assistant_delta, usage_normalizer: usage_normalizer, request_error_class: request_error_class) end end cancellation&.raise_if_cancelled! process_codex_sse_block(buffer, state, on_reasoning_delta: on_reasoning_delta, on_assistant_delta: on_assistant_delta, usage_normalizer: usage_normalizer, request_error_class: request_error_class) unless buffer.empty? flush_codex_reasoning_delta(state, on_reasoning_delta: on_reasoning_delta) (state) rescue JSON::ParserError => e raise "Codex OAuth returned invalid SSE JSON: #{e.}" end |
.parse_openai_chat_sse(body, on_assistant_delta: nil, usage_normalizer: nil) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/kward/model/stream_parser.rb', line 16 def parse_openai_chat_sse(body, on_assistant_delta: nil, usage_normalizer: nil) content = +"" tool_calls = [] usage = nil body.split(/\r?\n\r?\n/).each do |block| data = block.lines.filter_map { |line| line.start_with?("data:") ? line.delete_prefix("data:").strip : nil }.join("\n") next if data.empty? || data == "[DONE]" event = JSON.parse(data) usage ||= usage_normalizer&.call(event["usage"]) choice = Array(event["choices"]).first || {} delta = choice["delta"] || {} if delta["content"] text = delta["content"].to_s content << text on_assistant_delta&.call(text) end Array(delta["tool_calls"]).each do |tool_call| merge_streaming_tool_call(tool_calls, tool_call) end = choice["message"] || {} content << ["content"].to_s if content.empty? && ["content"] Array(["tool_calls"]).each { |tool_call| merge_streaming_tool_call(tool_calls, tool_call) } end result = { "role" => "assistant", "content" => content } result["tool_calls"] = finalized_streaming_tool_calls(tool_calls) unless tool_calls.empty? result["usage"] = usage if usage result rescue JSON::ParserError => e raise "Copilot returned invalid SSE JSON: #{e.}" end |
.process_anthropic_sse_block(block, state, on_reasoning_delta: nil, on_assistant_delta: nil, usage_normalizer: nil, request_error_class: nil) ⇒ Object
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
# File 'lib/kward/model/stream_parser.rb', line 110 def process_anthropic_sse_block(block, state, on_reasoning_delta: nil, on_assistant_delta: nil, usage_normalizer: nil, request_error_class: nil) event_name = nil data = block.lines.filter_map do |line| event_name = line.delete_prefix("event:").strip if line.start_with?("event:") line.start_with?("data:") ? line.delete_prefix("data:").strip : nil end.join("\n") return if data.empty? || data == "[DONE]" raise anthropic_sse_error(data, request_error_class: request_error_class) if event_name == "error" event = JSON.parse(data) case event["type"] when "message_start" state[:usage] ||= usage_normalizer&.call(event.dig("message", "usage")) when "content_block_start" block_data = event["content_block"] || {} state[:blocks][event["index"].to_i] = block_data.merge("partial_json" => "") if block_data["type"] == "text" text = block_data["text"].to_s state[:content] << text on_assistant_delta&.call(text) unless text.empty? elsif block_data["type"] == "thinking" text = block_data["thinking"].to_s state[:reasoning_summary] << text on_reasoning_delta&.call(text) unless text.empty? end when "content_block_delta" current = state[:blocks][event["index"].to_i] ||= { "partial_json" => "" } delta = event["delta"] || {} case delta["type"] when "text_delta" text = delta["text"].to_s state[:content] << text on_assistant_delta&.call(text) when "thinking_delta" text = delta["thinking"].to_s state[:reasoning_summary] << text on_reasoning_delta&.call(text) when "input_json_delta" current["partial_json"] = current["partial_json"].to_s + delta["partial_json"].to_s end when "content_block_stop" block_data = state[:blocks][event["index"].to_i] tool_call = anthropic_tool_call(block_data) state[:tool_calls] << tool_call if tool_call when "message_delta" state[:usage] = usage_normalizer&.call(event["usage"]) || state[:usage] end end |
.process_codex_sse_block(block, state, on_reasoning_delta: nil, on_assistant_delta: nil, usage_normalizer: nil, request_error_class: nil) ⇒ Object
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 |
# File 'lib/kward/model/stream_parser.rb', line 242 def process_codex_sse_block(block, state, on_reasoning_delta: nil, on_assistant_delta: nil, usage_normalizer: nil, request_error_class: nil) data = block.lines.filter_map { |line| line.start_with?("data:") ? line.delete_prefix("data:").strip : nil }.join("\n") return if data.empty? || data == "[DONE]" event = JSON.parse(data) case event["type"] when "response.output_item.added" codex_output_item_added(state, event["item"]) when "response.content_part.added" codex_content_part_added(state, event["part"]) when "response.output_text.delta", "response.refusal.delta" codex_output_text_delta(state, event["delta"], on_assistant_delta: on_assistant_delta) when "response.reasoning_summary_part.added" codex_reasoning_summary_part_added(state, event["part"]) when "response.reasoning_summary_text.delta" codex_reasoning_delta(state, event["delta"], on_reasoning_delta: on_reasoning_delta) when "response.reasoning_summary_part.done" codex_reasoning_part_done(state, on_reasoning_delta: on_reasoning_delta) when "response.reasoning_text.delta" codex_raw_reasoning_delta(state, event["delta"], on_reasoning_delta: on_reasoning_delta) when "response.reasoning_text.done" codex_raw_reasoning_done(state, event["text"], on_reasoning_delta: on_reasoning_delta) when "response.function_call_arguments.delta", "response.custom_tool_call_input.delta" codex_tool_arguments_delta(state, event["delta"]) when "response.function_call_arguments.done" codex_tool_arguments_done(state, event["arguments"]) when "response.output_item.done" codex_output_item_done(state, event["item"], on_assistant_delta: on_assistant_delta, on_reasoning_delta: on_reasoning_delta) when "response.completed" response = event["response"] state[:usage] ||= usage_normalizer&.call(response["usage"]) if response.is_a?(Hash) state[:usage] ||= usage_normalizer&.call(event["usage"]) if response.is_a?(Hash) && response["output"].is_a?(Array) && state[:response_item_keys].empty? response["output"].each do |item| codex_output_item_done(state, item, on_assistant_delta: on_assistant_delta, on_reasoning_delta: on_reasoning_delta) end end when "response.failed", "response.incomplete" raise codex_sse_error(event, request_error_class: request_error_class) end end |
.raw_reasoning_from_codex_items(items) ⇒ Object
724 725 726 727 728 729 730 |
# File 'lib/kward/model/stream_parser.rb', line 724 def raw_reasoning_from_codex_items(items) items.flat_map do |item| next [] unless item.is_a?(Hash) && item["type"] == "reasoning" && item["content"].is_a?(Array) item["content"].filter_map { |part| part["text"] if part.is_a?(Hash) && part["type"] == "reasoning_text" } end.join end |
.reasoning_summary_from_codex_items(items) ⇒ Object
712 713 714 715 716 717 718 719 720 721 722 |
# File 'lib/kward/model/stream_parser.rb', line 712 def reasoning_summary_from_codex_items(items) items.flat_map do |item| next [] unless item.is_a?(Hash) if item["type"] == "reasoning" && item["summary"].is_a?(Array) item["summary"].filter_map { |part| part["text"] if part.is_a?(Hash) } else [] end end.join end |
.remember_codex_item(state, item) ⇒ Object
589 590 591 592 593 594 595 596 597 598 |
# File 'lib/kward/model/stream_parser.rb', line 589 def remember_codex_item(state, item) key = codex_item_key(item) if state[:items_by_id].key?(key) stored = state[:items_by_id][key] stored.replace(merge_codex_item(stored, item)) else state[:items_by_id][key] = item state[:response_item_keys] << key end end |
.sanitize_codex_reasoning_summary_item(item) ⇒ Object
531 532 533 534 535 536 537 538 539 540 541 542 543 |
# File 'lib/kward/model/stream_parser.rb', line 531 def sanitize_codex_reasoning_summary_item(item) return unless item["summary"].is_a?(Array) pending = +"" item["summary"].each do |part| next unless part.is_a?(Hash) && part.key?("text") pending << part["text"].to_s sanitized = sanitize_codex_reasoning_text(pending, keep_incomplete_comment: true) part["text"] = sanitized[:text] pending.replace(sanitized[:pending]) end end |
.sanitize_codex_reasoning_text(text, keep_incomplete_comment: false) ⇒ Object
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 |
# File 'lib/kward/model/stream_parser.rb', line 452 def sanitize_codex_reasoning_text(text, keep_incomplete_comment: false) string = text.to_s visible = +"" index = 0 while (start_index = string.index("<!--", index)) end_index = string.index("-->", start_index + 4) if end_index visible << string[index...start_index] index = end_index + 3 elsif keep_incomplete_comment visible << string[index...start_index] return { text: visible, pending: string[start_index..] } else visible << string[index..] index = string.length end end visible << string[index..].to_s visible = compact_blank_codex_reasoning_lines(visible) keep_incomplete_comment ? { text: visible, pending: +"" } : visible end |
.split_trailing_comment_prefix(text) ⇒ Object
444 445 446 447 448 449 450 |
# File 'lib/kward/model/stream_parser.rb', line 444 def split_trailing_comment_prefix(text) string = text.to_s prefix = ["<!-", "<!", "<"].find { |candidate| string.end_with?(candidate) } return [string, +""] unless prefix [string[0...-prefix.length], prefix.dup] end |
.text_from_codex_items(items) ⇒ Object
698 699 700 701 702 703 704 705 706 707 708 709 710 |
# File 'lib/kward/model/stream_parser.rb', line 698 def text_from_codex_items(items) items.flat_map do |item| next [] unless item.is_a?(Hash) if ["output_text", "text"].include?(item["type"]) item["text"].to_s elsif item["type"] == "message" && item["content"].is_a?(Array) item["content"].filter_map { |part| part["text"] if part.is_a?(Hash) && ["output_text", "text"].include?(part["type"]) } else [] end end.join end |
.visible_codex_message_items(items, tool_calls: []) ⇒ Object
662 663 664 665 666 667 668 669 |
# File 'lib/kward/model/stream_parser.rb', line 662 def (items, tool_calls: []) = Array(items).select { |item| item.is_a?(Hash) && item["type"] == "message" } = .select { |item| (item) == "final_answer" } return unless .empty? return [] unless tool_calls.empty? .reject { |item| (item) == "commentary" } end |
.visible_codex_reasoning_delta(state, delta) ⇒ Object
429 430 431 432 433 434 435 |
# File 'lib/kward/model/stream_parser.rb', line 429 def visible_codex_reasoning_delta(state, delta) state[:pending_reasoning_delta] << delta.to_s sanitized = sanitize_codex_reasoning_text(state[:pending_reasoning_delta], keep_incomplete_comment: true) text, pending_prefix = split_trailing_comment_prefix(sanitized[:text]) state[:pending_reasoning_delta].replace(pending_prefix + sanitized[:pending]) text end |