googleapis / googleapis/python-genai
Add support for recursive Pydantic models
- Dominant language
- Python
- Stars
- 4k
- Forks
- 1k
- Avg merge
- 2d 11h
- Merged PRs (30d)
- 40
Description
Thanks for stopping by to let us know something could be better!
**PLEASE READ**: If you have a support contract with Google, please create an issue in the [support console](https://cloud.google.com/support/) instead of filing on GitHub. This will ensure a timely response.
---
**Is your feature request related to a problem? Please describe.**
Yes. I'm encountering a problem when trying to use recursive Pydantic models as a response schema for `google.genai.Client`. Specifically, when using a recursive model (e.g., an `AND` or `OR` block that can contain nested instances of itself), the call to `generate_content` fails with a `RecursionError: maximum recursion depth exceeded`.
**Describe the solution you'd like**
I would like the SDK and/or backend to support recursive Pydantic models correctly in the `response_schema` argument for structured generation using Gemini models. This is critical for representing complex hierarchical or tree-structured data (e.g., nested guidelines with logical operators like AND/OR).
**Describe alternatives you've considered**
- Flattening the model structure manually, which becomes unmanageable and error-prone for deeply nested logical rules.
- Using a post-processing step to manually reconstruct the recursive data structure from a less structured JSON output, which defeats the purpose of using `response_schema`.
**Additional context**
Here is a simplified example of what I am trying to achieve:
```python
from __future__ import annotations
from google import genai
from google.genai.types import GenerateContentConfig
from pydantic import BaseModel
class Condition(BaseModel):
condition: str
class ANDBlock(BaseModel):
AND: list[ANDBlock | ORBlock | Condition]
class ORBlock(BaseModel):
OR: list[ANDBlock | ORBlock | Condition]
class Conditions(BaseModel):
conditions: ANDBlock | ORBlock
client = genai.Client(api_key='...')
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="""Please structure the following rules into logical groups using AND/OR:
- The user must be over 18 years old.
- The user must have a valid driver's license or state-issued ID
- The user must not have committed any misdemeanor in last 18 months and the user must not have been fined in last 24 months.
- The user must have proof of insurance.
- A background check must be completed.
""",
config=GenerateContentConfig(
system_instruction="Convert the rules into a logical tree using nested AND/OR blocks.",
response_mime_type="application/json",
response_schema=Conditions
)
)
```
This raises following exception:
```RecursionError: maximum recursion depth exceeded```
Contributor guide
Assessment
This issue has not been assessed yet.