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
37 changes: 22 additions & 15 deletions src/agents/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -960,21 +960,28 @@ def _convert_tool_output_as_structured(
# If the output is either a single or list of the known structured output types, convert to
# ResponseFunctionCallOutputItemListParam.
if isinstance(output, list | tuple):
maybe_converted_output_list = [
cls._maybe_get_output_as_structured_function_output(item) for item in output
parts: list[str | ValidToolOutputPydanticModels] = []
for item in output:
# Both ToolOutputText fields are already valid for these plain dictionaries.
# Keep just the immutable text until the whole list qualifies.
if type(item) is dict and len(item) == 2:
kind, text = item.get("type"), item.get("text")
if type(kind) is str and kind == "text" and type(text) is str:
parts.append(text)
continue
structured = cls._maybe_get_output_as_structured_function_output(item)
if structured is None:
return None
parts.append(structured)

if not parts:
return None
return [
{"type": "input_text", "text": part}
if isinstance(part, str)
else cls._convert_single_tool_output_pydantic_model(part)
for part in parts
]
# An empty list/tuple has no structured items; ``all([])`` is ``True``,
# so guard against it to avoid emitting an empty structured-output list
# (which would drop the tool result) and stringify instead.
if maybe_converted_output_list and all(
item is not None for item in maybe_converted_output_list
):
return [
cls._convert_single_tool_output_pydantic_model(item)
for item in maybe_converted_output_list
if item is not None
]
return None

maybe_converted_output = cls._maybe_get_output_as_structured_function_output(output)
if maybe_converted_output is not None:
Expand All @@ -985,7 +992,7 @@ def _convert_tool_output_as_structured(
def _maybe_get_output_as_structured_function_output(
cls, output: Any
) -> ValidToolOutputPydanticModels | None:
if isinstance(output, ToolOutputText | ToolOutputImage | ToolOutputFileContent):
if isinstance(output, ValidToolOutputPydanticModels):
return output
elif isinstance(output, dict):
# Require explicit 'type' field in dict to be considered a structured output
Expand Down
21 changes: 12 additions & 9 deletions src/agents/run_internal/tool_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -2201,15 +2201,18 @@ async def _invoke_tool_and_run_post_invoke(
self.output_items_by_tool_run[id(task_state.tool_run)] = output_item
if self.tool_output_committer is not None:
self.tool_output_committer(output_item)
extracted_custom_data = await maybe_extract_custom_data(
func_tool.custom_data_extractor,
FunctionToolCustomDataContext(
tool_context=tool_context,
tool=func_tool,
output=final_result,
raw_item=copy.deepcopy(raw_output_item),
),
)
extractor = func_tool.custom_data_extractor
extracted_custom_data = None
if extractor is not None:
extracted_custom_data = await maybe_extract_custom_data(
extractor,
FunctionToolCustomDataContext(
tool_context=tool_context,
tool=func_tool,
output=final_result,
raw_item=copy.deepcopy(raw_output_item),
),
)
custom_data = merge_custom_data(tool_context._custom_data, extracted_custom_data)
if custom_data:
self.custom_data_by_tool_run[id(task_state.tool_run)] = custom_data
Expand Down
22 changes: 22 additions & 0 deletions tests/test_tool_custom_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
RunContextWrapper,
RunHooks,
Runner,
ToolOutputText,
UserError,
function_tool,
)
Expand Down Expand Up @@ -79,6 +80,27 @@ def get_data() -> str:
)


@pytest.mark.asyncio
async def test_function_tool_extractor_cannot_mutate_nested_model_input() -> None:
def extract(ctx: Any) -> dict[str, Any]:
ctx.raw_item["output"][0]["text"] = "changed by extractor"
return {"label": "visible"}

@function_tool(custom_data_extractor=extract)
def get_data() -> list[ToolOutputText]:
return [ToolOutputText(text="original")]

model = ScriptedModel()
model.extend([[get_function_tool_call("get_data", "{}")], [get_text_message("done")]])
result = await Runner.run(Agent(name="test", model=model, tools=[get_data]), input="user")

item = _tool_output_items(result.new_items)[0]
assert item.custom_data == {"label": "visible"}
expected = [{"type": "input_text", "text": "original"}]
assert cast(dict[str, Any], item.raw_item)["output"] == expected
assert cast(dict[str, Any], model.calls[-1].input[-1])["output"] == expected


@pytest.mark.asyncio
async def test_function_tool_custom_data_rejects_non_json_compatible_data() -> None:
@function_tool(custom_data_extractor=lambda _ctx: {"bad": object()})
Expand Down
23 changes: 23 additions & 0 deletions tests/test_tool_output_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,3 +404,26 @@ def test_tool_call_output_item_empty_tuple_not_converted() -> None:
assert payload["call_id"] == call.call_id
assert isinstance(payload["output"], str)
assert payload["output"] == "()"


def test_text_dictionary_list_preserves_order_and_detaches_returned_blocks() -> None:
parts = [{"type": "text", "text": ""}, {"text": "été", "type": "text"}]
payload = ItemHelpers.tool_call_output_item(_make_tool_call(), parts)
parts[1]["text"] = "changed"
assert payload["output"] == [
{"type": "input_text", "text": ""},
{"type": "input_text", "text": "été"},
]


def test_text_dictionary_list_still_coerces_or_rejects_non_string_values() -> None:
first = {"type": "text", "text": "first"}
payload = ItemHelpers.tool_call_output_item(
_make_tool_call(), [first, {"type": "text", "text": b"second"}]
)
assert payload["output"] == [
{"type": "input_text", "text": "first"},
{"type": "input_text", "text": "second"},
]
invalid = [first, {"type": "text", "text": None}]
assert ItemHelpers.tool_call_output_item(_make_tool_call(), invalid)["output"] == str(invalid)
Loading