|
4 | 4 | This module provides utilities to convert API responses to TOON format, |
5 | 5 | which reduces token usage by 30-60% compared to JSON. |
6 | 6 | """ |
7 | | - |
8 | 7 | from typing import Any, Dict, Optional |
9 | 8 |
|
10 | 9 | try: |
11 | 10 | from toon import encode as toon_encode |
12 | | - |
13 | 11 | TOON_AVAILABLE = True |
14 | 12 | except ImportError: |
15 | 13 | TOON_AVAILABLE = False |
|
19 | 17 | def convert_to_toon(data: Any, options: Optional[Dict[str, Any]] = None) -> str: |
20 | 18 | """ |
21 | 19 | Convert data to TOON format. |
22 | | -
|
| 20 | + |
23 | 21 | Args: |
24 | 22 | data: Python dict or list to convert to TOON format |
25 | 23 | options: Optional encoding options for TOON |
26 | 24 | - delimiter: 'comma' (default), 'tab', or 'pipe' |
27 | 25 | - indent: Number of spaces per level (default: 2) |
28 | 26 | - key_folding: 'off' (default) or 'safe' |
29 | 27 | - flatten_depth: Max depth for key folding (default: None) |
30 | | -
|
| 28 | + |
31 | 29 | Returns: |
32 | 30 | TOON formatted string |
33 | | -
|
| 31 | + |
34 | 32 | Raises: |
35 | 33 | ImportError: If toonify library is not installed |
36 | 34 | """ |
37 | 35 | if not TOON_AVAILABLE or toon_encode is None: |
38 | 36 | raise ImportError( |
39 | | - "toonify library is not installed. " "Install it with: pip install toonify" |
| 37 | + "toonify library is not installed. " |
| 38 | + "Install it with: pip install toonify" |
40 | 39 | ) |
41 | | - |
| 40 | + |
42 | 41 | return toon_encode(data, options=options) |
43 | 42 |
|
44 | 43 |
|
45 | | -def process_response_with_toon( |
46 | | - response: Dict[str, Any], return_toon: bool = False |
47 | | -) -> Any: |
| 44 | +def process_response_with_toon(response: Dict[str, Any], return_toon: bool = False) -> Any: |
48 | 45 | """ |
49 | 46 | Process API response and optionally convert to TOON format. |
50 | | -
|
| 47 | + |
51 | 48 | Args: |
52 | 49 | response: The API response dictionary |
53 | 50 | return_toon: If True, convert the response to TOON format |
54 | | -
|
| 51 | + |
55 | 52 | Returns: |
56 | 53 | Either the original response dict or TOON formatted string |
57 | 54 | """ |
58 | 55 | if not return_toon: |
59 | 56 | return response |
60 | | - |
| 57 | + |
61 | 58 | # Convert the response to TOON format |
62 | 59 | return convert_to_toon(response) |
| 60 | + |
0 commit comments