Skip to content

Agent output

AgentOutputSchemaBase

Bases: ABC

An object that captures the JSON schema of the output, as well as validating/parsing JSON produced by the LLM into the output type.

Source code in .tmp/v0/src/agents/agent_output.py
class AgentOutputSchemaBase(abc.ABC):
    """An object that captures the JSON schema of the output, as well as validating/parsing JSON
    produced by the LLM into the output type.
    """

    @abc.abstractmethod
    def is_plain_text(self) -> bool:
        """Whether the output type is plain text (versus a JSON object)."""
        pass

    @abc.abstractmethod
    def name(self) -> str:
        """The name of the output type."""
        pass

    @abc.abstractmethod
    def json_schema(self) -> dict[str, Any]:
        """Returns the JSON schema of the output. Will only be called if the output type is not
        plain text.
        """
        pass

    @abc.abstractmethod
    def is_strict_json_schema(self) -> bool:
        """Whether the JSON schema is in strict mode. Strict mode constrains the JSON schema
        features, but guarantees valid JSON. See here for details:
        https://platform.openai.com/docs/guides/structured-outputs#supported-schemas
        """
        pass

    @abc.abstractmethod
    def validate_json(self, json_str: str) -> Any:
        """Validate a JSON string against the output type. You must return the validated object,
        or raise a `ModelBehaviorError` if the JSON is invalid.
        """
        pass

is_plain_text abstractmethod

is_plain_text() -> bool

Whether the output type is plain text (versus a JSON object).

Source code in .tmp/v0/src/agents/agent_output.py
@abc.abstractmethod
def is_plain_text(self) -> bool:
    """Whether the output type is plain text (versus a JSON object)."""
    pass

name abstractmethod

name() -> str

The name of the output type.

Source code in .tmp/v0/src/agents/agent_output.py
@abc.abstractmethod
def name(self) -> str:
    """The name of the output type."""
    pass

json_schema abstractmethod

json_schema() -> dict[str, Any]

Returns the JSON schema of the output. Will only be called if the output type is not plain text.

Source code in .tmp/v0/src/agents/agent_output.py
@abc.abstractmethod
def json_schema(self) -> dict[str, Any]:
    """Returns the JSON schema of the output. Will only be called if the output type is not
    plain text.
    """
    pass

is_strict_json_schema abstractmethod

is_strict_json_schema() -> bool

Whether the JSON schema is in strict mode. Strict mode constrains the JSON schema features, but guarantees valid JSON. See here for details: https://platform.openai.com/docs/guides/structured-outputs#supported-schemas

Source code in .tmp/v0/src/agents/agent_output.py
@abc.abstractmethod
def is_strict_json_schema(self) -> bool:
    """Whether the JSON schema is in strict mode. Strict mode constrains the JSON schema
    features, but guarantees valid JSON. See here for details:
    https://platform.openai.com/docs/guides/structured-outputs#supported-schemas
    """
    pass

validate_json abstractmethod

validate_json(json_str: str) -> Any

Validate a JSON string against the output type. You must return the validated object, or raise a ModelBehaviorError if the JSON is invalid.

Source code in .tmp/v0/src/agents/agent_output.py
@abc.abstractmethod
def validate_json(self, json_str: str) -> Any:
    """Validate a JSON string against the output type. You must return the validated object,
    or raise a `ModelBehaviorError` if the JSON is invalid.
    """
    pass

AgentOutputSchema dataclass

Bases: AgentOutputSchemaBase

An object that captures the JSON schema of the output, as well as validating/parsing JSON produced by the LLM into the output type.

Source code in .tmp/v0/src/agents/agent_output.py
@dataclass(init=False)
class AgentOutputSchema(AgentOutputSchemaBase):
    """An object that captures the JSON schema of the output, as well as validating/parsing JSON
    produced by the LLM into the output type.
    """

    output_type: type[Any]
    """The type of the output."""

    _type_adapter: TypeAdapter[Any]
    """A type adapter that wraps the output type, so that we can validate JSON."""

    _bare_root_adapter: TypeAdapter[Any] | None
    """The original validator for previously supported bare non-object RootModel outputs."""

    _is_wrapped: bool
    """Whether the output type is wrapped in a dictionary. This is generally done if the base
    output type cannot be represented as a JSON Schema object.
    """

    _output_schema: dict[str, Any]
    """The JSON schema of the output."""

    _strict_json_schema: bool
    """Whether the JSON schema is in strict mode. We **strongly** recommend setting this to True,
    as it increases the likelihood of correct JSON input.
    """

    def __init__(self, output_type: type[Any], strict_json_schema: bool = True):
        """
        Args:
            output_type: The type of the output.
            strict_json_schema: Whether the JSON schema is in strict mode. We **strongly** recommend
                setting this to True, as it increases the likelihood of correct JSON input.
        """
        self.output_type = output_type
        self._strict_json_schema = strict_json_schema
        self._bare_root_adapter = None

        if output_type is None or output_type is str:
            self._is_wrapped = False
            self._type_adapter = TypeAdapter(output_type)
            self._output_schema = self._type_adapter.json_schema()
            return

        # We should wrap for things that are not plain text, and for things that would definitely
        # not be a JSON Schema object.
        self._is_wrapped = not _is_subclass_of_base_model_or_dict(output_type)

        if not self._is_wrapped:
            self._type_adapter = TypeAdapter(output_type)
            self._output_schema = self._type_adapter.json_schema()
            if (
                self._strict_json_schema
                and isinstance(output_type, type)
                and issubclass(output_type, RootModel)
            ):
                # A RootModel exposes the JSON shape of its root, which may itself be a reference.
                try:
                    direct_schema, root_error = _prepare_strict_json_schema(self._output_schema)
                except UserError as e:
                    raise _invalid_strict_output_type() from e
                if root_error is None:
                    if _root_can_be_object(direct_schema):
                        self._output_schema = direct_schema
                        return
                    # Custom providers may still return the bare value accepted before wrapping.
                    self._bare_root_adapter = self._type_adapter
                self._is_wrapped = True

        if self._is_wrapped:
            OutputType = TypedDict(
                "OutputType",
                {
                    _WRAPPER_DICT_KEY: output_type,  # type: ignore
                },
            )
            self._type_adapter = TypeAdapter(OutputType)
            self._output_schema = self._type_adapter.json_schema()

        if self._strict_json_schema:
            try:
                self._output_schema = ensure_strict_json_schema(self._output_schema)
            except UserError as e:
                raise _invalid_strict_output_type() from e

    def is_plain_text(self) -> bool:
        """Whether the output type is plain text (versus a JSON object)."""
        return self.output_type is None or self.output_type is str

    def is_strict_json_schema(self) -> bool:
        """Whether the JSON schema is in strict mode."""
        return self._strict_json_schema

    def json_schema(self) -> dict[str, Any]:
        """The JSON schema of the output type."""
        if self.is_plain_text():
            raise UserError("Output type is plain text, so no JSON schema is available")
        return self._output_schema

    def validate_json(self, json_str: str) -> Any:
        """Validate a JSON string against the output type. Returns the validated object, or raises
        a `ModelBehaviorError` if the JSON is invalid.
        """
        redacted_error: ModelBehaviorError | None = None
        # An object must match the advertised envelope, even when bare scalar or list JSON is valid.
        bare_adapter = (
            self._bare_root_adapter
            if self._bare_root_adapter is not None and not json_str.lstrip().startswith("{")
            else None
        )
        try:
            validated = _json.validate_json(
                json_str,
                bare_adapter or self._type_adapter,
                partial=False,
                strict=True if self._strict_json_schema else None,
            )
        except ModelBehaviorError as error:
            if not _is_error_data_redacted(error):
                raise
            _detach_data_redacted_error_traceback(error)
            redacted_error = error

        if redacted_error is not None:
            self = cast(Any, None)
            bare_adapter = None
            json_str = "<redacted>"
            _raise_data_redacted_error(redacted_error)
        if self._is_wrapped and bare_adapter is None:
            if not isinstance(validated, dict):
                _error_tracing.attach_error_to_current_span(
                    SpanError(
                        message="Invalid JSON",
                        data={"details": f"Expected a dict, got {type(validated)}"},
                    )
                )
                raise ModelBehaviorError(
                    f"Expected a dict, got {type(validated)} for JSON: {json_str}"
                )

            if _WRAPPER_DICT_KEY not in validated:
                _error_tracing.attach_error_to_current_span(
                    SpanError(
                        message="Invalid JSON",
                        data={"details": f"Could not find key {_WRAPPER_DICT_KEY} in JSON"},
                    )
                )
                raise ModelBehaviorError(
                    f"Could not find key {_WRAPPER_DICT_KEY} in JSON: {json_str}"
                )
            return validated[_WRAPPER_DICT_KEY]
        return validated

    def name(self) -> str:
        """The name of the output type."""
        return _type_to_str(self.output_type)

output_type instance-attribute

output_type: type[Any] = output_type

The type of the output.

__init__

__init__(
    output_type: type[Any], strict_json_schema: bool = True
)

Parameters:

Name Type Description Default
output_type type[Any]

The type of the output.

required
strict_json_schema bool

Whether the JSON schema is in strict mode. We strongly recommend setting this to True, as it increases the likelihood of correct JSON input.

True
Source code in .tmp/v0/src/agents/agent_output.py
def __init__(self, output_type: type[Any], strict_json_schema: bool = True):
    """
    Args:
        output_type: The type of the output.
        strict_json_schema: Whether the JSON schema is in strict mode. We **strongly** recommend
            setting this to True, as it increases the likelihood of correct JSON input.
    """
    self.output_type = output_type
    self._strict_json_schema = strict_json_schema
    self._bare_root_adapter = None

    if output_type is None or output_type is str:
        self._is_wrapped = False
        self._type_adapter = TypeAdapter(output_type)
        self._output_schema = self._type_adapter.json_schema()
        return

    # We should wrap for things that are not plain text, and for things that would definitely
    # not be a JSON Schema object.
    self._is_wrapped = not _is_subclass_of_base_model_or_dict(output_type)

    if not self._is_wrapped:
        self._type_adapter = TypeAdapter(output_type)
        self._output_schema = self._type_adapter.json_schema()
        if (
            self._strict_json_schema
            and isinstance(output_type, type)
            and issubclass(output_type, RootModel)
        ):
            # A RootModel exposes the JSON shape of its root, which may itself be a reference.
            try:
                direct_schema, root_error = _prepare_strict_json_schema(self._output_schema)
            except UserError as e:
                raise _invalid_strict_output_type() from e
            if root_error is None:
                if _root_can_be_object(direct_schema):
                    self._output_schema = direct_schema
                    return
                # Custom providers may still return the bare value accepted before wrapping.
                self._bare_root_adapter = self._type_adapter
            self._is_wrapped = True

    if self._is_wrapped:
        OutputType = TypedDict(
            "OutputType",
            {
                _WRAPPER_DICT_KEY: output_type,  # type: ignore
            },
        )
        self._type_adapter = TypeAdapter(OutputType)
        self._output_schema = self._type_adapter.json_schema()

    if self._strict_json_schema:
        try:
            self._output_schema = ensure_strict_json_schema(self._output_schema)
        except UserError as e:
            raise _invalid_strict_output_type() from e

is_plain_text

is_plain_text() -> bool

Whether the output type is plain text (versus a JSON object).

Source code in .tmp/v0/src/agents/agent_output.py
def is_plain_text(self) -> bool:
    """Whether the output type is plain text (versus a JSON object)."""
    return self.output_type is None or self.output_type is str

is_strict_json_schema

is_strict_json_schema() -> bool

Whether the JSON schema is in strict mode.

Source code in .tmp/v0/src/agents/agent_output.py
def is_strict_json_schema(self) -> bool:
    """Whether the JSON schema is in strict mode."""
    return self._strict_json_schema

json_schema

json_schema() -> dict[str, Any]

The JSON schema of the output type.

Source code in .tmp/v0/src/agents/agent_output.py
def json_schema(self) -> dict[str, Any]:
    """The JSON schema of the output type."""
    if self.is_plain_text():
        raise UserError("Output type is plain text, so no JSON schema is available")
    return self._output_schema

validate_json

validate_json(json_str: str) -> Any

Validate a JSON string against the output type. Returns the validated object, or raises a ModelBehaviorError if the JSON is invalid.

Source code in .tmp/v0/src/agents/agent_output.py
def validate_json(self, json_str: str) -> Any:
    """Validate a JSON string against the output type. Returns the validated object, or raises
    a `ModelBehaviorError` if the JSON is invalid.
    """
    redacted_error: ModelBehaviorError | None = None
    # An object must match the advertised envelope, even when bare scalar or list JSON is valid.
    bare_adapter = (
        self._bare_root_adapter
        if self._bare_root_adapter is not None and not json_str.lstrip().startswith("{")
        else None
    )
    try:
        validated = _json.validate_json(
            json_str,
            bare_adapter or self._type_adapter,
            partial=False,
            strict=True if self._strict_json_schema else None,
        )
    except ModelBehaviorError as error:
        if not _is_error_data_redacted(error):
            raise
        _detach_data_redacted_error_traceback(error)
        redacted_error = error

    if redacted_error is not None:
        self = cast(Any, None)
        bare_adapter = None
        json_str = "<redacted>"
        _raise_data_redacted_error(redacted_error)
    if self._is_wrapped and bare_adapter is None:
        if not isinstance(validated, dict):
            _error_tracing.attach_error_to_current_span(
                SpanError(
                    message="Invalid JSON",
                    data={"details": f"Expected a dict, got {type(validated)}"},
                )
            )
            raise ModelBehaviorError(
                f"Expected a dict, got {type(validated)} for JSON: {json_str}"
            )

        if _WRAPPER_DICT_KEY not in validated:
            _error_tracing.attach_error_to_current_span(
                SpanError(
                    message="Invalid JSON",
                    data={"details": f"Could not find key {_WRAPPER_DICT_KEY} in JSON"},
                )
            )
            raise ModelBehaviorError(
                f"Could not find key {_WRAPPER_DICT_KEY} in JSON: {json_str}"
            )
        return validated[_WRAPPER_DICT_KEY]
    return validated

name

name() -> str

The name of the output type.

Source code in .tmp/v0/src/agents/agent_output.py
def name(self) -> str:
    """The name of the output type."""
    return _type_to_str(self.output_type)