Skip to content

Conversation

@selamw1
Copy link

@selamw1 selamw1 commented Feb 11, 2026

Fixes json.JSONDecodeError caused by LLMs returning JSON with trailing commas.

Changes

  • Added a regex pre-processing step in RestaurantAgent to strip trailing commas before calling json.loads().
  • Improves parsing robustness and prevents unnecessary retries.

Fixes

Resolves #480

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request aims to fix JSON decoding errors from LLM-generated content by removing trailing commas. The approach of using a regular expression is sound. However, the implemented regex is not fully robust and can fail in cases of multiple trailing commas. I've suggested a more robust regex that handles these cases correctly.

raise ValueError("Cleaned JSON string is empty.")

# Autofix: Remove trailing commas from arrays and objects
json_string_cleaned = re.sub(r",\s*([\]}])", r"\1", json_string_cleaned)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current regex only handles a single trailing comma. It would fail to fix a string with multiple trailing commas, like [1, 2,,], which would be converted to the still-invalid [1, 2,]. Using a positive lookahead is more robust and handles multiple trailing commas correctly in a single pass.

Suggested change
json_string_cleaned = re.sub(r",\s*([\]}])", r"\1", json_string_cleaned)
json_string_cleaned = re.sub(r",(?=\s*[\]}])", "", json_string_cleaned)

@selamw1 selamw1 force-pushed the fix/llm-json-trailing-comma branch 2 times, most recently from 95077f0 to b2afa00 Compare February 11, 2026 23:33
@selamw1 selamw1 force-pushed the fix/llm-json-trailing-comma branch from b2afa00 to b08a1da Compare February 11, 2026 23:39
raise ValueError("Cleaned JSON string is empty.")

# Autofix: Remove trailing commas from arrays and objects
json_string_cleaned = re.sub(r",(?=\s*[\]}])", "", json_string_cleaned)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for this

can you put it in the SDK here:
https://github.com/google/A2UI/blob/main/a2a_agents/python/a2ui_agent/src/a2ui/extension/send_a2ui_to_client_toolset.py#L265

and add some tests

I think flow would be
if not jsonschema.validate():
run fixers
if trailing comma fixer does something
emit warning

jsonschema.validate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

Autofix malformed JSON returned by the LLM

2 participants