jdogo 2.1.0__py3-none-any.whl

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.
jdogo/__init__.py ADDED
@@ -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
+
jdogo/_read.py ADDED
@@ -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
jdogo/adapters.py ADDED
@@ -0,0 +1,250 @@
1
+ """
2
+ AI Framework Adapters & Analytics Bridge for JDogo Python SDK.
3
+ Integrations compatible with LangChain, LlamaIndex, OpenAI tool calling, Pandas, and Polars.
4
+ """
5
+
6
+ from typing import Any, List, Dict, Union, Optional, Callable
7
+ import json
8
+ from .compact import encode as compact_encode, decode as compact_decode
9
+ from .typed import encode as typed_encode, decode as typed_decode
10
+ from .legible import encode_legible_keys, instruction_for
11
+ from .doc import encode as doc_encode, decode as doc_decode
12
+ from .optimizer import JDOGO_LLM_INSTRUCTION, estimate_tokens
13
+ from .compute import generate_schema_card, COMPUTE_ROUTING_INSTRUCTION
14
+
15
+
16
+ # Describes the 2.x document for models that read or write it (the pipe-format text is JDOGO_LLM_INSTRUCTION, for 'v1')
17
+ DOC_INSTRUCTION = (
18
+ "Data is in JDogo: the first line, after '@', names the columns; each following line is one row with "
19
+ "comma-separated cells in that order. '~' is null. 'col=V' in the header means every row has value V."
20
+ )
21
+
22
+ class JDogoDocumentCompressor:
23
+ """
24
+ Compresses retrieved RAG document lists into an ultra-compact tabular JDogo representation
25
+ or a hoisted Schema Card. Reduces prompt context overhead by 40-90% compared to raw JSON.
26
+ """
27
+
28
+ def __init__(self, mode: str = "auto", include_instruction: bool = True):
29
+ # 'auto' (default): the prompt layout measured in live runs; 'compact': the 2.x document;
30
+ # 'typed'; 'schema_card'; 'v1': the old pipe format
31
+ self.mode = mode
32
+ self.include_instruction = include_instruction
33
+
34
+ def compress_documents(self, documents: List[Union[Dict[str, Any], Any]]) -> str:
35
+ if not documents:
36
+ return ""
37
+
38
+ extracted = []
39
+ for doc in documents:
40
+ if isinstance(doc, dict):
41
+ extracted.append(doc)
42
+ elif hasattr(doc, "page_content"):
43
+ item = {"content": getattr(doc, "page_content", "")}
44
+ if hasattr(doc, "metadata") and isinstance(doc.metadata, dict):
45
+ item.update(doc.metadata)
46
+ extracted.append(item)
47
+ else:
48
+ extracted.append({"value": str(doc)})
49
+
50
+ if self.mode == "schema_card":
51
+ card = generate_schema_card(extracted)
52
+ if self.include_instruction:
53
+ return f"{COMPUTE_ROUTING_INSTRUCTION}\n\n[Retrieved Schema Card]:\n{card}"
54
+ return card
55
+ elif self.mode in ("auto", "legible"):
56
+ payload = encode_legible_keys(extracted)
57
+ if self.include_instruction:
58
+ instr = instruction_for(payload)
59
+ return f"{instr}\n\n[Retrieved Context]:\n{payload}" if instr else f"[Retrieved Context]:\n{payload}"
60
+ return payload
61
+ elif self.mode == "v1":
62
+ payload = compact_encode(extracted)
63
+ if self.include_instruction:
64
+ return f"{JDOGO_LLM_INSTRUCTION}\n\n[Retrieved Context]:\n{payload}"
65
+ return payload
66
+ elif self.mode == "typed":
67
+ payload = typed_encode(extracted)
68
+ else:
69
+ payload = doc_encode(extracted)
70
+
71
+ if self.include_instruction:
72
+ return f"{DOC_INSTRUCTION}\n\n[Retrieved Context]:\n{payload}"
73
+ return payload
74
+
75
+ class JDogoOutputParser:
76
+ """
77
+ Instructs LLMs to generate responses in JDogo format and parses them back into native Python dictionaries.
78
+ """
79
+
80
+ def __init__(self, fields: Optional[List[str]] = None, mode: str = "compact"):
81
+ self.fields = fields
82
+ self.mode = mode
83
+
84
+ def get_format_instructions(self) -> str:
85
+ sep = "|" if self.mode == "v1" else ","
86
+ base = JDOGO_LLM_INSTRUCTION if self.mode == "v1" else DOC_INSTRUCTION
87
+ if self.fields:
88
+ fields_str = ",".join(self.fields)
89
+ return (
90
+ f"{base}\n"
91
+ f"Your response MUST start with the header '@{fields_str}' on the first line, "
92
+ f"followed by data rows separated by '{sep}'. Do not include markdown fences or explanation."
93
+ )
94
+ return (
95
+ f"{base}\n"
96
+ f"Your response MUST start with '@col1,col2,...' followed by data rows separated by '{sep}'. "
97
+ f"Do not include markdown code fences or conversational prose."
98
+ )
99
+
100
+ def parse(self, text: str) -> List[Dict[str, Any]]:
101
+ cleaned = text.strip()
102
+ if cleaned.startswith("```"):
103
+ lines = cleaned.splitlines()
104
+ if len(lines) >= 2 and lines[-1].startswith("```"):
105
+ cleaned = "\n".join(lines[1:-1]).strip()
106
+
107
+ # 2.x first (it also reads JSON); the 1.x reader only if the reply is not a valid document
108
+ try:
109
+ result = doc_decode(cleaned)
110
+ except Exception:
111
+ result = compact_decode(cleaned)
112
+
113
+ if isinstance(result, list):
114
+ return result
115
+ elif isinstance(result, dict):
116
+ return [result]
117
+ return []
118
+
119
+ def jdogo_tool(fn: Optional[Callable[..., Any]] = None, *, include_instruction: bool = False):
120
+ """
121
+ Decorator for agent tools and database functions. Automatically transforms returned
122
+ lists of dicts, tables, or DataFrames into compact JDogo document format.
123
+ """
124
+ def decorator(func: Callable[..., Any]):
125
+ def wrapper(*args, **kwargs) -> str:
126
+ res = func(*args, **kwargs)
127
+ if hasattr(res, "to_dict"):
128
+ try:
129
+ res = res.to_dict(orient="records")
130
+ except TypeError:
131
+ pass
132
+ elif hasattr(res, "to_dicts"):
133
+ res = res.to_dicts()
134
+
135
+ if isinstance(res, (list, dict)):
136
+ encoded = doc_encode(res)
137
+ if include_instruction:
138
+ return f"{instruction_for(encoded)}\n{encoded}"
139
+ return encoded
140
+ return str(res)
141
+ wrapper.__name__ = func.__name__
142
+ wrapper.__doc__ = func.__doc__
143
+ wrapper._is_jdogo_tool = True
144
+ return wrapper
145
+
146
+ if fn is not None:
147
+ return decorator(fn)
148
+ return decorator
149
+
150
+ def wrap_tool_function(tool_fn: Optional[Callable[..., Any]] = None, *, mode: str = "compact") -> Any:
151
+ def decorator(func: Callable[..., Any]):
152
+ def wrapper(*args, **kwargs) -> str:
153
+ res = func(*args, **kwargs)
154
+ if hasattr(res, "to_dict"):
155
+ try:
156
+ res = res.to_dict(orient="records")
157
+ except TypeError:
158
+ pass
159
+ elif hasattr(res, "to_dicts"):
160
+ res = res.to_dicts()
161
+
162
+ if isinstance(res, (list, dict)):
163
+ if mode == "v1":
164
+ return compact_encode(res)
165
+ if mode == "typed":
166
+ return typed_encode(res)
167
+ if mode in ("auto", "legible"):
168
+ return encode_legible_keys(res)
169
+ return doc_encode(res) # 'compact': the lossless 2.x document
170
+ return str(res)
171
+ wrapper.__name__ = func.__name__
172
+ wrapper.__doc__ = func.__doc__
173
+ wrapper._is_jdogo_tool = True
174
+ return wrapper
175
+
176
+ if tool_fn is not None:
177
+ return decorator(tool_fn)
178
+ return decorator
179
+
180
+ def from_dataframe(df: Any) -> str:
181
+ """Serializes a Pandas, Polars, or Arrow DataFrame to compact JDogo text."""
182
+ if hasattr(df, "to_dict"):
183
+ try:
184
+ return doc_encode(df.to_dict(orient="records"))
185
+ except TypeError:
186
+ return doc_encode(df.to_dict())
187
+ if hasattr(df, "to_dicts"):
188
+ return doc_encode(df.to_dicts())
189
+ raise ValueError("Expected a DataFrame with .to_dict() or .to_dicts() method")
190
+
191
+ def to_dataframe(text: str, library: str = "pandas") -> Any:
192
+ """Deserializes a JDogo document directly into a Pandas or Polars DataFrame."""
193
+ rows = doc_decode(text)
194
+ if not isinstance(rows, list):
195
+ rows = [rows]
196
+ if library.lower() == "polars":
197
+ import polars as pl
198
+ return pl.DataFrame(rows)
199
+ import pandas as pd
200
+ return pd.DataFrame(rows)
201
+
202
+ def dataframe_to_schema_card(df: Any) -> str:
203
+ """Generates a hoisted JDogo Schema Card directly from a Pandas, Polars, or Arrow DataFrame."""
204
+ if hasattr(df, "to_dict"):
205
+ try:
206
+ records = df.to_dict(orient="records")
207
+ except TypeError:
208
+ records = df.to_dict()
209
+ elif hasattr(df, "to_dicts"):
210
+ records = df.to_dicts()
211
+ else:
212
+ raise ValueError("Expected a DataFrame with .to_dict() or .to_dicts() method")
213
+ return generate_schema_card(records)
214
+
215
+ class JDogoAccessor:
216
+ """Pandas DataFrame extension accessor providing .jdogo namespace."""
217
+ def __init__(self, pandas_obj: Any):
218
+ self._obj = pandas_obj
219
+
220
+ def encode(self, mode: str = "doc") -> str:
221
+ """"doc" and "compact": the 2.x document (as jdogo.dumps); "typed"; "v1": the old pipe format."""
222
+ if mode == "v1":
223
+ records = self._obj.to_dict(orient="records")
224
+ return compact_encode(records)
225
+ elif mode == "typed":
226
+ records = self._obj.to_dict(orient="records")
227
+ return typed_encode(records)
228
+ return from_dataframe(self._obj)
229
+
230
+ def schema_card(self) -> str:
231
+ return dataframe_to_schema_card(self._obj)
232
+
233
+ def ask(self, question: str, llm: Any, **kwargs: Any) -> Any:
234
+ from .ai import ask as compute_ask
235
+ records = self._obj.to_dict(orient="records")
236
+ return compute_ask(question, records, llm, **kwargs)
237
+
238
+ def register_pandas_accessor() -> bool:
239
+ """Registers the 'jdogo' accessor with pandas if pandas is installed."""
240
+ try:
241
+ import pandas as pd
242
+ if not hasattr(pd.DataFrame, "jdogo"):
243
+ pd.api.extensions.register_dataframe_accessor("jdogo")(JDogoAccessor)
244
+ return True
245
+ except (ImportError, Exception):
246
+ return False
247
+
248
+ # Attempt automatic registration if pandas is already imported
249
+ register_pandas_accessor()
250
+