Skip to content

Conversation

@hangweizhang
Copy link

Fixes #768
When the LLM returns tool arguments as JSON with literal newlines inside string values (e.g. HTML), the JSON is invalid, parsing fails, and the tool gets an empty input (all parameters null).
Changes:
Add JsonParseHelper: escape \n/\r inside JSON strings and parse with fallback.
ToolCallsAccumulator: parse raw content via parseMapWithNewlineFallback when args are empty.
ToolExecutor: build merged input first (including parsing content when input is empty), then validate the merged input instead of the raw content.
Tests: JsonParseHelperTest, ToolCallsAccumulatorTest (newlines in content), ToolExecutorTest (empty input + content with newlines).

zhanghangwei added 2 commits February 10, 2026 10:35
…gentscope-ai#768)

Parse tool input with fallback when content contains literal newlines (e.g.
HTML). Validate merged input instead of raw content.
@hangweizhang hangweizhang requested a review from a team February 10, 2026 03:02
@cla-assistant
Copy link

cla-assistant bot commented Feb 10, 2026

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ hangweizhang
❌ zhanghangwei


zhanghangwei seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@gemini-code-assist
Copy link

Summary of Changes

Hello @hangweizhang, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical issue where tool arguments returned by LLMs containing literal newlines within JSON string values (such as embedded HTML) caused parsing failures, leading to tools receiving empty or invalid inputs. The changes introduce a resilient JSON parsing utility that automatically escapes these problematic newlines, ensuring that tool calls are correctly interpreted and executed even with malformed LLM outputs. This significantly improves the reliability of tool invocation within the system.

Highlights

  • Robust JSON Parsing for Tool Arguments: Introduced a new JsonParseHelper utility to handle cases where Large Language Models (LLMs) return tool arguments as JSON with literal newlines (e.g., HTML content) inside string values, which would otherwise lead to invalid JSON and parsing failures.
  • Enhanced ToolCallsAccumulator: Updated the ToolCallsAccumulator to utilize the new JsonParseHelper for parsing raw content when initial arguments are empty, ensuring that tool inputs with unescaped newlines are correctly processed.
  • Improved ToolExecutor Input Handling: Refactored the ToolExecutor to merge preset parameters and tool call inputs, incorporating a fallback mechanism to parse raw content using JsonParseHelper if the input map is empty. Validation now occurs on this merged, potentially sanitized, input.
  • Comprehensive Test Coverage: Added new unit tests for JsonParseHelper, ToolCallsAccumulator, and ToolExecutor to validate the correct handling of JSON with literal newlines and ensure the robustness of the parsing and execution flow.
Changelog
  • agentscope-core/pom.xml
    • Updated license header formatting.
  • agentscope-core/src/main/java/io/agentscope/core/agent/accumulator/ToolCallsAccumulator.java
    • Replaced direct JsonUtils usage with JsonParseHelper for raw content parsing.
    • Implemented fallback parsing for raw content to handle literal newlines in JSON strings.
  • agentscope-core/src/main/java/io/agentscope/core/tool/ToolExecutor.java
    • Imported JsonParseHelper and JsonUtils.
    • Refactored input merging logic to include a fallback for parsing raw content with newlines when the input map is empty.
    • Modified validation to occur on the merged input, ensuring consistency with the actual data passed to the tool.
  • agentscope-core/src/main/java/io/agentscope/core/util/JsonParseHelper.java
    • Added new utility class JsonParseHelper.
    • Implemented parseMapWithNewlineFallback method for robust JSON parsing with newline sanitization.
    • Implemented escapeNewlinesInJsonStrings method to escape literal newlines and carriage returns within JSON string values.
  • agentscope-core/src/test/java/io/agentscope/core/agent/accumulator/ToolCallsAccumulatorTest.java
    • Added a new test case to verify parsing of raw content containing literal newlines in strings.
  • agentscope-core/src/test/java/io/agentscope/core/tool/ToolExecutorTest.java
    • Added a test case to ensure tools run correctly when input is empty but content contains JSON with newlines.
  • agentscope-core/src/test/java/io/agentscope/core/util/JsonParseHelperTest.java
    • Added comprehensive unit tests for JsonParseHelper methods, covering valid JSON, newlines in strings, and edge cases.
Activity
  • No human activity has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@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 introduces a robust solution for handling malformed JSON from LLMs, specifically when string values contain literal newlines. The introduction of JsonParseHelper centralizes the logic for sanitizing and parsing such JSON, which is a great approach. The changes in ToolCallsAccumulator and ToolExecutor correctly leverage this new helper to provide fallback parsing. The added tests are comprehensive and cover the new functionality well. I have one suggestion to improve the maintainability of the new helper class by adding logging for parsing failures.

Comment on lines +26 to +55
public final class JsonParseHelper {

private JsonParseHelper() {}

/**
* Parse a JSON string into a map, with fallback to sanitizing literal newlines inside
* strings when the first attempt fails. Use for tool input JSON that may contain
* multi-line content (e.g. HTML).
*
* @param json JSON string (e.g. tool call arguments)
* @return parsed map, or null if parsing failed even after sanitization
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> parseMapWithNewlineFallback(String json) {
if (json == null || json.isEmpty()) {
return null;
}
try {
Object parsed = JsonUtils.getJsonCodec().fromJson(json, Map.class);
return parsed != null ? (Map<String, Object>) parsed : null;
} catch (Exception e) {
String sanitized = escapeNewlinesInJsonStrings(json);
try {
Object parsed = JsonUtils.getJsonCodec().fromJson(sanitized, Map.class);
return parsed != null ? (Map<String, Object>) parsed : null;
} catch (Exception e2) {
return null;
}
}
}

Choose a reason for hiding this comment

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

medium

While the fallback logic is great for robustness, swallowing exceptions without logging can make it very difficult to debug issues where JSON parsing fails for unexpected reasons. It's a good practice to log these exceptions, at least at a debug or warn level, to provide visibility into why parsing is failing. This helps in identifying if the sanitization logic needs to be improved or if the input is fundamentally malformed.

public final class JsonParseHelper {

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(JsonParseHelper.class);

    private JsonParseHelper() {}

    /**
     * Parse a JSON string into a map, with fallback to sanitizing literal newlines inside
     * strings when the first attempt fails. Use for tool input JSON that may contain
     * multi-line content (e.g. HTML).
     *
     * @param json JSON string (e.g. tool call arguments)
     * @return parsed map, or null if parsing failed even after sanitization
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> parseMapWithNewlineFallback(String json) {
        if (json == null || json.isEmpty()) {
            return null;
        }
        try {
            Object parsed = JsonUtils.getJsonCodec().fromJson(json, Map.class);
            return parsed != null ? (Map<String, Object>) parsed : null;
        } catch (Exception e) {
            logger.debug("Failed to parse JSON, trying to sanitize newlines. Error: {}", e.getMessage());
            String sanitized = escapeNewlinesInJsonStrings(json);
            try {
                Object parsed = JsonUtils.getJsonCodec().fromJson(sanitized, Map.class);
                return parsed != null ? (Map<String, Object>) parsed : null;
            } catch (Exception e2) {
                logger.warn("Failed to parse JSON even after sanitizing newlines. Error: {}", e2.getMessage());
                return null;
            }
        }
    }

@codecov
Copy link

codecov bot commented Feb 10, 2026

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]:很奇怪的一个bug,我让agent写入一个带有格式的html文件,整个参数都是空

1 participant