Skip to content

Fix: Prevents merging of tool arguments during preprocessing#2909

Merged
winglian merged 4 commits into
axolotl-ai-cloud:mainfrom
greenhestu:fix/redundant-none-chat-template
Jul 15, 2025
Merged

Fix: Prevents merging of tool arguments during preprocessing#2909
winglian merged 4 commits into
axolotl-ai-cloud:mainfrom
greenhestu:fix/redundant-none-chat-template

Conversation

@greenhestu

@greenhestu greenhestu commented Jul 12, 2025

Copy link
Copy Markdown
Contributor

Description

This PR modifies the data preprocessing logic for tool calls. It resolves an issue where arguments from multiple tools were being merged during preprocessing, causing unnecessary fields to be populated with null values.

This change reforms the structure of tool_calls within the preprocessed data. By removing extraneous null arguments, each tool call in the training data now strictly adheres to its own schema, ensuring it matches the format expected by standard chat templates.

Motivation and Context

Problem:

The current logic merges the function signatures of all available tools, likely due to the schema unification behavior of Hugging Face's datasets.load_dataset with JSON files. (See HF Docs on JSON loading).

Impact:

This results in training data where tool_calls contain extraneous arguments with null values.
A model fine-tuned on this data performs poorly when used for inference with standard chat templates (e.g., in vLLM), as there is a mismatch between the training format and the expected inference format.

Example:

{"messages":[{"role":"user","content":"move to (0, 1)"},{"role":"assistant","content":"","tool_calls":[{"function":{"name":"move","arguments":{"x":0,"y":1}}}]}],"tools":[{"type":"function","function":{"name":"move","description":"Move to a given location measured in meters","parameters":{"type":"object","properties":{"x":{"type":"number","description":"The x coordinate of the location, negative values are to the left, positive values are to the right"},"y":{"type":"number","description":"The y coordinate of the location, negative values are backward, positive values are forward"}},"required":["x","y"]}}},{"type":"function","function":{"name":"turn","description":"Turn the robot to a given direction","parameters":{"type":"object","properties":{"theta":{"type":"integer","description":"The angle to turn to, in degrees, positive values are counter-clockwise, negative values are clockwise"}},"required":["theta"]}}},{"type":"function","function":{"name":"invalid_prompt","description":"call when the user's prompt is invalid","parameters":{"type":"object","properties":{"message":{"type":"string","description":"why the prompt is invalid"}},"required":["message"]}}}],"add_generation_prompt":false}
{"messages":[{"role":"user","content":"turn 270 degree"},{"role":"assistant","content":"","tool_calls":[{"function":{"name":"turn","arguments":{"theta": 270}}}]}],"tools":[{"type":"function","function":{"name":"move","description":"Move to a given location measured in meters","parameters":{"type":"object","properties":{"x":{"type":"number","description":"The x coordinate of the location, negative values are to the left, positive values are to the right"},"y":{"type":"number","description":"The y coordinate of the location, negative values are backward, positive values are forward"}},"required":["x","y"]}}},{"type":"function","function":{"name":"turn","description":"Turn the robot to a given direction","parameters":{"type":"object","properties":{"theta":{"type":"integer","description":"The angle to turn to, in degrees, positive values are counter-clockwise, negative values are clockwise"}},"required":["theta"]}}},{"type":"function","function":{"name":"invalid_prompt","description":"call when the user's prompt is invalid","parameters":{"type":"object","properties":{"message":{"type":"string","description":"why the prompt is invalid"}},"required":["message"]}}}],"add_generation_prompt":false}
{"messages":[{"role":"user","content":"jump high"},{"role":"assistant","content":"","tool_calls":[{"function":{"name":"invalid_prompt","arguments":{"message": "jump is not a valid action"}}}]}],"tools":[{"type":"function","function":{"name":"move","description":"Move to a given location measured in meters","parameters":{"type":"object","properties":{"x":{"type":"number","description":"The x coordinate of the location, negative values are to the left, positive values are to the right"},"y":{"type":"number","description":"The y coordinate of the location, negative values are backward, positive values are forward"}},"required":["x","y"]}}},{"type":"function","function":{"name":"turn","description":"Turn the robot to a given direction","parameters":{"type":"object","properties":{"theta":{"type":"integer","description":"The angle to turn to, in degrees, positive values are counter-clockwise, negative values are clockwise"}},"required":["theta"]}}},{"type":"function","function":{"name":"invalid_prompt","description":"call when the user's prompt is invalid","parameters":{"type":"object","properties":{"message":{"type":"string","description":"why the prompt is invalid"}},"required":["message"]}}}],"add_generation_prompt":false}

Applying the chat template to the data above produces the following result (first column)

<|im_start|>system
# Tools

You may call one or more functions to assist with the user query.

You are provided with function signatures within <tools></tools> XML tags:
<tools>
{"type": "function", "function": {"name": "move", "description": "Move to a given location measured in meters", "parameters": {"type": "object", "properties": {"x": {"type": "number", "description": "The x coordinate of the location, negative values are to the left, positive values are to the right"}, "y": {"type": "number", "description": "The y coordinate of the location, negative values are backward, positive values are forward"}}, "required": ["x", "y"]}}}
{"type": "function", "function": {"name": "turn", "description": "Turn the robot to a given direction", "parameters": {"type": "object", "properties": {"theta": {"type": "integer", "description": "The angle to turn to, in degrees, positive values are counter-clockwise, negative values are clockwise"}}, "required": ["theta"]}}}
{"type": "function", "function": {"name": "invalid_prompt", "description": "call when the user's prompt is invalid", "parameters": {"type": "object", "properties": {"message": {"type": "string", "description": "why the prompt is invalid"}}, "required": ["message"]}}}
</tools>

For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:
<tool_call>
{"name": <function-name>, "arguments": <args-json-object>}
</tool_call><|im_end|>
<|im_start|>user
move to (0, 1)<|im_end|>
<|im_start|>assistant
<think>

</think>

<tool_call>
{"name": "move", "arguments": {"x": 0, "y": 1}}
</tool_call><|im_end|>

axolotl preprocess --debug makes following output

  • Before this PR (contains "theta": null and "message" null)
(User prompt and tool tokens omitted.)
(-100, 198) <|im_start|>(-100, 151644) assistant(-100, 77091) 
(-100, 198) <think>(-100, 151667) 

(-100, 271) </think>(-100, 151668) 

(-100, 271) <tool_call>(151657, 151657) 
(198, 198) {"(4913, 4913) name(606, 606) ":(788, 788)  "(330, 330) move(3397, 3397) ",(497, 497)  "(330, 330) arguments(16370, 16370) ":(788, 788)  {"(5212, 5212) x(87, 87) ":(788, 788)  (220, 220) 0(15, 15) ,(11, 11)  "(330, 330) y(88, 88) ":(788, 788)  (220, 220) 1(16, 16) ,(11, 11)  "(330, 330) theta(15976, 15976) ":(788, 788)  null(845, 845) ,(11, 11)  "(330, 330) message(1994, 1994) ":(788, 788)  null(845, 845) }}
(11248, 11248) </tool_call>(151658, 151658) <|im_end|>(151645, 151645) 
(-100, 198)
  • After this PR (Correct arguments for "move" tool)
(User prompt and tool tokens omitted.)
(-100, 198) <|im_start|>(-100, 151644) assistant(-100, 77091) 
(-100, 198) <think>(-100, 151667) 

(-100, 271) </think>(-100, 151668) 

(-100, 271) <tool_call>(151657, 151657) 
(198, 198) {"(4913, 4913) name(606, 606) ":(788, 788)  "(330, 330) move(3397, 3397) ",(497, 497)  "(330, 330) arguments(16370, 16370) ":(788, 788)  {"(5212, 5212) x(87, 87) ":(788, 788)  (220, 220) 0(15, 15) ,(11, 11)  "(330, 330) y(88, 88) ":(788, 788)  (220, 220) 1(16, 16) }}
(11248, 11248) </tool_call>(151658, 151658) <|im_end|>(151645, 151645) 
(-100, 198)

How has this been tested?

This change was evaluated using the qwen3-1.7b model with vLLM for inference.
The results are as follows:

Before fine-tuning: 55.5% accuracy
After fine-tuning (before this PR): 29.8% (Performance degraded)
After fine-tuning (this PR): 90.3% (Performance improved)

Summary by CodeRabbit

  • Bug Fixes
    • Improved prompt processing by filtering out any entries with missing values before tokenization, ensuring cleaner serialized outputs.
  • Tests
    • Added tests to verify that optional fields are correctly omitted in tool call outputs, preventing null values in serialized chat prompts.

@coderabbitai

coderabbitai Bot commented Jul 12, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

A helper function was introduced within the tokenize_prompt method of the ChatTemplateStrategy class to recursively remove None values from dictionaries and lists in the prompt input. This function is applied to both single and batched prompts before tokenization, ensuring clean input data for further processing. Additionally, a new test module was added to verify that null fields do not appear in tool call JSON outputs after tokenization, covering both single and batched cases.

Changes

File Change Summary
src/axolotl/prompt_strategies/chat_template.py Added a recursive helper to remove None values from prompt dictionaries and lists before tokenization in ChatTemplateStrategy.
tests/prompt_strategies/test_chat_template_ds_schema_unification.py Added new tests verifying that null fields are omitted in tool call JSON outputs after tokenization, for both single and batched prompts. Included fixtures for dataset, tokenizer, and prompt strategy.

Suggested labels

scheduled_release

Suggested reviewers

  • winglian

Poem

In the warren of code, a helper was born,
To sweep out the Nones, both hidden and worn.
Now prompts are all tidy, no empties remain,
As tokenization hops forward, clear in its lane.
Tests watch with keen eyes, no nulls to be found,
In JSON they vanish, no errors abound.
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0968e15 and 4619f2c.

📒 Files selected for processing (1)
  • src/axolotl/prompt_strategies/chat_template.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/axolotl/prompt_strategies/chat_template.py
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/axolotl/prompt_strategies/chat_template.py (1)

381-394: Consider extracting the helper function for better maintainability.

While the current implementation works, defining the helper function inside the method limits its reusability and impacts code organization.

Consider extracting the function to the class level or module level:

+    @staticmethod
+    def _remove_none_values(obj):
+        """Recursively remove None values from dictionaries and lists."""
+        if isinstance(obj, dict):
+            return {k: ChatTemplateStrategy._remove_none_values(v) for k, v in obj.items() if v is not None}
+        if isinstance(obj, list):
+            return [ChatTemplateStrategy._remove_none_values(elem) for elem in obj]
+        return obj
+
     def tokenize_prompt(self, prompt: dict[str, Any]):
         """
         Public method that can handle either a single prompt or a batch of prompts.
         """
-        def _remove_none_values(obj):
-            if isinstance(obj, dict):
-                return {k: _remove_none_values(v) for k, v in obj.items() if v is not None}
-            if isinstance(obj, list):
-                return [_remove_none_values(elem) for elem in obj]
-            return obj

         if not self.is_prompt_batched(prompt) or not self.supports_batched:
             return self._tokenize_single_prompt(prompt)

         res = defaultdict(lambda: [])
         feature_names = list(prompt.keys())

-        prompt = _remove_none_values(prompt)
+        prompt = self._remove_none_values(prompt)

This improves code organization and allows the function to be tested independently.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eb66255 and 769e78a.

📒 Files selected for processing (1)
  • src/axolotl/prompt_strategies/chat_template.py (1 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
src/axolotl/prompt_strategies/chat_template.py

[refactor] 382-385: Unnecessary "elif" after "return", remove the leading "el" from "elif"

(R1705)

🔇 Additional comments (1)
src/axolotl/prompt_strategies/chat_template.py (1)

394-394: None value removal is safe for all prompt structures

The _remove_none_values helper only drops keys whose values are literally None. Downstream code always uses prompt.get(key, None) or explicit is None checks (e.g. in _get_tools, _get_messages, default‐value branches in __init__), so removing None entries simply falls back to the same default logic. No intentional None values are relied on, and no changes are required.

Comment thread src/axolotl/prompt_strategies/chat_template.py
@codecov

codecov Bot commented Jul 12, 2025

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

📢 Thoughts on this report? Let us know!

@winglian

winglian commented Jul 12, 2025

Copy link
Copy Markdown
Collaborator

@greenhestu Thanks for tracking this down. I wrote up a quick test case, but it doesn't pass. see https://gist.github.com/winglian/b1b658a37b2dc337448aef9f10080095

EDIT: found the issue and added separate tests for batched and non-batched parsing

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
tests/prompt_strategies/test_chat_template_ds_schema_unification.py (1)

67-76: Apply the same robustness improvements to batched test.

The batched test has the same fragility issues as the single prompt test. Additionally, it's missing proper iteration over the batch results.

Apply this refactor to fix the batched test:

 def test_schema_unification_batched(
     self, messages_w_tools, qwen3_prompt_strategy, qwen3_tokenizer
 ):
     rows = messages_w_tools.map(qwen3_prompt_strategy.tokenize_prompt, batched=True)
-    for row in rows:
-        decoded = qwen3_tokenizer.decode(row["input_ids"])
-        tool_call = decoded.split("<tool_call>")[-1].split("</tool_call>")[0]
-        assert '"message": null' not in tool_call
-        assert '"theta": null' not in tool_call
+    
+    # Iterate through batch results properly
+    for i in range(len(rows["input_ids"])):
+        decoded = qwen3_tokenizer.decode(rows["input_ids"][i])
+        
+        # More robust tool call extraction and validation
+        if "<tool_call>" in decoded and "</tool_call>" in decoded:
+            tool_call = decoded.split("<tool_call>")[-1].split("</tool_call>")[0]
+            
+            try:
+                tool_data = json.loads(tool_call)
+                if "arguments" in tool_data:
+                    for key, value in tool_data["arguments"].items():
+                        assert value is not None, f"Found null value for argument '{key}' in batch item {i}"
+            except json.JSONDecodeError:
+                pytest.fail(f"Tool call is not valid JSON in batch item {i}: {tool_call}")
+        else:
+            pytest.fail(f"No tool call found in decoded output for batch item {i}")
🧹 Nitpick comments (2)
tests/prompt_strategies/test_chat_template_ds_schema_unification.py (2)

15-25: Consider improving test data readability and maintainability.

The JSON test data is embedded as long single-line strings, making it difficult to read, debug, and maintain. Consider extracting this to separate JSON files or formatting it more readably.

Example refactor to improve readability:

-    jsons = """
-{"messages":[{"role":"user","content":"move to (0, 1)"},{"role":"assistant","content":"","tool_calls":[{"function":{"name":"move","arguments":{"x":0,"y":1}}}]}],"tools":[...]}
-{"messages":[{"role":"user","content":"turn 270 degree"},{"role":"assistant","content":"","tool_calls":[{"function":{"name":"turn","arguments":{"theta": 270}}}]}],"tools":[...]}
-    """.strip().split("\n")
+    test_data = [
+        {
+            "messages": [
+                {"role": "user", "content": "move to (0, 1)"},
+                {
+                    "role": "assistant", 
+                    "content": "",
+                    "tool_calls": [{"function": {"name": "move", "arguments": {"x": 0, "y": 1}}}]
+                }
+            ],
+            "tools": [...],  # Tool definitions
+            "add_generation_prompt": False
+        },
+        # Additional test cases...
+    ]

52-76: Consider adding edge case tests to improve coverage.

The current tests cover basic functionality but miss important edge cases that could reveal issues with the schema unification fix.

Consider adding these additional test cases:

def test_schema_unification_edge_cases(
    self, qwen3_prompt_strategy, qwen3_tokenizer
):
    """Test edge cases for schema unification"""
    
    # Test with empty tool calls
    empty_tool_data = {
        "messages": [
            {"role": "user", "content": "test"},
            {"role": "assistant", "content": "", "tool_calls": []}
        ],
        "tools": [],
        "add_generation_prompt": False
    }
    
    # Test with malformed tool definitions
    malformed_tool_data = {
        "messages": [
            {"role": "user", "content": "test"},
            {"role": "assistant", "content": "No tool calls"}
        ],
        "tools": [{"type": "function", "function": {"name": "incomplete"}}],
        "add_generation_prompt": False
    }
    
    # Add assertions for these edge cases
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 769e78a and 0968e15.

📒 Files selected for processing (2)
  • src/axolotl/prompt_strategies/chat_template.py (1 hunks)
  • tests/prompt_strategies/test_chat_template_ds_schema_unification.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/axolotl/prompt_strategies/chat_template.py
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: greenhestu
PR: axolotl-ai-cloud/axolotl#2909
File: src/axolotl/prompt_strategies/chat_template.py:381-386
Timestamp: 2025-07-12T13:14:29.237Z
Learning: In src/axolotl/prompt_strategies/chat_template.py, the _remove_none_values function uses hasattr(obj, "items") instead of isinstance(obj, dict) for dictionary detection to support duck typing. This allows the function to work with any object that implements a dictionary-like interface, including custom classes, OrderedDict, defaultdict, etc.
🔇 Additional comments (2)
tests/prompt_strategies/test_chat_template_ds_schema_unification.py (2)

1-13: Imports and documentation look good.

The file has clear documentation and appropriate imports for the testing functionality.


28-34: No action needed: download_qwen3_half_billion_model fixture is defined
The download_qwen3_half_billion_model fixture lives in tests/conftest.py as a session-scoped, autouse fixture, so it’s available in your test without any local definition.

Comment thread tests/prompt_strategies/test_chat_template_ds_schema_unification.py

@NanoCode012 NanoCode012 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you for the clear issue and fix.

This brings up a second issue, whether this could also occur for tools, since it has a lot of nested elements. For example, one int field could have a min attribute. Would this also appear as null for a string field due to the potential schema merge?

Either way, your fix should catch it.

@winglian winglian added the bug Something isn't working label Jul 14, 2025
@winglian winglian merged commit a061446 into axolotl-ai-cloud:main Jul 15, 2025
15 checks passed
@greenhestu

Copy link
Copy Markdown
Contributor Author

That’s definitely an issue—thanks for pointing it out.

Then we need to use something other than load_dataset to load the JSONL file.

  • (As lhoestq mentioned in this discussion, 🤗 Datasets isn’t suitable for such a dataset when the same field can appear with different data types)

I considered using orjsonl, but I’m not familiar with this repo, and the loading code is heavily tied to datasets. Fixing it would take more time than I can spare right now.

Would it be better to close this PR and continue the discussion in an issue instead?

@greenhestu

Copy link
Copy Markdown
Contributor Author

Oh, it’s already been merged. Thanks!

@NanoCode012

Copy link
Copy Markdown
Collaborator

For now, I think your fix covers that case too. Thank you for the PR!

@greenhestu

Copy link
Copy Markdown
Contributor Author

I now see you were talking about schema merging for nested elements.

I had confused it with a type conflict issue, like when a field type changes from a integer to a string.

{"messages":[{"role":"user","content":"send data1 1"},{"role":"assistant","content":"","tool_calls":[{"function":{"name":"send_data1","arguments":{"data":1}}}]}],"tools":[{"type":"function","function":{"name":"send_data1","description":"send data","parameters":{"type":"object","properties":{"data":{"type":"integer","description":"the data"}},"required":["data"]}}},{"type":"function","function":{"name":"send_data2","description":"send data","parameters":{"type":"object","properties":{"data":{"type":"string","description":"the data"}},"required":["data"]}}}],"add_generation_prompt":false}
{"messages":[{"role":"user","content":"send data2 2"},{"role":"assistant","content":"","tool_calls":[{"function":{"name":"send_data2","arguments":{"data":"2"}}}]}],"tools":[{"type":"function","function":{"name":"send_data1","description":"send data","parameters":{"type":"object","properties":{"data":{"type":"integer","description":"the data"}},"required":["data"]}}},{"type":"function","function":{"name":"send_data2","description":"send data","parameters":{"type":"object","properties":{"data":{"type":"string","description":"the data"}},"required":["data"]}}}],"add_generation_prompt":false}

pyarrow.lib.ArrowInvalid: JSON parse error: Column(/messages/[]/tool_calls/[]/function/arguments/data) changed from number to string in row 1

This could be avoided by using different field names for different types, though.

Appreciate the review!

@gamersover

Copy link
Copy Markdown
Contributor

I have a pr to solve this issue. The root cause is that arguments is of type dict. The ideal solution would be to change arguments to a string type, which would resolve all related problems. #3136

I now see you were talking about schema merging for nested elements.

I had confused it with a type conflict issue, like when a field type changes from a integer to a string.

{"messages":[{"role":"user","content":"send data1 1"},{"role":"assistant","content":"","tool_calls":[{"function":{"name":"send_data1","arguments":{"data":1}}}]}],"tools":[{"type":"function","function":{"name":"send_data1","description":"send data","parameters":{"type":"object","properties":{"data":{"type":"integer","description":"the data"}},"required":["data"]}}},{"type":"function","function":{"name":"send_data2","description":"send data","parameters":{"type":"object","properties":{"data":{"type":"string","description":"the data"}},"required":["data"]}}}],"add_generation_prompt":false}
{"messages":[{"role":"user","content":"send data2 2"},{"role":"assistant","content":"","tool_calls":[{"function":{"name":"send_data2","arguments":{"data":"2"}}}]}],"tools":[{"type":"function","function":{"name":"send_data1","description":"send data","parameters":{"type":"object","properties":{"data":{"type":"integer","description":"the data"}},"required":["data"]}}},{"type":"function","function":{"name":"send_data2","description":"send data","parameters":{"type":"object","properties":{"data":{"type":"string","description":"the data"}},"required":["data"]}}}],"add_generation_prompt":false}

pyarrow.lib.ArrowInvalid: JSON parse error: Column(/messages/[]/tool_calls/[]/function/arguments/data) changed from number to string in row 1

This could be avoided by using different field names for different types, though.

Appreciate the review!

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

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants