Skip to content

refactor: add try except logic for JSON parsing and response handling #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 22 additions & 8 deletions agent_gateway/gateway/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,18 +94,32 @@ def _parse_snowflake_response(self, data_str):
# Remove the 'data: ' prefix if it exists
if obj.startswith("data: "):
obj = obj[6:]
# Load the JSON object into a Python dictionary
json_dict = json.loads(obj, strict=False)
# Append the JSON dictionary to the list
json_list.append(json_dict)
try:
# Load the JSON object into a Python dictionary
json_dict = json.loads(obj, strict=False)
# Append the JSON dictionary to the list
json_list.append(json_dict)
except json.JSONDecodeError as e:
gateway_logger.log(
logging.ERROR,
f"Failed to parse JSON object: {obj}. Error: {e}",
)
continue

completion = ""
choices = {}
for chunk in json_list:
choices = chunk["choices"][0]

if "content" in choices["delta"].keys():
completion += choices["delta"]["content"]
# Ensure 'choices' key exists in the chunk
if "choices" in chunk and chunk["choices"]:
choices = chunk["choices"][0]

# Ensure 'delta' key exists in choices and it contains 'content'
if "delta" in choices and "content" in choices["delta"]:
completion += choices["delta"]["content"]
else:
gateway_logger.log(
logging.WARNING, f"Missing or empty 'choices' in chunk: {chunk}"
)

return completion
except KeyError as e:
Expand Down
Loading