|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from collections.abc import Iterable, Iterator |
| 4 | +from typing import Any, cast |
| 5 | + |
| 6 | +import httpx |
| 7 | +import pytest |
| 8 | +from openai import NOT_GIVEN |
| 9 | +from openai.types.chat.chat_completion import ChatCompletion |
| 10 | +from openai.types.responses import ToolParam |
| 11 | + |
| 12 | +from agents import ( |
| 13 | + ModelSettings, |
| 14 | + ModelTracing, |
| 15 | + OpenAIChatCompletionsModel, |
| 16 | + OpenAIResponsesModel, |
| 17 | + generation_span, |
| 18 | +) |
| 19 | +from agents.models import ( |
| 20 | + openai_chatcompletions as chat_module, |
| 21 | + openai_responses as responses_module, |
| 22 | +) |
| 23 | + |
| 24 | + |
| 25 | +class _SingleUseIterable: |
| 26 | + """Helper iterable that raises if iterated more than once.""" |
| 27 | + |
| 28 | + def __init__(self, values: list[object]) -> None: |
| 29 | + self._values = list(values) |
| 30 | + self.iterations = 0 |
| 31 | + |
| 32 | + def __iter__(self) -> Iterator[object]: |
| 33 | + if self.iterations: |
| 34 | + raise RuntimeError("Iterable should have been materialized exactly once.") |
| 35 | + self.iterations += 1 |
| 36 | + yield from self._values |
| 37 | + |
| 38 | + |
| 39 | +def _force_materialization(value: object) -> None: |
| 40 | + if isinstance(value, dict): |
| 41 | + for nested in value.values(): |
| 42 | + _force_materialization(nested) |
| 43 | + elif isinstance(value, list): |
| 44 | + for nested in value: |
| 45 | + _force_materialization(nested) |
| 46 | + elif isinstance(value, Iterable) and not isinstance(value, (str, bytes, bytearray)): |
| 47 | + list(value) |
| 48 | + |
| 49 | + |
| 50 | +@pytest.mark.allow_call_model_methods |
| 51 | +@pytest.mark.asyncio |
| 52 | +async def test_chat_completions_materializes_iterator_payload( |
| 53 | + monkeypatch: pytest.MonkeyPatch, |
| 54 | +) -> None: |
| 55 | + message_iter = _SingleUseIterable([{"type": "text", "text": "hi"}]) |
| 56 | + tool_iter = _SingleUseIterable([{"type": "string"}]) |
| 57 | + |
| 58 | + chat_converter = cast(Any, chat_module).Converter |
| 59 | + |
| 60 | + monkeypatch.setattr( |
| 61 | + chat_converter, |
| 62 | + "items_to_messages", |
| 63 | + classmethod(lambda _cls, _input: [{"role": "user", "content": message_iter}]), |
| 64 | + ) |
| 65 | + monkeypatch.setattr( |
| 66 | + chat_converter, |
| 67 | + "tool_to_openai", |
| 68 | + classmethod( |
| 69 | + lambda _cls, _tool: { |
| 70 | + "type": "function", |
| 71 | + "function": { |
| 72 | + "name": "dummy", |
| 73 | + "parameters": {"properties": tool_iter}, |
| 74 | + }, |
| 75 | + } |
| 76 | + ), |
| 77 | + ) |
| 78 | + |
| 79 | + captured_kwargs: dict[str, Any] = {} |
| 80 | + |
| 81 | + class DummyCompletions: |
| 82 | + async def create(self, **kwargs): |
| 83 | + captured_kwargs.update(kwargs) |
| 84 | + _force_materialization(kwargs["messages"]) |
| 85 | + if kwargs["tools"] is not NOT_GIVEN: |
| 86 | + _force_materialization(kwargs["tools"]) |
| 87 | + return ChatCompletion( |
| 88 | + id="dummy-id", |
| 89 | + created=0, |
| 90 | + model="gpt-4", |
| 91 | + object="chat.completion", |
| 92 | + choices=[], |
| 93 | + usage=None, |
| 94 | + ) |
| 95 | + |
| 96 | + class DummyClient: |
| 97 | + def __init__(self) -> None: |
| 98 | + self.chat = type("_Chat", (), {"completions": DummyCompletions()})() |
| 99 | + self.base_url = httpx.URL("http://example.test") |
| 100 | + |
| 101 | + model = OpenAIChatCompletionsModel(model="gpt-4", openai_client=DummyClient()) # type: ignore[arg-type] |
| 102 | + |
| 103 | + with generation_span(disabled=True) as span: |
| 104 | + await cast(Any, model)._fetch_response( |
| 105 | + system_instructions=None, |
| 106 | + input="ignored", |
| 107 | + model_settings=ModelSettings(), |
| 108 | + tools=[object()], |
| 109 | + output_schema=None, |
| 110 | + handoffs=[], |
| 111 | + span=span, |
| 112 | + tracing=ModelTracing.DISABLED, |
| 113 | + stream=False, |
| 114 | + ) |
| 115 | + |
| 116 | + assert message_iter.iterations == 1 |
| 117 | + assert tool_iter.iterations == 1 |
| 118 | + assert isinstance(captured_kwargs["messages"][0]["content"], list) |
| 119 | + assert isinstance(captured_kwargs["tools"][0]["function"]["parameters"]["properties"], list) |
| 120 | + |
| 121 | + |
| 122 | +@pytest.mark.allow_call_model_methods |
| 123 | +@pytest.mark.asyncio |
| 124 | +async def test_responses_materializes_iterator_payload(monkeypatch: pytest.MonkeyPatch) -> None: |
| 125 | + input_iter = _SingleUseIterable([{"type": "input_text", "text": "hello"}]) |
| 126 | + tool_iter = _SingleUseIterable([{"type": "string"}]) |
| 127 | + |
| 128 | + responses_item_helpers = cast(Any, responses_module).ItemHelpers |
| 129 | + responses_converter = cast(Any, responses_module).Converter |
| 130 | + |
| 131 | + monkeypatch.setattr( |
| 132 | + responses_item_helpers, |
| 133 | + "input_to_new_input_list", |
| 134 | + classmethod(lambda _cls, _input: [{"role": "user", "content": input_iter}]), |
| 135 | + ) |
| 136 | + |
| 137 | + converted_tools = responses_module.ConvertedTools( |
| 138 | + tools=cast( |
| 139 | + list[ToolParam], |
| 140 | + [ |
| 141 | + { |
| 142 | + "type": "function", |
| 143 | + "name": "dummy", |
| 144 | + "parameters": {"properties": tool_iter}, |
| 145 | + } |
| 146 | + ], |
| 147 | + ), |
| 148 | + includes=[], |
| 149 | + ) |
| 150 | + monkeypatch.setattr( |
| 151 | + responses_converter, |
| 152 | + "convert_tools", |
| 153 | + classmethod(lambda _cls, _tools, _handoffs: converted_tools), |
| 154 | + ) |
| 155 | + |
| 156 | + captured_kwargs: dict[str, Any] = {} |
| 157 | + |
| 158 | + class DummyResponses: |
| 159 | + async def create(self, **kwargs): |
| 160 | + captured_kwargs.update(kwargs) |
| 161 | + _force_materialization(kwargs["input"]) |
| 162 | + _force_materialization(kwargs["tools"]) |
| 163 | + return object() |
| 164 | + |
| 165 | + class DummyClient: |
| 166 | + def __init__(self) -> None: |
| 167 | + self.responses = DummyResponses() |
| 168 | + |
| 169 | + model = OpenAIResponsesModel(model="gpt-4.1", openai_client=DummyClient()) # type: ignore[arg-type] |
| 170 | + |
| 171 | + await cast(Any, model)._fetch_response( |
| 172 | + system_instructions=None, |
| 173 | + input="ignored", |
| 174 | + model_settings=ModelSettings(), |
| 175 | + tools=[], |
| 176 | + output_schema=None, |
| 177 | + handoffs=[], |
| 178 | + previous_response_id=None, |
| 179 | + conversation_id=None, |
| 180 | + stream=False, |
| 181 | + prompt=None, |
| 182 | + ) |
| 183 | + |
| 184 | + assert input_iter.iterations == 1 |
| 185 | + assert tool_iter.iterations == 1 |
| 186 | + assert isinstance(captured_kwargs["input"][0]["content"], list) |
| 187 | + assert isinstance(captured_kwargs["tools"][0]["parameters"]["properties"], list) |
0 commit comments