lio-lang 0.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.
lio_lang-0.1.0/LICENSE ADDED
@@ -0,0 +1,200 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may accept support,
167
+ warranty, indemnity, or other liability obligations and/or rights
168
+ consistent with this License. However, in accepting such obligations,
169
+ You may act only on behalf of and on Your own responsibility, not on
170
+ behalf of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ APPENDIX: How to apply the Apache License to your work.
178
+
179
+ To apply the Apache License to your work, attach the following
180
+ boilerplate notice, with the fields enclosed by brackets "[]"
181
+ replaced with your own identifying information. (Don't include
182
+ the brackets!) The text should be enclosed in the appropriate
183
+ comment syntax for the file format. We also recommend that a
184
+ file or class name and description of purpose be included on the
185
+ same "printed page" as the copyright notice for easier
186
+ identification within third-party archives.
187
+
188
+ Copyright 2026 Estevao Fonseca
189
+
190
+ Licensed under the Apache License, Version 2.0 (the "License");
191
+ you may not use this file except in compliance with the License.
192
+ You may obtain a copy of the License at
193
+
194
+ http://www.apache.org/licenses/LICENSE-2.0
195
+
196
+ Unless required by applicable law or agreed to in writing, software
197
+ distributed under the License is distributed on an "AS IS" BASIS,
198
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
199
+ See the License for the specific language governing permissions and
200
+ limitations under the License.
lio_lang-0.1.0/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ lio-lang
2
+ Copyright 2026 Estevao Fonseca
3
+
4
+ This product includes software developed by Estevao Fonseca
5
+ (https://github.com/estevaofon/lio-lang).
@@ -0,0 +1,492 @@
1
+ Metadata-Version: 2.4
2
+ Name: lio-lang
3
+ Version: 0.1.0
4
+ Summary: Structured key:value protocol for machine-to-machine LLM communication
5
+ Author: Estevao
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/estevaofon/lio-lang
8
+ Project-URL: Repository, https://github.com/estevaofon/lio-lang
9
+ Project-URL: Issues, https://github.com/estevaofon/lio-lang/issues
10
+ Project-URL: Documentation, https://github.com/estevaofon/lio-lang#readme
11
+ Keywords: llm,prompt-engineering,agents,anthropic,openai,claude
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.11
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ License-File: NOTICE
27
+ Provides-Extra: anthropic
28
+ Requires-Dist: anthropic>=0.40.0; extra == "anthropic"
29
+ Provides-Extra: benchmarks
30
+ Requires-Dist: anthropic>=0.40.0; extra == "benchmarks"
31
+ Requires-Dist: python-dotenv>=1.0.0; extra == "benchmarks"
32
+ Requires-Dist: pydantic>=2.0; extra == "benchmarks"
33
+ Provides-Extra: dev
34
+ Requires-Dist: pytest>=8.0; extra == "dev"
35
+ Requires-Dist: anthropic>=0.40.0; extra == "dev"
36
+ Requires-Dist: python-dotenv>=1.0.0; extra == "dev"
37
+ Requires-Dist: pydantic>=2.0; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # lio-lang
41
+
42
+ Protocolo estruturado key:value para comunicacao maquina-a-maquina com LLMs.
43
+ Substitui a prosa que o modelo produz entre tool calls e em respostas
44
+ finais por um formato compacto parecido com JSON, voltado para outputs
45
+ que serao consumidos por codigo, agentes ou automacao em vez de lidos
46
+ por humanos.
47
+
48
+ ```python
49
+ import lio
50
+
51
+ prompt = lio.system_prompt(mode="agentic", language="en")
52
+ report = lio.validate(model_text) # compliance check
53
+ natural = lio.render(lio_text) # LIO -> natural for display
54
+ metrics = lio.measure( # cost/savings math
55
+ natural_input_tokens=582, natural_output_tokens=25378,
56
+ lio_input_tokens=4311, lio_output_tokens=5488,
57
+ model="claude-opus-4-6",
58
+ )
59
+ ```
60
+
61
+ Sem dependencias obrigatorias. Licenca Apache 2.0. Python 3.11+.
62
+
63
+ ---
64
+
65
+ ## Instalacao
66
+
67
+ ```bash
68
+ pip install lio-lang # core, zero dependencias
69
+ pip install lio-lang[anthropic] # com wrapper da SDK Anthropic
70
+ pip install lio-lang[benchmarks] # com deps para rodar os benchmarks
71
+
72
+ # Ou com uv
73
+ uv sync
74
+ uv sync --extra anthropic
75
+ uv sync --extra benchmarks
76
+ ```
77
+
78
+ ---
79
+
80
+ ## Quickstart
81
+
82
+ ```python
83
+ import anthropic
84
+ import lio
85
+
86
+ client = anthropic.Anthropic()
87
+
88
+ response = client.messages.create(
89
+ model="claude-opus-4-6",
90
+ max_tokens=16000,
91
+ system=lio.system_prompt(mode="single_shot", language="en"),
92
+ messages=[{"role": "user", "content": "Write a Python prime filter function"}],
93
+ )
94
+
95
+ raw_text = "".join(b.text for b in response.content if b.type == "text")
96
+
97
+ # Check the response is compliant LIO
98
+ report = lio.validate(raw_text)
99
+ print(f"compliant: {report.compliant} (score {report.score})")
100
+
101
+ # Convert LIO to natural language for human display (no extra API call)
102
+ print(lio.render(raw_text, language="en"))
103
+ ```
104
+
105
+ Exemplos rodaveis em `examples/`:
106
+
107
+ ```bash
108
+ # Exercita toda a API publica, funciona offline e online
109
+ uv run examples/quickstart.py # sem API key: so offline
110
+ uv run --extra anthropic examples/quickstart.py # com API key: online tambem
111
+
112
+ # Compara baseline natural vs LIO roundtrip lado a lado
113
+ uv run --extra anthropic examples/full_flow.py --prompt "Faca uma funcao de ordenacao"
114
+ uv run --extra anthropic examples/full_flow.py --prompt "Write a debounce function" --language en
115
+ ```
116
+
117
+ ---
118
+
119
+ ## API publica
120
+
121
+ | Funcao | Proposito |
122
+ |---|---|
123
+ | `lio.system_prompt(mode, language)` | Retorna a string do system prompt LIO. `mode="agentic"` (multi-turno com tools) ou `"single_shot"`. `language="en"` ou `"pt"`. |
124
+ | `lio.validate(text)` | Checa se um text block e LIO valido. Retorna `ComplianceReport(compliant, score, reasons)`. |
125
+ | `lio.render(lio_text, language)` | Converte LIO de volta para linguagem natural para display. Rule-based, zero chamadas de API. Fallback seguro retorna o input inalterado. |
126
+ | `lio.measure(...)` | Calcula economia de custo a partir de contagens pareadas de tokens. Retorna `EconomyMetrics` com custo, economia percentual, breakdown de input/output. |
127
+ | `lio.middleware.wrap_call` | Decorator que injeta o system prompt LIO em qualquer funcao de chamada LLM e opcionalmente roda um callback de telemetria. |
128
+
129
+ ### Exemplo de middleware
130
+
131
+ ```python
132
+ import lio
133
+ from lio.middleware import wrap_call
134
+
135
+ def telemetry(response):
136
+ text = "".join(b.text for b in response.content if b.type == "text")
137
+ r = lio.validate(text)
138
+ print(f"[lio] compliance={r.score:.2f}")
139
+
140
+ @wrap_call(mode="agentic", language="en", on_response=telemetry)
141
+ def call_claude(messages, **kwargs):
142
+ return client.messages.create(
143
+ model="claude-opus-4-6",
144
+ max_tokens=16000,
145
+ messages=messages,
146
+ **kwargs,
147
+ )
148
+
149
+ # Cada chamada vai automaticamente:
150
+ # 1. receber o system prompt LIO injetado
151
+ # 2. ser validada via callback
152
+ response = call_claude(messages=[{"role": "user", "content": "..."}])
153
+ ```
154
+
155
+ ---
156
+
157
+ ## Filosofia
158
+
159
+ **LIO estrutura informacao, nao comprime.**
160
+
161
+ O objetivo nao e "economizar tokens a qualquer custo". E transferir a
162
+ mesma informacao que linguagem natural transferiria, eliminando o
163
+ overhead de apresentacao: prosa, markdown, pedagogia, cortesia,
164
+ decoracao visual.
165
+
166
+ O que cai fora sao as sobras de linguagem natural, nao os dados.
167
+ Detalhes tecnicos que perderiam funcionalidade se abreviados
168
+ (paths absolutos, identificadores exatos, valores de config, schemas)
169
+ sao preservados. Quando a resposta precisa de valores que o consumidor
170
+ vai substituir, usa-se placeholders explicitos `<REPLACE:nome>` em vez
171
+ de tentar comprimir com truques que colidem com sintaxe da linguagem
172
+ alvo.
173
+
174
+ A analogia correta e com JSON, nao com compressao lossy:
175
+
176
+ > LIO esta para prosa assim como JSON esta para XML-verboso: mesma
177
+ > informacao, sem a gordura de apresentacao. JSON nao e "compressao
178
+ > lossy de XML"; e uma estruturacao diferente da mesma informacao.
179
+ > LIO tem a mesma relacao com a prosa de LLM.
180
+
181
+ Consequencias praticas:
182
+
183
+ - Uma resposta LIO pode ser longa se a informacao exige.
184
+ - Use quantos campos forem necessarios para manter precisao tecnica.
185
+ - Alternativas validas sao preservadas via campo `variant`.
186
+ - O modelo mantem liberdade de planejamento, nao e constrangido a
187
+ "escolher uma resposta e descartar as outras".
188
+
189
+ ---
190
+
191
+ ## Sintaxe
192
+
193
+ ### Gramatica minima
194
+
195
+ ```
196
+ field = key ':' value
197
+ value = escalar | '[' lista ']' | '{' objeto '}' | '<REPLACE:' nome '>'
198
+ text_block = sequencia de fields, separados por espaco ou newline
199
+ ```
200
+
201
+ Escalares sao literais. Listas usam virgula. Objetos usam virgula entre pares.
202
+
203
+ ### Campos reservados
204
+
205
+ Uma letra para a estrutura base:
206
+
207
+ | Campo | Uso |
208
+ |---|---|
209
+ | `T` | task type |
210
+ | `O` | object / target |
211
+ | `P` | params |
212
+ | `C` | context |
213
+ | `F` | expected format |
214
+ | `X` | constraints |
215
+ | `S` | status (`ok`, `err`, `partial`) |
216
+ | `R` | result |
217
+ | `D` | data |
218
+ | `W` | warning |
219
+ | `E` | error |
220
+ | `Q` | query |
221
+ | `N` | count |
222
+
223
+ Palavras-chave para semantica adicional:
224
+
225
+ | Campo | Uso |
226
+ |---|---|
227
+ | `step` | acao atual (loops agenticos) |
228
+ | `next` | proxima acao |
229
+ | `fix` | correcao proposta |
230
+ | `issues` | lista de problemas encontrados |
231
+ | `causes` | lista de causas possiveis |
232
+ | `variant` | resposta alternativa valida |
233
+ | `note` | observacao nao obvia |
234
+ | `code` | bloco de codigo (passa intacto) |
235
+ | `steps` | sequencia de passos |
236
+
237
+ Voce pode introduzir campos novos quando fizer sentido.
238
+
239
+ ### Placeholders explicitos
240
+
241
+ Quando a resposta precisa de valores que o consumidor deve substituir,
242
+ use `<REPLACE:nome_descritivo>`. Por que nao outras opcoes:
243
+
244
+ - `$variavel` ou `${variavel}` colidem com bash, nginx, make
245
+ - `{{variavel}}` colide com Jinja, Mustache, Go templates
246
+ - `__variavel__` fragil, nao se destaca
247
+ - `<REPLACE:nome>` angle brackets sao slot universal, `REPLACE` e
248
+ explicito, nenhuma linguagem mainstream usa esse token literal
249
+
250
+ Exemplo (config nginx com SSL):
251
+
252
+ ```
253
+ S:ok R:nginx_config
254
+ code:{
255
+ server {
256
+ listen 443 ssl http2;
257
+ server_name <REPLACE:your_domain>;
258
+ ssl_certificate /etc/letsencrypt/live/<REPLACE:your_domain>/fullchain.pem;
259
+ ssl_certificate_key /etc/letsencrypt/live/<REPLACE:your_domain>/privkey.pem;
260
+ location / { proxy_pass http://localhost:3000; }
261
+ }
262
+ }
263
+ W:run_certbot_first->certbot --nginx -d <REPLACE:your_domain>
264
+ ```
265
+
266
+ ### O que LIO nao tem
267
+
268
+ O mesmo que JSON nao tem: markdown headers, tabelas, listas bullet,
269
+ emoji decorativo, blocos de citacao, negrito/italico, preambulo
270
+ ("Aqui esta..."), cortesia ("Espero que ajude"), ou prosa explicativa
271
+ redundante com o conteudo.
272
+
273
+ Codigo dentro de `code:{}` passa intacto, pode conter qualquer sintaxe
274
+ da linguagem alvo.
275
+
276
+ ---
277
+
278
+ ## Quando usar LIO
279
+
280
+ Use onde o consumidor da resposta **nao e um humano**, ou onde a
281
+ resposta sera processada por codigo antes de chegar em humano.
282
+
283
+ **Casos ideais:**
284
+ - Pipelines agentic (agente LLM agente) - nenhum humano le o intermediario
285
+ - Workflows automatizados (n8n, Make, Zapier)
286
+ - RAG chains - query, retrieve, LLM, resposta estruturada downstream
287
+ - Multi-agent systems onde agentes conversam entre si
288
+ - Batch processing - milhares de chamadas identicas em formato
289
+ - Coding agent plugins - raciocinio intermediario entre tool calls
290
+
291
+ **Nao use para:**
292
+ - Chat direto com humano - o humano precisa ler a resposta
293
+ - Tarefas criativas (escrita, brainstorm) - a verbosidade e o produto
294
+ - Educacao e explicacoes - tokens de explicacao sao o produto
295
+ - Respostas onde a prosa **e** o valor (emails, documentacao)
296
+
297
+ ---
298
+
299
+ ## Padroes de integracao
300
+
301
+ ### 1. Injecao direta do system prompt
302
+
303
+ O mais simples. Funciona com qualquer SDK:
304
+
305
+ ```python
306
+ import anthropic
307
+ import lio
308
+
309
+ client = anthropic.Anthropic()
310
+ response = client.messages.create(
311
+ model="claude-opus-4-6",
312
+ max_tokens=16000,
313
+ system=lio.system_prompt(mode="agentic", language="en"),
314
+ messages=[{"role": "user", "content": "..."}],
315
+ )
316
+ ```
317
+
318
+ ### 2. Middleware decorator
319
+
320
+ Se voce ja tem uma funcao que chama a LLM, so decora:
321
+
322
+ ```python
323
+ import lio
324
+ from lio.middleware import wrap_call
325
+
326
+ @wrap_call(mode="agentic", language="en", on_response=lambda r: print("[lio] ok"))
327
+ def call_llm(messages, **kwargs):
328
+ return client.messages.create(
329
+ model="claude-opus-4-6",
330
+ max_tokens=16000,
331
+ messages=messages,
332
+ **kwargs,
333
+ )
334
+
335
+ response = call_llm(messages=[{"role": "user", "content": "..."}])
336
+ ```
337
+
338
+ ### 3. Renderizacao para UI
339
+
340
+ Se o consumidor final e humano, converta LIO de volta para natural
341
+ antes de mostrar:
342
+
343
+ ```python
344
+ text = "".join(b.text for b in response.content if b.type == "text")
345
+ human_view = lio.render(text, language="en")
346
+ print(human_view)
347
+ ```
348
+
349
+ Transformacao rule-based local, sem chamada de API. Cobre os padroes
350
+ comuns (`S:ok code:{...}`, `issues:[...] fix:[...]`, objetos aninhados,
351
+ listas) e faz fallback seguro retornando o input inalterado quando nao
352
+ reconhece a forma.
353
+
354
+ ---
355
+
356
+ ## Benchmarks
357
+
358
+ Bateria de 15 tarefas single-shot contra `claude-opus-4-6`, pareando
359
+ prompts em linguagem natural com prompts em LIO. Roda com:
360
+
361
+ ```bash
362
+ python -m benchmarks.run # 15 tarefas, ~$1
363
+ python -m benchmarks.multi_turn # sessao agentic, ~$0.15
364
+ python -m benchmarks.fidelity # LLM-as-judge, ~$0.30
365
+ ```
366
+
367
+ ### Resultados representativos
368
+
369
+ | Cenario | Compliance | Fidelidade | Economia custo | Economia output |
370
+ |---|---|---|---|---|
371
+ | Single-shot, 15 tarefas | 100% | 95% | 69-75% | 79-82% |
372
+ | Multi-turn agentic, 3 turnos | 100% | - | 40-55% | 55-73% |
373
+ | Roundtrip Fibonacci (example full_flow) | 100% | - | 70-75% | 83-87% |
374
+
375
+ Compliance e medido pelo validator local (`lio.validate`). Fidelidade
376
+ e medida com LLM-as-judge calibrado em `benchmarks/fidelity.py`.
377
+ Economia de output varia por categoria:
378
+
379
+ | Categoria | Economia de output |
380
+ |---|---|
381
+ | debug | ~70% |
382
+ | cfg | ~85% |
383
+ | refactor | ~85% |
384
+ | code | ~80% |
385
+ | analyze | ~65% |
386
+
387
+ Economia efetiva varia com a proporcao de text vs tool_use no output
388
+ total. Para coding agents com uso pesado de tools, a economia por
389
+ sessao tipicamente fica entre 30-50%, pois LIO so afeta os text blocks
390
+ do modelo - tool_use blocks JSON permanecem identicos.
391
+
392
+ ---
393
+
394
+ ## Limites conhecidos
395
+
396
+ 1. **Economia depende do shape da tarefa.** Tarefas prose-heavy
397
+ (explicacoes, analises, debug) capturam 60-75%. Tarefas
398
+ tool-heavy (coding agents com muito read/write/bash) capturam
399
+ 30-50%. Tarefas onde o output e dominado por codigo cru dentro
400
+ de `code:{}` capturam 20-30% (o codigo passa intacto).
401
+
402
+ 2. **Input savings sao frequentemente negativos.** O system prompt
403
+ LIO adiciona ~500 tokens por chamada. Em prompts curtos isso
404
+ domina o input. A economia vem do output, que custa 5x mais
405
+ que input no Opus. Em sessoes longas com historico acumulado,
406
+ input savings vira positivo.
407
+
408
+ 3. **LIO requer modelos inteligentes.** Testado em Opus 4.6 e
409
+ Sonnet 4.6. Nao recomendado para Haiku - o overhead cognitivo
410
+ de seguir o protocolo nao compensa para modelos menores.
411
+ Haiku pode ser usado como decoder LIO->natural barato.
412
+
413
+ 4. **Drift de compliance em prompts-gatilho.** Palavras como
414
+ "relatorio"/"report" no prompt do usuario ativam priors fortes
415
+ para output em markdown. O validator detecta drift (inclui
416
+ detecao de markdown inclusive dentro de `code:{}` blocks), e a
417
+ filosofia "estrutura nao compressao" mitiga, mas vale atencao.
418
+
419
+ 5. **Fidelidade depende de juiz calibrado.** LLM-as-judge pode
420
+ penalizar LIO por "omissoes" que sao na verdade over-delivery
421
+ da resposta natural (info que o usuario nao pediu). O juiz em
422
+ `benchmarks/fidelity.py` e calibrado para ancorar o julgamento
423
+ na pergunta do usuario, nao na resposta natural de referencia.
424
+
425
+ ---
426
+
427
+ ## Estrutura do repositorio
428
+
429
+ ```
430
+ lio-lang/
431
+ ├── lio/
432
+ │ ├── __init__.py # API publica
433
+ │ ├── protocol.py # factory de system prompts
434
+ │ ├── validator.py # compliance checker
435
+ │ ├── render.py # LIO -> natural (rule-based)
436
+ │ ├── metrics.py # calculo de economia + tabela de pricing
437
+ │ ├── client.py # wrapper opcional da Anthropic SDK
438
+ │ ├── languages/
439
+ │ │ ├── en.py # prompts em ingles
440
+ │ │ └── pt.py # prompts em portugues
441
+ │ └── middleware/
442
+ │ └── generic.py # wrap_call decorator
443
+ ├── tests/
444
+ │ ├── test_validator.py
445
+ │ ├── test_render.py
446
+ │ └── test_metrics.py
447
+ ├── benchmarks/
448
+ │ ├── tasks.jsonl # 15 tarefas pareadas
449
+ │ ├── run.py # benchmark single-shot
450
+ │ ├── multi_turn.py # benchmark agentic
451
+ │ ├── fidelity.py # LLM-as-judge
452
+ │ └── compare.py # relatorio comparativo
453
+ ├── examples/
454
+ │ ├── quickstart.py # exercita toda a API (offline + online)
455
+ │ └── full_flow.py # comparacao natural vs LIO roundtrip
456
+ ├── pyproject.toml
457
+ ├── LICENSE # MIT
458
+ └── README.md # este arquivo
459
+ ```
460
+
461
+ ---
462
+
463
+ ## Desenvolvimento
464
+
465
+ ```bash
466
+ git clone https://github.com/estevaofon/lio-lang
467
+ cd lio-lang
468
+ uv sync --extra dev # ou: pip install -e .[dev]
469
+
470
+ # Rodar os testes
471
+ pytest tests/
472
+
473
+ # Rodar os exemplos (offline, sem API key)
474
+ uv run examples/quickstart.py --offline
475
+
476
+ # Rodar os exemplos com API real (precisa ANTHROPIC_API_KEY em .env)
477
+ uv run --extra anthropic examples/quickstart.py
478
+ uv run --extra anthropic examples/full_flow.py --prompt "sua pergunta"
479
+
480
+ # Rodar benchmark completo (custo ~$1.50 em API)
481
+ uv run --extra benchmarks python -m benchmarks.run
482
+ uv run --extra benchmarks python -m benchmarks.multi_turn
483
+ uv run --extra benchmarks python -m benchmarks.fidelity
484
+ ```
485
+
486
+ ---
487
+
488
+ ## Licenca
489
+
490
+ Apache License 2.0. Ver `LICENSE` e `NOTICE`.
491
+
492
+ Copyright 2026 Estevao Fonseca.