Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8e30b01

Browse files
committed
Enable non-strict output types
1 parent 5639606 commit 8e30b01

File tree

4 files changed

+63
-2
lines changed

4 files changed

+63
-2
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import asyncio
2+
from dataclasses import dataclass
3+
4+
from agents import Agent, Runner
5+
6+
"""This example demonstrates how to use an output type that is not in strict mode. Strict mode
7+
allows us to guarantee valid JSON output, but some schemas are not strict-compatible.
8+
9+
In this example, we define an output type that is not strict-compatible, and then we run the
10+
agent with strict_json_schema=False.
11+
12+
To understand which schemas are strict-compatible, see:
13+
https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#supported-schemas
14+
"""
15+
16+
17+
@dataclass
18+
class OutputType:
19+
jokes: dict[int, str]
20+
"""A list of jokes, indexed by joke number."""
21+
22+
23+
async def main():
24+
agent = Agent(
25+
name="Assistant",
26+
instructions="You are a helpful assistant.",
27+
output_type=OutputType,
28+
)
29+
30+
input = "Tell me 3 short jokes."
31+
32+
# First, let's try with a strict output type. This should raise an exception.
33+
try:
34+
result = await Runner.run(agent, input)
35+
raise AssertionError("Should have raised an exception")
36+
except Exception as e:
37+
print(f"Error: {e}")
38+
39+
# Now let's try again with a non-strict output type. This should work.
40+
agent.output_schema_strict = False
41+
result = await Runner.run(agent, input)
42+
print(result.final_output)
43+
44+
45+
if __name__ == "__main__":
46+
asyncio.run(main())

src/agents/agent.py

Lines changed: 8 additions & 0 deletions
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

Lines changed: 8 additions & 1 deletion
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

Lines changed: 1 addition & 1 deletion
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)