Skip to content

Commit 497b069

Browse files
committed
Enable non-strict output types
1 parent 5639606 commit 497b069

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

src/agents/agent.py

+8
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,14 @@ class Agent(Generic[TContext]):
144144
output_type: type[Any] | None = None
145145
"""The type of the output object. If not provided, the output will be `str`."""
146146

147+
output_schema_strict: bool = True
148+
"""Whether the output JSON schema passed to the LLM should be strict.
149+
150+
We **strongly** recommend setting this to True, as it increases the likelihood of correct JSON
151+
being produced. However, for output types that cannot be converted to strict JSON, you can
152+
set this to False.
153+
"""
154+
147155
hooks: AgentHooks[TContext] | None = None
148156
"""A class that receives callbacks on various lifecycle events for this agent.
149157
"""

src/agents/agent_output.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,14 @@ def __init__(self, output_type: type[Any], strict_json_schema: bool = True):
7171
self._output_schema = self._type_adapter.json_schema()
7272

7373
if self.strict_json_schema:
74-
self._output_schema = ensure_strict_json_schema(self._output_schema)
74+
try:
75+
self._output_schema = ensure_strict_json_schema(self._output_schema)
76+
except UserError as e:
77+
raise UserError(
78+
"Strict JSON schema is enabled, but the output type is not valid. "
79+
"Either make the output type strict, or pass output_schema_strict=False to "
80+
"your Agent()"
81+
) from e
7582

7683
def is_plain_text(self) -> bool:
7784
"""Whether the output type is plain text (versus a JSON object)."""

src/agents/run.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -934,7 +934,7 @@ def _get_output_schema(cls, agent: Agent[Any]) -> AgentOutputSchema | None:
934934
if agent.output_type is None or agent.output_type is str:
935935
return None
936936

937-
return AgentOutputSchema(agent.output_type)
937+
return AgentOutputSchema(agent.output_type, strict_json_schema=agent.output_schema_strict)
938938

939939
@classmethod
940940
def _get_handoffs(cls, agent: Agent[Any]) -> list[Handoff]:

0 commit comments

Comments
 (0)