MCPcopy Create free account
hub / github.com/acking-you/static_flow / stream_reply

Function stream_reply

scripts/test_llm_gateway_chat.py:446–502  ·  view source on GitHub ↗

Consume a streaming gateway response and print text as it arrives.

(
    request: urllib.request.Request,
    endpoint: str,
    show_usage: bool,
    show_raw: bool,
    timeout: int,
)

Source from the content-addressed store, hash-verified

444
445
446def stream_reply(
447 request: urllib.request.Request,
448 endpoint: str,
449 show_usage: bool,
450 show_raw: bool,
451 timeout: int,
452) -> int:
453 """Consume a streaming gateway response and print text as it arrives."""
454 usage = None
455 printed_content = False
456 last_event = None
457 try:
458 with urllib.request.urlopen(request, timeout=timeout) as response:
459 event_lines: list[str] = []
460 while True:
461 raw_line = response.readline()
462 if not raw_line:
463 if event_lines:
464 _, maybe_usage, did_print, maybe_value = flush_sse_event(
465 event_lines, endpoint
466 )
467 usage = maybe_usage or usage
468 printed_content = printed_content or did_print
469 last_event = maybe_value or last_event
470 break
471 line = raw_line.decode("utf-8", errors="replace").rstrip("\r\n")
472 if not line:
473 done, maybe_usage, did_print, maybe_value = flush_sse_event(
474 event_lines, endpoint
475 )
476 usage = maybe_usage or usage
477 printed_content = printed_content or did_print
478 last_event = maybe_value or last_event
479 event_lines.clear()
480 if done:
481 break
482 continue
483 event_lines.append(line)
484 except urllib.error.HTTPError as exc:
485 detail = exc.read().decode("utf-8", errors="replace")
486 print(f"HTTP {exc.code}: {detail}", file=sys.stderr)
487 return 1
488 except Exception as exc:
489 print(f"Request failed: {exc}", file=sys.stderr)
490 return 1
491
492 if printed_content:
493 print()
494
495 print_usage_summary(usage)
496
497 if show_usage and usage is not None:
498 print(json.dumps(usage, ensure_ascii=False, indent=2), file=sys.stderr)
499 if show_raw and last_event is not None:
500 print(json.dumps(last_event, ensure_ascii=False, indent=2), file=sys.stderr)
501
502 return 0
503

Callers 1

mainFunction · 0.85

Calls 4

flush_sse_eventFunction · 0.85
print_usage_summaryFunction · 0.85
decodeMethod · 0.80
appendMethod · 0.80

Tested by

no test coverage detected