TypeChat icon indicating copy to clipboard operation
TypeChat copied to clipboard

Generate JSON wire schemas for Python runtime types supported by Pydantic

Open robgruen opened this issue 1 month ago • 1 comments

Summary

Generate appropriate JSON wire schemas for Python runtime types that the existing Pydantic-backed validator already supports.

Currently, validation can convert JSON values into native Python objects, but prompt-schema generation rejects their annotations. This blocks normal translator construction before a model is called.

This is a Python companion to #451. It is primarily a schema-generation coverage gap, not a request to implement a new deserialization framework.

Reproduction

from datetime import datetime
from typing_extensions import TypedDict
from typechat import Failure, Success, TypeChatValidator, python_type_to_typescript_schema

class Event(TypedDict):
    timestamp: datetime

validator = TypeChatValidator(Event)

result = validator.validate_object({
    "timestamp": "2022-08-20T08:30:00.000Z"
})
assert isinstance(result, Success)
assert isinstance(result.value["timestamp"], datetime)

invalid = validator.validate_object({"timestamp": "not-a-date"})
assert isinstance(invalid, Failure)

conversion = python_type_to_typescript_schema(Event)
print(conversion.errors)

Runtime conversion succeeds, but schema generation reports:

datetime was not a TypedDict, dataclass, or type alias, and cannot be translated.

The default translator raises during construction. The problem is the schema converter's handling of these classes, not Pydantic's ability to validate and construct the runtime value.

Verified affected types

For each type below, the existing validator accepted the listed JSON field value and returned the corresponding native Python type. The schema converter rejected the annotation, and translator construction failed with zero model calls.

Python type Accepted JSON field value with the tested default configuration
datetime.datetime "2022-08-20T08:30:00.000Z"
datetime.date "2022-08-20"
datetime.time "08:30:00"
datetime.timedelta "PT1H"
uuid.UUID "12345678-1234-5678-1234-567812345678"
decimal.Decimal "12.50"
bytes "hello"

Dictionary, set, and frozen-set translation was also checked and already works end-to-end. Dataclass conversion is already supported as well; those capabilities should be preserved, not reimplemented.

Proposed direction

  • Describe the JSON input representation in the generated prompt schema, while retaining the native Python annotation and typed validation result.
  • Reuse existing Pydantic validation/conversion behavior.
  • Provide useful format guidance, such as ISO date/time or UUID strings, rather than emitting empty interfaces or unconstrained placeholders.
  • Document representations and relevant configuration limits. Decimal precision, timezone handling, and byte encodings must not be silently changed.
  • For bytes, the advertised representation must match the validator's configured decoding behavior; do not assume all configurations use the same encoding.

At minimum, the verified representations above should be usable in normal translation. Additional representations should be documented and tested against the validator rather than inferred from the Python type name alone.

Acceptance criteria

  • [ ] The datetime reproduction produces a JSON-compatible prompt schema without conversion errors, and translator construction succeeds with normal schema checking enabled.
  • [ ] Cover the verified type list, including representative nested/list/dictionary/optional-field uses.
  • [ ] Offline translation tests return the correct native Python types from valid JSON responses.
  • [ ] Invalid date/time/UUID/etc. values still produce meaningful validation failures and participate in the existing response-repair flow.
  • [ ] Tests cover the selected wire formats and document any unsupported configuration variants.
  • [ ] Existing dictionary, set, frozen-set, dataclass, and ordinary JSON-field behavior remains unchanged.
  • [ ] Truly unsupported annotations still fail during schema construction before any model request.
  • [ ] Update Python documentation with supported types, wire representations, examples, and limitations.

Scope and related work

  • #451: Related TypeScript/Zod wire-schema-to-runtime mapping work.
  • #452: Missing TypeScript standard-library declarations are not this Python implementation's root cause.
  • #455: Python NewType annotation support is a separate, independently implementable converter improvement.
  • #453: Python's existing fail-fast schema-conversion checks should remain in place.

Do not add a TypeScript compiler/minimal-library dependency to Python, disable schema checks, or add automatic arbitrary-class hydration to address this issue.

Reconfirmed offline with Python 3.14.7 and Pydantic 2.13.4 against the current working tree. The relevant converter is unchanged from the source revision linked above. No live model/API calls were used.

robgruen avatar Oct 13 '26 00:10 robgruen

I'd like to take this one if nobody else is working on it.

I can reproduce it on main (c2215ed). For the types in the table, validation returns the native value. The schema converter, however, reports <type> was not a TypedDict, dataclass, or type alias, and cannot be translated., so translator construction fails before any model call.

Here is what I plan to do, following the proposed direction and acceptance criteria above:

  • In python_type_to_ts_nodes.py, map each verified type to string in the prompt schema, with a short format note. Examples: ISO 8601 datetime/date/time, an ISO 8601 duration for timedelta, a canonical UUID string, and a decimal string for Decimal. The annotation and the validated Python type stay the same.
  • For bytes, take the advertised encoding from how the validator is configured. If I can't derive it reliably, I'll document that limitation instead of guessing.
  • Tests:
    • offline translation tests that return the native types for plain, nested, list[...], dict[...] and Optional[...] fields;
    • invalid values that still fail validation and go through the repair flow;
    • truly unsupported classes that still fail at schema construction.
  • Update the Python docs to list the supported types, their wire formats and the limitations.

Does that match what you had in mind?

14H034160212 avatar Nov 07 '26 03:11 14H034160212