@@ -38,33 +38,45 @@ def handle_stream(&block)
3838
3939 private
4040
41- def to_json_stream ( &block )
41+ def to_json_stream ( &)
4242 buffer = String . new
4343 parser = EventStreamParser ::Parser . new
4444
45+ create_stream_processor ( parser , buffer , &)
46+ end
47+
48+ def create_stream_processor ( parser , buffer , &)
4549 if Faraday ::VERSION . start_with? ( '1' )
4650 # Faraday 1.x: on_data receives (chunk, size)
47- proc do |chunk , size |
48- RubyLLM . logger . debug "Received chunk: #{ chunk } "
49-
50- if error_chunk? ( chunk )
51- handle_error_chunk ( chunk , nil )
52- else
53- yield handle_sse ( chunk , parser , nil , &block )
54- end
55- end
51+ legacy_stream_processor ( parser , &)
5652 else
5753 # Faraday 2.x: on_data receives (chunk, bytes, env)
58- proc do |chunk , _bytes , env |
59- RubyLLM . logger . debug "Received chunk: #{ chunk } "
60-
61- if error_chunk? ( chunk )
62- handle_error_chunk ( chunk , env )
63- elsif env &.status != 200
64- handle_failed_response ( chunk , buffer , env )
65- else
66- yield handle_sse ( chunk , parser , env , &block )
67- end
54+ stream_processor ( parser , buffer , &)
55+ end
56+ end
57+
58+ def process_stream_chunk ( chunk , parser , _env , &)
59+ RubyLLM . logger . debug "Received chunk: #{ chunk } "
60+
61+ if error_chunk? ( chunk )
62+ handle_error_chunk ( chunk , nil )
63+ else
64+ yield handle_sse ( chunk , parser , nil , &)
65+ end
66+ end
67+
68+ def legacy_stream_processor ( parser , &block )
69+ proc do |chunk , _size |
70+ process_stream_chunk ( chunk , parser , nil , &block )
71+ end
72+ end
73+
74+ def stream_processor ( parser , buffer , &block )
75+ proc do |chunk , _bytes , env |
76+ if env &.status == 200
77+ process_stream_chunk ( chunk , parser , env , &block )
78+ else
79+ handle_failed_response ( chunk , buffer , env )
6880 end
6981 end
7082 end
0 commit comments