maf-cachebench 0.3.0__tar.gz → 0.4.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.
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/PKG-INFO +32 -2
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/README.md +28 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/pyproject.toml +4 -2
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/pyproject.toml.orig +4 -4
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/__init__.py +3 -1
- maf_cachebench-0.4.0/src/maf_cachebench/_behavior.py +62 -0
- maf_cachebench-0.4.0/src/maf_cachebench/_configuration.py +167 -0
- maf_cachebench-0.4.0/src/maf_cachebench/_diagnostics.py +98 -0
- maf_cachebench-0.4.0/src/maf_cachebench/_lifecycle.py +229 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_live.py +151 -119
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_live_cli.py +22 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_records.py +12 -2
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_strategies.py +9 -2
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/LICENSE +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/__main__.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_advise_cli.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_advisor.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_cli.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_cli_selection.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_fill.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_metrics.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_providers.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_recall.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_recall_cli.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_report.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_run_identity.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_runner.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_summary.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_summary_cli.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_tokenizers.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_transcripts.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/_types.py +0 -0
- {maf_cachebench-0.3.0 → maf_cachebench-0.4.0}/src/maf_cachebench/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: maf-cachebench
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Benchmark for Microsoft Agent Framework compaction strategies: what each one costs in prompt-cache hits and what it loses, measured on a replayed conversation or a live agent.
|
|
5
5
|
Keywords: benchmark,compaction,prompt-cache,agent-framework,microsoft-agent-framework
|
|
6
6
|
Author: SOKOLAI BV
|
|
@@ -16,15 +16,17 @@ Classifier: Programming Language :: Python :: 3.13
|
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.14
|
|
17
17
|
Classifier: Topic :: Software Development :: Testing
|
|
18
18
|
Requires-Dist: agent-framework-core>=1.22.0,<1.23
|
|
19
|
-
Requires-Dist: maf-compaction>=0.
|
|
19
|
+
Requires-Dist: maf-compaction>=0.8.0,<0.9
|
|
20
20
|
Requires-Dist: httpx>=0.27,<1
|
|
21
21
|
Requires-Dist: agent-framework-foundry>=1.15.0,<2 ; extra == 'foundry'
|
|
22
22
|
Requires-Dist: azure-identity>=1.17,<2 ; extra == 'foundry'
|
|
23
|
+
Requires-Dist: aiohttp>=3.9,<4 ; extra == 'foundry'
|
|
23
24
|
Requires-Dist: agent-framework-mistral>=1.0.0b261015,<2 ; extra == 'mistral'
|
|
24
25
|
Requires-Dist: agent-framework-ollama>=1.0.0b261015,<2 ; extra == 'ollama'
|
|
25
26
|
Requires-Dist: ollama>=0.5.3,<0.6 ; extra == 'ollama'
|
|
26
27
|
Requires-Dist: agent-framework-openai>=1.17.0,<2 ; extra == 'openai'
|
|
27
28
|
Requires-Dist: azure-identity>=1.17,<2 ; extra == 'openai'
|
|
29
|
+
Requires-Dist: aiohttp>=3.9,<4 ; extra == 'openai'
|
|
28
30
|
Requires-Dist: tiktoken>=0.8,<1 ; extra == 'tiktoken'
|
|
29
31
|
Requires-Python: >=3.12, <3.15
|
|
30
32
|
Project-URL: Homepage, https://www.sokol.ai
|
|
@@ -100,6 +102,34 @@ cachebench_live --from-jsonl runs/cell.jsonl
|
|
|
100
102
|
|
|
101
103
|
`--results-jsonl` is not optional in practice: a cell runs for hours, and the file is appended one record per seed the moment it is scored, so a stopped run keeps what it paid for. `--from-jsonl` rebuilds the table and the verdict from the records with no provider configured, and files that measured the same cell merge into one table.
|
|
102
104
|
|
|
105
|
+
## Compaction controls and session experiments
|
|
106
|
+
|
|
107
|
+
`cachebench_live` supports `maf-compaction>=0.8.0,<0.9`, including the `SessionPersistence` API used by record-bearing `roundtrip` and `restart` experiments. Persistence support is checked before any model calls.
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
cachebench_live foundry:gpt-5.6-luna --dry-run \
|
|
111
|
+
--strategies none,tool_and_user_summary_anchored --summarizer-provider foundry:gpt-5.6-luna \
|
|
112
|
+
--preserve-prompt-cache --session-mode restart --history-mode replay --stream \
|
|
113
|
+
--max-summary-input-tokens 12000 --summary-input-policy chunk \
|
|
114
|
+
--summary-options-json '{"max_tokens": 1024}' --summary-timeout-seconds 60
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
| Area | Controls |
|
|
118
|
+
|---|---|
|
|
119
|
+
| Recall | `--preserve-prompt-cache`, `--record-instruction`, `--no-supports-tool-choice`, `--forced-call-timeout-seconds`, `--min-groups-before-repeat` |
|
|
120
|
+
| Summary input | `--max-summary-input-tokens`, `--summary-input-policy skip\|chunk`, `--chunk-cache-size` (zero disables the cache) |
|
|
121
|
+
| Summary requests | `--summary-options-json`, `--retry-without-summary-options`, `--summary-timeout-seconds` |
|
|
122
|
+
| Summary backoff | `--max-consecutive-summary-failures` and `--summary-backoff-seconds`, set together |
|
|
123
|
+
| Summary prompts | `--user-summary-prompt`, `--user-fold-prompt`, `--record-merge-prompt` |
|
|
124
|
+
| Composed overflow | `--overflow-policy shed\|raise`, `--estimate-margin` |
|
|
125
|
+
| Request lifecycle | `--session-mode memory\|roundtrip\|restart`, `--history-mode incremental\|replay`, `--stream` |
|
|
126
|
+
|
|
127
|
+
`roundtrip` serializes and reloads the whole framework session between requests. `restart` also reconstructs the agent and compaction objects. Record-bearing strategies use the native persistence adapter with detached JSON snapshots and an exclusive local lease, saving only completed requests; other strategies restore their available decision state. These experiments use an in-memory store and rebuild objects in the same process: they do not measure disk latency, process crashes or distributed locking. `replay` resubmits the original conversation, including previously summarized messages, so replayed summaries and restored recall identities are exercised without duplicating stored history. `--stream` consumes the complete response within the persistence lifetime.
|
|
128
|
+
|
|
129
|
+
Programmatic callers pass `CompactionOptions(...)` through `StrategyOptions(compaction=...)`. Existing record, user-summary, fold, coverage and chain controls remain available. Each option and the installed CacheBench, compaction and framework versions become part of the recorded cell identity. Schema 23 records also contain `compaction_diagnostics`, including forced-call failures, ignored pins, summary replay/skips and final recall-disabled state. Older records remain readable with unknown new settings and diagnostics; they are grouped separately.
|
|
130
|
+
|
|
131
|
+
Each completed provider attempt is metered, including an attempt rejected and retried by recall middleware. Independent probes restore the complete supported strategy, middleware and gate state, including pin disablement and summary backoff. Costs from older schemas can undercount internal retries and should not be pooled with new runs.
|
|
132
|
+
|
|
103
133
|
## Reading the table
|
|
104
134
|
|
|
105
135
|
Rows that keep at least `--min-correctness` of the control's accuracy come first, cheapest first; the rest follow below a line. The columns to read, in order:
|
|
@@ -61,6 +61,34 @@ cachebench_live --from-jsonl runs/cell.jsonl
|
|
|
61
61
|
|
|
62
62
|
`--results-jsonl` is not optional in practice: a cell runs for hours, and the file is appended one record per seed the moment it is scored, so a stopped run keeps what it paid for. `--from-jsonl` rebuilds the table and the verdict from the records with no provider configured, and files that measured the same cell merge into one table.
|
|
63
63
|
|
|
64
|
+
## Compaction controls and session experiments
|
|
65
|
+
|
|
66
|
+
`cachebench_live` supports `maf-compaction>=0.8.0,<0.9`, including the `SessionPersistence` API used by record-bearing `roundtrip` and `restart` experiments. Persistence support is checked before any model calls.
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
cachebench_live foundry:gpt-5.6-luna --dry-run \
|
|
70
|
+
--strategies none,tool_and_user_summary_anchored --summarizer-provider foundry:gpt-5.6-luna \
|
|
71
|
+
--preserve-prompt-cache --session-mode restart --history-mode replay --stream \
|
|
72
|
+
--max-summary-input-tokens 12000 --summary-input-policy chunk \
|
|
73
|
+
--summary-options-json '{"max_tokens": 1024}' --summary-timeout-seconds 60
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
| Area | Controls |
|
|
77
|
+
|---|---|
|
|
78
|
+
| Recall | `--preserve-prompt-cache`, `--record-instruction`, `--no-supports-tool-choice`, `--forced-call-timeout-seconds`, `--min-groups-before-repeat` |
|
|
79
|
+
| Summary input | `--max-summary-input-tokens`, `--summary-input-policy skip\|chunk`, `--chunk-cache-size` (zero disables the cache) |
|
|
80
|
+
| Summary requests | `--summary-options-json`, `--retry-without-summary-options`, `--summary-timeout-seconds` |
|
|
81
|
+
| Summary backoff | `--max-consecutive-summary-failures` and `--summary-backoff-seconds`, set together |
|
|
82
|
+
| Summary prompts | `--user-summary-prompt`, `--user-fold-prompt`, `--record-merge-prompt` |
|
|
83
|
+
| Composed overflow | `--overflow-policy shed\|raise`, `--estimate-margin` |
|
|
84
|
+
| Request lifecycle | `--session-mode memory\|roundtrip\|restart`, `--history-mode incremental\|replay`, `--stream` |
|
|
85
|
+
|
|
86
|
+
`roundtrip` serializes and reloads the whole framework session between requests. `restart` also reconstructs the agent and compaction objects. Record-bearing strategies use the native persistence adapter with detached JSON snapshots and an exclusive local lease, saving only completed requests; other strategies restore their available decision state. These experiments use an in-memory store and rebuild objects in the same process: they do not measure disk latency, process crashes or distributed locking. `replay` resubmits the original conversation, including previously summarized messages, so replayed summaries and restored recall identities are exercised without duplicating stored history. `--stream` consumes the complete response within the persistence lifetime.
|
|
87
|
+
|
|
88
|
+
Programmatic callers pass `CompactionOptions(...)` through `StrategyOptions(compaction=...)`. Existing record, user-summary, fold, coverage and chain controls remain available. Each option and the installed CacheBench, compaction and framework versions become part of the recorded cell identity. Schema 23 records also contain `compaction_diagnostics`, including forced-call failures, ignored pins, summary replay/skips and final recall-disabled state. Older records remain readable with unknown new settings and diagnostics; they are grouped separately.
|
|
89
|
+
|
|
90
|
+
Each completed provider attempt is metered, including an attempt rejected and retried by recall middleware. Independent probes restore the complete supported strategy, middleware and gate state, including pin disablement and summary backoff. Costs from older schemas can undercount internal retries and should not be pooled with new runs.
|
|
91
|
+
|
|
64
92
|
## Reading the table
|
|
65
93
|
|
|
66
94
|
Rows that keep at least `--min-correctness` of the control's accuracy come first, cheapest first; the rest follow below a line. The columns to read, in order:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "maf-cachebench"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.4.0"
|
|
4
4
|
description = "Benchmark for Microsoft Agent Framework compaction strategies: what each one costs in prompt-cache hits and what it loses, measured on a replayed conversation or a live agent."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.12,<3.15"
|
|
@@ -25,7 +25,7 @@ classifiers = [
|
|
|
25
25
|
]
|
|
26
26
|
dependencies = [
|
|
27
27
|
"agent-framework-core>=1.22.0,<1.23",
|
|
28
|
-
"maf-compaction>=0.
|
|
28
|
+
"maf-compaction>=0.8.0,<0.9",
|
|
29
29
|
"httpx>=0.27,<1",
|
|
30
30
|
]
|
|
31
31
|
|
|
@@ -37,10 +37,12 @@ email = "info@sokolai.com"
|
|
|
37
37
|
openai = [
|
|
38
38
|
"agent-framework-openai>=1.17.0,<2",
|
|
39
39
|
"azure-identity>=1.17,<2",
|
|
40
|
+
"aiohttp>=3.9,<4",
|
|
40
41
|
]
|
|
41
42
|
foundry = [
|
|
42
43
|
"agent-framework-foundry>=1.15.0,<2",
|
|
43
44
|
"azure-identity>=1.17,<2",
|
|
45
|
+
"aiohttp>=3.9,<4",
|
|
44
46
|
]
|
|
45
47
|
mistral = ["agent-framework-mistral>=1.0.0b261015,<2"]
|
|
46
48
|
ollama = [
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "maf-cachebench"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.4.0"
|
|
4
4
|
description = "Benchmark for Microsoft Agent Framework compaction strategies: what each one costs in prompt-cache hits and what it loses, measured on a replayed conversation or a live agent."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.12,<3.15"
|
|
@@ -29,7 +29,7 @@ dependencies = [
|
|
|
29
29
|
# read; the same minor as maf-compaction pins, for the same reason.
|
|
30
30
|
"agent-framework-core>=1.22.0,<1.23",
|
|
31
31
|
# The record strategy must accept the same target as the recall tool.
|
|
32
|
-
"maf-compaction>=0.
|
|
32
|
+
"maf-compaction>=0.8.0,<0.9",
|
|
33
33
|
# Model prices are fetched from OpenRouter for the advisor's cost table.
|
|
34
34
|
"httpx>=0.27,<1",
|
|
35
35
|
]
|
|
@@ -38,8 +38,8 @@ dependencies = [
|
|
|
38
38
|
# One extra per provider route; a run needs only the client it points at. The floors are the
|
|
39
39
|
# client versions qualified with the framework band; the Mistral and Ollama clients
|
|
40
40
|
# have only pre-release versions on the index, so their floors name one.
|
|
41
|
-
openai = ["agent-framework-openai>=1.17.0,<2", "azure-identity>=1.17,<2"]
|
|
42
|
-
foundry = ["agent-framework-foundry>=1.15.0,<2", "azure-identity>=1.17,<2"]
|
|
41
|
+
openai = ["agent-framework-openai>=1.17.0,<2", "azure-identity>=1.17,<2", "aiohttp>=3.9,<4"]
|
|
42
|
+
foundry = ["agent-framework-foundry>=1.15.0,<2", "azure-identity>=1.17,<2", "aiohttp>=3.9,<4"]
|
|
43
43
|
mistral = ["agent-framework-mistral>=1.0.0b261015,<2"]
|
|
44
44
|
# The Ollama route builds the client's own async HTTP client, so that package is named too.
|
|
45
45
|
ollama = ["agent-framework-ollama>=1.0.0b261015,<2", "ollama>=0.5.3,<0.6"]
|
|
@@ -16,6 +16,7 @@ import importlib.metadata
|
|
|
16
16
|
from ._advise_cli import main as advise_main
|
|
17
17
|
from ._advisor import ModelPricing, StrategyCost, Verdict, advise, cost_of, fetch_openrouter_pricing
|
|
18
18
|
from ._cli import build_parser, main, run_benchmark
|
|
19
|
+
from ._configuration import CompactionOptions
|
|
19
20
|
from ._fill import FillPlan, plan_fill
|
|
20
21
|
from ._live import (
|
|
21
22
|
AGENT_KINDS,
|
|
@@ -107,9 +108,10 @@ from ._types import CellKey, CellSummary, Transcript, TranscriptTurn, TurnRecord
|
|
|
107
108
|
try:
|
|
108
109
|
__version__ = importlib.metadata.version(__name__)
|
|
109
110
|
except importlib.metadata.PackageNotFoundError:
|
|
110
|
-
__version__ = "0.
|
|
111
|
+
__version__ = "0.4.0" # Fallback for development mode
|
|
111
112
|
|
|
112
113
|
__all__ = [
|
|
114
|
+
"CompactionOptions",
|
|
113
115
|
"AGENT_KINDS",
|
|
114
116
|
"DEFAULT_COMBINED_REPEATS",
|
|
115
117
|
"DEFAULT_PROBE_REPEATS",
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Detached behavioral snapshots for independent probes and request retries."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from copy import deepcopy
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, cast
|
|
9
|
+
|
|
10
|
+
from maf_compaction import RecallGate, ToolResultRecallMiddleware
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class BehaviorSnapshot:
|
|
15
|
+
"""Behavioral state, excluding cumulative measurement counters where the API permits."""
|
|
16
|
+
|
|
17
|
+
strategy: Any
|
|
18
|
+
session_state: bool
|
|
19
|
+
recall: dict[str, Any] | None
|
|
20
|
+
gate: dict[str, Any] | None
|
|
21
|
+
encoded_decisions: bool = False
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def snapshot_behavior(strategy: Any, recall: ToolResultRecallMiddleware | None) -> BehaviorSnapshot:
|
|
25
|
+
"""Copy every public behavioral surface supported by the installed strategy."""
|
|
26
|
+
take = getattr(strategy, "session_state", None)
|
|
27
|
+
session_state = callable(take)
|
|
28
|
+
if not session_state:
|
|
29
|
+
take = getattr(strategy, "decision_state", None)
|
|
30
|
+
state = take() if callable(take) else None
|
|
31
|
+
serialize = getattr(state, "to_dict", None)
|
|
32
|
+
encoded = not session_state and callable(serialize)
|
|
33
|
+
if encoded and callable(serialize):
|
|
34
|
+
state = serialize()
|
|
35
|
+
gate = getattr(recall.arm, "__self__", None) if recall is not None else None
|
|
36
|
+
return BehaviorSnapshot(
|
|
37
|
+
deepcopy(state),
|
|
38
|
+
session_state,
|
|
39
|
+
json.loads(json.dumps(recall.session_state())) if recall is not None else None,
|
|
40
|
+
gate.session_state() if isinstance(gate, RecallGate) else None,
|
|
41
|
+
encoded,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def restore_behavior(
|
|
46
|
+
strategy: Any, recall: ToolResultRecallMiddleware | None, snapshot: BehaviorSnapshot
|
|
47
|
+
) -> None:
|
|
48
|
+
"""Restore a snapshot into either the original objects or a freshly constructed stack."""
|
|
49
|
+
if snapshot.strategy is not None:
|
|
50
|
+
state = deepcopy(snapshot.strategy)
|
|
51
|
+
if snapshot.session_state:
|
|
52
|
+
strategy.restore_session_state(state)
|
|
53
|
+
elif snapshot.encoded_decisions:
|
|
54
|
+
strategy.restore_decisions(cast(Any, type(strategy.decision_state())).from_dict(state))
|
|
55
|
+
else:
|
|
56
|
+
strategy.restore_decisions(state)
|
|
57
|
+
if recall is not None and snapshot.recall is not None:
|
|
58
|
+
recall.forget_pending()
|
|
59
|
+
recall.restore_session_state(json.loads(json.dumps(snapshot.recall)))
|
|
60
|
+
gate = getattr(recall.arm, "__self__", None)
|
|
61
|
+
if isinstance(gate, RecallGate) and snapshot.gate is not None:
|
|
62
|
+
gate.restore_session_state(dict(snapshot.gate))
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Serializable controls for recall, summaries and session lifecycle experiments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
from dataclasses import dataclass, fields
|
|
8
|
+
from math import isfinite
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import maf_compaction
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True, slots=True)
|
|
15
|
+
class CompactionOptions:
|
|
16
|
+
"""Controls shared by the live runner, its CLI and recorded cell identity."""
|
|
17
|
+
|
|
18
|
+
preserve_prompt_cache: bool = False
|
|
19
|
+
record_instruction: str | None = None
|
|
20
|
+
supports_tool_choice: bool = True
|
|
21
|
+
forced_call_timeout_seconds: float | None = None
|
|
22
|
+
min_groups_before_repeat: int = 4
|
|
23
|
+
max_summary_input_tokens: int | None = None
|
|
24
|
+
summary_timeout_seconds: float | None = None
|
|
25
|
+
summary_input_policy: str = "skip"
|
|
26
|
+
summary_options_json: str = "{}"
|
|
27
|
+
retry_without_summary_options: bool = False
|
|
28
|
+
chunk_cache_size: int = 128
|
|
29
|
+
max_consecutive_summary_failures: int | None = None
|
|
30
|
+
summary_backoff_seconds: float | None = None
|
|
31
|
+
overflow_policy: str = "shed"
|
|
32
|
+
estimate_margin: float = 0.0
|
|
33
|
+
user_summary_prompt: str | None = None
|
|
34
|
+
user_fold_prompt: str | None = None
|
|
35
|
+
record_merge_prompt: str | None = None
|
|
36
|
+
session_mode: str = "memory"
|
|
37
|
+
history_mode: str = "incremental"
|
|
38
|
+
stream: bool = False
|
|
39
|
+
|
|
40
|
+
def __post_init__(self) -> None:
|
|
41
|
+
"""Reject invalid controls before a provider is contacted."""
|
|
42
|
+
for name in (
|
|
43
|
+
"forced_call_timeout_seconds",
|
|
44
|
+
"min_groups_before_repeat",
|
|
45
|
+
"max_summary_input_tokens",
|
|
46
|
+
"summary_timeout_seconds",
|
|
47
|
+
"max_consecutive_summary_failures",
|
|
48
|
+
"summary_backoff_seconds",
|
|
49
|
+
):
|
|
50
|
+
value = getattr(self, name)
|
|
51
|
+
if value is not None and (isinstance(value, bool) or not isfinite(value) or value <= 0):
|
|
52
|
+
raise ValueError(f"{name} must be positive and finite, or None.")
|
|
53
|
+
if type(self.chunk_cache_size) is not int or self.chunk_cache_size < 0:
|
|
54
|
+
raise ValueError("chunk_cache_size must be a non-negative integer.")
|
|
55
|
+
if (self.max_consecutive_summary_failures is None) != (
|
|
56
|
+
self.summary_backoff_seconds is None
|
|
57
|
+
):
|
|
58
|
+
raise ValueError(
|
|
59
|
+
"Set max_consecutive_summary_failures and summary_backoff_seconds together."
|
|
60
|
+
)
|
|
61
|
+
for name, choices in (
|
|
62
|
+
("summary_input_policy", ("skip", "chunk")),
|
|
63
|
+
("overflow_policy", ("shed", "raise")),
|
|
64
|
+
("session_mode", ("memory", "roundtrip", "restart")),
|
|
65
|
+
("history_mode", ("incremental", "replay")),
|
|
66
|
+
):
|
|
67
|
+
if getattr(self, name) not in choices:
|
|
68
|
+
raise ValueError(f"{name} must be one of {choices}.")
|
|
69
|
+
if not isfinite(self.estimate_margin) or not 0 <= self.estimate_margin < 1:
|
|
70
|
+
raise ValueError("estimate_margin must be finite and in [0, 1).")
|
|
71
|
+
options = json.loads(self.summary_options_json)
|
|
72
|
+
if not isinstance(options, dict):
|
|
73
|
+
raise ValueError("summary_options_json must contain a JSON object.")
|
|
74
|
+
object.__setattr__(
|
|
75
|
+
self, "summary_options_json", json.dumps(options, sort_keys=True, allow_nan=False)
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
def summary_kwargs(self) -> dict[str, Any]:
|
|
79
|
+
"""Return the user-summary constructor controls."""
|
|
80
|
+
return {
|
|
81
|
+
name: getattr(self, name)
|
|
82
|
+
for name in (
|
|
83
|
+
"max_summary_input_tokens",
|
|
84
|
+
"summary_timeout_seconds",
|
|
85
|
+
"summary_input_policy",
|
|
86
|
+
"retry_without_summary_options",
|
|
87
|
+
"chunk_cache_size",
|
|
88
|
+
"max_consecutive_summary_failures",
|
|
89
|
+
"summary_backoff_seconds",
|
|
90
|
+
)
|
|
91
|
+
} | {
|
|
92
|
+
"summary_options": json.loads(self.summary_options_json),
|
|
93
|
+
"prompt": self.user_summary_prompt,
|
|
94
|
+
"fold_prompt": self.user_fold_prompt,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def add_compaction_arguments(parser: argparse.ArgumentParser) -> None:
|
|
99
|
+
"""Expose the serialized controls without a separate set of CLI defaults."""
|
|
100
|
+
group = parser.add_argument_group("compaction behavior and session lifecycle")
|
|
101
|
+
help_text = {
|
|
102
|
+
"preserve_prompt_cache": "Keep recall guidance stable across ordinary and forced turns.",
|
|
103
|
+
"record_instruction": "Custom recall instruction sent to the model.",
|
|
104
|
+
"supports_tool_choice": "Whether the model supports forcing a named recall tool.",
|
|
105
|
+
"forced_call_timeout_seconds": "Timeout for a forced recall attempt.",
|
|
106
|
+
"min_groups_before_repeat": "Minimum new tool groups before another recall record.",
|
|
107
|
+
"max_summary_input_tokens": "Maximum input tokens in one user-summary request.",
|
|
108
|
+
"summary_timeout_seconds": "Timeout for one user-summary request.",
|
|
109
|
+
"summary_input_policy": "Skip or chunk user-summary input exceeding its limit.",
|
|
110
|
+
"summary_options_json": "JSON object of model options for user summaries.",
|
|
111
|
+
"retry_without_summary_options": "Retry a rejected summary request without its options.",
|
|
112
|
+
"chunk_cache_size": "Maximum cached summary chunks; zero disables caching.",
|
|
113
|
+
"max_consecutive_summary_failures": "Failures before backoff; requires its duration.",
|
|
114
|
+
"summary_backoff_seconds": "Summary backoff duration; requires a failure threshold.",
|
|
115
|
+
"overflow_policy": "Shed context or raise when the composed budget cannot be met.",
|
|
116
|
+
"estimate_margin": "Composed token-estimate safety margin in [0, 1).",
|
|
117
|
+
"user_summary_prompt": "Custom user-summary prompt.",
|
|
118
|
+
"user_fold_prompt": "Custom prompt for folding remembered requests.",
|
|
119
|
+
"record_merge_prompt": "Custom prompt for merging recall records.",
|
|
120
|
+
"session_mode": "Keep objects, round-trip JSON, or also rebuild objects each request.",
|
|
121
|
+
"history_mode": "Send each new input or replay the original conversation.",
|
|
122
|
+
"stream": "Consume complete streaming responses, including persistence cleanup.",
|
|
123
|
+
}
|
|
124
|
+
choices = {
|
|
125
|
+
"summary_input_policy": ("skip", "chunk"),
|
|
126
|
+
"overflow_policy": ("shed", "raise"),
|
|
127
|
+
"session_mode": ("memory", "roundtrip", "restart"),
|
|
128
|
+
"history_mode": ("incremental", "replay"),
|
|
129
|
+
}
|
|
130
|
+
defaults = CompactionOptions()
|
|
131
|
+
for field in fields(defaults):
|
|
132
|
+
default = getattr(defaults, field.name)
|
|
133
|
+
flag = "--" + field.name.replace("_", "-")
|
|
134
|
+
kwargs: dict[str, Any] = {"default": default, "help": help_text[field.name]}
|
|
135
|
+
if field.name in choices:
|
|
136
|
+
kwargs["choices"] = choices[field.name]
|
|
137
|
+
if isinstance(default, bool):
|
|
138
|
+
kwargs["action"] = argparse.BooleanOptionalAction
|
|
139
|
+
elif field.name.endswith("seconds") or field.name == "estimate_margin":
|
|
140
|
+
kwargs["type"] = float
|
|
141
|
+
elif field.name in {
|
|
142
|
+
"min_groups_before_repeat",
|
|
143
|
+
"max_summary_input_tokens",
|
|
144
|
+
"chunk_cache_size",
|
|
145
|
+
"max_consecutive_summary_failures",
|
|
146
|
+
}:
|
|
147
|
+
kwargs["type"] = int
|
|
148
|
+
else:
|
|
149
|
+
kwargs["type"] = str
|
|
150
|
+
group.add_argument(flag, **kwargs)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def compaction_options(args: argparse.Namespace) -> CompactionOptions:
|
|
154
|
+
"""Read all controls from one parsed command line."""
|
|
155
|
+
return CompactionOptions(
|
|
156
|
+
**{field.name: getattr(args, field.name) for field in fields(CompactionOptions)}
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def validate_session_support(options: CompactionOptions, *, has_recall: bool) -> None:
|
|
161
|
+
"""Reject unsupported persistence experiments before any comparison row makes calls."""
|
|
162
|
+
if options.session_mode != "memory" and has_recall:
|
|
163
|
+
if not hasattr(maf_compaction, "SessionPersistence"):
|
|
164
|
+
raise ValueError(
|
|
165
|
+
"Session experiments with recall require maf-compaction's SessionPersistence "
|
|
166
|
+
"API; install the release containing it or use --session-mode memory."
|
|
167
|
+
)
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Decision counters and measurements of the current history."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from copy import deepcopy
|
|
6
|
+
from typing import Any, cast
|
|
7
|
+
|
|
8
|
+
from agent_framework import Message, TokenizerProtocol
|
|
9
|
+
from agent_framework._compaction import (
|
|
10
|
+
EXCLUDED_KEY,
|
|
11
|
+
GROUP_ANNOTATION_KEY,
|
|
12
|
+
SUMMARY_OF_GROUP_IDS_KEY,
|
|
13
|
+
SUMMARY_OF_MESSAGE_IDS_KEY,
|
|
14
|
+
annotate_token_counts,
|
|
15
|
+
included_token_count,
|
|
16
|
+
)
|
|
17
|
+
from maf_compaction import USER_SUMMARY_MARKER
|
|
18
|
+
|
|
19
|
+
COUNTER_LABELS = {
|
|
20
|
+
"records_found": "REC",
|
|
21
|
+
"fallbacks_used": "FALLBACK",
|
|
22
|
+
"fallbacks_after_record": "RECFALLBACK",
|
|
23
|
+
"fallbacks_held_after_record": "RECHELD",
|
|
24
|
+
"forced_calls": "FORCED",
|
|
25
|
+
"reforced_calls": "REFORCED",
|
|
26
|
+
"records_forced": "RECFORCED",
|
|
27
|
+
"records_volunteered": "RECVOLUNTEERED",
|
|
28
|
+
"records_truncated": "TRUNCATED",
|
|
29
|
+
"ignored_forced_calls": "RECALLIGNORED",
|
|
30
|
+
"failed_forced_calls": "RECALLFAILED",
|
|
31
|
+
"declined_collapses": "NOGAIN",
|
|
32
|
+
"user_compactions": "USERCOMPACT",
|
|
33
|
+
"user_summaries_replayed": "USERREPLAY",
|
|
34
|
+
"user_passes_below_trigger": "USERUNDER",
|
|
35
|
+
"user_passes_declined": "USERHELD",
|
|
36
|
+
"user_passes_waited": "USERWAIT",
|
|
37
|
+
"user_summary_failures": "USERSUMMFAIL",
|
|
38
|
+
"user_summary_skips": "USERSUMMSKIP",
|
|
39
|
+
"user_folds": "USERFOLD",
|
|
40
|
+
"records_merged": "RECMERGE",
|
|
41
|
+
"record_merges_rejected": "RECMERGEREJ",
|
|
42
|
+
"user_summaries_merged": "USERMERGE",
|
|
43
|
+
"user_merges_rejected": "USERMERGEREJ",
|
|
44
|
+
"record_rewrites": "RECHARDER",
|
|
45
|
+
"record_rewrites_rejected": "RECHARDERREJ",
|
|
46
|
+
"record_rewrites_skipped": "RECHARDERSKIP",
|
|
47
|
+
"record_merges_skipped": "RECMERGESKIP",
|
|
48
|
+
"record_summary_failures": "RECSUMMFAIL",
|
|
49
|
+
"last_resort_fallbacks": "LASTFALLBACK",
|
|
50
|
+
"chain_targets_reached": "CHAINTARGET",
|
|
51
|
+
"chain_targets_missed": "CHAINSHORT",
|
|
52
|
+
"chain_decisions_kept": "CHAINKEPT",
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
OBSERVATION_LABELS = {
|
|
57
|
+
"records_in_conversation": "RECORDS",
|
|
58
|
+
"user_messages_replaced": "USERREPLACED",
|
|
59
|
+
"user_summaries_in_conversation": "USERSUMMARIES",
|
|
60
|
+
"user_summary_tokens": "USERSUMMTOKENS",
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def counters(strategy: Any, recall: Any) -> dict[str, int]:
|
|
65
|
+
"""Read cumulative counters without counting a composed proxy twice."""
|
|
66
|
+
result: dict[str, int] = {}
|
|
67
|
+
for name in COUNTER_LABELS:
|
|
68
|
+
values = [getattr(source, name, 0) for source in (strategy, recall)]
|
|
69
|
+
result[name] = max(value if isinstance(value, int) else 0 for value in values)
|
|
70
|
+
return result
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def summary_measurements(messages: list[Message], tokenizer: TokenizerProtocol) -> dict[str, int]:
|
|
74
|
+
"""Measure linked summaries still included in history, including decreases after folds."""
|
|
75
|
+
summaries: list[Message] = []
|
|
76
|
+
for message in messages:
|
|
77
|
+
if (
|
|
78
|
+
message.role != "user"
|
|
79
|
+
or not message.text.startswith(USER_SUMMARY_MARKER)
|
|
80
|
+
or message.additional_properties.get(EXCLUDED_KEY)
|
|
81
|
+
):
|
|
82
|
+
continue
|
|
83
|
+
annotation = message.additional_properties.get(GROUP_ANNOTATION_KEY)
|
|
84
|
+
if not isinstance(annotation, dict):
|
|
85
|
+
continue
|
|
86
|
+
links = cast(dict[str, Any], annotation)
|
|
87
|
+
if all(
|
|
88
|
+
isinstance(ids := links.get(key), list)
|
|
89
|
+
and bool(cast(list[Any], ids))
|
|
90
|
+
and all(isinstance(value, str) and value for value in cast(list[Any], ids))
|
|
91
|
+
for key in (SUMMARY_OF_MESSAGE_IDS_KEY, SUMMARY_OF_GROUP_IDS_KEY)
|
|
92
|
+
):
|
|
93
|
+
summaries.append(deepcopy(message))
|
|
94
|
+
annotate_token_counts(summaries, tokenizer=tokenizer, force_retokenize=True)
|
|
95
|
+
return {
|
|
96
|
+
"user_summaries_in_conversation": len(summaries),
|
|
97
|
+
"user_summary_tokens": included_token_count(summaries),
|
|
98
|
+
}
|