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