跳转至

Agent output

AgentOutputSchemaBase

Bases: ABC

一个用于捕获输出的 JSON schema,并将 LLM 生成的 JSON 验证/解析为输出类型的对象。

Source code in src/agents/agent_output.py
class AgentOutputSchemaBase(abc.ABC):
    """一个用于捕获输出的 JSON schema,并将 LLM 生成的 JSON 验证/解析为输出类型的对象。"""

    @abc.abstractmethod
    def is_plain_text(self) -> bool:
        """输出类型是否为纯文本(而不是 JSON 对象)。"""
        pass

    @abc.abstractmethod
    def name(self) -> str:
        """输出类型的名称。"""
        pass

    @abc.abstractmethod
    def json_schema(self) -> dict[str, Any]:
        """返回输出的 JSON schema。仅当输出类型不是纯文本时才会被调用。"""
        pass

    @abc.abstractmethod
    def is_strict_json_schema(self) -> bool:
        """JSON schema 是否为严格模式。严格模式限制了 JSON schema 的特性,但保证了有效的 JSON。
        详情见:https://platform.openai.com/docs/guides/structured-outputs#supported-schemas
        """
        pass

    @abc.abstractmethod
    def validate_json(self, json_str: str) -> Any:
        """根据输出类型验证 JSON 字符串。你必须返回验证后的对象,或者在 JSON 无效时抛出 `ModelBehaviorError`。"""
        pass

is_plain_text abstractmethod

is_plain_text() -> bool

输出类型是否为纯文本(而不是 JSON 对象)。

Source code in src/agents/agent_output.py
@abc.abstractmethod
def is_plain_text(self) -> bool:
    """输出类型是否为纯文本(而不是 JSON 对象)。"""
    pass

name abstractmethod

name() -> str

输出类型的名称。

Source code in src/agents/agent_output.py
@abc.abstractmethod
def name(self) -> str:
    """输出类型的名称。"""
    pass

json_schema abstractmethod

json_schema() -> dict[str, Any]

返回输出的 JSON schema。仅当输出类型不是纯文本时才会被调用。

Source code in src/agents/agent_output.py
@abc.abstractmethod
def json_schema(self) -> dict[str, Any]:
    """返回输出的 JSON schema。仅当输出类型不是纯文本时才会被调用。"""
    pass

is_strict_json_schema abstractmethod

is_strict_json_schema() -> bool

JSON schema 是否为严格模式。严格模式限制了 JSON schema 的特性,但保证了有效的 JSON。 详情见:https://platform.openai.com/docs/guides/structured-outputs#supported-schemas

Source code in src/agents/agent_output.py
@abc.abstractmethod
def is_strict_json_schema(self) -> bool:
    """JSON schema 是否为严格模式。严格模式限制了 JSON schema 的特性,但保证了有效的 JSON。
    详情见:https://platform.openai.com/docs/guides/structured-outputs#supported-schemas
    """
    pass

validate_json abstractmethod

validate_json(json_str: str) -> Any

根据输出类型验证 JSON 字符串。你必须返回验证后的对象,或者在 JSON 无效时抛出 ModelBehaviorError

Source code in src/agents/agent_output.py
@abc.abstractmethod
def validate_json(self, json_str: str) -> Any:
    """根据输出类型验证 JSON 字符串。你必须返回验证后的对象,或者在 JSON 无效时抛出 `ModelBehaviorError`。"""
    pass

AgentOutputSchema dataclass

Bases: AgentOutputSchemaBase

一个用于捕获输出的 JSON schema,并将 LLM 生成的 JSON 验证/解析为输出类型的对象。

Source code in src/agents/agent_output.py
@dataclass(init=False)
class AgentOutputSchema(AgentOutputSchemaBase):
    """一个用于捕获输出的 JSON schema,并将 LLM 生成的 JSON 验证/解析为输出类型的对象。"""

    output_type: type[Any]
    """输出的类型。"""

    _type_adapter: TypeAdapter[Any]
    """包装输出类型的类型适配器,用于验证 JSON。"""

    _is_wrapped: bool
    """输出类型是否被包裹在字典中。如果基础输出类型无法表示为 JSON Schema 对象,通常会这样做。"""

    _output_schema: dict[str, Any]
    """输出的 JSON schema。"""

    _strict_json_schema: bool
    """JSON schema 是否为严格模式。我们**强烈**建议将其设置为 True,这样可以提高获得正确 JSON 输入的概率。"""

    def __init__(self, output_type: type[Any], strict_json_schema: bool = True):
        """
        参数:
            output_type: 输出的类型。
            strict_json_schema: JSON schema 是否为严格模式。我们**强烈**建议将其设置为 True,这样可以提高获得正确 JSON 输入的概率。
        """
        self.output_type = output_type
        self._strict_json_schema = strict_json_schema

        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

        # 对于非纯文本类型,以及那些肯定不是 JSON Schema 对象的类型,我们应该进行包裹。
        self._is_wrapped = not _is_subclass_of_base_model_or_dict(output_type)

        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()
        else:
            self._type_adapter = TypeAdapter(output_type)
            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 UserError(
                    "启用了严格 JSON schema,但输出类型无效。请将输出类型设为严格,或在 Agent() 中传递 output_schema_strict=False"
                ) from e

    def is_plain_text(self) -> bool:
        """输出类型是否为纯文本(而不是 JSON 对象)。"""
        return self.output_type is None or self.output_type is str

    def is_strict_json_schema(self) -> bool:
        """JSON schema 是否为严格模式。"""
        return self._strict_json_schema

    def json_schema(self) -> dict[str, Any]:
        """输出类型的 JSON schema。"""
        if self.is_plain_text():
            raise UserError("输出类型为纯文本,因此没有可用的 JSON schema")
        return self._output_schema

    def validate_json(self, json_str: str) -> Any:
        """根据输出类型验证 JSON 字符串。返回验证后的对象,或在 JSON 无效时抛出 `ModelBehaviorError`。"""
        validated = _json.validate_json(json_str, self._type_adapter, partial=False)
        if self._is_wrapped:
            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:
        """输出类型的名称。"""
        return _type_to_str(self.output_type)

output_type instance-attribute

output_type: type[Any] = output_type

输出的类型。

__init__

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

output_type: 输出的类型。 strict_json_schema: JSON schema 是否为严格模式。我们强烈建议将其设置为 True,这样可以提高获得正确 JSON 输入的概率。

Source code in src/agents/agent_output.py
def __init__(self, output_type: type[Any], strict_json_schema: bool = True):
    """
    参数:
        output_type: 输出的类型。
        strict_json_schema: JSON schema 是否为严格模式。我们**强烈**建议将其设置为 True,这样可以提高获得正确 JSON 输入的概率。
    """
    self.output_type = output_type
    self._strict_json_schema = strict_json_schema

    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

    # 对于非纯文本类型,以及那些肯定不是 JSON Schema 对象的类型,我们应该进行包裹。
    self._is_wrapped = not _is_subclass_of_base_model_or_dict(output_type)

    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()
    else:
        self._type_adapter = TypeAdapter(output_type)
        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 UserError(
                "启用了严格 JSON schema,但输出类型无效。请将输出类型设为严格,或在 Agent() 中传递 output_schema_strict=False"
            ) from e

is_plain_text

is_plain_text() -> bool

输出类型是否为纯文本(而不是 JSON 对象)。

Source code in src/agents/agent_output.py
def is_plain_text(self) -> bool:
    """输出类型是否为纯文本(而不是 JSON 对象)。"""
    return self.output_type is None or self.output_type is str

is_strict_json_schema

is_strict_json_schema() -> bool

JSON schema 是否为严格模式。

Source code in src/agents/agent_output.py
def is_strict_json_schema(self) -> bool:
    """JSON schema 是否为严格模式。"""
    return self._strict_json_schema

json_schema

json_schema() -> dict[str, Any]

输出类型的 JSON schema。

Source code in src/agents/agent_output.py
def json_schema(self) -> dict[str, Any]:
    """输出类型的 JSON schema。"""
    if self.is_plain_text():
        raise UserError("输出类型为纯文本,因此没有可用的 JSON schema")
    return self._output_schema

validate_json

validate_json(json_str: str) -> Any

根据输出类型验证 JSON 字符串。返回验证后的对象,或在 JSON 无效时抛出 ModelBehaviorError

Source code in src/agents/agent_output.py
def validate_json(self, json_str: str) -> Any:
    """根据输出类型验证 JSON 字符串。返回验证后的对象,或在 JSON 无效时抛出 `ModelBehaviorError`。"""
    validated = _json.validate_json(json_str, self._type_adapter, partial=False)
    if self._is_wrapped:
        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

输出类型的名称。

Source code in src/agents/agent_output.py
def name(self) -> str:
    """输出类型的名称。"""
    return _type_to_str(self.output_type)