crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

Converter falls back to an unnecessary LLM refit when a valid JSON object is followed by prose containing braces

Open Luckyou-d opened this issue 4 weeks ago • 1 comments

Description

handle_partial_json / async_handle_partial_json in crewai/utilities/converter.py locate the JSON object in an LLM response with the greedy regex ({.*}) (re.DOTALL). The match spans from the first { to the last } in the whole result string, so a valid JSON object followed by prose that itself contains braces fails to parse:

# current main
result = '{"name": "Charlie", "age": 35}

Note: configuration uses {"debug": true} mode.'
# _JSON_PATTERN.search matches the whole string -> json.loads raises "Extra data"
# -> convert_with_instructions fallback

Two adjacent objects ('{"a": 1}{"b": 2}') hit the same path.

Impact

  • With an agent: an extra LLM refit call is made even though a perfectly valid object was present - slower and more expensive on every response that happens to mention {...} in prose.
  • Without an agent (e.g. pure post-processing via Converter._coerce_response_to_pydantic): the fallback raises TypeError: Agent must be provided if converter_cls is not specified. even though parsing was possible.

Steps to reproduce

from pydantic import BaseModel
from crewai.utilities.converter import handle_partial_json

class SimpleModel(BaseModel):
    name: str
    age: int

# raises TypeError on main:
handle_partial_json(
    '{"name": "Charlie", "age": 35}

Note: configuration uses {"debug": true} mode.',
    SimpleModel, False, None,
)

Expected behavior

The first complete JSON object should be extracted and validated directly; the LLM-refit fallback should be reserved for results that contain no complete object (truncated JSON, non-JSON curly blocks).

Suggested fix

Scan with json.JSONDecoder(strict=False).raw_decode from each { and return the first object that parses, preserving the current lenient handling of literal control characters in strings. Apply to both the sync and async variants.

Luckyou-d avatar Nov 05 '26 09:11 Luckyou-d

Fix opened in #9124 (clean branch, single-purpose).

Luckyou-d avatar Nov 05 '26 09:11 Luckyou-d