Skip to content

fix(messages): add InstructionPart to ModelRequestPart discriminated union#5697

Open
devteamaegis wants to merge 2 commits into
pydantic:mainfrom
devteamaegis:fix/instruction-part-roundtrip
Open

fix(messages): add InstructionPart to ModelRequestPart discriminated union#5697
devteamaegis wants to merge 2 commits into
pydantic:mainfrom
devteamaegis:fix/instruction-part-roundtrip

Conversation

@devteamaegis
Copy link
Copy Markdown
Contributor

Problem

InstructionPart has part_kind: Literal['instruction'] = 'instruction' and its
docstring states "Part type identifier, used as a discriminator for deserialization."
It can appear in ModelRequest.parts during normal agent runs, but it was not
included
in the ModelRequestPart discriminated union.

As a result, any serialized message history containing an InstructionPart in its
parts list would fail to reload:

from pydantic_ai import InstructionPart, ModelMessagesTypeAdapter, ModelRequest, UserPromptPart

req = ModelRequest(parts=[
    UserPromptPart(content='Hello'),
    InstructionPart(content='Be concise.'),
])

serialized = ModelMessagesTypeAdapter.dump_json([req])  # succeeds with warnings
ModelMessagesTypeAdapter.validate_json(serialized)       # raises ValidationError!
# Input tag 'instruction' found using _model_request_part_discriminator()
# does not match any of the expected tags:
# 'system-prompt', 'user-prompt', 'tool-search-return', 'tool-return', 'retry-prompt'

This silently corrupted message histories in Temporal/durable-exec workflows, resumed
runs, and any code that persists history to JSON and reloads it.

Fix

Add Annotated[InstructionPart, pydantic.Tag('instruction')] to the ModelRequestPart
union (one line change in messages.py).

Tests

Added TestInstructionParts::test_instruction_part_in_parts_roundtrip — a regression
test that round-trips a ModelRequest containing both static and dynamic
InstructionPart instances alongside a UserPromptPart through
dump_jsonvalidate_json and asserts full fidelity.

Fixes #5696.

@github-actions github-actions Bot added size: S Small PR (≤100 weighted lines) bug Report that something isn't working, or PR implementing a fix labels May 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Report that something isn't working, or PR implementing a fix size: S Small PR (≤100 weighted lines)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[roundtrip-sweep] ModelRequest.parts: InstructionPart fails to deserialize after serialization

1 participant