Generate a TOON structure template from a schema definition. This function creates a response structure template that can be included in LLM prompts to specify the expected output format without examples. Args: schema: Schema definition as a dict or list of dicts
(
schema: Union[Dict[str, Any], List[Dict[str, Any]]],
options: Optional[Dict[str, Any]] = None
)
| 9 | |
| 10 | |
| 11 | def generate_structure( |
| 12 | schema: Union[Dict[str, Any], List[Dict[str, Any]]], |
| 13 | options: Optional[Dict[str, Any]] = None |
| 14 | ) -> str: |
| 15 | """ |
| 16 | Generate a TOON structure template from a schema definition. |
| 17 | |
| 18 | This function creates a response structure template that can be included |
| 19 | in LLM prompts to specify the expected output format without examples. |
| 20 | |
| 21 | Args: |
| 22 | schema: Schema definition as a dict or list of dicts |
| 23 | - For simple fields: {"field_name": "description"} |
| 24 | - For nested objects: {"field_name": {"nested_field": "description"}} |
| 25 | - For arrays: {"field_name": [{"array_field": "description"}]} |
| 26 | - List at root level creates a tabular array template |
| 27 | options: Optional encoding options |
| 28 | - delimiter: ',' (default), '\t', or '|' |
| 29 | - indent: int (default 2) |
| 30 | |
| 31 | Returns: |
| 32 | TOON formatted structure template string |
| 33 | |
| 34 | Examples: |
| 35 | >>> schema = { |
| 36 | ... "name": "name of the person", |
| 37 | ... "age": "age of the person", |
| 38 | ... "occupation": "job description of the person" |
| 39 | ... } |
| 40 | >>> print(generate_structure(schema)) |
| 41 | name: <name of the person> |
| 42 | age: <age of the person> |
| 43 | occupation: <job description of the person> |
| 44 | |
| 45 | >>> schema = [{"id": "user id", "name": "user name"}] |
| 46 | >>> print(generate_structure(schema)) |
| 47 | [N]{id,name}: |
| 48 | <user id>,<user name> |
| 49 | ... |
| 50 | """ |
| 51 | if options is None: |
| 52 | options = {} |
| 53 | |
| 54 | delimiter = options.get('delimiter', DEFAULT_DELIMITER) |
| 55 | indent = options.get('indent', DEFAULT_INDENT) |
| 56 | |
| 57 | if isinstance(schema, list): |
| 58 | return _generate_array_structure(schema, 0, delimiter, indent) |
| 59 | elif isinstance(schema, dict): |
| 60 | return _generate_object_structure(schema, 0, delimiter, indent) |
| 61 | else: |
| 62 | return "<value>" |
| 63 | |
| 64 | |
| 65 | def _generate_object_structure( |
searching dependent graphs…