microsoft / TypeChat

TypeChat is a library that makes it easy to build natural language interfaces using types.
https://microsoft.github.io/TypeChat/
MIT License
8.06k stars 379 forks source link

Add `@dataclass` support to Python #160

Closed DanielRosenwasser closed 5 months ago

DanielRosenwasser commented 6 months ago

Currently, our Python implementation only supports TypedDicts. This is okay, but I think we need to support dataclasses.

Given a reference to Event for the following code,

from dataclasses import dataclass, field

@dataclass
class EventTimeRange:
    ...

@dataclass
class Event:
    day: str
    time_range: EventTimeRange
    description: str
    location: str | None
    participants: list[str] = field(default_factory=list)

We should generate the following schema for Event:

interface Event {
    day: string;
    time_range: EventTimeRange;
    description: string;
    location: string | null;
    participants: string[];
}

I've adapted this example from the calendar example. Note two things:

  1. The presence of a default makes a field optional, but does not necessarily make it null-able.
  2. The presence of | None in an annotation makes a field null-able, but not necessarily optional.