pydantic_models_to_grammar.py 55 KB

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