Skip to content

Commit c98780a

Browse files
yeesiancopybara-github
authored andcommitted
fix: Handle the streaming of JSON delimited by newlines
FUTURE_COPYBARA_INTEGRATE_REVIEW=#4861 from googleapis:release-please--branches--main 039f2cb PiperOrigin-RevId: 719423860
1 parent 713ffac commit c98780a

File tree

2 files changed

+20
-12
lines changed

2 files changed

+20
-12
lines changed

vertexai/reasoning_engines/_reasoning_engines.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -840,9 +840,9 @@ def _method(self, **kwargs) -> Iterable[Any]:
840840
),
841841
)
842842
for chunk in response:
843-
parsed_json = _utils.to_parsed_json(chunk)
844-
if parsed_json is not None:
845-
yield parsed_json
843+
for parsed_json in _utils.to_parsed_json(chunk):
844+
if parsed_json is not None:
845+
yield parsed_json
846846

847847
_method.__name__ = method_name
848848
_method.__doc__ = doc

vertexai/reasoning_engines/_utils.py

+17-9
Original file line numberDiff line numberDiff line change
@@ -104,22 +104,30 @@ def to_parsed_json(body: httpbody_pb2.HttpBody) -> Any:
104104
data = getattr(body, "data", None)
105105

106106
if content_type is None or data is None or "application/json" not in content_type:
107-
return body
107+
yield body
108+
return
108109

109110
try:
110111
utf8_data = data.decode("utf-8")
111112
except Exception as e:
112113
_LOGGER.warning(f"Failed to decode data: {data}. Exception: {e}")
113-
return body
114+
yield body
115+
return
114116

115117
if not utf8_data:
116-
return None
117-
118-
try:
119-
return json.loads(utf8_data)
120-
except Exception as e:
121-
_LOGGER.warning(f"Failed to parse JSON: {utf8_data}. Exception: {e}")
122-
return body # Return the raw body on error
118+
yield None
119+
return
120+
121+
# Handle the case of multiple dictionaries delimited by newlines.
122+
for line in utf8_data.split("\n"):
123+
if line:
124+
try:
125+
line = json.loads(line)
126+
except Exception as e:
127+
_LOGGER.warning(
128+
f"failed to parse json: {line}. Exception: {e}"
129+
)
130+
yield line
123131

124132

125133
def generate_schema(

0 commit comments

Comments
 (0)