Created
February 23, 2024 00:48
-
-
Save seanchatmangpt/f9fcce49b3ad188f09c4ae44e8f3129d to your computer and use it in GitHub Desktop.
Simplest pydantic instance creator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ast | |
import inspect | |
import dspy | |
from typing import Type | |
from pydantic import BaseModel | |
class User(BaseModel): | |
name: str | |
age: int | |
is_active: bool = True | |
class GeneratePydanticInstance(dspy.Module): | |
def __init__(self): | |
super().__init__() | |
def forward(self, pydantic_class: Type[BaseModel], prompt): | |
# Validate and create an instance of the Pydantic class | |
classify = dspy.Predict('cls, prompt -> dict') | |
response = classify(cls=inspect.getsource(pydantic_class), prompt=prompt) | |
res_dict = ast.literal_eval(response.dict) | |
return pydantic_class.model_validate(res_dict) | |
def main(): | |
lm = dspy.OpenAI(max_tokens=200) | |
dspy.settings.configure(lm=lm) | |
# Assume `generate_instance` is an instance of `GeneratePydanticInstance` | |
generate_instance = GeneratePydanticInstance() | |
# Generate the Pydantic instance | |
pred = generate_instance(User, "My name is Sean, I am 41, and I am not active") | |
# Print the instance | |
print(f"Generated Pydantic Instance: {type(pred)}\n{pred}") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment