google-gemini / generative-ai-python

The official Python library for the Google Gemini API
https://pypi.org/project/google-generativeai/
Apache License 2.0
1.62k stars 322 forks source link

KeyError: 'properties' while using Enum in Structured Output #551

Closed PraveenKS30 closed 2 months ago

PraveenKS30 commented 2 months ago

Description of the bug:

Bug :

 result = model.generate_content(
             ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\google\generativeai\generative_models.py", line 305, in generate_content
    request = self._prepare_request(
              ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\google\generativeai\generative_models.py", line 156, in _prepare_request
    generation_config = generation_types.to_generation_config_dict(generation_config)
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\google\generativeai\types\generation_types.py", line 209, in to_generation_config_dict
    _normalize_schema(generation_config)
  File "C:\Python311\Lib\site-packages\google\generativeai\types\generation_types.py", line 191, in _normalize_schema
    response_schema = content_types._schema_for_class(response_schema)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\google\generativeai\types\content_types.py", line 300, in _schema_for_class
    schema = _build_schema("dummy", {"dummy": (cls, pydantic.Field())})
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\google\generativeai\types\content_types.py", line 386, in _build_schema
    unpack_defs(value, defs)
  File "C:\Python311\Lib\site-packages\google\generativeai\types\content_types.py", line 404, in unpack_defs
    properties = schema["properties"]
                 ~~~~~~^^^^^^^^^^^^^^
**KeyError: 'properties'**

Code :

import enum
from typing_extensions import TypedDict
import google.generativeai as genai

class Grade(enum.Enum):
    A_PLUS = "a+"
    A = "a"
    B = "b"
    C = "c"
    D = "d"
    F = "f"

class Recipe(TypedDict):
    recipe_name: str
    grade: Grade

model = genai.GenerativeModel("gemini-1.5-pro-latest")

result = model.generate_content(
    "List about 10 cookie recipes, grade them based on popularity",
    generation_config=genai.GenerationConfig(
        response_mime_type="application/json", response_schema=list[Recipe]
    ),
)
print(result)

Actual vs expected behavior:

Actual : properties = schema["properties"] KeyError: 'properties'

Expected :

[{"grade": "a+", "recipe_name": "Chocolate Chip Cookies"}, ...]

Any other information you'd like to share?

No response

gh640 commented 2 months ago

It's not a bug. Use the latest version 0.8.0. I confirmed the script works with 0.8.0.

See also:

https://x.com/practical_wp/status/1833771501591642318

MarkDaoust commented 2 months ago

Yes. Thanks @gh640!