agentscope-ai/agentscope · error · StructuredOutputError

Invalid structured output from model {model_name}: {e}

Error message

Invalid structured output from model {model_name}: {e}

What it means

The model's structured output was parsed but failed validation against the provided schema (JSON schema validation or Pydantic model_validate). The error chains the underlying ValidationError and wraps it in StructuredOutputError with the model name.

Source

Thrown at src/agentscope/model/_base.py:731

            # Validate the output
            if isinstance(structured_model, dict):
                jsonschema.validate(structured_output, structured_model)

            elif issubclass(structured_model, BaseModel):
                structured_model.model_validate(structured_output)

            else:
                raise ValueError(
                    "The structured_model is expected to be a subclass of "
                    "Pydantic.BaseModel or a dict, "
                    f"but got {type(structured_model)}.",
                )
        except (
            ToolJSONDecodeError,
            jsonschema.ValidationError,
            PydanticValidationError,
        ) as e:
            raise StructuredOutputError(
                f"Invalid structured output from model {model_name}: {e}",
            ) from e

        return StructuredResponse(
            id=completed_response.id,
            created_at=completed_response.created_at,
            content=structured_output,
            usage=completed_response.usage,
            finished_reason=completed_response.finished_reason,
        )

View on GitHub (pinned to e90f1c7592)

Solutions

  1. Read the chained ValidationError: it names the exact field and violation — fix the prompt or schema accordingly
  2. Make schema fields Optional with defaults so the model isn't forced to fill everything
  3. Add field descriptions and examples in the Pydantic model so the model knows expected formats
  4. Retry the call; wrap in a repair loop that feeds the validation error back to the model

Example fix

# before
class Out(BaseModel):
    age: int  # model returns "25" string -> ValidationError

# after
from pydantic import Field
class Out(BaseModel):
    age: int = Field(..., description='Age in years as an integer, e.g. 25')
Defensive patterns

Strategy: try-catch

Try / catch

try:
    res = await model.generate_structured_output(msgs, Schema)
except StructuredOutputError as e:
    if not isinstance(e.__cause__, (ValueError,)) or 'validation' not in str(e.__cause__).lower():
        raise
    # repair loop: send validation error back to model
    msgs.append(Msg('user', f'Fix these validation errors: {e.__cause__}'))

Prevention

When it happens

Trigger: Model returns JSON that is missing required fields, has wrong types (string where int expected), extra fields not allowed, or enum values outside the allowed set.

Common situations: Strict Pydantic schema with required fields the model omits; model coercing numbers to strings; schemas with additionalProperties=False; vague prompts letting the model guess field formats.

Understand the failure class

Background: Schema validation failed / invalid input schema: payload rejected because its shape doesn't match the expected schema — this error's family across 28 libraries.

Related errors


AI-assisted analysis of agentscope-ai/agentscope@e90f1c7592 (2026-08-28). Data as JSON: /api/errors/6510b1fcd5f74b5c. Report an issue: GitHub.