Skip to content

Commit f093ced

Browse files
fix: preserve function-call aliases across RunState restoration (#5358)
1 parent f50525c commit f093ced

4 files changed

Lines changed: 232 additions & 90 deletions

File tree

‎src/agents/run_state.py‎

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -545,7 +545,9 @@ def _copy_pydantic_value(
545545
if normalized_field_name in allowed_fields_set:
546546
copied_fields_set.add(normalized_field_name)
547547

548-
copied_model = declared_model_type.model_construct(
548+
# The OpenAI override expects wire aliases; these copied keys are field names.
549+
copied_model = cast(Any, BaseModel.model_construct).__func__(
550+
declared_model_type,
549551
_fields_set=set(copied_fields_set),
550552
**copied_fields,
551553
**copied_extra,
@@ -662,7 +664,8 @@ def _validate_declared_payload(
662664
"""Validate a declared payload after filling only missing required values."""
663665
while True:
664666
try:
665-
return model_adapter.validate_python(explicit)
667+
# Approval snapshots are dumped with Python field names, including aliased fields.
668+
return model_adapter.validate_python(explicit, by_name=True)
666669
except ValidationError as error:
667670
filled_missing_value = False
668671
for detail in error.errors(
@@ -823,7 +826,7 @@ def _copy_tool_approval_raw_item(raw_item: Any) -> Any:
823826
copied_realized,
824827
copied_baseline,
825828
)
826-
validated_model = model_adapter.validate_python(merged)
829+
validated_model = model_adapter.validate_python(merged, by_name=True)
827830
_restore_pydantic_fields_set(validated_model, copied_raw_item)
828831
return validated_model
829832
if dict in raw_item_mro:
@@ -3324,7 +3327,7 @@ def _parse_with_adapter(adapter: TypeAdapter[Any], data: dict[str, Any]) -> Any:
33243327

33253328
def _parse_apply_patch_call(data: dict[str, Any]) -> Any:
33263329
try:
3327-
return ResponseFunctionToolCall(**data)
3330+
return ResponseFunctionToolCall.model_validate(data, by_name=True)
33283331
except Exception:
33293332
return data
33303333

@@ -3379,7 +3382,10 @@ def _deserialize_function_actions() -> list[_DeserializedFunctionAction]:
33793382
dict(tool_call_data_raw) if isinstance(tool_call_data_raw, Mapping) else {}
33803383
)
33813384
try:
3382-
tool_call = ResponseFunctionToolCall(**tool_call_data)
3385+
# RunState stores Python field names, including alias-only provider fields.
3386+
tool_call = ResponseFunctionToolCall.model_validate(
3387+
tool_call_data, by_name=True
3388+
)
33833389
except Exception:
33843390
continue
33853391
_ensure_restored_tool_call_allowed(
@@ -3418,7 +3424,7 @@ def _deserialize_function_actions() -> list[_DeserializedFunctionAction]:
34183424
"handoffs",
34193425
"handoff",
34203426
handoffs_map,
3421-
lambda data: ResponseFunctionToolCall(**data),
3427+
lambda data: ResponseFunctionToolCall.model_validate(data, by_name=True),
34223428
lambda tool_call, handoff: ToolRunHandoff(tool_call=tool_call, handoff=handoff),
34233429
_resolve_handoff_tool_name,
34243430
),
@@ -3591,7 +3597,7 @@ def _deserialize_tool_call_raw_item(normalized_raw_item: Mapping[str, Any]) -> A
35913597

35923598
if tool_type == "function_call":
35933599
try:
3594-
return ResponseFunctionToolCall(**normalized_raw_item)
3600+
return ResponseFunctionToolCall.model_validate(normalized_raw_item, by_name=True)
35953601
except Exception:
35963602
return normalized_raw_item
35973603

@@ -3605,7 +3611,7 @@ def _deserialize_tool_call_raw_item(normalized_raw_item: Mapping[str, Any]) -> A
36053611
return normalized_raw_item
36063612

36073613
try:
3608-
return ResponseFunctionToolCall(**normalized_raw_item)
3614+
return ResponseFunctionToolCall.model_validate(normalized_raw_item, by_name=True)
36093615
except Exception:
36103616
return normalized_raw_item
36113617

@@ -5058,7 +5064,7 @@ def _deserialize_model_responses(responses_data: list[dict[str, Any]]) -> list[M
50585064
output.append(item)
50595065
elif item.get("type") == "message":
50605066
output.append(_deserialize_message_output_item(item))
5061-
elif item.get("type") == "program":
5067+
elif item.get("type") in {"program", "function_call"}:
50625068
output.append(_deserialize_tool_call_raw_item(item))
50635069
elif item.get("type") == "program_output":
50645070
output.append(_deserialize_tool_call_output_raw_item(item))
@@ -5260,7 +5266,9 @@ def _resolve_agent_info(
52605266
result.append(ReasoningItem(agent=agent, raw_item=raw_item_reason))
52615267

52625268
elif item_type == "handoff_call_item":
5263-
raw_item_handoff = ResponseFunctionToolCall(**normalized_raw_item)
5269+
raw_item_handoff = ResponseFunctionToolCall.model_validate(
5270+
normalized_raw_item, by_name=True
5271+
)
52645272
result.append(HandoffCallItem(agent=agent, raw_item=raw_item_handoff))
52655273

52665274
elif item_type == "handoff_output_item":

‎src/agents/testing/model.py‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -947,13 +947,16 @@ def _stream_events_for_step(
947947
),
948948
cast(
949949
TResponseStreamEvent,
950-
ResponseFunctionCallArgumentsDoneEvent(
951-
type="response.function_call_arguments.done",
952-
item_id=item_id,
953-
output_index=output_index,
954-
arguments=output_item.arguments,
955-
name=output_item.name,
956-
sequence_number=sequence_number + 1,
950+
# Older openai models require name; newer ones retain it as an extra.
951+
ResponseFunctionCallArgumentsDoneEvent.model_validate(
952+
{
953+
"type": "response.function_call_arguments.done",
954+
"item_id": item_id,
955+
"output_index": output_index,
956+
"arguments": output_item.arguments,
957+
"name": output_item.name,
958+
"sequence_number": sequence_number + 1,
959+
}
957960
),
958961
),
959962
]

‎tests/test_run_state_aliases.py‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""Approval persistence must accept the names emitted by provider model dumps."""
2+
3+
from __future__ import annotations
4+
5+
import pytest
6+
from openai.types.responses import ResponseFunctionToolCall
7+
8+
from agents import Agent, RunConfig, Runner, RunState
9+
from agents.decorators import tool
10+
from agents.testing import ModelStep, ScriptedModel
11+
12+
from .test_responses import get_text_message
13+
14+
15+
@pytest.mark.asyncio
16+
@pytest.mark.skipif(
17+
"async_" not in ResponseFunctionToolCall.model_fields,
18+
reason="Older supported openai versions do not declare the async alias",
19+
)
20+
@pytest.mark.parametrize("approve", [True, False], ids=["approve", "reject"])
21+
@pytest.mark.parametrize(
22+
("serialization", "async_value"),
23+
[("live", None), ("json", None), ("string", None), ("json", False), ("string", True)],
24+
)
25+
async def test_function_call_alias_survives_approval_resume(
26+
serialization: str, async_value: bool | None, approve: bool
27+
) -> None:
28+
executions: list[str] = []
29+
30+
@tool(needs_approval=True)
31+
async def needs_ok() -> str:
32+
executions.append("called")
33+
return "approved output"
34+
35+
call = ResponseFunctionToolCall.model_validate(
36+
{
37+
"id": "fc_alias",
38+
"call_id": "call_alias",
39+
"type": "function_call",
40+
"name": "needs_ok",
41+
"arguments": "{}",
42+
"async": async_value,
43+
}
44+
)
45+
model = ScriptedModel([ModelStep(output=[call]), ModelStep(output=[get_text_message("done")])])
46+
agent = Agent(name="Alias approval", model=model, tools=[needs_ok])
47+
config = RunConfig(tracing_disabled=True)
48+
result = await Runner.run(agent, "start", run_config=config)
49+
assert len(result.interruptions) == 1
50+
state = result.to_state()
51+
if serialization == "json":
52+
saved = state.to_json()
53+
# Released snapshots use Python field names. Keep that durable representation readable.
54+
assert (
55+
saved["current_step"]["data"]["interruptions"][0]["raw_item"]["async_"] is async_value
56+
)
57+
saved["$schemaVersion"] = "1.18"
58+
state = await RunState.from_json(agent, saved)
59+
elif serialization == "string":
60+
state = await RunState.from_string(agent, state.to_string())
61+
62+
interruption = state.get_interruptions()[0]
63+
assert isinstance(interruption.raw_item, ResponseFunctionToolCall)
64+
assert interruption.raw_item.async_ is async_value
65+
assert "async_" in interruption.raw_item.model_fields_set
66+
assert "async_" not in (interruption.raw_item.model_extra or {})
67+
if approve:
68+
state.approve(interruption)
69+
else:
70+
state.reject(interruption)
71+
resumed = await Runner.run(agent, state, run_config=config)
72+
assert resumed.final_output == "done"
73+
assert resumed.interruptions == []
74+
assert executions == (["called"] if approve else [])
75+
restored_call = resumed.raw_responses[0].output[0]
76+
assert isinstance(restored_call, ResponseFunctionToolCall)
77+
assert restored_call.async_ is async_value
78+
assert "async_" not in (restored_call.model_extra or {})
79+
model.assert_complete()

0 commit comments

Comments
 (0)