Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Agent output

AgentOutputSchemaBase

Bases:ABC

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

Source code insrc/agents/agent_output.py
classAgentOutputSchemaBase(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.abstractmethoddefis_plain_text(self)->bool:"""Whether the output type is plain text (versus a JSON object)."""pass@abc.abstractmethoddefname(self)->str:"""The name of the output type."""pass@abc.abstractmethoddefjson_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.abstractmethoddefis_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.abstractmethoddefvalidate_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_textabstractmethod

is_plain_text()->bool

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

Source code insrc/agents/agent_output.py
@abc.abstractmethoddefis_plain_text(self)->bool:"""Whether the output type is plain text (versus a JSON object)."""pass

nameabstractmethod

name()->str

The name of the output type.

Source code insrc/agents/agent_output.py
@abc.abstractmethoddefname(self)->str:"""The name of the output type."""pass

json_schemaabstractmethod

json_schema()->dict[str,Any]

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

Source code insrc/agents/agent_output.py
@abc.abstractmethoddefjson_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_schemaabstractmethod

is_strict_json_schema()->bool

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

Source code insrc/agents/agent_output.py
@abc.abstractmethoddefis_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_jsonabstractmethod

validate_json(json_str:str)->Any

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

Source code insrc/agents/agent_output.py
@abc.abstractmethoddefvalidate_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

AgentOutputSchemadataclass

Bases:AgentOutputSchemaBase

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

Source code insrc/agents/agent_output.py
@dataclass(init=False)classAgentOutputSchema(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."""_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_typeself._strict_json_schema=strict_json_schemaifoutput_typeisNoneoroutput_typeisstr:self._is_wrapped=Falseself._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)ifself._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()ifself._strict_json_schema:try:self._output_schema=ensure_strict_json_schema(self._output_schema)exceptUserErrorase:raiseUserError("Strict JSON schema is enabled, but the output type is not valid. ""Either make the output type strict, ""or wrap your type with AgentOutputSchema(YourType, strict_json_schema=False)")fromedefis_plain_text(self)->bool:"""Whether the output type is plain text (versus a JSON object)."""returnself.output_typeisNoneorself.output_typeisstrdefis_strict_json_schema(self)->bool:"""Whether the JSON schema is in strict mode."""returnself._strict_json_schemadefjson_schema(self)->dict[str,Any]:"""The JSON schema of the output type."""ifself.is_plain_text():raiseUserError("Output type is plain text, so no JSON schema is available")returnself._output_schemadefvalidate_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.        """validated=_json.validate_json(json_str,self._type_adapter,partial=False)ifself._is_wrapped:ifnotisinstance(validated,dict):_error_tracing.attach_error_to_current_span(SpanError(message="Invalid JSON",data={"details":f"Expected a dict, got{type(validated)}"},))raiseModelBehaviorError(f"Expected a dict, got{type(validated)} for JSON:{json_str}")if_WRAPPER_DICT_KEYnotinvalidated:_error_tracing.attach_error_to_current_span(SpanError(message="Invalid JSON",data={"details":f"Could not find key{_WRAPPER_DICT_KEY} in JSON"},))raiseModelBehaviorError(f"Could not find key{_WRAPPER_DICT_KEY} in JSON:{json_str}")returnvalidated[_WRAPPER_DICT_KEY]returnvalidateddefname(self)->str:"""The name of the output type."""return_type_to_str(self.output_type)

output_typeinstance-attribute

output_type:type[Any]=output_type

The type of the output.

__init__

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

Parameters:

NameTypeDescriptionDefault
output_typetype[Any]

The type of the output.

required
strict_json_schemabool

Whether the JSON schema is in strict mode. Westrongly recommendsetting this to True, as it increases the likelihood of correct JSON input.

True
Source code insrc/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_typeself._strict_json_schema=strict_json_schemaifoutput_typeisNoneoroutput_typeisstr:self._is_wrapped=Falseself._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)ifself._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()ifself._strict_json_schema:try:self._output_schema=ensure_strict_json_schema(self._output_schema)exceptUserErrorase:raiseUserError("Strict JSON schema is enabled, but the output type is not valid. ""Either make the output type strict, ""or wrap your type with AgentOutputSchema(YourType, strict_json_schema=False)")frome

is_plain_text

is_plain_text()->bool

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

Source code insrc/agents/agent_output.py
defis_plain_text(self)->bool:"""Whether the output type is plain text (versus a JSON object)."""returnself.output_typeisNoneorself.output_typeisstr

is_strict_json_schema

is_strict_json_schema()->bool

Whether the JSON schema is in strict mode.

Source code insrc/agents/agent_output.py
defis_strict_json_schema(self)->bool:"""Whether the JSON schema is in strict mode."""returnself._strict_json_schema

json_schema

json_schema()->dict[str,Any]

The JSON schema of the output type.

Source code insrc/agents/agent_output.py
defjson_schema(self)->dict[str,Any]:"""The JSON schema of the output type."""ifself.is_plain_text():raiseUserError("Output type is plain text, so no JSON schema is available")returnself._output_schema

validate_json

validate_json(json_str:str)->Any

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

Source code insrc/agents/agent_output.py
defvalidate_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.    """validated=_json.validate_json(json_str,self._type_adapter,partial=False)ifself._is_wrapped:ifnotisinstance(validated,dict):_error_tracing.attach_error_to_current_span(SpanError(message="Invalid JSON",data={"details":f"Expected a dict, got{type(validated)}"},))raiseModelBehaviorError(f"Expected a dict, got{type(validated)} for JSON:{json_str}")if_WRAPPER_DICT_KEYnotinvalidated:_error_tracing.attach_error_to_current_span(SpanError(message="Invalid JSON",data={"details":f"Could not find key{_WRAPPER_DICT_KEY} in JSON"},))raiseModelBehaviorError(f"Could not find key{_WRAPPER_DICT_KEY} in JSON:{json_str}")returnvalidated[_WRAPPER_DICT_KEY]returnvalidated

name

name()->str

The name of the output type.

Source code insrc/agents/agent_output.py
defname(self)->str:"""The name of the output type."""return_type_to_str(self.output_type)

[8]ページ先頭

©2009-2025 Movatter.jp