microsoft/autogen · error · ValueError

Expected a single JSON object, but found {len(json_objs)}

Error message

Expected a single JSON object, but found {len(json_objs)}

What it means

When converting a previous AssistantMessage's tool calls back into Anthropic ToolUseBlocks, the client parses each function-call arguments string expecting exactly one JSON object (Anthropic requires tool input as a single object). If extract_json_from_str finds zero or multiple JSON objects in the string, it raises ValueError reporting how many were found. The nearby except json.JSONDecodeError fallback never fires because this ValueError is a different exception type.

Source

Thrown at python/packages/autogen-ext/src/autogen_ext/models/anthropic/_anthropic_client.py:252

    return __empty_content_to_whitespace(message.content)


def assistant_message_to_anthropic(message: AssistantMessage) -> MessageParam:
    assert_valid_name(message.source)

    if isinstance(message.content, list):
        # Tool calls
        tool_use_blocks: List[ToolUseBlock] = []

        for func_call in message.content:
            # Parse the arguments and convert to dict if it's a JSON string
            args = func_call.arguments
            args = __empty_content_to_whitespace(args)
            if isinstance(args, str):
                try:
                    json_objs = extract_json_from_str(args)
                    if len(json_objs) != 1:
                        raise ValueError(f"Expected a single JSON object, but found {len(json_objs)}")
                    args_dict = json_objs[0]
                except json.JSONDecodeError:
                    args_dict = {"text": args}
            else:
                args_dict = args

            tool_use_blocks.append(
                ToolUseBlock(
                    type="tool_use",
                    id=func_call.id,
                    name=func_call.name,
                    input=args_dict,
                )
            )

        # Include thought if available
        content_blocks: List[ContentBlock] = []
        if hasattr(message, "thought") and message.thought is not None:

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Sanitize stored tool-call arguments to a single JSON object before replaying history (validate with json.loads and re-dump).
  2. When constructing FunctionCall objects yourself, always pass json.dumps({...}) as arguments, never concatenated objects.
  3. If a legacy call's args are unrecoverable, replace with {} and a note, or drop that turn from the context.

Example fix

# before
FunctionCall(id='1', name='run', arguments='{"a":1}{"b":2}')  # ValueError on replay

# after
import json
FunctionCall(id='1', name='run', arguments=json.dumps({"a": 1, "b": 2}))
Defensive patterns

Strategy: validation

Validate before calling

import json

def safe_args(args) -> str:
    if isinstance(args, str):
        try:
            obj = json.loads(args)
            if isinstance(obj, dict):
                return args
        except json.JSONDecodeError:
            pass
        return json.dumps({'text': args})
    return json.dumps(args)

Type guard

def is_single_json_object(args: str) -> bool:
    try:
        return isinstance(json.loads(args), dict)
    except (json.JSONDecodeError, TypeError):
        return False

Try / catch

try:
    res = await client.create(history)
except ValueError as e:
    if 'single JSON object' in str(e):
        history = [sanitize_function_calls(m) for m in history]
        res = await client.create(history)
    else:
        raise

Prevention

When it happens

Trigger: Replaying a conversation where a tool call's arguments contain two concatenated JSON objects (e.g. '{"a":1}{"b":2}'), an empty/whitespace string after coercion, or text with no complete JSON; function-calling models that emit malformed argument strings.

Common situations: Multi-turn agents feeding history back through the Anthropic client after a different model produced sloppy tool args; hand-built histories with copy-paste concatenation; truncation mid-JSON leaving zero parseable objects.

Related errors


AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15). Data as JSON: /api/errors/4d9f28c4aeddd47f. Report an issue: GitHub.