Skip to content

Instantly share code, notes, and snippets.

@kasperjunge
Created January 25, 2024 20:57
Show Gist options
  • Save kasperjunge/7177a2d6201600c85b51a83be5f03406 to your computer and use it in GitHub Desktop.
Save kasperjunge/7177a2d6201600c85b51a83be5f03406 to your computer and use it in GitHub Desktop.
Pydantic to OpenAI Function Calling
from pydantic import BaseModel, Field
import json
class ReceiptDataExtractor(BaseModel):
date: str = Field(description="The date.")
amount: float = Field(description="The total amount.")
supplier: str = Field(description="The supplier.")
class Config:
function_meta = {
"function_name": "receipt_data_extractor",
"function_description": "Extract meta data from receipts."
}
def convert_to_custom_schema(model):
# Check if the model is a subclass of BaseModel
if not issubclass(model, BaseModel):
raise TypeError("Model must be a subclass of pydantic.BaseModel")
# Check if Config and function_meta are correctly defined
if not hasattr(model, 'Config') or not hasattr(model.Config, 'function_meta'):
raise ValueError("Model must have a 'Config' class with a 'function_meta' attribute")
# Check for function_name and function_description in function_meta
if 'function_name' not in model.Config.function_meta or 'function_description' not in model.Config.function_meta:
raise ValueError("Model's 'Config.function_meta' must contain 'function_name' and 'function_description'")
# Generate the schema from the Pydantic model
schema = model.schema()
# Retrieve custom metadata from Config
function_name = model.Config.function_meta["function_name"]
function_description = model.Config.function_meta["function_description"]
# Create the custom schema structure
custom_schema = {
"type": "function",
"function": {
"name": function_name,
"description": function_description,
"parameters": {
"type": "object",
"properties": {},
"required": schema.get('required', [])
}
}
}
# Map the properties from Pydantic schema to the custom schema
for prop, details in schema.get('properties', {}).items():
custom_schema["function"]["parameters"]["properties"][prop] = {
"type": details["type"],
"description": details.get("description", "")
}
return custom_schema
# Usage
try:
custom_schema = convert_to_custom_schema(ReceiptDataExtractor)
print(json.dumps(custom_schema, indent=4))
except (TypeError, ValueError) as e:
print(f"Error: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment