Skip to content

Fix typing errors from mypy when calling completion #911

Closed as not planned
Closed as not planned
@achrome

Description

@achrome

Confirm this is an issue with the Python library and not an underlying OpenAI API

  • This is an issue with the Python library

Describe the bug

Mypy doesn't seem to play very well with the type annotations that the SDK has generated. I can see that OpenAI uses Stainless and that might be the issue in itself, but as it stands the type annotations aren't very well documented.

See below for the exact use case and how to reproduce.

I'd propose either updating the annotations to be more semantically correct, or updating the documentation and usage if the idea is to keep the annotations more strict.

Option 1 seems like a better option until a full migration to stricter types can be reached, likely in a major version.

To Reproduce

When calling completion like so

client = AsyncOpenAI(api_key=<API_KEY>)
messages = [
    {"role": "user", "content": "some test message"}
]
completion = await client.chat.completions.create(
    model="gpt-3.5-turbo-0613", # Actual model doesn't matter here
    messages=messages # Mypy shows a type mismatch error here
)

I did a little bit of digging and found that the messages arg in chat.completions.create is annotated as ChatCompletionMessageParam, however the method is smart enough to take and serialize plain dicts as well. I haven't seen the rest of the endpoints, but my guess is that this annotation issue is present throughout.

I can get around it by using the appropriate types instead. So, the following works

from openai.types.chat import ChatCompletionMessageParam, ChatCompletionUserMessageParam
messages: list[ChatCompletionMessageParam] = [
    ChatCompletionUserMessageParam(role="user", content="some test message")
]
# This seems to satisfy mypy

Code snippets

No response

OS

Linux

Python version

3.12

Library version

v1.3.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions