Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
291 changes: 291 additions & 0 deletions native/codex/tests/test_json_output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,291 @@
import asyncio
import traceback
from copy import deepcopy
from typing import Any

import pytest

from openai_agents import Agent
from openai_agents.codex.extensions.json_output import json_schema_check
from openai_agents.codex.extensions.output import OutputRejected, accept_output
from openai_agents.codex.testing import MockModel


@pytest.mark.parametrize("stream", [False, True], ids=["run", "stream"])
@pytest.mark.parametrize("text", ["{}", '{"name":"Ada"}', '{"count":2}'])
def test_optional_fields_and_defaults(mock_model: MockModel, stream: bool, text: str) -> None:
schema: dict[str, Any] = {
"type": "object",
"properties": {
"name": {"type": "string"},
"count": {"type": "integer", "default": 1},
},
"additionalProperties": False,
}
original = deepcopy(schema)
check = json_schema_check(schema)
mock_model.reply(text)

async def run() -> None:
agent = Agent(model="offline")
source = (
agent.stream("Answer", environment=None)
if stream
else agent.run("Answer", environment=None)
)
accepted = await accept_output(source, check=check)
assert accepted.text == text

asyncio.run(run())
assert schema == original
assert len(mock_model.requests) == 1


@pytest.mark.parametrize("stream", [False, True], ids=["run", "stream"])
@pytest.mark.parametrize(
"text",
[
'{"secret":"synthetic candidate"}',
'{"count":"synthetic candidate"}',
'{"secret":',
"```json\n{}\n```",
"{} {}",
'{"count":NaN}',
'{"count":Infinity}',
'{"count":-Infinity}',
'{"count":1e400}',
'{"count":1,"count":2}',
],
)
def test_rejected_candidates_stay_out_of_diagnostics(
mock_model: MockModel, stream: bool, text: str
) -> None:
check = json_schema_check(
{
"type": "object",
"properties": {"count": {"type": "number"}},
"additionalProperties": False,
}
)
mock_model.reply(text)

async def run() -> None:
agent = Agent(model="offline")
source = (
agent.stream("Answer", environment=None)
if stream
else agent.run("Answer", environment=None)
)
with pytest.raises(OutputRejected) as error:
await accept_output(source, check=check)
assert str(error.value) == "Output rejected by the application check"
assert error.value.__context__ is None
assert error.value.__cause__ is None
assert text not in "".join(traceback.format_exception(error.value))

asyncio.run(run())
assert len(mock_model.requests) == 1


@pytest.mark.parametrize("stream", [False, True], ids=["run", "stream"])
def test_commentary_json_is_not_accepted(mock_model: MockModel, stream: bool) -> None:
mock_model.respond(
{
"type": "message",
"role": "assistant",
"phase": "commentary",
"content": [{"type": "output_text", "text": "{}"}],
}
)

async def run() -> None:
agent = Agent(model="offline")
source = (
agent.stream("Answer", environment=None)
if stream
else agent.run("Answer", environment=None)
)
with pytest.raises(OutputRejected, match="Turn ended with commentary"):
await accept_output(source, check=json_schema_check({"type": "object"}))

asyncio.run(run())


def test_local_refs_and_reusable_schema_snapshot() -> None:
schema: dict[str, Any] = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$defs": {"name": {"type": "string"}},
"type": "object",
"properties": {"name": {"$ref": "#/$defs/name"}},
"required": ["name"],
"default": {"$ref": "annotation data"},
}
check = json_schema_check(schema)
schema["required"].append("other")

async def run() -> None:
assert await check('{"name":"Ada"}')
assert not await check('{"name":1}')
assert not await check("{}")
assert await check('{"name":"Grace"}')

asyncio.run(run())


@pytest.mark.parametrize(
"schema",
[
{"type": "not-a-type"},
{"required": "name"},
{"$schema": "https://json-schema.org/draft/2019-09/schema"},
{"$ref": "https://example.invalid/schema"},
{"$ref": "file:///not-a-schema"},
{"$defs": {"unused": {"$dynamicRef": "other.json#node"}}},
{"anyOf": [True, {"$ref": "https://example.invalid/unused"}]},
],
)
def test_schema_mistakes_and_external_refs_fail_at_construction(schema: dict[str, Any]) -> None:
with pytest.raises(ValueError):
json_schema_check(schema)


@pytest.mark.parametrize(
("schema", "text", "accepted"),
[
(True, "null", True),
(False, "null", False),
({"type": "integer"}, "3", True),
({"type": "array", "items": {"type": "boolean"}}, "[true,false]", True),
({"type": "string", "format": "email"}, '"annotation only"', True),
({"$ref": "#/$defs/missing"}, '"synthetic candidate"', False),
],
)
def test_standard_instances_and_unresolved_refs(
schema: dict[str, Any] | bool, text: str, accepted: bool
) -> None:
assert asyncio.run(json_schema_check(schema)(text)) is accepted


@pytest.mark.parametrize(
"schema",
[
{"pattern": "^ok$"},
{"properties": {"label": {"pattern": "^ok$"}}},
{"items": {"patternProperties": {"^ok$": True}}},
{"$defs": {"name": {"pattern": "^ok$"}}, "$ref": "#/$defs/name"},
{"default": {"pattern": "^ok$"}, "$ref": "#/default"},
{"$defs": {"x": {"default": {"pattern": "^ok$"}}}, "$ref": "#/$defs/x/default"},
{"$defs": {"x": {"default": {"pattern": "^ok$"}}}, "$ref": "#/$defs/x%2Fdefault"},
{"default": {"patternProperties": {"^ok$": True}}, "$dynamicRef": "#/default"},
],
)
def test_regex_constraints_fail_before_receiving_output(schema: dict[str, Any]) -> None:
with pytest.raises(ValueError):
json_schema_check(schema)


def test_regex_keyword_names_in_data_are_allowed() -> None:
check = json_schema_check(
{
"properties": {"pattern": True, "patternProperties": {"type": "string"}},
"default": {"pattern": "literal"},
}
)
assert asyncio.run(check('{"pattern": true, "patternProperties": "data"}'))


@pytest.mark.parametrize(
("text", "accepted"),
[
("0.28", True),
("0.29", True),
("-0.29", True),
("28e-2", True),
("0.285", False),
("0.30000000000000000001", False),
("123456789012345678901234567890.29", True),
("123456789012345678901234567890.291", False),
("1e-999999999", False),
("0e-999999999", True),
],
)
def test_fractional_multiples(text: str, accepted: bool) -> None:
check = json_schema_check({"type": "number", "multipleOf": 0.01})
assert asyncio.run(check(text)) is accepted


@pytest.mark.parametrize(
("schema", "text", "accepted"),
[
({"type": "integer"}, "2.0", True),
({"type": "integer"}, "2.00000000000000000001", False),
({"minimum": 0.29, "maximum": 0.29}, "0.290", True),
({"const": 0.29}, "0.29", True),
({"enum": [0.29]}, "0.29000000000000000001", False),
],
)
def test_exact_json_numbers(schema: dict[str, Any], text: str, accepted: bool) -> None:
assert asyncio.run(json_schema_check(schema)(text)) is accepted


def test_recursive_alternatives_fail_at_construction() -> None:
ref = {"$ref": "#/$defs/node"}
variants = [{"properties": {"next": ref, "kind": {"const": kind}}} for kind in ("a", "b")]
with pytest.raises(ValueError):
json_schema_check({"$defs": {"node": {"oneOf": variants}}, **ref})


def test_acyclic_references_count_each_expansion() -> None:
definitions: dict[str, Any] = {"0": {"type": "number"}}
for i in range(1, 10):
definitions[str(i)] = {"allOf": [{"$ref": f"#/$defs/{i - 1}"}] * 2}
with pytest.raises(ValueError):
json_schema_check({"$defs": definitions, "$ref": "#/$defs/9"})


@pytest.mark.parametrize(
"schema",
[
{"$defs": {"a": {"$dynamicRef": "#/$defs/a"}}},
{"$defs": {"a": {"$id": "child", "$defs": {"a": True}}}},
{"uniqueItems": True},
{"unevaluatedProperties": False},
{"unevaluatedItems": True},
{"enum": list(range(512))},
{"dependentRequired": {"key": [str(i) for i in range(511)]}},
],
)
def test_unbounded_schema_work_fails_at_construction(schema: dict[str, Any]) -> None:
with pytest.raises(ValueError):
json_schema_check(schema)


@pytest.mark.parametrize(
"text",
[
'"' + "a" * 65_535 + '"',
"[" * 33 + "0" + "]" * 33,
"[" + ",".join(["0"] * 2048) + "]",
"0." + "1" * 1023,
],
)
def test_large_candidates_fail_closed(text: str) -> None:
assert not asyncio.run(json_schema_check(True)(text))


def test_budget_limits_schema_and_candidate_together() -> None:
check = json_schema_check({"items": {"enum": list(range(30))}})
assert asyncio.run(check("[" + ",".join(["0"] * 1023) + "]"))
assert not asyncio.run(check("[" + ",".join(["0"] * 1024) + "]"))


def test_repeated_local_definitions_with_exact_amounts() -> None:
amount = {"$ref": "#/$defs/amount"}
check = json_schema_check(
{
"$defs": {"amount": {"type": "number", "multipleOf": 0.01}},
"properties": {"cost": amount, "fee": amount},
}
)
assert asyncio.run(check('{"cost":0.28,"fee":0.29}'))
assert not asyncio.run(check('{"cost":0.28,"fee":0.285}'))
Loading
Loading