Find answers from the community

Updated last year

Has anyone tried getting llm to write

At a glance
Has anyone tried getting llm to write the pydantic model?

I have everything working with pydantic and extracting desired fields, but now i want to enable the end user to provide natural language for the desired extraction and then have step where the llm defines the pydantic model

Would be great if it could be just an easy json to class function etc
L
k
6 comments
lol so this is kind of hacky, but what if you defined a pydantic model that caputres the needed fields to define another model πŸ˜†
After a lot of trial an error i got it to work like this, its pretty easy to get gpt4 to write that json schema below

Plain Text
from langchain.chains.openai_functions import (
    convert_to_openai_function,
    get_openai_output_parser,
)
from langchain.pydantic_v1 import BaseModel, Field

# Example usage
json_schema = '''
{
    "title": "TypeOfLaw",
    "description": "Identifying information about the types of law that attorneys practice.",
    "properties": {
        "criminal_law": {"type": "bool"},
        "civil_rights_law": {"type": "bool"},
        "family_law": {"type": "bool"},
        "real_estate_law": {"type": "bool"},
        "corporate_law": {"type": "bool"},
        "insurance_law": {"type": "bool"},
        "labor_and_employment_law": {"type": "bool"},
        "environmental_law": {"type": "bool"},
        "personal_injury_law": {"type": "bool"},
        "immigration_law": {"type": "bool"},
        "intellectual_property_law": {"type": "bool"},
        "tax_law": {"type": "bool"},
    "required": []
}
'''

# Parse the JSON schema
schema = json.loads(json_schema)
properties = schema.get('properties', {})

# Function to generate Python code for the Pydantic model from the JSON schema
def generate_pydantic_model_code(schema_properties, title, description):
    # Start of the class definition
    model_code = f"class {title}(BaseModel):\n"
    model_code += f"    \"\"\"{description}\"\"\"\n"

    # Add each field to the class definition
    for field in schema_properties:
        model_code += f"    {field}: Optional[bool] = None\n"

    return model_code

# Generate the Python code for the Pydantic model
model_code = generate_pydantic_model_code(properties, schema['title'], schema['description'])

# Execute the generated code to create the Pydantic model
exec(model_code, globals())

# Retrieve the dynamically created model class
DynamicallyCreatedModel = globals()[schema['title']]

openai_functions = [convert_to_openai_function(DynamicallyCreatedModel)]
I think you could make this more stable by using openai's function calling api to generate the model schema πŸ‘€
but very cool
yes thats a great idea
Add a reply
Sign up and join the conversation on Discord