Skip to content

TypeSpec to Python emitter bug when emitting base/derived models #2735

@dargilco

Description

@dargilco

I have this base model and two derived models with discriminator decorator in my TypeSpec (comments removed for brevity):

@discriminator("type")
model ChatCompletionsResponseFormat {
  type: string;
}

model ChatCompletionsResponseFormatText extends ChatCompletionsResponseFormat {
  type: "text";
}

model ChatCompletionsResponseFormatJSON extends ChatCompletionsResponseFormat {
  type: "json_object";
}

This is the emitted Python code in _models.py (comments removed for brevity):

class ChatCompletionsResponseFormat(_model_base.Model):

    __mapping__: Dict[str, _model_base.Model] = {}
    type: str = rest_discriminator(name="type")

    @overload
    def __init__(
        self,
        *,
        type: str,
    ): ...

    @overload
    def __init__(self, mapping: Mapping[str, Any]):

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)


class ChatCompletionsResponseFormatJSON(ChatCompletionsResponseFormat, discriminator="json_object"):

    type: Literal["json_object"] = rest_discriminator(name="type")


class ChatCompletionsResponseFormatText(ChatCompletionsResponseFormat, discriminator="text"):

    type: Literal["text"] = rest_discriminator(name="type")

When I run a sample that tries to use one of the two derived classes as input arguments in the operator method, for example response_format=ChatCompletionsResponseFormatJSON(), I get the following error Missing required parameter: 'response_format.type'

To fix it I had to update the two derived classes in the auto generated code in _models.py to implement missing init methods, as following (giving example for only one of the derived classes):

class ChatCompletionsResponseFormatJSON(ChatCompletionsResponseFormat, discriminator="json_object"):

    type: Literal["json_object"] = rest_discriminator(name="type")

    @overload
    def __init__(self): ...

    @overload
    def __init__(self, mapping: Mapping[str, Any]):

    def __init__(self, *args: Any, **kwargs: Any) -> None: 
        super().__init__(*args, type="json_object", **kwargs)

So this seems like an emitter bug to me.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions