jdogo 2.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. jdogo-2.1.0/LICENSE +202 -0
  2. jdogo-2.1.0/PKG-INFO +127 -0
  3. jdogo-2.1.0/README.md +94 -0
  4. jdogo-2.1.0/jdogo/__init__.py +183 -0
  5. jdogo-2.1.0/jdogo/_read.py +42 -0
  6. jdogo-2.1.0/jdogo/adapters.py +250 -0
  7. jdogo-2.1.0/jdogo/ai.py +474 -0
  8. jdogo-2.1.0/jdogo/cli.py +307 -0
  9. jdogo-2.1.0/jdogo/compact.py +274 -0
  10. jdogo-2.1.0/jdogo/compute.py +1508 -0
  11. jdogo-2.1.0/jdogo/context.py +455 -0
  12. jdogo-2.1.0/jdogo/doc.py +1356 -0
  13. jdogo-2.1.0/jdogo/legible.py +1253 -0
  14. jdogo-2.1.0/jdogo/middleware.py +131 -0
  15. jdogo-2.1.0/jdogo/optimizer.py +268 -0
  16. jdogo-2.1.0/jdogo/providers.py +101 -0
  17. jdogo-2.1.0/jdogo/streaming.py +125 -0
  18. jdogo-2.1.0/jdogo/typed.py +167 -0
  19. jdogo-2.1.0/jdogo.egg-info/PKG-INFO +127 -0
  20. jdogo-2.1.0/jdogo.egg-info/SOURCES.txt +44 -0
  21. jdogo-2.1.0/jdogo.egg-info/dependency_links.txt +1 -0
  22. jdogo-2.1.0/jdogo.egg-info/entry_points.txt +2 -0
  23. jdogo-2.1.0/jdogo.egg-info/requires.txt +6 -0
  24. jdogo-2.1.0/jdogo.egg-info/top_level.txt +1 -0
  25. jdogo-2.1.0/pyproject.toml +45 -0
  26. jdogo-2.1.0/setup.cfg +4 -0
  27. jdogo-2.1.0/tests/test_adapters.py +90 -0
  28. jdogo-2.1.0/tests/test_adapters_extra.py +48 -0
  29. jdogo-2.1.0/tests/test_ask.py +170 -0
  30. jdogo-2.1.0/tests/test_cli_and_ai.py +297 -0
  31. jdogo-2.1.0/tests/test_compute_conformance.py +114 -0
  32. jdogo-2.1.0/tests/test_conformance.py +34 -0
  33. jdogo-2.1.0/tests/test_context.py +90 -0
  34. jdogo-2.1.0/tests/test_doc.py +147 -0
  35. jdogo-2.1.0/tests/test_doc_lossless.py +123 -0
  36. jdogo-2.1.0/tests/test_doc_repeat.py +37 -0
  37. jdogo-2.1.0/tests/test_iter_decode.py +53 -0
  38. jdogo-2.1.0/tests/test_jdogo.py +200 -0
  39. jdogo-2.1.0/tests/test_legible.py +65 -0
  40. jdogo-2.1.0/tests/test_middleware.py +36 -0
  41. jdogo-2.1.0/tests/test_number_vectors.py +43 -0
  42. jdogo-2.1.0/tests/test_optimizer_receipt.py +93 -0
  43. jdogo-2.1.0/tests/test_providers.py +57 -0
  44. jdogo-2.1.0/tests/test_read_vectors.py +24 -0
  45. jdogo-2.1.0/tests/test_streaming.py +52 -0
  46. jdogo-2.1.0/tests/test_value_vectors.py +26 -0
jdogo-2.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
jdogo-2.1.0/PKG-INFO ADDED
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: jdogo
3
+ Version: 2.1.0
4
+ Summary: Compact, lossless text format for structured data: about half the tokens of JSON for language models, every value back exactly
5
+ Author: JDogo Project
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://jdogo.dev
8
+ Project-URL: Documentation, https://jdogo.dev/docs/
9
+ Project-URL: Source, https://github.com/jdogo-dev/jdogo-python
10
+ Project-URL: Issues, https://github.com/jdogo-dev/jdogo-python/issues
11
+ Project-URL: Changelog, https://github.com/jdogo-dev/jdogo-python/blob/main/CHANGELOG.md
12
+ Project-URL: Specification, https://github.com/jdogo-dev/jdogo-spec
13
+ Keywords: jdogo,serialization,llm,tokens,json,agents,mcp
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Operating System :: OS Independent
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Provides-Extra: sbom
29
+ Requires-Dist: cyclonedx-bom>=5.0.0; extra == "sbom"
30
+ Provides-Extra: test
31
+ Requires-Dist: pytest>=7.0.0; extra == "test"
32
+ Dynamic: license-file
33
+
34
+ # JDogo for Python
35
+
36
+ [![CI](https://github.com/jdogo-dev/jdogo-python/actions/workflows/ci.yml/badge.svg)](https://github.com/jdogo-dev/jdogo-python/actions/workflows/ci.yml)
37
+ [![PyPI](https://img.shields.io/pypi/v/jdogo.svg)](https://pypi.org/project/jdogo/)
38
+ [![Python](https://img.shields.io/pypi/pyversions/jdogo.svg)](https://pypi.org/project/jdogo/)
39
+ [![Spec](https://img.shields.io/badge/spec-2.1-blue.svg)](https://github.com/jdogo-dev/jdogo-spec)
40
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green.svg)](LICENSE)
41
+
42
+ **JDogo** is a compact, lossless text format for structured data. Sent to a language model, it costs about half the tokens of JSON (−53% on 60 production payloads, measured with o200k), and every value comes back exactly. This is the Python implementation: no runtime dependencies, Python 3.9+.
43
+
44
+ Website, docs and playground: **[jdogo.dev](https://jdogo.dev)**
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install jdogo
50
+ ```
51
+
52
+ Optional: `pip install tiktoken` for exact token counts in `optimize()` (otherwise they are estimated).
53
+
54
+ ## Use
55
+
56
+ ```python
57
+ import jdogo
58
+
59
+ orders = [{"id": 1001 + i, "customer": f"Customer {i % 3}",
60
+ "status": ["shipped", "pending"][i % 2], "total": 20 + 5 * i} for i in range(6)]
61
+
62
+ text = jdogo.dumps(orders)
63
+ assert jdogo.loads(text) == orders # exactly the same value back
64
+ ```
65
+
66
+ ```text
67
+ @id+,customer,status,total
68
+ 1001,Customer 0,shipped,20
69
+ 1,Customer 1,pending,25
70
+ 1,Customer 2,shipped,30
71
+ ...
72
+ ```
73
+
74
+ The header names each column once; `id+` stores the step between rows instead of each id. Any JSON is also valid JDogo, so readers accept both.
75
+
76
+ ### Send the cheaper format
77
+
78
+ ```python
79
+ text, receipt = jdogo.optimize(rows)
80
+ # receipt: {"chosen": "jdogo", "reason": "fewest tokens", "savedPercent": 49.2, "tokenizer": "o200k_base (measured)", ...}
81
+ ```
82
+
83
+ `optimize()` counts the instruction a model needs to read JDogo and sends JSON when that is cheaper (a row or two). It never sends a format that does not decode back to your data.
84
+
85
+ ### Exact answers with `ask()`
86
+
87
+ ```python
88
+ res = jdogo.ask("How many orders are pending?", orders, llm=call_model)
89
+ res.answer # 3
90
+ res.expression # count where status = "pending"
91
+ res.row_refs # [1002, 1004, 1006]
92
+ res.check # "passed": a second, independent evaluator agrees
93
+ ```
94
+
95
+ The model writes a short expression; JDogo computes the answer locally over all rows, names the rows it used and checks the result. Counting questions: 150 of 150 right with `ask()`, against 74 when models read the rows themselves.
96
+
97
+ ### More
98
+
99
+ | | |
100
+ |---|---|
101
+ | Prompts | `format_query_prompt(question, data)`, `instruction_for(text)` |
102
+ | Agents | `@jdogo_tool`, `jdogo.providers` (OpenAI and Anthropic tool calls) |
103
+ | Web | `JDogoFastAPIMiddleware`, `jdogo_flask_response` (`Accept: application/jdogo`) |
104
+ | Data | `from_dataframe`, `to_dataframe`, the `df.jdogo` accessor |
105
+ | Streaming | `JDogoStreamReader`, `JDogoStreamWriter`, `iter_decode` |
106
+ | Context sync (experimental) | `jdogo.context`: snapshots, deltas, signed envelopes |
107
+ | CLI | `jdogo compact`, `decode`, `cost`, `diff`, `gbnf` |
108
+
109
+ Full guide: [jdogo.dev/docs](https://jdogo.dev/docs/).
110
+
111
+ ## Compatibility
112
+
113
+ This package implements **JDogo spec 2.1** ([jdogo-spec](https://github.com/jdogo-dev/jdogo-spec), pinned as the `spec/` submodule). It writes the same bytes as the [Java](https://github.com/jdogo-dev/jdogo-java) and [TypeScript](https://github.com/jdogo-dev/jdogo-js) implementations, checked by the shared fixtures and by the cross-language fuzzing in [jdogo](https://github.com/jdogo-dev/jdogo).
114
+
115
+ ## Development
116
+
117
+ ```bash
118
+ git clone --recurse-submodules https://github.com/jdogo-dev/jdogo-python
119
+ cd jdogo-python
120
+ python -m unittest discover -s tests
121
+ ```
122
+
123
+ Contributions are welcome: see [CONTRIBUTING](https://github.com/jdogo-dev/.github/blob/main/CONTRIBUTING.md). Report security issues privately: see [SECURITY](https://github.com/jdogo-dev/.github/blob/main/SECURITY.md).
124
+
125
+ ## License
126
+
127
+ [Apache-2.0](LICENSE)
jdogo-2.1.0/README.md ADDED
@@ -0,0 +1,94 @@
1
+ # JDogo for Python
2
+
3
+ [![CI](https://github.com/jdogo-dev/jdogo-python/actions/workflows/ci.yml/badge.svg)](https://github.com/jdogo-dev/jdogo-python/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/jdogo.svg)](https://pypi.org/project/jdogo/)
5
+ [![Python](https://img.shields.io/pypi/pyversions/jdogo.svg)](https://pypi.org/project/jdogo/)
6
+ [![Spec](https://img.shields.io/badge/spec-2.1-blue.svg)](https://github.com/jdogo-dev/jdogo-spec)
7
+ [![License](https://img.shields.io/badge/license-Apache--2.0-green.svg)](LICENSE)
8
+
9
+ **JDogo** is a compact, lossless text format for structured data. Sent to a language model, it costs about half the tokens of JSON (−53% on 60 production payloads, measured with o200k), and every value comes back exactly. This is the Python implementation: no runtime dependencies, Python 3.9+.
10
+
11
+ Website, docs and playground: **[jdogo.dev](https://jdogo.dev)**
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ pip install jdogo
17
+ ```
18
+
19
+ Optional: `pip install tiktoken` for exact token counts in `optimize()` (otherwise they are estimated).
20
+
21
+ ## Use
22
+
23
+ ```python
24
+ import jdogo
25
+
26
+ orders = [{"id": 1001 + i, "customer": f"Customer {i % 3}",
27
+ "status": ["shipped", "pending"][i % 2], "total": 20 + 5 * i} for i in range(6)]
28
+
29
+ text = jdogo.dumps(orders)
30
+ assert jdogo.loads(text) == orders # exactly the same value back
31
+ ```
32
+
33
+ ```text
34
+ @id+,customer,status,total
35
+ 1001,Customer 0,shipped,20
36
+ 1,Customer 1,pending,25
37
+ 1,Customer 2,shipped,30
38
+ ...
39
+ ```
40
+
41
+ The header names each column once; `id+` stores the step between rows instead of each id. Any JSON is also valid JDogo, so readers accept both.
42
+
43
+ ### Send the cheaper format
44
+
45
+ ```python
46
+ text, receipt = jdogo.optimize(rows)
47
+ # receipt: {"chosen": "jdogo", "reason": "fewest tokens", "savedPercent": 49.2, "tokenizer": "o200k_base (measured)", ...}
48
+ ```
49
+
50
+ `optimize()` counts the instruction a model needs to read JDogo and sends JSON when that is cheaper (a row or two). It never sends a format that does not decode back to your data.
51
+
52
+ ### Exact answers with `ask()`
53
+
54
+ ```python
55
+ res = jdogo.ask("How many orders are pending?", orders, llm=call_model)
56
+ res.answer # 3
57
+ res.expression # count where status = "pending"
58
+ res.row_refs # [1002, 1004, 1006]
59
+ res.check # "passed": a second, independent evaluator agrees
60
+ ```
61
+
62
+ The model writes a short expression; JDogo computes the answer locally over all rows, names the rows it used and checks the result. Counting questions: 150 of 150 right with `ask()`, against 74 when models read the rows themselves.
63
+
64
+ ### More
65
+
66
+ | | |
67
+ |---|---|
68
+ | Prompts | `format_query_prompt(question, data)`, `instruction_for(text)` |
69
+ | Agents | `@jdogo_tool`, `jdogo.providers` (OpenAI and Anthropic tool calls) |
70
+ | Web | `JDogoFastAPIMiddleware`, `jdogo_flask_response` (`Accept: application/jdogo`) |
71
+ | Data | `from_dataframe`, `to_dataframe`, the `df.jdogo` accessor |
72
+ | Streaming | `JDogoStreamReader`, `JDogoStreamWriter`, `iter_decode` |
73
+ | Context sync (experimental) | `jdogo.context`: snapshots, deltas, signed envelopes |
74
+ | CLI | `jdogo compact`, `decode`, `cost`, `diff`, `gbnf` |
75
+
76
+ Full guide: [jdogo.dev/docs](https://jdogo.dev/docs/).
77
+
78
+ ## Compatibility
79
+
80
+ This package implements **JDogo spec 2.1** ([jdogo-spec](https://github.com/jdogo-dev/jdogo-spec), pinned as the `spec/` submodule). It writes the same bytes as the [Java](https://github.com/jdogo-dev/jdogo-java) and [TypeScript](https://github.com/jdogo-dev/jdogo-js) implementations, checked by the shared fixtures and by the cross-language fuzzing in [jdogo](https://github.com/jdogo-dev/jdogo).
81
+
82
+ ## Development
83
+
84
+ ```bash
85
+ git clone --recurse-submodules https://github.com/jdogo-dev/jdogo-python
86
+ cd jdogo-python
87
+ python -m unittest discover -s tests
88
+ ```
89
+
90
+ Contributions are welcome: see [CONTRIBUTING](https://github.com/jdogo-dev/.github/blob/main/CONTRIBUTING.md). Report security issues privately: see [SECURITY](https://github.com/jdogo-dev/.github/blob/main/SECURITY.md).
91
+
92
+ ## License
93
+
94
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,183 @@
1
+ """
2
+ JDogo: Ultra-compact, LLM-optimized serialization format and context management SDK.
3
+ """
4
+
5
+ __version__ = "2.1.0"
6
+
7
+ from typing import Any, IO
8
+ import io
9
+
10
+ from .compact import encode as compact_encode, decode as compact_decode
11
+ from .typed import encode as typed_encode, decode as typed_decode
12
+ from .doc import encode as doc_encode, decode as doc_decode, iter_decode
13
+ from .streaming import JDogoStreamReader, JDogoStreamWriter
14
+ from . import doc
15
+ from . import context
16
+ from . import providers
17
+ from . import legible
18
+ from .legible import encode_legible_keys, encode_legible_keys_dense, instruction_for, format_prompt, is_plain_table
19
+ from .optimizer import (
20
+ estimate_tokens, calculate_savings, optimize_prompt, wrap_tool_call,
21
+ JDOGO_LLM_INSTRUCTION, optimize, OptimizationResult
22
+ )
23
+ from .adapters import (
24
+ JDogoDocumentCompressor, JDogoOutputParser, wrap_tool_function, jdogo_tool,
25
+ from_dataframe, to_dataframe, dataframe_to_schema_card, JDogoAccessor, register_pandas_accessor
26
+ )
27
+ from .ai import (
28
+ get_system_prompt_header, wrap_tool_output, compress_context,
29
+ STANDARD_JDOGO_SYSTEM_PROMPT, format_query_prompt, parse_grounded_answer,
30
+ is_count_question, ground,
31
+ format_compute_prompt, format_routing_prompt, parse_compute_answer, run_compute,
32
+ COMPUTE_INSTRUCTION, COMPUTE_ROUTING_INSTRUCTION, is_need_rows, is_group_by_query,
33
+ ask, AskResult
34
+ )
35
+ from .compute import verify_result
36
+ from .middleware import jdogo_response, jdogo_flask_response, JDogoFastAPIMiddleware
37
+ def cli_main():
38
+ """CLI entrypoint."""
39
+ from .cli import main
40
+ return main()
41
+
42
+ MAX_DEPTH = 64
43
+
44
+ def _check_depth(obj: Any, max_depth: int = MAX_DEPTH) -> None:
45
+ """Refuse values nested deeper than every JDogo decoder reads, so dumps never writes
46
+ text that loads (or Java, or TypeScript) would reject."""
47
+ stack = [(obj, 1)]
48
+ while stack:
49
+ v, d = stack.pop()
50
+ if isinstance(v, dict):
51
+ children = v.values()
52
+ elif isinstance(v, (list, tuple)):
53
+ children = v
54
+ else:
55
+ continue
56
+ if d > max_depth:
57
+ raise ValueError(f"Maximum recursion depth exceeded: {d} > {max_depth}")
58
+ stack.extend((c, d + 1) for c in children)
59
+
60
+ def dumps(obj: Any, mode: str = "compact") -> str:
61
+ """Serialize obj to JDogo text.
62
+
63
+ mode: "compact" (default, the lossless document format, same as doc_encode and Java's
64
+ DocCodec.encode), "typed" (!JDOGO/2), "readable" (full keys and values) or "v1" (the older
65
+ 1.x pipe-delimited format, kept only for systems that still read it; it is not lossless).
66
+ """
67
+ m = mode.lower()
68
+ if m not in ("v1", "legacy"):
69
+ _check_depth(obj)
70
+ if m == "typed":
71
+ return typed_encode(obj)
72
+ if m == "readable":
73
+ return encode_legible_keys(obj)
74
+ if m in ("v1", "legacy"):
75
+ return compact_encode(obj)
76
+ if m != "compact":
77
+ raise ValueError(f"unknown mode {mode!r}: use compact, typed, readable or v1")
78
+ return doc_encode(obj)
79
+
80
+ def encode_readable(obj: Any) -> str:
81
+ """Readable JDogo: full key names and full values, with no deltas, hoisted prefixes or ditto marks.
82
+ Larger than doc_encode, but easy to read in logs. Decode it with doc_decode. Same output as the
83
+ Java (DocCodec.encodeLegibleKeys) and TypeScript (encodeReadable) SDKs."""
84
+ return encode_legible_keys(obj)
85
+
86
+ def loads(s: str, format: str = "auto") -> Any:
87
+ """Deserialize JDogo text to a Python object.
88
+
89
+ format "auto" (default) reads typed (!JDOGO/2) and document text (which includes any JSON).
90
+ Text written by 1.x still loads: when it is not a valid document and carries a 1.x marker
91
+ (a '@' header with '|'-separated rows), the 1.x reader is used. Anything else that does not
92
+ parse raises ValueError; it is never turned into made-up values. Pass "v1" to force the 1.x reader, or "doc" to refuse anything but the document format.
93
+ """
94
+ f = format.lower()
95
+ if f in ("v1", "legacy"):
96
+ return compact_decode(s)
97
+ if f == "doc":
98
+ return doc_decode(s[1:] if s.startswith("\ufeff") else s)
99
+ if f != "auto":
100
+ raise ValueError(f"unknown format {format!r}: use auto, doc or v1")
101
+ from ._read import read
102
+ return read(s)
103
+
104
+ def dump(obj: Any, fp: IO[str], mode: str = "compact") -> None:
105
+ """Serialize obj as a JDogo formatted stream to fp."""
106
+ fp.write(dumps(obj, mode=mode))
107
+
108
+ def load(fp: IO[str]) -> Any:
109
+ """Deserialize fp to a Python object."""
110
+ return loads(fp.read())
111
+
112
+ encode = dumps
113
+ decode = loads
114
+
115
+ def to_columnar_dict(text: str) -> dict:
116
+ """Parses JDogo text directly into a columnar dictionary {col_name: [values]}."""
117
+ rows = loads(text)
118
+ if not rows or not isinstance(rows, list) or not isinstance(rows[0], dict):
119
+ return {}
120
+ cols = list(rows[0].keys())
121
+ res = {c: [] for c in cols}
122
+ for r in rows:
123
+ for c in cols:
124
+ res[c].append(r.get(c))
125
+ return res
126
+
127
+ def to_pandas(text: str):
128
+ """Converts JDogo text directly into a Pandas DataFrame if pandas is installed."""
129
+ import pandas as pd
130
+ return pd.DataFrame(to_columnar_dict(text))
131
+
132
+ __all__ = [
133
+ "dumps",
134
+ "loads",
135
+ "encode",
136
+ "decode",
137
+ "dump",
138
+ "load",
139
+ "to_columnar_dict",
140
+ "to_pandas",
141
+ "compact_encode",
142
+ "encode_readable",
143
+ "compact_decode",
144
+ "doc_encode",
145
+ "doc_decode",
146
+ "doc",
147
+ "context",
148
+ "providers",
149
+ "typed_encode",
150
+ "typed_decode",
151
+ "estimate_tokens",
152
+ "calculate_savings",
153
+ "optimize_prompt",
154
+ "wrap_tool_call",
155
+ "optimize",
156
+ "OptimizationResult",
157
+ "JDOGO_LLM_INSTRUCTION",
158
+ "JDogoDocumentCompressor",
159
+ "JDogoOutputParser",
160
+ "wrap_tool_function",
161
+ "JDogoStreamReader",
162
+ "JDogoStreamWriter",
163
+ "jdogo_tool",
164
+ "from_dataframe",
165
+ "to_dataframe",
166
+ "get_system_prompt_header",
167
+ "wrap_tool_output",
168
+ "compress_context",
169
+ "STANDARD_JDOGO_SYSTEM_PROMPT",
170
+ "format_query_prompt",
171
+ "parse_grounded_answer",
172
+ "is_count_question",
173
+ "ground",
174
+ "format_compute_prompt",
175
+ "parse_compute_answer",
176
+ "run_compute",
177
+ "verify_result",
178
+ "jdogo_response",
179
+ "jdogo_flask_response",
180
+ "JDogoFastAPIMiddleware",
181
+ "cli_main",
182
+ ]
183
+
@@ -0,0 +1,42 @@
1
+ """One reading rule for loads(), the HTTP middleware and the CLI.
2
+
3
+ Text is read as a 2.x document (which includes any JSON). The 1.x reader is used only when the
4
+ document reader fails *and* the text carries a 1.x marker, so stored 1.x data keeps loading while
5
+ malformed input raises an error instead of turning into invented values.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Any
11
+
12
+ from .compact import decode as _v1_decode
13
+ from .doc import decode as _doc_decode
14
+ from .typed import decode as _typed_decode
15
+
16
+ _V1_OBJECT = re.compile(r"\{[^{}:\"]*=") # 1.x object literal: {key=value}, never ':' between key and value
17
+
18
+
19
+ def looks_v1(text: str) -> bool:
20
+ """Whether text carries a marker only the 1.x format writes: a '@' header with '|'-separated
21
+ rows, a {key=value} object, or the special headers '@', '@empty[]' and '@nulls[n]'."""
22
+ s = text.lstrip(" \t\r\n")
23
+ if not s.startswith("@"):
24
+ return False
25
+ first, _, rest = s.partition("\n")
26
+ first = first.rstrip("\r")
27
+ if first == "@" or first.startswith("@empty[]") or first.startswith("@nulls["):
28
+ return True
29
+ return "|" in rest or bool(_V1_OBJECT.search(rest))
30
+
31
+
32
+ def read(text: str) -> Any:
33
+ if text.startswith(""):
34
+ text = text[1:]
35
+ if text.lstrip(" \t\r\n").startswith("!JDOGO/2"):
36
+ return _typed_decode(text)
37
+ try:
38
+ return _doc_decode(text)
39
+ except (ValueError, IndexError, KeyError, TypeError):
40
+ if looks_v1(text):
41
+ return _v1_decode(text)
42
+ raise