๐ PydanType: Pydantic to TypedDict Converter
Convert your Pydantic models to TypedDict with ease! ๐
๐ Motivation
Recently, Google Gemini introduced the ability to generate structured output, but here's the catch: unlike many environments that accept Pydantic models, they require TypeDict. It was tricky for me since I had a lot of Pydantic models in other projects, and I figured I wasnโt the only one. So, I created a simple utility that converts any Pydantic model to TypeDict, making it compatible with Gemini. Hopefully, this helps you as well! ๐ก
That's when this utility was born! Now you can:
- Define your models in Pydantic (with all its validation goodness) ๐
- Convert them to TypedDict when needed (for APIs like Gemini) ๐
- Enjoy the benefits of both! ๐
๐ Quick Start
Try it out instantly in our Colab notebook:
Install the package:
pip install pip install git+https://github.com/unclecode/pydantype.git
Use it in your code:
from pydantic import BaseModel
from pydantype import convert
class MyModel(BaseModel):
name: str
age: int
MyTypedDict = convert(MyModel)
๐ Gemini 1.5 Pro Example
Here's how you can use this utility with Google's Gemini 1.5 Pro:
import google.generativeai as genai
from pydantic import BaseModel
from typing import List
from pydantype import convert
class Recipe(BaseModel):
recipe_name: str
ingredients: str
class RecipeList(BaseModel):
recipes: List[Recipe]
RecipeListDict = convert(RecipeList)
model = genai.GenerativeModel('gemini-1.5-pro',
generation_config={
"response_mime_type": "application/json",
"response_schema": RecipeListDict
})
prompt = "List 3 popular cookie recipes"
response = model.generate_content(prompt)
print(response.text)
๐จ General Example
Here's a more general example showcasing various Pydantic features:
from typing import List, Optional
from pydantic import BaseModel, Field
from pydantype import convert
class Address(BaseModel):
street: str
city: str
country: str = Field(default="Unknown")
class Person(BaseModel):
name: str
age: int
address: Address
hobbies: List[str] = []
nickname: Optional[str] = None
PersonDict = convert(Person)
# PersonDict is now a TypedDict with the same structure as Person
๐ Features
- Converts simple and complex Pydantic models ๐
- Handles nested models, lists, and dictionaries ๐
- Supports optional fields and unions ๐ค
- Preserves type hints for better static analysis ๐
๐ค Contributing
Contributions are welcome! Feel free to open issues or submit pull requests. ๐
๐ License
This project is licensed under the MIT License. See the LICENSE file for details.
Happy coding! ๐๐