1
0

pydantic_models_to_grammar.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  1. from __future__ import annotations
  2. import inspect
  3. import json
  4. import re
  5. from copy import copy
  6. from enum import Enum
  7. from inspect import getdoc, isclass
  8. from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union, get_args, get_origin, get_type_hints
  9. from docstring_parser import parse
  10. from pydantic import BaseModel, create_model
  11. if TYPE_CHECKING:
  12. from types import GenericAlias
  13. else:
  14. # python 3.8 compat
  15. from typing import _GenericAlias as GenericAlias
  16. # TODO: fix this
  17. # pyright: reportAttributeAccessIssue=information
  18. class PydanticDataType(Enum):
  19. """
  20. Defines the data types supported by the grammar_generator.
  21. Attributes:
  22. STRING (str): Represents a string data type.
  23. BOOLEAN (str): Represents a boolean data type.
  24. INTEGER (str): Represents an integer data type.
  25. FLOAT (str): Represents a float data type.
  26. OBJECT (str): Represents an object data type.
  27. ARRAY (str): Represents an array data type.
  28. ENUM (str): Represents an enum data type.
  29. CUSTOM_CLASS (str): Represents a custom class data type.
  30. """
  31. STRING = "string"
  32. TRIPLE_QUOTED_STRING = "triple_quoted_string"
  33. MARKDOWN_CODE_BLOCK = "markdown_code_block"
  34. BOOLEAN = "boolean"
  35. INTEGER = "integer"
  36. FLOAT = "float"
  37. OBJECT = "object"
  38. ARRAY = "array"
  39. ENUM = "enum"
  40. ANY = "any"
  41. NULL = "null"
  42. CUSTOM_CLASS = "custom-class"
  43. CUSTOM_DICT = "custom-dict"
  44. SET = "set"
  45. def map_pydantic_type_to_gbnf(pydantic_type: type[Any]) -> str:
  46. origin_type = get_origin(pydantic_type)
  47. origin_type = pydantic_type if origin_type is None else origin_type
  48. if isclass(origin_type) and issubclass(origin_type, str):
  49. return PydanticDataType.STRING.value
  50. elif isclass(origin_type) and issubclass(origin_type, bool):
  51. return PydanticDataType.BOOLEAN.value
  52. elif isclass(origin_type) and issubclass(origin_type, int):
  53. return PydanticDataType.INTEGER.value
  54. elif isclass(origin_type) and issubclass(origin_type, float):
  55. return PydanticDataType.FLOAT.value
  56. elif isclass(origin_type) and issubclass(origin_type, Enum):
  57. return PydanticDataType.ENUM.value
  58. elif isclass(origin_type) and issubclass(origin_type, BaseModel):
  59. return format_model_and_field_name(origin_type.__name__)
  60. elif origin_type is list:
  61. element_type = get_args(pydantic_type)[0]
  62. return f"{map_pydantic_type_to_gbnf(element_type)}-list"
  63. elif origin_type is set:
  64. element_type = get_args(pydantic_type)[0]
  65. return f"{map_pydantic_type_to_gbnf(element_type)}-set"
  66. elif origin_type is Union:
  67. union_types = get_args(pydantic_type)
  68. union_rules = [map_pydantic_type_to_gbnf(ut) for ut in union_types]
  69. return f"union-{'-or-'.join(union_rules)}"
  70. elif origin_type is Optional:
  71. element_type = get_args(pydantic_type)[0]
  72. return f"optional-{map_pydantic_type_to_gbnf(element_type)}"
  73. elif isclass(origin_type):
  74. return f"{PydanticDataType.CUSTOM_CLASS.value}-{format_model_and_field_name(origin_type.__name__)}"
  75. elif origin_type is dict:
  76. key_type, value_type = get_args(pydantic_type)
  77. return f"custom-dict-key-type-{format_model_and_field_name(map_pydantic_type_to_gbnf(key_type))}-value-type-{format_model_and_field_name(map_pydantic_type_to_gbnf(value_type))}"
  78. else:
  79. return "unknown"
  80. def format_model_and_field_name(model_name: str) -> str:
  81. parts = re.findall("[A-Z][^A-Z]*", model_name)
  82. if not parts: # Check if the list is empty
  83. return model_name.lower().replace("_", "-")
  84. return "-".join(part.lower().replace("_", "-") for part in parts)
  85. def generate_list_rule(element_type):
  86. """
  87. Generate a GBNF rule for a list of a given element type.
  88. :param element_type: The type of the elements in the list (e.g., 'string').
  89. :return: A string representing the GBNF rule for a list of the given type.
  90. """
  91. rule_name = f"{map_pydantic_type_to_gbnf(element_type)}-list"
  92. element_rule = map_pydantic_type_to_gbnf(element_type)
  93. list_rule = rf'{rule_name} ::= "[" {element_rule} ("," {element_rule})* "]"'
  94. return list_rule
  95. def get_members_structure(cls, rule_name):
  96. if issubclass(cls, Enum):
  97. # Handle Enum types
  98. members = [f'"\\"{member.value}\\""' for name, member in cls.__members__.items()]
  99. return f"{cls.__name__.lower()} ::= " + " | ".join(members)
  100. if cls.__annotations__ and cls.__annotations__ != {}:
  101. result = f'{rule_name} ::= "{{"'
  102. # Modify this comprehension
  103. members = [
  104. f' "\\"{name}\\"" ":" {map_pydantic_type_to_gbnf(param_type)}'
  105. for name, param_type in get_type_hints(cls).items()
  106. if name != "self"
  107. ]
  108. result += '"," '.join(members)
  109. result += ' "}"'
  110. return result
  111. if rule_name == "custom-class-any":
  112. result = f"{rule_name} ::= "
  113. result += "value"
  114. return result
  115. init_signature = inspect.signature(cls.__init__)
  116. parameters = init_signature.parameters
  117. result = f'{rule_name} ::= "{{"'
  118. # Modify this comprehension too
  119. members = [
  120. f' "\\"{name}\\"" ":" {map_pydantic_type_to_gbnf(param.annotation)}'
  121. for name, param in parameters.items()
  122. if name != "self" and param.annotation != inspect.Parameter.empty
  123. ]
  124. result += '", "'.join(members)
  125. result += ' "}"'
  126. return result
  127. def regex_to_gbnf(regex_pattern: str) -> str:
  128. """
  129. Translate a basic regex pattern to a GBNF rule.
  130. Note: This function handles only a subset of simple regex patterns.
  131. """
  132. gbnf_rule = regex_pattern
  133. # Translate common regex components to GBNF
  134. gbnf_rule = gbnf_rule.replace("\\d", "[0-9]")
  135. gbnf_rule = gbnf_rule.replace("\\s", "[ \t\n]")
  136. # Handle quantifiers and other regex syntax that is similar in GBNF
  137. # (e.g., '*', '+', '?', character classes)
  138. return gbnf_rule
  139. def generate_gbnf_integer_rules(max_digit=None, min_digit=None):
  140. """
  141. Generate GBNF Integer Rules
  142. Generates GBNF (Generalized Backus-Naur Form) rules for integers based on the given maximum and minimum digits.
  143. Parameters:
  144. max_digit (int): The maximum number of digits for the integer. Default is None.
  145. min_digit (int): The minimum number of digits for the integer. Default is None.
  146. Returns:
  147. integer_rule (str): The identifier for the integer rule generated.
  148. additional_rules (list): A list of additional rules generated based on the given maximum and minimum digits.
  149. """
  150. additional_rules = []
  151. # Define the rule identifier based on max_digit and min_digit
  152. integer_rule = "integer-part"
  153. if max_digit is not None:
  154. integer_rule += f"-max{max_digit}"
  155. if min_digit is not None:
  156. integer_rule += f"-min{min_digit}"
  157. # Handling Integer Rules
  158. if max_digit is not None or min_digit is not None:
  159. # Start with an empty rule part
  160. integer_rule_part = ""
  161. # Add mandatory digits as per min_digit
  162. if min_digit is not None:
  163. integer_rule_part += "[0-9] " * min_digit
  164. # Add optional digits up to max_digit
  165. if max_digit is not None:
  166. optional_digits = max_digit - (min_digit if min_digit is not None else 0)
  167. integer_rule_part += "".join(["[0-9]? " for _ in range(optional_digits)])
  168. # Trim the rule part and append it to additional rules
  169. integer_rule_part = integer_rule_part.strip()
  170. if integer_rule_part:
  171. additional_rules.append(f"{integer_rule} ::= {integer_rule_part}")
  172. return integer_rule, additional_rules
  173. def generate_gbnf_float_rules(max_digit=None, min_digit=None, max_precision=None, min_precision=None):
  174. """
  175. Generate GBNF float rules based on the given constraints.
  176. :param max_digit: Maximum number of digits in the integer part (default: None)
  177. :param min_digit: Minimum number of digits in the integer part (default: None)
  178. :param max_precision: Maximum number of digits in the fractional part (default: None)
  179. :param min_precision: Minimum number of digits in the fractional part (default: None)
  180. :return: A tuple containing the float rule and additional rules as a list
  181. Example Usage:
  182. max_digit = 3
  183. min_digit = 1
  184. max_precision = 2
  185. min_precision = 1
  186. generate_gbnf_float_rules(max_digit, min_digit, max_precision, min_precision)
  187. Output:
  188. ('float-3-1-2-1', ['integer-part-max3-min1 ::= [0-9] [0-9] [0-9]?', 'fractional-part-max2-min1 ::= [0-9] [0-9]?', 'float-3-1-2-1 ::= integer-part-max3-min1 "." fractional-part-max2-min
  189. *1'])
  190. Note:
  191. GBNF stands for Generalized Backus-Naur Form, which is a notation technique to specify the syntax of programming languages or other formal grammars.
  192. """
  193. additional_rules = []
  194. # Define the integer part rule
  195. integer_part_rule = (
  196. "integer-part"
  197. + (f"-max{max_digit}" if max_digit is not None else "")
  198. + (f"-min{min_digit}" if min_digit is not None else "")
  199. )
  200. # Define the fractional part rule based on precision constraints
  201. fractional_part_rule = "fractional-part"
  202. fractional_rule_part = ""
  203. if max_precision is not None or min_precision is not None:
  204. fractional_part_rule += (f"-max{max_precision}" if max_precision is not None else "") + (
  205. f"-min{min_precision}" if min_precision is not None else ""
  206. )
  207. # Minimum number of digits
  208. fractional_rule_part = "[0-9]" * (min_precision if min_precision is not None else 1)
  209. # Optional additional digits
  210. fractional_rule_part += "".join(
  211. [" [0-9]?"] * ((max_precision - (
  212. min_precision if min_precision is not None else 1)) if max_precision is not None else 0)
  213. )
  214. additional_rules.append(f"{fractional_part_rule} ::= {fractional_rule_part}")
  215. # Define the float rule
  216. float_rule = f"float-{max_digit if max_digit is not None else 'X'}-{min_digit if min_digit is not None else 'X'}-{max_precision if max_precision is not None else 'X'}-{min_precision if min_precision is not None else 'X'}"
  217. additional_rules.append(f'{float_rule} ::= {integer_part_rule} "." {fractional_part_rule}')
  218. # Generating the integer part rule definition, if necessary
  219. if max_digit is not None or min_digit is not None:
  220. integer_rule_part = "[0-9]"
  221. if min_digit is not None and min_digit > 1:
  222. integer_rule_part += " [0-9]" * (min_digit - 1)
  223. if max_digit is not None:
  224. integer_rule_part += "".join([" [0-9]?"] * (max_digit - (min_digit if min_digit is not None else 1)))
  225. additional_rules.append(f"{integer_part_rule} ::= {integer_rule_part.strip()}")
  226. return float_rule, additional_rules
  227. def generate_gbnf_rule_for_type(
  228. model_name, field_name, field_type, is_optional, processed_models, created_rules, field_info=None
  229. ) -> tuple[str, list[str]]:
  230. """
  231. Generate GBNF rule for a given field type.
  232. :param model_name: Name of the model.
  233. :param field_name: Name of the field.
  234. :param field_type: Type of the field.
  235. :param is_optional: Whether the field is optional.
  236. :param processed_models: List of processed models.
  237. :param created_rules: List of created rules.
  238. :param field_info: Additional information about the field (optional).
  239. :return: Tuple containing the GBNF type and a list of additional rules.
  240. :rtype: tuple[str, list]
  241. """
  242. rules = []
  243. field_name = format_model_and_field_name(field_name)
  244. gbnf_type = map_pydantic_type_to_gbnf(field_type)
  245. origin_type = get_origin(field_type)
  246. origin_type = field_type if origin_type is None else origin_type
  247. if isclass(origin_type) and issubclass(origin_type, BaseModel):
  248. nested_model_name = format_model_and_field_name(field_type.__name__)
  249. nested_model_rules, _ = generate_gbnf_grammar(field_type, processed_models, created_rules)
  250. rules.extend(nested_model_rules)
  251. gbnf_type, rules = nested_model_name, rules
  252. elif isclass(origin_type) and issubclass(origin_type, Enum):
  253. enum_values = [f'"\\"{e.value}\\""' for e in field_type] # Adding escaped quotes
  254. enum_rule = f"{model_name}-{field_name} ::= {' | '.join(enum_values)}"
  255. rules.append(enum_rule)
  256. gbnf_type, rules = model_name + "-" + field_name, rules
  257. elif origin_type is list: # Array
  258. element_type = get_args(field_type)[0]
  259. element_rule_name, additional_rules = generate_gbnf_rule_for_type(
  260. model_name, f"{field_name}-element", element_type, is_optional, processed_models, created_rules
  261. )
  262. rules.extend(additional_rules)
  263. array_rule = f"""{model_name}-{field_name} ::= "[" ws {element_rule_name} ("," ws {element_rule_name})* "]" """
  264. rules.append(array_rule)
  265. gbnf_type, rules = model_name + "-" + field_name, rules
  266. elif origin_type is set: # Array
  267. element_type = get_args(field_type)[0]
  268. element_rule_name, additional_rules = generate_gbnf_rule_for_type(
  269. model_name, f"{field_name}-element", element_type, is_optional, processed_models, created_rules
  270. )
  271. rules.extend(additional_rules)
  272. array_rule = f"""{model_name}-{field_name} ::= "[" ws {element_rule_name} ("," ws {element_rule_name})* "]" """
  273. rules.append(array_rule)
  274. gbnf_type, rules = model_name + "-" + field_name, rules
  275. elif gbnf_type.startswith("custom-class-"):
  276. rules.append(get_members_structure(field_type, gbnf_type))
  277. elif gbnf_type.startswith("custom-dict-"):
  278. key_type, value_type = get_args(field_type)
  279. additional_key_type, additional_key_rules = generate_gbnf_rule_for_type(
  280. model_name, f"{field_name}-key-type", key_type, is_optional, processed_models, created_rules
  281. )
  282. additional_value_type, additional_value_rules = generate_gbnf_rule_for_type(
  283. model_name, f"{field_name}-value-type", value_type, is_optional, processed_models, created_rules
  284. )
  285. gbnf_type = rf'{gbnf_type} ::= "{{" ( {additional_key_type} ": " {additional_value_type} ("," "\n" ws {additional_key_type} ":" {additional_value_type})* )? "}}" '
  286. rules.extend(additional_key_rules)
  287. rules.extend(additional_value_rules)
  288. elif gbnf_type.startswith("union-"):
  289. union_types = get_args(field_type)
  290. union_rules = []
  291. for union_type in union_types:
  292. if isinstance(union_type, GenericAlias):
  293. union_gbnf_type, union_rules_list = generate_gbnf_rule_for_type(
  294. model_name, field_name, union_type, False, processed_models, created_rules
  295. )
  296. union_rules.append(union_gbnf_type)
  297. rules.extend(union_rules_list)
  298. elif not issubclass(union_type, type(None)):
  299. union_gbnf_type, union_rules_list = generate_gbnf_rule_for_type(
  300. model_name, field_name, union_type, False, processed_models, created_rules
  301. )
  302. union_rules.append(union_gbnf_type)
  303. rules.extend(union_rules_list)
  304. # Defining the union grammar rule separately
  305. if len(union_rules) == 1:
  306. union_grammar_rule = f"{model_name}-{field_name}-optional ::= {' | '.join(union_rules)} | null"
  307. else:
  308. union_grammar_rule = f"{model_name}-{field_name}-union ::= {' | '.join(union_rules)}"
  309. rules.append(union_grammar_rule)
  310. if len(union_rules) == 1:
  311. gbnf_type = f"{model_name}-{field_name}-optional"
  312. else:
  313. gbnf_type = f"{model_name}-{field_name}-union"
  314. elif isclass(origin_type) and issubclass(origin_type, str):
  315. if field_info and hasattr(field_info, "json_schema_extra") and field_info.json_schema_extra is not None:
  316. triple_quoted_string = field_info.json_schema_extra.get("triple_quoted_string", False)
  317. markdown_string = field_info.json_schema_extra.get("markdown_code_block", False)
  318. gbnf_type = PydanticDataType.TRIPLE_QUOTED_STRING.value if triple_quoted_string else PydanticDataType.STRING.value
  319. gbnf_type = PydanticDataType.MARKDOWN_CODE_BLOCK.value if markdown_string else gbnf_type
  320. elif field_info and hasattr(field_info, "pattern"):
  321. # Convert regex pattern to grammar rule
  322. regex_pattern = field_info.regex.pattern
  323. gbnf_type = f"pattern-{field_name} ::= {regex_to_gbnf(regex_pattern)}"
  324. else:
  325. gbnf_type = PydanticDataType.STRING.value
  326. elif (
  327. isclass(origin_type)
  328. and issubclass(origin_type, float)
  329. and field_info
  330. and hasattr(field_info, "json_schema_extra")
  331. and field_info.json_schema_extra is not None
  332. ):
  333. # Retrieve precision attributes for floats
  334. max_precision = (
  335. field_info.json_schema_extra.get("max_precision") if field_info and hasattr(field_info,
  336. "json_schema_extra") else None
  337. )
  338. min_precision = (
  339. field_info.json_schema_extra.get("min_precision") if field_info and hasattr(field_info,
  340. "json_schema_extra") else None
  341. )
  342. max_digits = field_info.json_schema_extra.get("max_digit") if field_info and hasattr(field_info,
  343. "json_schema_extra") else None
  344. min_digits = field_info.json_schema_extra.get("min_digit") if field_info and hasattr(field_info,
  345. "json_schema_extra") else None
  346. # Generate GBNF rule for float with given attributes
  347. gbnf_type, rules = generate_gbnf_float_rules(
  348. max_digit=max_digits, min_digit=min_digits, max_precision=max_precision, min_precision=min_precision
  349. )
  350. elif (
  351. isclass(origin_type)
  352. and issubclass(origin_type, int)
  353. and field_info
  354. and hasattr(field_info, "json_schema_extra")
  355. and field_info.json_schema_extra is not None
  356. ):
  357. # Retrieve digit attributes for integers
  358. max_digits = field_info.json_schema_extra.get("max_digit") if field_info and hasattr(field_info,
  359. "json_schema_extra") else None
  360. min_digits = field_info.json_schema_extra.get("min_digit") if field_info and hasattr(field_info,
  361. "json_schema_extra") else None
  362. # Generate GBNF rule for integer with given attributes
  363. gbnf_type, rules = generate_gbnf_integer_rules(max_digit=max_digits, min_digit=min_digits)
  364. else:
  365. gbnf_type, rules = gbnf_type, []
  366. return gbnf_type, rules
  367. def generate_gbnf_grammar(model: type[BaseModel], processed_models: set[type[BaseModel]], created_rules: dict[str, list[str]]) -> tuple[list[str], bool]:
  368. """
  369. Generate GBnF Grammar
  370. Generates a GBnF grammar for a given model.
  371. :param model: A Pydantic model class to generate the grammar for. Must be a subclass of BaseModel.
  372. :param processed_models: A set of already processed models to prevent infinite recursion.
  373. :param created_rules: A dict containing already created rules to prevent duplicates.
  374. :return: A list of GBnF grammar rules in string format. And two booleans indicating if an extra markdown or triple quoted string is in the grammar.
  375. Example Usage:
  376. ```
  377. model = MyModel
  378. processed_models = set()
  379. created_rules = dict()
  380. gbnf_grammar = generate_gbnf_grammar(model, processed_models, created_rules)
  381. ```
  382. """
  383. if model in processed_models:
  384. return [], False
  385. processed_models.add(model)
  386. model_name = format_model_and_field_name(model.__name__)
  387. if not issubclass(model, BaseModel):
  388. # For non-Pydantic classes, generate model_fields from __annotations__ or __init__
  389. if hasattr(model, "__annotations__") and model.__annotations__:
  390. model_fields = {name: (typ, ...) for name, typ in get_type_hints(model).items()}
  391. else:
  392. init_signature = inspect.signature(model.__init__)
  393. parameters = init_signature.parameters
  394. model_fields = {name: (param.annotation, param.default) for name, param in parameters.items() if
  395. name != "self"}
  396. else:
  397. # For Pydantic models, use model_fields and check for ellipsis (required fields)
  398. model_fields = get_type_hints(model)
  399. model_rule_parts = []
  400. nested_rules = []
  401. has_markdown_code_block = False
  402. has_triple_quoted_string = False
  403. look_for_markdown_code_block = False
  404. look_for_triple_quoted_string = False
  405. for field_name, field_info in model_fields.items():
  406. if not issubclass(model, BaseModel):
  407. field_type, default_value = field_info
  408. # Check if the field is optional (not required)
  409. is_optional = (default_value is not inspect.Parameter.empty) and (default_value is not Ellipsis)
  410. else:
  411. field_type = field_info
  412. field_info = model.model_fields[field_name]
  413. is_optional = field_info.is_required is False and get_origin(field_type) is Optional
  414. rule_name, additional_rules = generate_gbnf_rule_for_type(
  415. model_name, format_model_and_field_name(field_name), field_type, is_optional, processed_models,
  416. created_rules, field_info
  417. )
  418. look_for_markdown_code_block = True if rule_name == "markdown_code_block" else False
  419. look_for_triple_quoted_string = True if rule_name == "triple_quoted_string" else False
  420. if not look_for_markdown_code_block and not look_for_triple_quoted_string:
  421. if rule_name not in created_rules:
  422. created_rules[rule_name] = additional_rules
  423. model_rule_parts.append(f' ws "\\"{field_name}\\"" ":" ws {rule_name}') # Adding escaped quotes
  424. nested_rules.extend(additional_rules)
  425. else:
  426. has_triple_quoted_string = look_for_triple_quoted_string
  427. has_markdown_code_block = look_for_markdown_code_block
  428. fields_joined = r' "," "\n" '.join(model_rule_parts)
  429. model_rule = rf'{model_name} ::= "{{" "\n" {fields_joined} "\n" ws "}}"'
  430. has_special_string = False
  431. if has_triple_quoted_string:
  432. model_rule += '"\\n" ws "}"'
  433. model_rule += '"\\n" triple-quoted-string'
  434. has_special_string = True
  435. if has_markdown_code_block:
  436. model_rule += '"\\n" ws "}"'
  437. model_rule += '"\\n" markdown-code-block'
  438. has_special_string = True
  439. all_rules = [model_rule] + nested_rules
  440. return all_rules, has_special_string
  441. def generate_gbnf_grammar_from_pydantic_models(
  442. models: list[type[BaseModel]], outer_object_name: str | None = None, outer_object_content: str | None = None,
  443. list_of_outputs: bool = False
  444. ) -> str:
  445. """
  446. Generate GBNF Grammar from Pydantic Models.
  447. This method takes a list of Pydantic models and uses them to generate a GBNF grammar string. The generated grammar string can be used for parsing and validating data using the generated
  448. * grammar.
  449. Args:
  450. models (list[type[BaseModel]]): A list of Pydantic models to generate the grammar from.
  451. outer_object_name (str): Outer object name for the GBNF grammar. If None, no outer object will be generated. Eg. "function" for function calling.
  452. outer_object_content (str): Content for the outer rule in the GBNF grammar. Eg. "function_parameters" or "params" for function calling.
  453. list_of_outputs (str, optional): Allows a list of output objects
  454. Returns:
  455. str: The generated GBNF grammar string.
  456. Examples:
  457. models = [UserModel, PostModel]
  458. grammar = generate_gbnf_grammar_from_pydantic(models)
  459. print(grammar)
  460. # Output:
  461. # root ::= UserModel | PostModel
  462. # ...
  463. """
  464. processed_models: set[type[BaseModel]] = set()
  465. all_rules = []
  466. created_rules: dict[str, list[str]] = {}
  467. if outer_object_name is None:
  468. for model in models:
  469. model_rules, _ = generate_gbnf_grammar(model, processed_models, created_rules)
  470. all_rules.extend(model_rules)
  471. if list_of_outputs:
  472. root_rule = r'root ::= (" "| "\n") "[" ws grammar-models ("," ws grammar-models)* ws "]"' + "\n"
  473. else:
  474. root_rule = r'root ::= (" "| "\n") grammar-models' + "\n"
  475. root_rule += "grammar-models ::= " + " | ".join(
  476. [format_model_and_field_name(model.__name__) for model in models])
  477. all_rules.insert(0, root_rule)
  478. return "\n".join(all_rules)
  479. elif outer_object_name is not None:
  480. if list_of_outputs:
  481. root_rule = (
  482. rf'root ::= (" "| "\n") "[" ws {format_model_and_field_name(outer_object_name)} ("," ws {format_model_and_field_name(outer_object_name)})* ws "]"'
  483. + "\n"
  484. )
  485. else:
  486. root_rule = f"root ::= {format_model_and_field_name(outer_object_name)}\n"
  487. model_rule = (
  488. rf'{format_model_and_field_name(outer_object_name)} ::= (" "| "\n") "{{" ws "\"{outer_object_name}\"" ":" ws grammar-models'
  489. )
  490. fields_joined = " | ".join(
  491. [rf"{format_model_and_field_name(model.__name__)}-grammar-model" for model in models])
  492. grammar_model_rules = f"\ngrammar-models ::= {fields_joined}"
  493. mod_rules = []
  494. for model in models:
  495. mod_rule = rf"{format_model_and_field_name(model.__name__)}-grammar-model ::= "
  496. mod_rule += (
  497. rf'"\"{model.__name__}\"" "," ws "\"{outer_object_content}\"" ":" ws {format_model_and_field_name(model.__name__)}' + "\n"
  498. )
  499. mod_rules.append(mod_rule)
  500. grammar_model_rules += "\n" + "\n".join(mod_rules)
  501. for model in models:
  502. model_rules, has_special_string = generate_gbnf_grammar(model, processed_models,
  503. created_rules)
  504. if not has_special_string:
  505. model_rules[0] += r'"\n" ws "}"'
  506. all_rules.extend(model_rules)
  507. all_rules.insert(0, root_rule + model_rule + grammar_model_rules)
  508. return "\n".join(all_rules)
  509. def get_primitive_grammar(grammar):
  510. """
  511. Returns the needed GBNF primitive grammar for a given GBNF grammar string.
  512. Args:
  513. grammar (str): The string containing the GBNF grammar.
  514. Returns:
  515. str: GBNF primitive grammar string.
  516. """
  517. type_list: list[type[object]] = []
  518. if "string-list" in grammar:
  519. type_list.append(str)
  520. if "boolean-list" in grammar:
  521. type_list.append(bool)
  522. if "integer-list" in grammar:
  523. type_list.append(int)
  524. if "float-list" in grammar:
  525. type_list.append(float)
  526. additional_grammar = [generate_list_rule(t) for t in type_list]
  527. primitive_grammar = r"""
  528. boolean ::= "true" | "false"
  529. null ::= "null"
  530. string ::= "\"" (
  531. [^"\\] |
  532. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F])
  533. )* "\"" ws
  534. ws ::= ([ \t\n] ws)?
  535. float ::= ("-"? ([0] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  536. integer ::= [0-9]+"""
  537. any_block = ""
  538. if "custom-class-any" in grammar:
  539. any_block = """
  540. value ::= object | array | string | number | boolean | null
  541. object ::=
  542. "{" ws (
  543. string ":" ws value
  544. ("," ws string ":" ws value)*
  545. )? "}" ws
  546. array ::=
  547. "[" ws (
  548. value
  549. ("," ws value)*
  550. )? "]" ws
  551. number ::= integer | float"""
  552. markdown_code_block_grammar = ""
  553. if "markdown-code-block" in grammar:
  554. markdown_code_block_grammar = r'''
  555. markdown-code-block ::= opening-triple-ticks markdown-code-block-content closing-triple-ticks
  556. markdown-code-block-content ::= ( [^`] | "`" [^`] | "`" "`" [^`] )*
  557. opening-triple-ticks ::= "```" "python" "\n" | "```" "c" "\n" | "```" "cpp" "\n" | "```" "txt" "\n" | "```" "text" "\n" | "```" "json" "\n" | "```" "javascript" "\n" | "```" "css" "\n" | "```" "html" "\n" | "```" "markdown" "\n"
  558. closing-triple-ticks ::= "```" "\n"'''
  559. if "triple-quoted-string" in grammar:
  560. markdown_code_block_grammar = r"""
  561. triple-quoted-string ::= triple-quotes triple-quoted-string-content triple-quotes
  562. triple-quoted-string-content ::= ( [^'] | "'" [^'] | "'" "'" [^'] )*
  563. triple-quotes ::= "'''" """
  564. return "\n" + "\n".join(additional_grammar) + any_block + primitive_grammar + markdown_code_block_grammar
  565. def generate_markdown_documentation(
  566. pydantic_models: list[type[BaseModel]], model_prefix="Model", fields_prefix="Fields",
  567. documentation_with_field_description=True
  568. ) -> str:
  569. """
  570. Generate markdown documentation for a list of Pydantic models.
  571. Args:
  572. pydantic_models (list[type[BaseModel]]): list of Pydantic model classes.
  573. model_prefix (str): Prefix for the model section.
  574. fields_prefix (str): Prefix for the fields section.
  575. documentation_with_field_description (bool): Include field descriptions in the documentation.
  576. Returns:
  577. str: Generated text documentation.
  578. """
  579. documentation = ""
  580. pyd_models: list[tuple[type[BaseModel], bool]] = [(model, True) for model in pydantic_models]
  581. for model, add_prefix in pyd_models:
  582. if add_prefix:
  583. documentation += f"{model_prefix}: {model.__name__}\n"
  584. else:
  585. documentation += f"Model: {model.__name__}\n"
  586. # Handling multi-line model description with proper indentation
  587. class_doc = getdoc(model)
  588. base_class_doc = getdoc(BaseModel)
  589. class_description = class_doc if class_doc and class_doc != base_class_doc else ""
  590. if class_description != "":
  591. documentation += " Description: "
  592. documentation += format_multiline_description(class_description, 0) + "\n"
  593. if add_prefix:
  594. # Indenting the fields section
  595. documentation += f" {fields_prefix}:\n"
  596. else:
  597. documentation += f" Fields:\n" # noqa: F541
  598. if isclass(model) and issubclass(model, BaseModel):
  599. for name, field_type in get_type_hints(model).items():
  600. # if name == "markdown_code_block":
  601. # continue
  602. if get_origin(field_type) == list:
  603. element_type = get_args(field_type)[0]
  604. if isclass(element_type) and issubclass(element_type, BaseModel):
  605. pyd_models.append((element_type, False))
  606. if get_origin(field_type) == Union:
  607. element_types = get_args(field_type)
  608. for element_type in element_types:
  609. if isclass(element_type) and issubclass(element_type, BaseModel):
  610. pyd_models.append((element_type, False))
  611. documentation += generate_field_markdown(
  612. name, field_type, model, documentation_with_field_description=documentation_with_field_description
  613. )
  614. documentation += "\n"
  615. if hasattr(model, "Config") and hasattr(model.Config,
  616. "json_schema_extra") and "example" in model.Config.json_schema_extra:
  617. documentation += f" Expected Example Output for {format_model_and_field_name(model.__name__)}:\n"
  618. json_example = json.dumps(model.Config.json_schema_extra["example"])
  619. documentation += format_multiline_description(json_example, 2) + "\n"
  620. return documentation
  621. def generate_field_markdown(
  622. field_name: str, field_type: type[Any], model: type[BaseModel], depth=1,
  623. documentation_with_field_description=True
  624. ) -> str:
  625. """
  626. Generate markdown documentation for a Pydantic model field.
  627. Args:
  628. field_name (str): Name of the field.
  629. field_type (type[Any]): Type of the field.
  630. model (type[BaseModel]): Pydantic model class.
  631. depth (int): Indentation depth in the documentation.
  632. documentation_with_field_description (bool): Include field descriptions in the documentation.
  633. Returns:
  634. str: Generated text documentation for the field.
  635. """
  636. indent = " " * depth
  637. field_info = model.model_fields.get(field_name)
  638. field_description = field_info.description if field_info and field_info.description else ""
  639. origin_type = get_origin(field_type)
  640. origin_type = field_type if origin_type is None else origin_type
  641. if origin_type == list:
  642. element_type = get_args(field_type)[0]
  643. field_text = f"{indent}{field_name} ({format_model_and_field_name(field_type.__name__)} of {format_model_and_field_name(element_type.__name__)})"
  644. if field_description != "":
  645. field_text += ":\n"
  646. else:
  647. field_text += "\n"
  648. elif origin_type == Union:
  649. element_types = get_args(field_type)
  650. types = []
  651. for element_type in element_types:
  652. types.append(format_model_and_field_name(element_type.__name__))
  653. field_text = f"{indent}{field_name} ({' or '.join(types)})"
  654. if field_description != "":
  655. field_text += ":\n"
  656. else:
  657. field_text += "\n"
  658. else:
  659. field_text = f"{indent}{field_name} ({format_model_and_field_name(field_type.__name__)})"
  660. if field_description != "":
  661. field_text += ":\n"
  662. else:
  663. field_text += "\n"
  664. if not documentation_with_field_description:
  665. return field_text
  666. if field_description != "":
  667. field_text += f" Description: {field_description}\n"
  668. # Check for and include field-specific examples if available
  669. if hasattr(model, "Config") and hasattr(model.Config,
  670. "json_schema_extra") and "example" in model.Config.json_schema_extra:
  671. field_example = model.Config.json_schema_extra["example"].get(field_name)
  672. if field_example is not None:
  673. example_text = f"'{field_example}'" if isinstance(field_example, str) else field_example
  674. field_text += f"{indent} Example: {example_text}\n"
  675. if isclass(origin_type) and issubclass(origin_type, BaseModel):
  676. field_text += f"{indent} Details:\n"
  677. for name, type_ in get_type_hints(field_type).items():
  678. field_text += generate_field_markdown(name, type_, field_type, depth + 2)
  679. return field_text
  680. def format_json_example(example: dict[str, Any], depth: int) -> str:
  681. """
  682. Format a JSON example into a readable string with indentation.
  683. Args:
  684. example (dict): JSON example to be formatted.
  685. depth (int): Indentation depth.
  686. Returns:
  687. str: Formatted JSON example string.
  688. """
  689. indent = " " * depth
  690. formatted_example = "{\n"
  691. for key, value in example.items():
  692. value_text = f"'{value}'" if isinstance(value, str) else value
  693. formatted_example += f"{indent}{key}: {value_text},\n"
  694. formatted_example = formatted_example.rstrip(",\n") + "\n" + indent + "}"
  695. return formatted_example
  696. def generate_text_documentation(
  697. pydantic_models: list[type[BaseModel]], model_prefix="Model", fields_prefix="Fields",
  698. documentation_with_field_description=True
  699. ) -> str:
  700. """
  701. Generate text documentation for a list of Pydantic models.
  702. Args:
  703. pydantic_models (list[type[BaseModel]]): List of Pydantic model classes.
  704. model_prefix (str): Prefix for the model section.
  705. fields_prefix (str): Prefix for the fields section.
  706. documentation_with_field_description (bool): Include field descriptions in the documentation.
  707. Returns:
  708. str: Generated text documentation.
  709. """
  710. documentation = ""
  711. pyd_models: list[tuple[type[BaseModel], bool]] = [(model, True) for model in pydantic_models]
  712. for model, add_prefix in pyd_models:
  713. if add_prefix:
  714. documentation += f"{model_prefix}: {model.__name__}\n"
  715. else:
  716. documentation += f"Model: {model.__name__}\n"
  717. # Handling multi-line model description with proper indentation
  718. class_doc = getdoc(model)
  719. base_class_doc = getdoc(BaseModel)
  720. class_description = class_doc if class_doc and class_doc != base_class_doc else ""
  721. if class_description != "":
  722. documentation += " Description: "
  723. documentation += "\n" + format_multiline_description(class_description, 2) + "\n"
  724. if isclass(model) and issubclass(model, BaseModel):
  725. documentation_fields = ""
  726. for name, field_type in get_type_hints(model).items():
  727. # if name == "markdown_code_block":
  728. # continue
  729. if get_origin(field_type) == list:
  730. element_type = get_args(field_type)[0]
  731. if isclass(element_type) and issubclass(element_type, BaseModel):
  732. pyd_models.append((element_type, False))
  733. if get_origin(field_type) == Union:
  734. element_types = get_args(field_type)
  735. for element_type in element_types:
  736. if isclass(element_type) and issubclass(element_type, BaseModel):
  737. pyd_models.append((element_type, False))
  738. documentation_fields += generate_field_text(
  739. name, field_type, model, documentation_with_field_description=documentation_with_field_description
  740. )
  741. if documentation_fields != "":
  742. if add_prefix:
  743. documentation += f" {fields_prefix}:\n{documentation_fields}"
  744. else:
  745. documentation += f" Fields:\n{documentation_fields}"
  746. documentation += "\n"
  747. if hasattr(model, "Config") and hasattr(model.Config,
  748. "json_schema_extra") and "example" in model.Config.json_schema_extra:
  749. documentation += f" Expected Example Output for {format_model_and_field_name(model.__name__)}:\n"
  750. json_example = json.dumps(model.Config.json_schema_extra["example"])
  751. documentation += format_multiline_description(json_example, 2) + "\n"
  752. return documentation
  753. def generate_field_text(
  754. field_name: str, field_type: type[Any], model: type[BaseModel], depth=1,
  755. documentation_with_field_description=True
  756. ) -> str:
  757. """
  758. Generate text documentation for a Pydantic model field.
  759. Args:
  760. field_name (str): Name of the field.
  761. field_type (type[Any]): Type of the field.
  762. model (type[BaseModel]): Pydantic model class.
  763. depth (int): Indentation depth in the documentation.
  764. documentation_with_field_description (bool): Include field descriptions in the documentation.
  765. Returns:
  766. str: Generated text documentation for the field.
  767. """
  768. indent = " " * depth
  769. field_info = model.model_fields.get(field_name)
  770. field_description = field_info.description if field_info and field_info.description else ""
  771. if get_origin(field_type) == list:
  772. element_type = get_args(field_type)[0]
  773. field_text = f"{indent}{field_name} ({format_model_and_field_name(field_type.__name__)} of {format_model_and_field_name(element_type.__name__)})"
  774. if field_description != "":
  775. field_text += ":\n"
  776. else:
  777. field_text += "\n"
  778. elif get_origin(field_type) == Union:
  779. element_types = get_args(field_type)
  780. types = []
  781. for element_type in element_types:
  782. types.append(format_model_and_field_name(element_type.__name__))
  783. field_text = f"{indent}{field_name} ({' or '.join(types)})"
  784. if field_description != "":
  785. field_text += ":\n"
  786. else:
  787. field_text += "\n"
  788. else:
  789. field_text = f"{indent}{field_name} ({format_model_and_field_name(field_type.__name__)})"
  790. if field_description != "":
  791. field_text += ":\n"
  792. else:
  793. field_text += "\n"
  794. if not documentation_with_field_description:
  795. return field_text
  796. if field_description != "":
  797. field_text += f"{indent} Description: " + field_description + "\n"
  798. # Check for and include field-specific examples if available
  799. if hasattr(model, "Config") and hasattr(model.Config,
  800. "json_schema_extra") and "example" in model.Config.json_schema_extra:
  801. field_example = model.Config.json_schema_extra["example"].get(field_name)
  802. if field_example is not None:
  803. example_text = f"'{field_example}'" if isinstance(field_example, str) else field_example
  804. field_text += f"{indent} Example: {example_text}\n"
  805. if isclass(field_type) and issubclass(field_type, BaseModel):
  806. field_text += f"{indent} Details:\n"
  807. for name, type_ in get_type_hints(field_type).items():
  808. field_text += generate_field_text(name, type_, field_type, depth + 2)
  809. return field_text
  810. def format_multiline_description(description: str, indent_level: int) -> str:
  811. """
  812. Format a multiline description with proper indentation.
  813. Args:
  814. description (str): Multiline description.
  815. indent_level (int): Indentation level.
  816. Returns:
  817. str: Formatted multiline description.
  818. """
  819. indent = " " * indent_level
  820. return indent + description.replace("\n", "\n" + indent)
  821. def save_gbnf_grammar_and_documentation(
  822. grammar, documentation, grammar_file_path="./grammar.gbnf", documentation_file_path="./grammar_documentation.md"
  823. ):
  824. """
  825. Save GBNF grammar and documentation to specified files.
  826. Args:
  827. grammar (str): GBNF grammar string.
  828. documentation (str): Documentation string.
  829. grammar_file_path (str): File path to save the GBNF grammar.
  830. documentation_file_path (str): File path to save the documentation.
  831. Returns:
  832. None
  833. """
  834. try:
  835. with open(grammar_file_path, "w") as file:
  836. file.write(grammar + get_primitive_grammar(grammar))
  837. print(f"Grammar successfully saved to {grammar_file_path}")
  838. except IOError as e:
  839. print(f"An error occurred while saving the grammar file: {e}")
  840. try:
  841. with open(documentation_file_path, "w") as file:
  842. file.write(documentation)
  843. print(f"Documentation successfully saved to {documentation_file_path}")
  844. except IOError as e:
  845. print(f"An error occurred while saving the documentation file: {e}")
  846. def remove_empty_lines(string):
  847. """
  848. Remove empty lines from a string.
  849. Args:
  850. string (str): Input string.
  851. Returns:
  852. str: String with empty lines removed.
  853. """
  854. lines = string.splitlines()
  855. non_empty_lines = [line for line in lines if line.strip() != ""]
  856. string_no_empty_lines = "\n".join(non_empty_lines)
  857. return string_no_empty_lines
  858. def generate_and_save_gbnf_grammar_and_documentation(
  859. pydantic_model_list,
  860. grammar_file_path="./generated_grammar.gbnf",
  861. documentation_file_path="./generated_grammar_documentation.md",
  862. outer_object_name: str | None = None,
  863. outer_object_content: str | None = None,
  864. model_prefix: str = "Output Model",
  865. fields_prefix: str = "Output Fields",
  866. list_of_outputs: bool = False,
  867. documentation_with_field_description=True,
  868. ):
  869. """
  870. Generate GBNF grammar and documentation, and save them to specified files.
  871. Args:
  872. pydantic_model_list: List of Pydantic model classes.
  873. grammar_file_path (str): File path to save the generated GBNF grammar.
  874. documentation_file_path (str): File path to save the generated documentation.
  875. outer_object_name (str): Outer object name for the GBNF grammar. If None, no outer object will be generated. Eg. "function" for function calling.
  876. outer_object_content (str): Content for the outer rule in the GBNF grammar. Eg. "function_parameters" or "params" for function calling.
  877. model_prefix (str): Prefix for the model section in the documentation.
  878. fields_prefix (str): Prefix for the fields section in the documentation.
  879. list_of_outputs (bool): Whether the output is a list of items.
  880. documentation_with_field_description (bool): Include field descriptions in the documentation.
  881. Returns:
  882. None
  883. """
  884. documentation = generate_markdown_documentation(
  885. pydantic_model_list, model_prefix, fields_prefix,
  886. documentation_with_field_description=documentation_with_field_description
  887. )
  888. grammar = generate_gbnf_grammar_from_pydantic_models(pydantic_model_list, outer_object_name, outer_object_content,
  889. list_of_outputs)
  890. grammar = remove_empty_lines(grammar)
  891. save_gbnf_grammar_and_documentation(grammar, documentation, grammar_file_path, documentation_file_path)
  892. def generate_gbnf_grammar_and_documentation(
  893. pydantic_model_list,
  894. outer_object_name: str | None = None,
  895. outer_object_content: str | None = None,
  896. model_prefix: str = "Output Model",
  897. fields_prefix: str = "Output Fields",
  898. list_of_outputs: bool = False,
  899. documentation_with_field_description=True,
  900. ):
  901. """
  902. Generate GBNF grammar and documentation for a list of Pydantic models.
  903. Args:
  904. pydantic_model_list: List of Pydantic model classes.
  905. outer_object_name (str): Outer object name for the GBNF grammar. If None, no outer object will be generated. Eg. "function" for function calling.
  906. outer_object_content (str): Content for the outer rule in the GBNF grammar. Eg. "function_parameters" or "params" for function calling.
  907. model_prefix (str): Prefix for the model section in the documentation.
  908. fields_prefix (str): Prefix for the fields section in the documentation.
  909. list_of_outputs (bool): Whether the output is a list of items.
  910. documentation_with_field_description (bool): Include field descriptions in the documentation.
  911. Returns:
  912. tuple: GBNF grammar string, documentation string.
  913. """
  914. documentation = generate_markdown_documentation(
  915. copy(pydantic_model_list), model_prefix, fields_prefix,
  916. documentation_with_field_description=documentation_with_field_description
  917. )
  918. grammar = generate_gbnf_grammar_from_pydantic_models(pydantic_model_list, outer_object_name, outer_object_content,
  919. list_of_outputs)
  920. grammar = remove_empty_lines(grammar + get_primitive_grammar(grammar))
  921. return grammar, documentation
  922. def generate_gbnf_grammar_and_documentation_from_dictionaries(
  923. dictionaries: list[dict[str, Any]],
  924. outer_object_name: str | None = None,
  925. outer_object_content: str | None = None,
  926. model_prefix: str = "Output Model",
  927. fields_prefix: str = "Output Fields",
  928. list_of_outputs: bool = False,
  929. documentation_with_field_description=True,
  930. ):
  931. """
  932. Generate GBNF grammar and documentation from a list of dictionaries.
  933. Args:
  934. dictionaries (list[dict]): List of dictionaries representing Pydantic models.
  935. outer_object_name (str): Outer object name for the GBNF grammar. If None, no outer object will be generated. Eg. "function" for function calling.
  936. outer_object_content (str): Content for the outer rule in the GBNF grammar. Eg. "function_parameters" or "params" for function calling.
  937. model_prefix (str): Prefix for the model section in the documentation.
  938. fields_prefix (str): Prefix for the fields section in the documentation.
  939. list_of_outputs (bool): Whether the output is a list of items.
  940. documentation_with_field_description (bool): Include field descriptions in the documentation.
  941. Returns:
  942. tuple: GBNF grammar string, documentation string.
  943. """
  944. pydantic_model_list = create_dynamic_models_from_dictionaries(dictionaries)
  945. documentation = generate_markdown_documentation(
  946. copy(pydantic_model_list), model_prefix, fields_prefix,
  947. documentation_with_field_description=documentation_with_field_description
  948. )
  949. grammar = generate_gbnf_grammar_from_pydantic_models(pydantic_model_list, outer_object_name, outer_object_content,
  950. list_of_outputs)
  951. grammar = remove_empty_lines(grammar + get_primitive_grammar(grammar))
  952. return grammar, documentation
  953. def create_dynamic_model_from_function(func: Callable[..., Any]):
  954. """
  955. Creates a dynamic Pydantic model from a given function's type hints and adds the function as a 'run' method.
  956. Args:
  957. func (Callable): A function with type hints from which to create the model.
  958. Returns:
  959. A dynamic Pydantic model class with the provided function as a 'run' method.
  960. """
  961. # Get the signature of the function
  962. sig = inspect.signature(func)
  963. # Parse the docstring
  964. assert func.__doc__ is not None
  965. docstring = parse(func.__doc__)
  966. dynamic_fields = {}
  967. param_docs = []
  968. for param in sig.parameters.values():
  969. # Exclude 'self' parameter
  970. if param.name == "self":
  971. continue
  972. # Assert that the parameter has a type annotation
  973. if param.annotation == inspect.Parameter.empty:
  974. raise TypeError(f"Parameter '{param.name}' in function '{func.__name__}' lacks a type annotation")
  975. # Find the parameter's description in the docstring
  976. param_doc = next((d for d in docstring.params if d.arg_name == param.name), None)
  977. # Assert that the parameter has a description
  978. if not param_doc or not param_doc.description:
  979. raise ValueError(
  980. f"Parameter '{param.name}' in function '{func.__name__}' lacks a description in the docstring")
  981. # Add parameter details to the schema
  982. param_docs.append((param.name, param_doc))
  983. if param.default == inspect.Parameter.empty:
  984. default_value = ...
  985. else:
  986. default_value = param.default
  987. dynamic_fields[param.name] = (
  988. param.annotation if param.annotation != inspect.Parameter.empty else str, default_value)
  989. # Creating the dynamic model
  990. dynamic_model = create_model(f"{func.__name__}", **dynamic_fields)
  991. for name, param_doc in param_docs:
  992. dynamic_model.model_fields[name].description = param_doc.description
  993. dynamic_model.__doc__ = docstring.short_description
  994. def run_method_wrapper(self):
  995. func_args = {name: getattr(self, name) for name, _ in dynamic_fields.items()}
  996. return func(**func_args)
  997. # Adding the wrapped function as a 'run' method
  998. setattr(dynamic_model, "run", run_method_wrapper)
  999. return dynamic_model
  1000. def add_run_method_to_dynamic_model(model: type[BaseModel], func: Callable[..., Any]):
  1001. """
  1002. Add a 'run' method to a dynamic Pydantic model, using the provided function.
  1003. Args:
  1004. model (type[BaseModel]): Dynamic Pydantic model class.
  1005. func (Callable): Function to be added as a 'run' method to the model.
  1006. Returns:
  1007. type[BaseModel]: Pydantic model class with the added 'run' method.
  1008. """
  1009. def run_method_wrapper(self):
  1010. func_args = {name: getattr(self, name) for name in model.model_fields}
  1011. return func(**func_args)
  1012. # Adding the wrapped function as a 'run' method
  1013. setattr(model, "run", run_method_wrapper)
  1014. return model
  1015. def create_dynamic_models_from_dictionaries(dictionaries: list[dict[str, Any]]):
  1016. """
  1017. Create a list of dynamic Pydantic model classes from a list of dictionaries.
  1018. Args:
  1019. dictionaries (list[dict]): List of dictionaries representing model structures.
  1020. Returns:
  1021. list[type[BaseModel]]: List of generated dynamic Pydantic model classes.
  1022. """
  1023. dynamic_models = []
  1024. for func in dictionaries:
  1025. model_name = format_model_and_field_name(func.get("name", ""))
  1026. dyn_model = convert_dictionary_to_pydantic_model(func, model_name)
  1027. dynamic_models.append(dyn_model)
  1028. return dynamic_models
  1029. def map_grammar_names_to_pydantic_model_class(pydantic_model_list):
  1030. output = {}
  1031. for model in pydantic_model_list:
  1032. output[format_model_and_field_name(model.__name__)] = model
  1033. return output
  1034. def json_schema_to_python_types(schema):
  1035. type_map = {
  1036. "any": Any,
  1037. "string": str,
  1038. "number": float,
  1039. "integer": int,
  1040. "boolean": bool,
  1041. "array": list,
  1042. }
  1043. return type_map[schema]
  1044. def list_to_enum(enum_name, values):
  1045. return Enum(enum_name, {value: value for value in values})
  1046. def convert_dictionary_to_pydantic_model(dictionary: dict[str, Any], model_name: str = "CustomModel") -> type[Any]:
  1047. """
  1048. Convert a dictionary to a Pydantic model class.
  1049. Args:
  1050. dictionary (dict): Dictionary representing the model structure.
  1051. model_name (str): Name of the generated Pydantic model.
  1052. Returns:
  1053. type[BaseModel]: Generated Pydantic model class.
  1054. """
  1055. fields: dict[str, Any] = {}
  1056. if "properties" in dictionary:
  1057. for field_name, field_data in dictionary.get("properties", {}).items():
  1058. if field_data == "object":
  1059. submodel = convert_dictionary_to_pydantic_model(dictionary, f"{model_name}_{field_name}")
  1060. fields[field_name] = (submodel, ...)
  1061. else:
  1062. field_type = field_data.get("type", "str")
  1063. if field_data.get("enum", []):
  1064. fields[field_name] = (list_to_enum(field_name, field_data.get("enum", [])), ...)
  1065. elif field_type == "array":
  1066. items = field_data.get("items", {})
  1067. if items != {}:
  1068. array = {"properties": items}
  1069. array_type = convert_dictionary_to_pydantic_model(array, f"{model_name}_{field_name}_items")
  1070. fields[field_name] = (List[array_type], ...)
  1071. else:
  1072. fields[field_name] = (list, ...)
  1073. elif field_type == "object":
  1074. submodel = convert_dictionary_to_pydantic_model(field_data, f"{model_name}_{field_name}")
  1075. fields[field_name] = (submodel, ...)
  1076. elif field_type == "required":
  1077. required = field_data.get("enum", [])
  1078. for key, field in fields.items():
  1079. if key not in required:
  1080. optional_type = fields[key][0]
  1081. fields[key] = (Optional[optional_type], ...)
  1082. else:
  1083. field_type = json_schema_to_python_types(field_type)
  1084. fields[field_name] = (field_type, ...)
  1085. if "function" in dictionary:
  1086. for field_name, field_data in dictionary.get("function", {}).items():
  1087. if field_name == "name":
  1088. model_name = field_data
  1089. elif field_name == "description":
  1090. fields["__doc__"] = field_data
  1091. elif field_name == "parameters":
  1092. return convert_dictionary_to_pydantic_model(field_data, f"{model_name}")
  1093. if "parameters" in dictionary:
  1094. field_data = {"function": dictionary}
  1095. return convert_dictionary_to_pydantic_model(field_data, f"{model_name}")
  1096. if "required" in dictionary:
  1097. required = dictionary.get("required", [])
  1098. for key, field in fields.items():
  1099. if key not in required:
  1100. optional_type = fields[key][0]
  1101. fields[key] = (Optional[optional_type], ...)
  1102. custom_model = create_model(model_name, **fields)
  1103. return custom_model