Skip to content

Personal AI, On Personal Devices

Python

fix(agents): normalize structured string tool inputs

Haotian Zheng20a742488362
diff --git a/src/openjarvis/agents/orchestrator.py b/src/openjarvis/agents/orchestrator.py
index 7241cb38..d97cceb1 100644
--- a/src/openjarvis/agents/orchestrator.py
+++ b/src/openjarvis/agents/orchestrator.py
@@ -13,6 +13,7 @@ Supports two modes:
from __future__ import annotations
import concurrent.futures
+import json
import re
from typing import Any, List, Optional
@@ -142,7 +143,10 @@ class OrchestratorAgent(ToolUsingAgent):
tool_call = ToolCall(
id=f"orch_{turns}",
name=parsed["tool"],
- arguments=parsed["input"] or "{}",
+ arguments=self._normalize_structured_tool_input(
+ parsed["tool"],
+ parsed["input"],
+ ),
)
tool_result = self._executor.execute(tool_call)
all_tool_results.append(tool_result)
@@ -162,6 +166,58 @@ class OrchestratorAgent(ToolUsingAgent):
# Max turns exceeded
return self._max_turns_result(all_tool_results, turns)
+ def _normalize_structured_tool_input(
+ self,
+ tool_name: str,
+ raw_input: str,
+ ) -> str:
+ """Map an unambiguous string input to the tool's JSON parameter."""
+ if not raw_input:
+ return "{}"
+
+ try:
+ parsed_input = json.loads(raw_input)
+ except json.JSONDecodeError:
+ parsed_input = raw_input
+
+ if isinstance(parsed_input, dict):
+ return raw_input
+ if not isinstance(parsed_input, str):
+ return raw_input
+
+ tool = next(
+ (
+ candidate
+ for candidate in self._tools
+ if candidate.spec.name == tool_name
+ ),
+ None,
+ )
+ if tool is None:
+ return raw_input
+
+ parameters = tool.spec.parameters
+ properties = parameters.get("properties", {})
+ required = parameters.get("required", [])
+ if not isinstance(properties, dict) or not isinstance(required, list):
+ return raw_input
+
+ if len(required) == 1 and required[0] in properties:
+ parameter_name = required[0]
+ elif not required and len(properties) == 1:
+ parameter_name = next(iter(properties))
+ else:
+ return raw_input
+
+ parameter_schema = properties[parameter_name]
+ if isinstance(parameter_schema, dict) and parameter_schema.get("type") not in (
+ None,
+ "string",
+ ):
+ return raw_input
+
+ return json.dumps({parameter_name: parsed_input})
+
@staticmethod
def _parse_structured_response(text: str) -> dict:
"""Parse THOUGHT/TOOL/INPUT/FINAL_ANSWER from model output."""
diff --git a/tests/test_orchestrator_learning/test_orchestrator_structured.py b/tests/test_orchestrator_learning/test_orchestrator_structured.py
index 63643935..e6578496 100644
--- a/tests/test_orchestrator_learning/test_orchestrator_structured.py
+++ b/tests/test_orchestrator_learning/test_orchestrator_structured.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import pytest
+
from openjarvis.agents.orchestrator import OrchestratorAgent
from openjarvis.core.types import ToolResult
from openjarvis.engine._stubs import InferenceEngine
@@ -58,6 +60,58 @@ class _MockTool(BaseTool):
return ToolResult(tool_name="calculator", content=str(expr), success=True)
+class _FileReadLikeTool(BaseTool):
+ """Small test double with one required and one optional parameter."""
+
+ tool_id = "file_read"
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name="file_read",
+ description="Read a file",
+ parameters={
+ "type": "object",
+ "properties": {
+ "path": {"type": "string"},
+ "max_lines": {"type": "integer"},
+ },
+ "required": ["path"],
+ },
+ )
+
+ def execute(self, **params) -> ToolResult:
+ return ToolResult(
+ tool_name="file_read",
+ content=params.get("path", ""),
+ success=True,
+ )
+
+
+class _AmbiguousTool(BaseTool):
+ """Test double whose bare input cannot map to one parameter safely."""
+
+ tool_id = "copy"
+
+ @property
+ def spec(self) -> ToolSpec:
+ return ToolSpec(
+ name="copy",
+ description="Copy a value",
+ parameters={
+ "type": "object",
+ "properties": {
+ "source": {"type": "string"},
+ "destination": {"type": "string"},
+ },
+ "required": ["source", "destination"],
+ },
+ )
+
+ def execute(self, **params) -> ToolResult:
+ return ToolResult(tool_name="copy", content="copied", success=True)
+
+
# -- Tests -------------------------------------------------------------------
@@ -80,6 +134,56 @@ class TestStructuredMode:
assert result.content == "4"
assert result.turns == 2
assert len(result.tool_results) == 1
+ assert result.tool_results[0].success is True
+ assert result.tool_results[0].content == "2+2"
+
+ @pytest.mark.parametrize(
+ "raw_input",
+ [
+ "notes/today.md",
+ '"notes/today.md"',
+ '{"path": "notes/today.md"}',
+ ],
+ )
+ def test_single_required_parameter_accepts_string_input(self, raw_input):
+ """Structured input maps unambiguous strings to the required field."""
+ engine = _MockEngine(
+ [
+ f"TOOL: file_read\nINPUT: {raw_input}",
+ "FINAL_ANSWER: done",
+ ]
+ )
+ agent = OrchestratorAgent(
+ engine=engine,
+ model="test",
+ tools=[_FileReadLikeTool()],
+ mode="structured",
+ )
+
+ result = agent.run("Read my notes")
+
+ assert result.tool_results[0].success is True
+ assert result.tool_results[0].content == "notes/today.md"
+
+ def test_multiple_required_parameters_do_not_guess_string_mapping(self):
+ """Ambiguous bare input remains invalid instead of choosing a field."""
+ engine = _MockEngine(
+ [
+ "TOOL: copy\nINPUT: notes/today.md",
+ "FINAL_ANSWER: done",
+ ]
+ )
+ agent = OrchestratorAgent(
+ engine=engine,
+ model="test",
+ tools=[_AmbiguousTool()],
+ mode="structured",
+ )
+
+ result = agent.run("Copy my notes")
+
+ assert result.tool_results[0].success is False
+ assert "Invalid arguments JSON" in result.tool_results[0].content
def test_direct_final_answer(self):
"""Test that FINAL_ANSWER on first turn works."""