ctxcache 0.3.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.
Files changed (50) hide show
  1. ctxcache/__init__.py +109 -0
  2. ctxcache/adapters/__init__.py +15 -0
  3. ctxcache/adapters/anthropic.py +34 -0
  4. ctxcache/adapters/base.py +25 -0
  5. ctxcache/adapters/bedrock.py +46 -0
  6. ctxcache/adapters/gemini.py +34 -0
  7. ctxcache/adapters/openai.py +42 -0
  8. ctxcache/bedrock_converse.py +67 -0
  9. ctxcache/bench/__init__.py +1 -0
  10. ctxcache/bench/runner.py +96 -0
  11. ctxcache/cli.py +326 -0
  12. ctxcache/compaction.py +102 -0
  13. ctxcache/cost.py +171 -0
  14. ctxcache/data/breaks.yaml +124 -0
  15. ctxcache/data/providers.toml +199 -0
  16. ctxcache/exceptions.py +23 -0
  17. ctxcache/fingerprint.py +68 -0
  18. ctxcache/guard.py +253 -0
  19. ctxcache/integrations/__init__.py +17 -0
  20. ctxcache/integrations/langchain.py +7 -0
  21. ctxcache/integrations/langgraph.py +144 -0
  22. ctxcache/integrations/openai_agents.py +42 -0
  23. ctxcache/integrations/pydantic_ai.py +44 -0
  24. ctxcache/layout.py +255 -0
  25. ctxcache/ledger.py +179 -0
  26. ctxcache/memory/__init__.py +25 -0
  27. ctxcache/memory/checks.py +53 -0
  28. ctxcache/memory/recall.py +50 -0
  29. ctxcache/memory/store.py +315 -0
  30. ctxcache/offload.py +134 -0
  31. ctxcache/openai_chat.py +61 -0
  32. ctxcache/otel.py +60 -0
  33. ctxcache/planner.py +167 -0
  34. ctxcache/policies/__init__.py +36 -0
  35. ctxcache/policies/route.py +179 -0
  36. ctxcache/replay.py +193 -0
  37. ctxcache/scenarios.py +250 -0
  38. ctxcache/segments.py +162 -0
  39. ctxcache/sim/__init__.py +13 -0
  40. ctxcache/sim/cache_sim.py +152 -0
  41. ctxcache/sim/tokens.py +56 -0
  42. ctxcache/testing.py +250 -0
  43. ctxcache/tools.py +49 -0
  44. ctxcache/trace.py +109 -0
  45. ctxcache/wrapper.py +609 -0
  46. ctxcache-0.3.0.dist-info/METADATA +218 -0
  47. ctxcache-0.3.0.dist-info/RECORD +50 -0
  48. ctxcache-0.3.0.dist-info/WHEEL +4 -0
  49. ctxcache-0.3.0.dist-info/entry_points.txt +2 -0
  50. ctxcache-0.3.0.dist-info/licenses/LICENSE +176 -0
ctxcache/__init__.py ADDED
@@ -0,0 +1,109 @@
1
+ """CtxCache: embeddable context engine that keeps an AI agent's prompt cache warm."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextvars
6
+ from collections.abc import Iterator
7
+ from contextlib import contextmanager
8
+ from typing import Literal, TypeVar
9
+
10
+ from ctxcache import memory, policies, tools
11
+ from ctxcache.exceptions import CtxCacheError, CtxCachePrefixBreak
12
+ from ctxcache.trace import TraceRecorder, get_trace_recorder
13
+
14
+ __version__ = "0.3.0"
15
+ __all__ = [
16
+ "wrap",
17
+ "session",
18
+ "volatile",
19
+ "tools",
20
+ "memory",
21
+ "policies",
22
+ "Mode",
23
+ "SessionContext",
24
+ "CtxCacheError",
25
+ "CtxCachePrefixBreak",
26
+ "get_trace_recorder",
27
+ "TraceRecorder",
28
+ ]
29
+
30
+ Mode = Literal["observe", "safe", "optimize"]
31
+
32
+
33
+ class SessionContext:
34
+ """Manages context and hints for a CtxCache-tracked agent session."""
35
+
36
+ def __init__(self, session_id: str, record: bool = False):
37
+ self.session_id = session_id
38
+ self.record = record
39
+ self._volatile_notes: list[str] = []
40
+ self._expected_pause: bool = False
41
+ self._expected_calls: int | None = None
42
+
43
+ def volatile(self, text: str) -> None:
44
+ """Add a volatile piece of text (e.g. timestamp, query snippet) to the tail."""
45
+ self._volatile_notes.append(text)
46
+
47
+ def pop_volatile(self) -> list[str]:
48
+ """Pop all pending volatile notes for inclusion in the upcoming turn."""
49
+ notes = list(self._volatile_notes)
50
+ self._volatile_notes.clear()
51
+ return notes
52
+
53
+ def expect_pause(self) -> None:
54
+ """Hint to planner that an upcoming human interaction or long tool pause is expected."""
55
+ self._expected_pause = True
56
+
57
+ def expect_calls(self, n: int) -> None:
58
+ """Hint to the planner the expected number of remaining calls."""
59
+ self._expected_calls = n
60
+
61
+
62
+ _current_session: contextvars.ContextVar[SessionContext | None] = contextvars.ContextVar(
63
+ "_current_session", default=None
64
+ )
65
+
66
+
67
+ @contextmanager
68
+ def session(name: str | None = None, record: bool = False) -> Iterator[SessionContext]:
69
+ """Context manager for an explicit CtxCache session."""
70
+ session_id = name or f"session-{id(object())}"
71
+ ctx = SessionContext(session_id=session_id, record=record)
72
+ token = _current_session.set(ctx)
73
+ try:
74
+ yield ctx
75
+ finally:
76
+ _current_session.reset(token)
77
+
78
+
79
+ def get_current_session() -> SessionContext | None:
80
+ return _current_session.get()
81
+
82
+
83
+ def volatile(text: str) -> None:
84
+ """Convenience helper to attach a volatile note to the active session."""
85
+ ctx = get_current_session()
86
+ if ctx is not None:
87
+ ctx.volatile(text)
88
+
89
+
90
+ T = TypeVar("T")
91
+
92
+
93
+ def wrap(
94
+ client: T,
95
+ mode: Mode = "safe",
96
+ record: bool = False,
97
+ strict: bool = False,
98
+ recorder: TraceRecorder | None = None,
99
+ ) -> T:
100
+ """Wrap a provider client with CtxCache context management.
101
+
102
+ The default mode is ``safe``: message and tool text stay the same.
103
+ Pass ``mode="observe"`` for a byte-identical first look, or
104
+ ``mode="optimize"`` to allow the documented layout moves.
105
+ """
106
+ from ctxcache.wrapper import WrappedClientProxy
107
+
108
+ proxy = WrappedClientProxy(client, mode=mode, record=record, strict=strict, recorder=recorder)
109
+ return proxy # type: ignore[return-value]
@@ -0,0 +1,15 @@
1
+ """Provider adapters package."""
2
+
3
+ from ctxcache.adapters.anthropic import parse_anthropic_usage
4
+ from ctxcache.adapters.base import NormalizedUsage
5
+ from ctxcache.adapters.bedrock import parse_bedrock_converse_usage
6
+ from ctxcache.adapters.gemini import parse_gemini_usage
7
+ from ctxcache.adapters.openai import parse_openai_usage
8
+
9
+ __all__ = [
10
+ "NormalizedUsage",
11
+ "parse_anthropic_usage",
12
+ "parse_bedrock_converse_usage",
13
+ "parse_openai_usage",
14
+ "parse_gemini_usage",
15
+ ]
@@ -0,0 +1,34 @@
1
+ """Anthropic usage parser and adapter (INV-06)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ctxcache.adapters.base import NormalizedUsage
8
+
9
+
10
+ def parse_anthropic_usage(usage_obj: Any) -> NormalizedUsage:
11
+ """Normalize Anthropic usage so read + write + uncached == input_tokens (INV-06)."""
12
+ raw: dict[str, Any] = {}
13
+ if hasattr(usage_obj, "model_dump"):
14
+ raw = usage_obj.model_dump()
15
+ elif isinstance(usage_obj, dict):
16
+ raw = usage_obj
17
+ else:
18
+ raw = {k: getattr(usage_obj, k) for k in dir(usage_obj) if not k.startswith("_")}
19
+
20
+ input_tokens = int(raw.get("input_tokens", 0) or 0)
21
+ read = int(raw.get("cache_read_input_tokens", 0) or 0)
22
+ write = int(raw.get("cache_creation_input_tokens", 0) or 0)
23
+ output = int(raw.get("output_tokens", 0) or 0)
24
+
25
+ uncached = max(0, input_tokens - read - write)
26
+
27
+ return NormalizedUsage(
28
+ read=read,
29
+ write=write,
30
+ uncached=uncached,
31
+ output=output,
32
+ total_input=input_tokens,
33
+ raw=raw,
34
+ )
@@ -0,0 +1,25 @@
1
+ """Base definitions for provider usage normalization (INV-06)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class NormalizedUsage:
11
+ """Canonical usage accounting where read + write + uncached == total_input (INV-06)."""
12
+
13
+ read: int
14
+ write: int
15
+ uncached: int
16
+ output: int
17
+ total_input: int
18
+ raw: dict[str, Any]
19
+
20
+ def __post_init__(self) -> None:
21
+ if self.read + self.write + self.uncached != self.total_input:
22
+ raise ValueError(
23
+ f"Usage does not reconcile: read ({self.read}) + write ({self.write}) + "
24
+ f"uncached ({self.uncached}) != total_input ({self.total_input})"
25
+ )
@@ -0,0 +1,46 @@
1
+ """Amazon Bedrock Converse usage parser (INV-06).
2
+
3
+ Converse reports the cache read, the cache write, and the uncached tail as
4
+ separate counts. ``inputTokens`` is the uncached tail, not the whole prompt.
5
+ ``totalTokens`` includes the output.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from ctxcache.adapters.base import NormalizedUsage
13
+
14
+
15
+ def _as_dict(usage_obj: Any) -> dict[str, Any]:
16
+ if isinstance(usage_obj, dict):
17
+ return usage_obj
18
+ if hasattr(usage_obj, "model_dump"):
19
+ dumped = usage_obj.model_dump()
20
+ if isinstance(dumped, dict):
21
+ return dumped
22
+ return {key: getattr(usage_obj, key) for key in dir(usage_obj) if not key.startswith("_")}
23
+
24
+
25
+ def _first_int(raw: dict[str, Any], *names: str) -> int:
26
+ for name in names:
27
+ if raw.get(name) is not None:
28
+ return int(raw[name] or 0)
29
+ return 0
30
+
31
+
32
+ def parse_bedrock_converse_usage(usage_obj: Any) -> NormalizedUsage:
33
+ """Normalize a Converse usage object so read + write + uncached is the input total."""
34
+ raw = _as_dict(usage_obj)
35
+ read = _first_int(raw, "cacheReadInputTokens", "cacheReadInputTokenCount")
36
+ write = _first_int(raw, "cacheWriteInputTokens", "cacheWriteInputTokenCount")
37
+ uncached = _first_int(raw, "inputTokens")
38
+ output = _first_int(raw, "outputTokens")
39
+ return NormalizedUsage(
40
+ read=read,
41
+ write=write,
42
+ uncached=uncached,
43
+ output=output,
44
+ total_input=read + write + uncached,
45
+ raw=raw,
46
+ )
@@ -0,0 +1,34 @@
1
+ """Gemini usage parser and adapter (INV-06)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ctxcache.adapters.base import NormalizedUsage
8
+
9
+
10
+ def parse_gemini_usage(usage_obj: Any) -> NormalizedUsage:
11
+ """Normalize Gemini usage so read + write + uncached == prompt_token_count (INV-06)."""
12
+ raw: dict[str, Any] = {}
13
+ if hasattr(usage_obj, "model_dump"):
14
+ raw = usage_obj.model_dump()
15
+ elif isinstance(usage_obj, dict):
16
+ raw = usage_obj
17
+ else:
18
+ raw = {k: getattr(usage_obj, k) for k in dir(usage_obj) if not k.startswith("_")}
19
+
20
+ prompt_tokens = int(raw.get("prompt_token_count", raw.get("promptTokenCount", 0)) or 0)
21
+ read = int(raw.get("cached_content_token_count", raw.get("cachedContentTokenCount", 0)) or 0)
22
+ output = int(raw.get("candidates_token_count", raw.get("candidatesTokenCount", 0)) or 0)
23
+
24
+ write = 0
25
+ uncached = max(0, prompt_tokens - read)
26
+
27
+ return NormalizedUsage(
28
+ read=read,
29
+ write=write,
30
+ uncached=uncached,
31
+ output=output,
32
+ total_input=prompt_tokens,
33
+ raw=raw,
34
+ )
@@ -0,0 +1,42 @@
1
+ """OpenAI usage parser and adapter (INV-06)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from ctxcache.adapters.base import NormalizedUsage
8
+
9
+
10
+ def parse_openai_usage(usage_obj: Any) -> NormalizedUsage:
11
+ """Normalize OpenAI usage so read + write + uncached == prompt_tokens (INV-06)."""
12
+ raw: dict[str, Any] = {}
13
+ if hasattr(usage_obj, "model_dump"):
14
+ raw = usage_obj.model_dump()
15
+ elif isinstance(usage_obj, dict):
16
+ raw = usage_obj
17
+ else:
18
+ raw = {k: getattr(usage_obj, k) for k in dir(usage_obj) if not k.startswith("_")}
19
+
20
+ prompt_tokens = int(raw.get("prompt_tokens", 0) or 0)
21
+ output = int(raw.get("completion_tokens", 0) or 0)
22
+
23
+ # Read tokens from prompt_tokens_details.cached_tokens
24
+ details = raw.get("prompt_tokens_details", {})
25
+ if isinstance(details, dict):
26
+ read = int(details.get("cached_tokens", 0) or 0)
27
+ elif hasattr(details, "cached_tokens"):
28
+ read = int(getattr(details, "cached_tokens", 0) or 0)
29
+ else:
30
+ read = 0
31
+
32
+ write = int(raw.get("cache_write_tokens", 0) or 0)
33
+ uncached = max(0, prompt_tokens - read - write)
34
+
35
+ return NormalizedUsage(
36
+ read=read,
37
+ write=write,
38
+ uncached=uncached,
39
+ output=output,
40
+ total_input=prompt_tokens,
41
+ raw=raw,
42
+ )
@@ -0,0 +1,67 @@
1
+ """Stdlib client for the Amazon Bedrock Converse API.
2
+
3
+ The API key is a bearer token and is never written to the ledger.
4
+ ``session_id`` is a CtxCache argument and is not sent.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import urllib.error
11
+ import urllib.request
12
+ from types import SimpleNamespace
13
+ from typing import Any
14
+
15
+ _BODY_KEYS = {"system", "messages", "inferenceConfig", "toolConfig"}
16
+ _CONVERSE_HOST = "https://bedrock-runtime.us-east-1.amazonaws.com"
17
+
18
+
19
+ def converse_endpoint(raw: str | None) -> str:
20
+ """Host for the Converse API.
21
+
22
+ A URL ending in ``/v1/chat/completions`` or ``/openai/v1/chat/completions``
23
+ is a different operation. Those paths are not used for Nova.
24
+ """
25
+ if not raw or not raw.strip():
26
+ return _CONVERSE_HOST
27
+ cleaned = raw.strip().rstrip("/")
28
+ if cleaned.endswith("/v1/chat/completions"):
29
+ return _CONVERSE_HOST
30
+ return cleaned
31
+
32
+
33
+ class BedrockConverse:
34
+ """Posts to ``{endpoint}/model/{modelId}/converse``."""
35
+
36
+ def __init__(self, endpoint: str, api_key: str) -> None:
37
+ self._endpoint = endpoint.rstrip("/")
38
+ self._api_key = api_key
39
+ self.last_payload: dict[str, Any] | None = None
40
+
41
+ def create(self, **kwargs: Any) -> SimpleNamespace:
42
+ model = str(kwargs.get("model", ""))
43
+ if not model:
44
+ raise RuntimeError("Bedrock Converse requires a model id")
45
+ payload = {key: value for key, value in kwargs.items() if key in _BODY_KEYS}
46
+ self.last_payload = payload
47
+ url = f"{self._endpoint}/model/{model}/converse"
48
+ request = urllib.request.Request(
49
+ url,
50
+ data=json.dumps(payload).encode(),
51
+ headers={
52
+ "Authorization": f"Bearer {self._api_key}",
53
+ "Content-Type": "application/json",
54
+ },
55
+ method="POST",
56
+ )
57
+ try:
58
+ with urllib.request.urlopen(request, timeout=120) as response:
59
+ raw = response.read().decode()
60
+ except urllib.error.HTTPError as exc:
61
+ detail = exc.read().decode(errors="replace")[:500]
62
+ raise RuntimeError(f"Bedrock Converse HTTP {exc.code}: {detail}") from exc
63
+ data = json.loads(raw)
64
+ if "error" in data:
65
+ raise RuntimeError(f"Bedrock Converse error: {data['error']}")
66
+ usage = data.get("usage") or {}
67
+ return SimpleNamespace(usage=usage, raw=data)
@@ -0,0 +1 @@
1
+ """CtxCache benchmarking and evaluation package."""
@@ -0,0 +1,96 @@
1
+ """Bench runner module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+
9
+ from bench.m0.runner import run_m0_kill_test
10
+ from bench.m2.runner import run_m2_benchmark
11
+ from bench.m3.runner import run_m3_benchmark
12
+ from bench.m4.runner import run_m4_benchmark
13
+ from bench.m5.runner import run_m5_benchmark
14
+ from bench.m6.runner import run_m6_benchmark
15
+
16
+
17
+ def main() -> None:
18
+ parser = argparse.ArgumentParser(description="CtxCache Benchmark Runner")
19
+ parser.add_argument("--m0", action="store_true", help="Run M0 kill test suite")
20
+ parser.add_argument("--m2", action="store_true", help="Run M2 benchmark suite")
21
+ parser.add_argument("--m3", action="store_true", help="Run M3 benchmark suite")
22
+ parser.add_argument("--m4", action="store_true", help="Run M4 benchmark suite")
23
+ parser.add_argument("--m5", action="store_true", help="Run M5 benchmark suite")
24
+ parser.add_argument("--m6", action="store_true", help="Run M6 benchmark suite")
25
+ parser.add_argument(
26
+ "--report", action="store_true", help="Generate/freeze Cache Efficiency Report"
27
+ )
28
+ parser.add_argument("--verify", action="store_true", help="Verify gate conditions")
29
+ args = parser.parse_args()
30
+
31
+ if args.m0:
32
+ summary = run_m0_kill_test()
33
+ print("\n" + json.dumps(summary, indent=2))
34
+ if args.verify:
35
+ if "GO" in summary.get("decision", ""):
36
+ print("\n[VERIFICATION PASSED] M0 Kill Test Decision: GO")
37
+ sys.exit(0)
38
+ else:
39
+ print(f"\n[VERIFICATION FAILED] Decision: {summary.get('decision')}")
40
+ sys.exit(1)
41
+ elif args.m2:
42
+ m2_summary = run_m2_benchmark()
43
+ print("\n" + json.dumps(m2_summary, indent=2))
44
+ if args.verify:
45
+ if m2_summary.get("gate_verified", False):
46
+ print("\n[VERIFICATION PASSED] M2 Benchmark Gate: VERIFIED")
47
+ sys.exit(0)
48
+ else:
49
+ print("\n[VERIFICATION FAILED] M2 Benchmark Gate conditions not met")
50
+ sys.exit(1)
51
+ elif args.m3:
52
+ m3_summary = run_m3_benchmark()
53
+ print("\n" + json.dumps(m3_summary, indent=2))
54
+ if args.verify:
55
+ if m3_summary.get("gate_verified", False):
56
+ print("\n[VERIFICATION PASSED] M3 Benchmark Gate: VERIFIED")
57
+ sys.exit(0)
58
+ else:
59
+ print("\n[VERIFICATION FAILED] M3 Benchmark Gate conditions not met")
60
+ sys.exit(1)
61
+ elif args.m4 or args.report:
62
+ m4_summary = run_m4_benchmark()
63
+ print("\n" + json.dumps(m4_summary, indent=2))
64
+ if args.verify:
65
+ if m4_summary.get("gate_verified", False):
66
+ print("\n[VERIFICATION PASSED] M4 Benchmark Gate: VERIFIED")
67
+ sys.exit(0)
68
+ else:
69
+ print("\n[VERIFICATION FAILED] M4 Benchmark Gate conditions not met")
70
+ sys.exit(1)
71
+ elif args.m5:
72
+ m5_summary = run_m5_benchmark()
73
+ print("\n" + json.dumps(m5_summary, indent=2))
74
+ if args.verify:
75
+ if m5_summary.get("gate_verified", False):
76
+ print("\n[VERIFICATION PASSED] M5 Benchmark Gate: VERIFIED")
77
+ sys.exit(0)
78
+ else:
79
+ print("\n[VERIFICATION FAILED] M5 Benchmark Gate conditions not met")
80
+ sys.exit(1)
81
+ elif args.m6:
82
+ m6_summary = run_m6_benchmark()
83
+ print("\n" + json.dumps(m6_summary, indent=2))
84
+ if args.verify:
85
+ if m6_summary.get("gate_verified", False):
86
+ print("\n[VERIFICATION PASSED] M6 Benchmark Gate: VERIFIED")
87
+ sys.exit(0)
88
+ else:
89
+ print("\n[VERIFICATION FAILED] M6 Benchmark Gate conditions not met")
90
+ sys.exit(1)
91
+ else:
92
+ print("CtxCache Benchmark Runner: specify --m0, --m2, --m3, --m4, --m5, or --m6.")
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()