pydantic_models_to_grammar.py 55 KB

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