Created
December 7, 2023 18:04
-
-
Save zachschillaci27/654c1d53d089bd3dbf3ddb3a4071c9f1 to your computer and use it in GitHub Desktop.
OpenAI API: Generate dummy function call for testing
This file contains hidden or 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 json | |
from typing import Any, Type | |
from pydantic import BaseModel | |
class FunctionSchemaForOpenAI(BaseModel): | |
name: str | |
description: str | |
func_schema: Type[BaseModel] | |
dummy_primitives: dict[str, Any] = { | |
"boolean": False, | |
"string": "", | |
} | |
def to_dict(self) -> dict[str, Any]: | |
return { | |
"name": self.name, | |
"description": self.description, | |
"parameters": self.func_schema.model_json_schema(), | |
} | |
def _generate_dummy_value( | |
self, schema_property: dict[str, Any], schema_defs: dict[str, Any] | |
) -> Any: | |
# Recursive function to generate dummy value | |
data_type = schema_property.get("type") | |
if data_type == "array": | |
item_type = schema_property["items"].get("type") | |
# If item type is not specified, it could be a reference | |
if not item_type: | |
ref = schema_property["items"].get("$ref") | |
if ref is not None: | |
# Resolve the reference | |
ref_schema = schema_defs[ref.split("/")[-1]] | |
return [self._generate_dummy_value(ref_schema, schema_defs)] | |
else: | |
# If it's a primitive type, simply return its default value wrapped in a list | |
return [self.dummy_primitives[item_type]] | |
elif data_type == "object": | |
return { | |
key: self._generate_dummy_value(value, schema_defs) | |
for key, value in schema_property["properties"].items() | |
} | |
else: | |
return self.dummy_primitives.get(data_type) | |
def generate_dummy_call(self) -> str: | |
schema = self.func_schema.model_json_schema() | |
schema_defs = schema.get("$defs", {}) | |
return json.dumps( | |
{ | |
key: self._generate_dummy_value(value, schema_defs) | |
for key, value in schema["properties"].items() | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment