Skip to content
Open
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
3 changes: 2 additions & 1 deletion python/restate/ext/openai/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ class RestateModelResponse(BaseModel):
"""

def to_input_items(self) -> list[TResponseInputItem]:
return [it.model_dump(exclude_unset=True) for it in self.output] # type: ignore
# by_alias: the Responses API expects wire names (e.g. `async`, not `async_`).
return [it.model_dump(exclude_unset=True, by_alias=True) for it in self.output] # type: ignore


class AgentsTerminalException(AgentsException, TerminalError):
Expand Down
10 changes: 7 additions & 3 deletions python/restate/serde.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,8 @@ class DefaultSerde(Serde[I]):
Behavior:
- Serialization:
- If the object is an instance of Pydantic's `BaseModel`,
it uses `model_dump_json()` for serialization.
it uses `model_dump_json(by_alias=True)` for serialization, so the JSON
uses the same field names `model_validate_json()` reads back.
- Otherwise, it falls back to `json.dumps()`.
- Deserialization:
- Uses `json.loads()` to convert byte arrays into Python objects.
Expand Down Expand Up @@ -307,7 +308,9 @@ def serialize(self, obj: typing.Optional[I]) -> bytes:
if Msgspec.is_struct(hint):
return Msgspec.encode(obj)
if is_pydantic(hint):
return obj.model_dump_json().encode("utf-8") # type: ignore[attr-defined]
# by_alias: model_validate_json() reads aliases, so dumping field names
# would break the round trip for aliased fields.
return obj.model_dump_json(by_alias=True).encode("utf-8") # type: ignore[attr-defined]
if is_dataclass(obj):
data = DaciteToDict(obj) # type: ignore
return json.dumps(data).encode("utf-8")
Expand Down Expand Up @@ -351,7 +354,8 @@ def serialize(self, obj: typing.Optional[I]) -> bytes:
"""
if obj is None:
return bytes()
json_str = obj.model_dump_json() # type: ignore[attr-defined]
# by_alias: see DefaultSerde.serialize.
json_str = obj.model_dump_json(by_alias=True) # type: ignore[attr-defined]
return json_str.encode("utf-8")


Expand Down
46 changes: 46 additions & 0 deletions tests/serde.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,49 @@ def extract_core_type_optional():
kind, tpe = extract_core_type(t)
assert kind == "simple"
assert tpe is t


def test_pydantic_serdes_round_trip_aliased_fields():
"""Aliased fields survive a round trip: dump and validate use the same names."""
from pydantic import BaseModel, ConfigDict, Field

from restate.serde import DefaultSerde, PydanticJsonSerde, Serde

class Call(BaseModel):
model_config = ConfigDict(extra="allow")
name: str
async_: bool = Field(alias="async")

call = Call.model_validate({"name": "get_weather", "async": True})
serdes: list[Serde[Call]] = [DefaultSerde(Call), PydanticJsonSerde(Call)]
for serde in serdes:
buf = serde.serialize(call)
assert b'"async":true' in buf
restored = serde.deserialize(buf)
assert restored == call
assert restored is not None and restored.model_extra == {}


def test_openai_model_response_replay_keeps_wire_names():
"""A journaled Responses API function call replays with `async`, not `async_`."""
import pytest

pytest.importorskip("agents")
from agents.usage import Usage
from openai.types.responses import ResponseFunctionToolCall

from restate.ext.openai.models import RestateModelResponse
from restate.serde import DefaultSerde

call = ResponseFunctionToolCall.model_validate(
{"type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": "{}", "async": False}
)
resp = RestateModelResponse(output=[call], usage=Usage(), response_id="resp_1")

serde = DefaultSerde(RestateModelResponse)
replayed = serde.deserialize(serde.serialize(resp))
assert replayed is not None
(raw_item,) = replayed.to_input_items()
item: dict = dict(raw_item)
assert "async_" not in item
assert item["async"] is False
Loading