langstate 0.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.
langstate/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from langstate.compress import compress
2
+
3
+ __all__ = ["compress"]
langstate/adapters.py ADDED
@@ -0,0 +1,221 @@
1
+ """
2
+ langstate.adapters — production backends for the scaffold summarizer.
3
+
4
+ Each adapter is a callable ``summarize(prompt: str) -> str`` that takes the
5
+ composed compression prompt and returns a natural-language scaffold summary.
6
+
7
+ Adapters are stdlib-only (urllib) to preserve the "zero heavy deps" promise
8
+ of langstate. API keys are read from the environment, not arguments —
9
+ adapters raise ``AdapterUnavailable`` when their key or backend is missing
10
+ so callers can gracefully degrade to the local adapter.
11
+
12
+ Production targets (one default per provider, per the Hermes spec):
13
+ - Anthropic: claude-opus-4-7 (env ANTHROPIC_API_KEY)
14
+ - OpenAI: gpt-4o-mini (env OPENAI_API_KEY)
15
+ - Local: qwen3:14b via Ollama (no key, localhost:11434)
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import os
22
+ import time
23
+ import urllib.error
24
+ import urllib.request
25
+ from typing import Callable, Optional
26
+
27
+ Summarizer = Callable[[str], str]
28
+
29
+
30
+ class AdapterUnavailable(RuntimeError):
31
+ """Raised when an adapter cannot run (missing key, unreachable, etc.)."""
32
+
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Ollama (local, default)
36
+ # ---------------------------------------------------------------------------
37
+
38
+ OLLAMA_URL = "http://localhost:11434/api/chat"
39
+ DEFAULT_LOCAL_MODEL = "qwen3:14b"
40
+
41
+
42
+ def ollama(
43
+ model: str = DEFAULT_LOCAL_MODEL,
44
+ url: str = OLLAMA_URL,
45
+ num_predict: int = 8000,
46
+ temperature: float = 0.2,
47
+ timeout: int = 600,
48
+ ) -> Summarizer:
49
+ """Build a summarizer that calls a local Ollama model."""
50
+
51
+ def _call(prompt: str) -> str:
52
+ payload = json.dumps({
53
+ "model": model,
54
+ "messages": [
55
+ {"role": "system", "content": "Respond directly. Do not think or reason. Just output the summary."},
56
+ {"role": "user", "content": prompt},
57
+ ],
58
+ "stream": False,
59
+ "options": {"num_predict": num_predict, "temperature": temperature},
60
+ }).encode()
61
+ req = urllib.request.Request(url, data=payload, headers={"Content-Type": "application/json"})
62
+ try:
63
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
64
+ result = json.loads(resp.read())
65
+ except (urllib.error.URLError, OSError) as e:
66
+ raise AdapterUnavailable(f"ollama unreachable at {url}: {e}") from e
67
+ content = (result.get("message") or {}).get("content", "").strip()
68
+ if not content:
69
+ raise RuntimeError("Ollama returned empty content. Increase num_predict.")
70
+ return content
71
+
72
+ return _call
73
+
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # OpenAI
77
+ # ---------------------------------------------------------------------------
78
+
79
+ OPENAI_URL = "https://api.openai.com/v1/chat/completions"
80
+ DEFAULT_OPENAI_MODEL = "gpt-4o-mini"
81
+
82
+
83
+ def openai(
84
+ model: str = DEFAULT_OPENAI_MODEL,
85
+ api_key: Optional[str] = None,
86
+ url: str = OPENAI_URL,
87
+ max_tokens: int = 4000,
88
+ temperature: float = 0.2,
89
+ timeout: int = 120,
90
+ ) -> Summarizer:
91
+ """Build a summarizer that calls the OpenAI chat completions API."""
92
+ key = api_key or os.environ.get("OPENAI_API_KEY")
93
+ if not key:
94
+ raise AdapterUnavailable("OPENAI_API_KEY not set")
95
+
96
+ def _call(prompt: str) -> str:
97
+ payload = json.dumps({
98
+ "model": model,
99
+ "messages": [
100
+ {"role": "system", "content": "Respond directly. Do not think or reason. Just output the summary."},
101
+ {"role": "user", "content": prompt},
102
+ ],
103
+ "temperature": temperature,
104
+ "max_tokens": max_tokens,
105
+ }).encode()
106
+ req = urllib.request.Request(
107
+ url,
108
+ data=payload,
109
+ headers={
110
+ "Content-Type": "application/json",
111
+ "Authorization": f"Bearer {key}",
112
+ },
113
+ )
114
+ try:
115
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
116
+ result = json.loads(resp.read())
117
+ except urllib.error.HTTPError as e:
118
+ body = e.read().decode(errors="replace")
119
+ raise AdapterUnavailable(f"openai HTTP {e.code}: {body[:200]}") from e
120
+ except (urllib.error.URLError, OSError) as e:
121
+ raise AdapterUnavailable(f"openai unreachable: {e}") from e
122
+ try:
123
+ return result["choices"][0]["message"]["content"].strip()
124
+ except (KeyError, IndexError) as e:
125
+ raise RuntimeError(f"openai unexpected response: {result}") from e
126
+
127
+ return _call
128
+
129
+
130
+ # ---------------------------------------------------------------------------
131
+ # Anthropic
132
+ # ---------------------------------------------------------------------------
133
+
134
+ ANTHROPIC_URL = "https://api.anthropic.com/v1/messages"
135
+ DEFAULT_ANTHROPIC_MODEL = "claude-opus-4-7"
136
+ ANTHROPIC_VERSION = "2023-06-01"
137
+
138
+
139
+ def anthropic(
140
+ model: str = DEFAULT_ANTHROPIC_MODEL,
141
+ api_key: Optional[str] = None,
142
+ url: str = ANTHROPIC_URL,
143
+ max_tokens: int = 4000,
144
+ temperature: float = 0.2,
145
+ timeout: int = 120,
146
+ ) -> Summarizer:
147
+ """Build a summarizer that calls the Anthropic messages API."""
148
+ key = api_key or os.environ.get("ANTHROPIC_API_KEY")
149
+ if not key:
150
+ raise AdapterUnavailable("ANTHROPIC_API_KEY not set")
151
+
152
+ def _call(prompt: str) -> str:
153
+ payload = json.dumps({
154
+ "model": model,
155
+ "max_tokens": max_tokens,
156
+ "temperature": temperature,
157
+ "system": "Respond directly. Do not think or reason. Just output the summary.",
158
+ "messages": [{"role": "user", "content": prompt}],
159
+ }).encode()
160
+ req = urllib.request.Request(
161
+ url,
162
+ data=payload,
163
+ headers={
164
+ "Content-Type": "application/json",
165
+ "x-api-key": key,
166
+ "anthropic-version": ANTHROPIC_VERSION,
167
+ },
168
+ )
169
+ try:
170
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
171
+ result = json.loads(resp.read())
172
+ except urllib.error.HTTPError as e:
173
+ body = e.read().decode(errors="replace")
174
+ raise AdapterUnavailable(f"anthropic HTTP {e.code}: {body[:200]}") from e
175
+ except (urllib.error.URLError, OSError) as e:
176
+ raise AdapterUnavailable(f"anthropic unreachable: {e}") from e
177
+ blocks = result.get("content") or []
178
+ text = "".join(b.get("text", "") for b in blocks if b.get("type") == "text").strip()
179
+ if not text:
180
+ raise RuntimeError(f"anthropic returned no text blocks: {result}")
181
+ return text
182
+
183
+ return _call
184
+
185
+
186
+ # ---------------------------------------------------------------------------
187
+ # Registry
188
+ # ---------------------------------------------------------------------------
189
+
190
+ REGISTRY = {
191
+ "local": ("qwen3:14b (Ollama)", ollama),
192
+ "openai": ("gpt-4o-mini", openai),
193
+ "anthropic": ("claude-opus-4-7", anthropic),
194
+ }
195
+
196
+
197
+ def build(name: str) -> Summarizer:
198
+ """Build a summarizer by name. Raises AdapterUnavailable if not usable."""
199
+ if name not in REGISTRY:
200
+ raise ValueError(f"unknown adapter {name!r}. choices: {list(REGISTRY)}")
201
+ _, factory = REGISTRY[name]
202
+ return factory()
203
+
204
+
205
+ def probe(name: str) -> dict:
206
+ """Check whether an adapter is usable; return {available, reason, latency_ms}."""
207
+ t0 = time.time()
208
+ try:
209
+ fn = build(name)
210
+ out = fn("Say OK.")
211
+ except AdapterUnavailable as e:
212
+ return {"name": name, "available": False, "reason": str(e), "latency_ms": None}
213
+ except Exception as e: # noqa: BLE001
214
+ return {"name": name, "available": False, "reason": f"{type(e).__name__}: {e}", "latency_ms": None}
215
+ return {
216
+ "name": name,
217
+ "available": True,
218
+ "reason": "ok",
219
+ "latency_ms": int((time.time() - t0) * 1000),
220
+ "sample": out[:80],
221
+ }
langstate/compress.py ADDED
@@ -0,0 +1,130 @@
1
+ """
2
+ langstate.compress — Scaffold-aware context compression for OpenAI-format messages.
3
+
4
+ Compresses conversation history into a state-preserving scaffold summary,
5
+ keeping the system prompt and recent turns verbatim. Uses a local Ollama
6
+ model (qwen3:4b) for zero-cost summarization.
7
+
8
+ Usage:
9
+ from langstate.compress import compress
10
+ compressed = compress(messages)
11
+ response = client.chat.completions.create(messages=compressed, model="gpt-4o")
12
+ """
13
+
14
+ from typing import Callable, Optional
15
+
16
+ from langstate import adapters as _adapters
17
+
18
+ OLLAMA_URL = "http://localhost:11434/api/chat"
19
+ DEFAULT_MODEL = "qwen3:4b"
20
+ PRESERVE_RECENT = 4 # keep last N user/assistant turns verbatim
21
+
22
+ Summarizer = Callable[[str], str]
23
+
24
+
25
+ def _count_tokens_approx(text: str) -> int:
26
+ """Rough token count: ~4 chars per token for English."""
27
+ return len(text) // 4
28
+
29
+
30
+ def _count_messages_tokens(messages: list[dict]) -> int:
31
+ """Approximate total tokens across all messages."""
32
+ return sum(_count_tokens_approx(m.get("content", "")) for m in messages)
33
+
34
+
35
+ def _build_compression_prompt(text: str) -> str:
36
+ """The scaffold compression instruction shared by every adapter."""
37
+ return (
38
+ "You are a scaffold state compressor. Your job is to compress a conversation "
39
+ "history into a concise state summary that preserves ALL of the following:\n"
40
+ "- Facts established (names, numbers, decisions, entities)\n"
41
+ "- Decisions made and their reasoning\n"
42
+ "- Current task state (what's done, what's pending, what's blocked)\n"
43
+ "- User preferences and constraints expressed\n"
44
+ "- Any commitments or agreements\n\n"
45
+ "Do NOT preserve:\n"
46
+ "- Greetings, pleasantries, filler\n"
47
+ "- Redundant re-statements of the same fact\n"
48
+ "- Verbose explanations when a short statement captures the same info\n\n"
49
+ "Output a compressed state summary in natural language. Use bullet points for "
50
+ "distinct facts. Be terse but complete. Preserve every fact and decision.\n\n"
51
+ "CONVERSATION TO COMPRESS:\n"
52
+ f"{text}"
53
+ )
54
+
55
+
56
+ def compress(
57
+ messages: list[dict],
58
+ preserve_recent: int = PRESERVE_RECENT,
59
+ model: str = DEFAULT_MODEL,
60
+ ollama_url: str = OLLAMA_URL,
61
+ min_turns_to_compress: int = 6,
62
+ summarizer: Optional[Summarizer] = None,
63
+ ) -> list[dict]:
64
+ """Compress an OpenAI-format messages array while preserving conversational state.
65
+
66
+ Args:
67
+ messages: List of dicts with "role" and "content" keys.
68
+ preserve_recent: Number of recent user/assistant turn pairs to keep verbatim.
69
+ model: Ollama model to use when no summarizer is given (back-compat).
70
+ ollama_url: Ollama API endpoint (back-compat).
71
+ min_turns_to_compress: Don't compress if fewer than this many messages.
72
+ summarizer: Optional ``summarize(prompt) -> str`` callable. If None, falls back
73
+ to a local Ollama adapter (qwen3:4b) for back-compat with the MVP.
74
+
75
+ Returns:
76
+ Compressed messages list in the same OpenAI format.
77
+ """
78
+ if not messages:
79
+ return []
80
+
81
+ # Count actual user/assistant turns, not total messages
82
+ n_turns = sum(1 for m in messages if m.get("role") in ("user", "assistant")) // 2
83
+ if n_turns < min_turns_to_compress:
84
+ return list(messages)
85
+
86
+ # Separate system prompt from conversation
87
+ system_msgs = [m for m in messages if m.get("role") == "system"]
88
+ conv_msgs = [m for m in messages if m.get("role") != "system"]
89
+
90
+ if not conv_msgs:
91
+ return list(messages)
92
+
93
+ # Split: history to compress vs recent turns to preserve
94
+ # preserve_recent refers to turn pairs, so preserve_recent*2 messages
95
+ preserve_count = preserve_recent * 2
96
+ if len(conv_msgs) <= preserve_count:
97
+ return list(messages)
98
+
99
+ history_msgs = conv_msgs[:-preserve_count]
100
+ recent_msgs = conv_msgs[-preserve_count:]
101
+
102
+ # Format history for summarization
103
+ history_text = "\n".join(
104
+ f"[{m['role'].upper()}]: {m.get('content', '')}" for m in history_msgs
105
+ )
106
+
107
+ # Compress via the chosen summarizer (default: local Ollama, MVP back-compat)
108
+ if summarizer is None:
109
+ summarizer = _adapters.ollama(model=model, url=ollama_url)
110
+ summary = summarizer(_build_compression_prompt(history_text))
111
+
112
+ # Build compressed messages
113
+ compressed = []
114
+
115
+ # Keep system prompt(s)
116
+ compressed.extend(system_msgs)
117
+
118
+ # Insert scaffold summary as a system message
119
+ compressed.append({
120
+ "role": "system",
121
+ "content": (
122
+ f"[SCAFFOLD STATE — compressed from {len(history_msgs)} earlier messages]\n"
123
+ f"{summary}"
124
+ ),
125
+ })
126
+
127
+ # Keep recent turns verbatim
128
+ compressed.extend(recent_msgs)
129
+
130
+ return compressed
langstate/te_check.py ADDED
@@ -0,0 +1,188 @@
1
+ """langstate.te_check — honest transfer-entropy proxy on the 100-message corpus.
2
+
3
+ We can't measure continuous transfer entropy against a closed model in the
4
+ usual way (no joint-distribution access). So we measure a downstream
5
+ *behavioral* TE proxy instead, which is the only defensible proxy when the
6
+ model is a black box:
7
+
8
+ TE-proxy = 1 - recall(probe | compressed)
9
+ ---------------------------
10
+ recall(probe | full_history)
11
+
12
+ Method (single constant probe model for all conditions to isolate the
13
+ compression signal):
14
+
15
+ * Probe model: ``qwen3:8b`` on local Ollama (deterministic, temperature 0).
16
+ * Probes: 10 cloze-style questions whose answers appear exactly once in
17
+ the early turns of the corpus.
18
+ * For each adapter ``A`` we form two conversations:
19
+ full_A = corpus + probe
20
+ compressed_A = compress(corpus, summarizer=A) + probe
21
+ and score the probe model's answer with case-insensitive substring
22
+ match against the ground-truth needle.
23
+ * Report per-adapter: recall_full, recall_compressed, delta.
24
+ delta ≈ 0 is the empirical TE-proxy-≈-zero claim.
25
+
26
+ This is an imperfect TE estimator but it is honestly labelled as a
27
+ *behavioral* proxy and the math is transparent.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import json
34
+ import sys
35
+ import time
36
+ import urllib.request
37
+ import urllib.error
38
+ from pathlib import Path
39
+
40
+ HERE = Path(__file__).resolve().parent
41
+ if str(HERE) not in sys.path:
42
+ sys.path.insert(0, str(HERE))
43
+
44
+ from adapters import REGISTRY, AdapterUnavailable, build # noqa: E402
45
+ from bench_adapters import build_corpus_100 # noqa: E402
46
+ from compress import compress # noqa: E402
47
+
48
+
49
+ PROBE_MODEL = "qwen3:8b"
50
+ OLLAMA_URL = "http://localhost:11434/api/chat"
51
+
52
+ # (question, ground_truth_substring) — answers appear verbatim in the corpus.
53
+ PROBES = [
54
+ ("What is the user's first name?", "roli"),
55
+ ("What is the name of the user's company?", "hermes"),
56
+ ("What acronym describes their core thesis?", "lpci"),
57
+ ("What measurement did they report as approximately zero?", "transfer entropy"),
58
+ ("What compression ratio did they measure?", "2.5"),
59
+ ("What is the name of the first product they plan to ship?", "compress"),
60
+ ("What conference submission deadline is driving their timeline?", "neurips"),
61
+ ("How large is the research corpus they built, in MB?", "530"),
62
+ ("Which researcher proved autoregressive chaining equals universal computation?", "schuurmans"),
63
+ ("What is their seed fundraise ask?", "2m"),
64
+ ]
65
+
66
+
67
+ def _ollama_chat(messages: list[dict], model: str = PROBE_MODEL, timeout: int = 120) -> str:
68
+ payload = json.dumps({
69
+ "model": model,
70
+ "messages": messages,
71
+ "stream": False,
72
+ "options": {"temperature": 0.0, "num_predict": 160, "seed": 7},
73
+ }).encode()
74
+ req = urllib.request.Request(
75
+ OLLAMA_URL,
76
+ data=payload,
77
+ headers={"Content-Type": "application/json"},
78
+ )
79
+ try:
80
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
81
+ result = json.loads(resp.read())
82
+ except (urllib.error.URLError, OSError) as e:
83
+ raise RuntimeError(f"probe model unreachable: {e}") from e
84
+ return (result.get("message") or {}).get("content", "").strip()
85
+
86
+
87
+ PROBE_SYSTEM = (
88
+ "Answer from the supplied conversation state only. "
89
+ "Respond with the single fact asked for, no preamble, no hedging. "
90
+ "If the answer is not present, say NOT_PRESENT."
91
+ )
92
+
93
+
94
+ def _score(answer: str, needle: str) -> int:
95
+ return int(needle.lower() in answer.lower())
96
+
97
+
98
+ def _run_probes(context_msgs: list[dict]) -> tuple[int, list[dict]]:
99
+ hits = 0
100
+ rows: list[dict] = []
101
+ for q, needle in PROBES:
102
+ convo = [{"role": "system", "content": PROBE_SYSTEM}, *context_msgs,
103
+ {"role": "user", "content": q}]
104
+ ans = _ollama_chat(convo)
105
+ ok = _score(ans, needle)
106
+ hits += ok
107
+ rows.append({"q": q, "needle": needle, "answer": ans[:200], "hit": ok})
108
+ return hits, rows
109
+
110
+
111
+ def run_adapter(name: str, corpus: list[dict]) -> dict:
112
+ """Compare recall under full vs compressed context for one adapter."""
113
+ try:
114
+ summarizer = build(name)
115
+ except AdapterUnavailable as e:
116
+ return {"adapter": name, "available": False, "reason": str(e)}
117
+
118
+ t0 = time.time()
119
+ try:
120
+ compressed = compress(corpus, summarizer=summarizer)
121
+ except Exception as e: # noqa: BLE001
122
+ return {"adapter": name, "available": False, "reason": f"compress: {e}"}
123
+ compress_seconds = time.time() - t0
124
+
125
+ # shared full-context recall only needs to run once per bench; we still
126
+ # do it per adapter so every row is a standalone comparison.
127
+ full_hits, full_rows = _run_probes(corpus)
128
+ comp_hits, comp_rows = _run_probes(compressed)
129
+
130
+ n = len(PROBES)
131
+ recall_full = full_hits / n
132
+ recall_comp = comp_hits / n
133
+ delta = recall_full - recall_comp
134
+ te_proxy = max(delta, 0.0)
135
+
136
+ return {
137
+ "adapter": name,
138
+ "label": REGISTRY[name][0],
139
+ "available": True,
140
+ "n_probes": n,
141
+ "recall_full": round(recall_full, 3),
142
+ "recall_compressed": round(recall_comp, 3),
143
+ "delta": round(delta, 3),
144
+ "te_proxy": round(te_proxy, 3),
145
+ "compress_seconds": round(compress_seconds, 2),
146
+ "rows_full": full_rows,
147
+ "rows_compressed": comp_rows,
148
+ }
149
+
150
+
151
+ def main() -> int:
152
+ ap = argparse.ArgumentParser()
153
+ ap.add_argument("--only", choices=list(REGISTRY))
154
+ ap.add_argument("--out", default=str(HERE / "te_results.json"))
155
+ args = ap.parse_args()
156
+
157
+ corpus = build_corpus_100()
158
+ names = [args.only] if args.only else list(REGISTRY)
159
+ rows = [run_adapter(n, corpus) for n in names]
160
+
161
+ print("=" * 78)
162
+ print(f"langstate.te_check — n={len(PROBES)} probes, probe_model={PROBE_MODEL}")
163
+ print("=" * 78)
164
+ print(f"{'adapter':<10} {'label':<22} {'full':>6} {'comp':>6} {'delta':>7} {'TE~':>6}")
165
+ print("-" * 78)
166
+ for r in rows:
167
+ if not r.get("available"):
168
+ print(f"{r['adapter']:<10} {'—':<22} {'—':>6} {'—':>6} {'—':>7} {'—':>6} SKIP: {r['reason'][:30]}")
169
+ continue
170
+ print(
171
+ f"{r['adapter']:<10} {r['label']:<22} "
172
+ f"{r['recall_full']:>6.1%} {r['recall_compressed']:>6.1%} "
173
+ f"{r['delta']:>+7.1%} {r['te_proxy']:>6.3f}"
174
+ )
175
+ print("=" * 78)
176
+
177
+ Path(args.out).write_text(json.dumps({
178
+ "probe_model": PROBE_MODEL,
179
+ "n_probes": len(PROBES),
180
+ "corpus_size": len(corpus),
181
+ "results": rows,
182
+ }, indent=2))
183
+ print(f"Wrote {args.out}")
184
+ return 0 if any(r.get("available") for r in rows) else 2
185
+
186
+
187
+ if __name__ == "__main__":
188
+ sys.exit(main())
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: langstate
3
+ Version: 0.1.0
4
+ Summary: Scaffold-aware context compression for OpenAI-format messages — preserve state at 50%+ token reduction via local Ollama, OpenAI, or Anthropic
5
+ Author-email: Rolando Bosch <rbosch@lpci.ai>
6
+ Maintainer-email: Hermes Labs <info@hermes-labs.ai>
7
+ License: Apache-2.0
8
+ Project-URL: Homepage, https://hermes-labs.ai
9
+ Project-URL: Repository, https://github.com/hermes-labs-ai/langstate
10
+ Project-URL: Issues, https://github.com/hermes-labs-ai/langstate/issues
11
+ Keywords: llm,context-compression,scaffold,agent,ollama,openai,token-optimization,language-state
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=8.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.4.0; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # langstate
28
+
29
+ Scaffold-aware context compression for OpenAI-format messages. `compress(messages)` preserves all conversational state — facts, decisions, task status, user preferences — while reducing tokens by 50-54%.
30
+
31
+ Backed by the LPCI thesis: stateless LLMs hold state via language scaffold with transfer entropy approximately zero (Markov property). This is the productization of that proof.
32
+
33
+ ## What it does
34
+
35
+ ```python
36
+ from langstate import compress
37
+
38
+ compressed = compress(messages)
39
+ # Drop-in replacement: same OpenAI format, fewer tokens, state preserved
40
+ response = client.chat.completions.create(messages=compressed, model="gpt-4o")
41
+ ```
42
+
43
+ The output is a valid OpenAI-format messages list:
44
+ - System prompts kept verbatim
45
+ - Last 4 turn-pairs kept verbatim
46
+ - Older turns compressed into a `[SCAFFOLD STATE]` system message via local or cloud model
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ # From GitHub (PyPI coming soon):
52
+ pip install git+https://github.com/hermes-labs-ai/langstate.git
53
+ ```
54
+
55
+ Requirements: Python 3.10+, no heavy dependencies (stdlib only). For local summarization, run [Ollama](https://ollama.ai) locally:
56
+
57
+ ```bash
58
+ ollama pull qwen3:4b
59
+ ```
60
+
61
+ ## Adapters
62
+
63
+ langstate ships three built-in summarizer backends:
64
+
65
+ | Adapter | Model | Cost | Key |
66
+ |---|---|---|---|
67
+ | `local` (default) | qwen3:14b via Ollama | zero | none |
68
+ | `openai` | gpt-4o-mini | API | `OPENAI_API_KEY` |
69
+ | `anthropic` | claude-opus-4-7 | API | `ANTHROPIC_API_KEY` |
70
+
71
+ ```python
72
+ from langstate import compress
73
+ from langstate.adapters import build
74
+
75
+ # Local Ollama (default, zero cost)
76
+ compressed = compress(messages)
77
+
78
+ # OpenAI
79
+ compressed = compress(messages, summarizer=build("openai"))
80
+
81
+ # Anthropic
82
+ compressed = compress(messages, summarizer=build("anthropic"))
83
+
84
+ # Any callable (prompt: str) -> str
85
+ compressed = compress(messages, summarizer=my_summarizer)
86
+ ```
87
+
88
+ ## Configuration
89
+
90
+ ```python
91
+ compress(
92
+ messages,
93
+ preserve_recent=4, # turn-pairs to keep verbatim (default: 4)
94
+ min_turns_to_compress=6, # skip compression for short conversations (default: 6)
95
+ model="qwen3:4b", # Ollama model when no summarizer is given
96
+ summarizer=None, # custom callable: (prompt: str) -> str
97
+ )
98
+ ```
99
+
100
+ ## Adapter probe
101
+
102
+ ```python
103
+ from langstate.adapters import probe, REGISTRY
104
+
105
+ for name in REGISTRY:
106
+ print(probe(name))
107
+ # {"name": "local", "available": True, "latency_ms": 423, ...}
108
+ # {"name": "openai", "available": False, "reason": "OPENAI_API_KEY not set", ...}
109
+ ```
110
+
111
+ ## License
112
+
113
+ Apache-2.0
114
+
115
+ ---
116
+
117
+ ## About Hermes Labs
118
+
119
+ Hermes Labs builds AI audit infrastructure for teams deploying AI agents in regulated environments.
120
+ All tools are released as open-source software — MIT or Apache-2.0, no SaaS tier.
121
+ The audit work is paid; the code is not.
122
+
123
+ **hermes-labs.ai**
124
+
125
+ ### OSS audit stack
126
+
127
+ | Layer | Tool | Description |
128
+ |---|---|---|
129
+ | Static audit | [lintlang](https://github.com/hermes-labs-ai/lintlang) | Agent-config static lint (HERM + H1-H7) |
130
+ | Static audit | [rule-audit](https://github.com/hermes-labs-ai/rule-audit) | Rule-logic audit: contradictions + gaps |
131
+ | Static audit | [scaffold-lint](https://github.com/hermes-labs-ai/scaffold-lint) | Scaffold budget + technique stacking |
132
+ | Static audit | [intent-verify](https://github.com/hermes-labs-ai/intent-verify) | Spec-drift checks |
133
+ | Runtime observability | [little-canary](https://github.com/hermes-labs-ai/little-canary) | Prompt injection detection |
134
+ | Runtime observability | [suy-sideguy](https://github.com/hermes-labs-ai/suy-sideguy) | Runtime policy guard |
135
+ | Runtime observability | [colony-probe](https://github.com/hermes-labs-ai/colony-probe) | Prompt confidentiality audit |
136
+ | Regression & scoring | [hermes-jailbench](https://github.com/hermes-labs-ai/hermes-jailbench) | Jailbreak regression benchmark |
137
+ | Regression & scoring | [agent-convergence-scorer](https://github.com/hermes-labs-ai/agent-convergence-scorer) | N-agent output consistency |
138
+ | Supporting infra | [claude-router](https://github.com/hermes-labs-ai/claude-router) | Model-tier + scaffold router |
139
+ | Supporting infra | [quickthink](https://github.com/hermes-labs-ai/quickthink) | Compressed planning scaffold for local LLMs |
140
+ | Supporting infra | [langstate](https://github.com/hermes-labs-ai/langstate) | Scaffold-aware context compression |
141
+ | Supporting infra | [agent-gorgon](https://github.com/hermes-labs-ai/agent-gorgon) | Tool-fabrication defense for Claude Code |
142
+ | Supporting infra | [zer0dex](https://github.com/hermes-labs-ai/zer0dex) | Dual-layer agent memory |
143
+ | Supporting infra | [forgetted](https://github.com/hermes-labs-ai/forgetted) | Mid-conversation incognito |
144
+ | Dev tools | [repo-audit](https://github.com/hermes-labs-ai/repo-audit) | Launch-readiness auditor |
145
+ | Dev tools | [quick-gate-python](https://github.com/hermes-labs-ai/quick-gate-python) | Python quality gate |
146
+ | Dev tools | [quick-gate-js](https://github.com/hermes-labs-ai/quick-gate-js) | JS/TS quality gate |
147
+ | Dev tools | [csv-quality-gate](https://github.com/hermes-labs-ai/csv-quality-gate) | CSV preflight validation |
@@ -0,0 +1,9 @@
1
+ langstate/__init__.py,sha256=rgrweBSyxB3dQ5AlbxVpkhe90RJItlNIGqObX1f8mr4,64
2
+ langstate/adapters.py,sha256=YOk8qXPvErn4S2KSh67G-Z8lcmmhHrC4ApIEVo-pwo4,7966
3
+ langstate/compress.py,sha256=7yhaa1OlaF5zxlZ1ULCx7Cfqz4ekcDzV_MXHfu0QSEw,4761
4
+ langstate/te_check.py,sha256=ai1icyGxfNwhtQyC5hj07qjarTuT-8drfPu3hHzpw_0,6824
5
+ langstate-0.1.0.dist-info/licenses/LICENSE,sha256=byQ0qi2Jx3CViKco3sEN2obVtCQ71D_Pvb2ey2jqpq0,11401
6
+ langstate-0.1.0.dist-info/METADATA,sha256=sO0IkmldkVSwLX-6rM_Tgrcg9In5kHOZUqZvoy8cHvc,6237
7
+ langstate-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
8
+ langstate-0.1.0.dist-info/top_level.txt,sha256=KVIEF9lYidENBxqDf_U9CnrBf3JCAu_1DtGWSFbC3Ho,10
9
+ langstate-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,203 @@
1
+ Copyright 2026 Hermes Labs / Rolando Bosch
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright [yyyy] [name of copyright owner]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
@@ -0,0 +1 @@
1
+ langstate