Repository navigation
Expand file tree
/
Copy pathtrajectory_compressor.py
More file actions
2070 lines (1782 loc) · 83.2 KB
/
Copy pathtrajectory_compressor.py
File metadata and controls
2070 lines (1782 loc) · 83.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Trajectory Compressor
Post-processes completed agent trajectories to compress them within a target
token budget while preserving training signal quality.
Compression Strategy:
1. Protect first turns (system, human, first gpt, first tool)
2. Protect last N turns (final actions and conclusions)
3. Compress MIDDLE turns only, starting from 2nd tool response
4. Compress only as much as needed to fit under target
5. Replace compressed region with a single human summary message
6. Keep remaining tool calls intact (model continues working after summary)
Usage:
# Compress a directory of JSONL files
python trajectory_compressor.py --input=data/my_run
# Compress a single JSONL file
python trajectory_compressor.py --input=data/trajectories.jsonl
# Compress 15% sample of a file
python trajectory_compressor.py --input=data/trajectories.jsonl --sample_percent=15
# Compress with custom output and token target
python trajectory_compressor.py --input=data/trajectories.jsonl --output=compressed.jsonl --target_max_tokens=16000
# Compress 10% sample from a directory
python trajectory_compressor.py --input=data/my_run --sample_percent=10
"""
import base64
import hashlib
import json
import os
import random
import time
import uuid
import yaml
import logging
import asyncio
import aiofiles
import aiofiles.os
import aiofiles.tempfile
import httpx
from pathlib import Path
from typing import Any
from dataclasses import dataclass, field
from datetime import datetime
from utils import base_url_host_matches, base_url_hostname
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn, TimeElapsedColumn, TimeRemainingColumn
from rich.console import Console
from hermes_constants import OPENROUTER_BASE_URL, get_hermes_home
from agent.retry_utils import jittered_backoff
from agent.secret_scope import get_secret
_KIMI_TOKENIZER_NAME = "moonshotai/Kimi-K2-Thinking"
_KIMI_TOKENIZER_REVISION = "main"
_KIMI_TOKENIZER_FILES = ("tokenizer_config.json", "tiktoken.model")
_FAST_TOKENIZER_FILES = ("tokenizer_config.json", "tokenizer.json")
_SENTENCEPIECE_TOKENIZER_FILES = (
("tokenizer_config.json", "tokenizer.model"),
("tokenizer_config.json", "spiece.model"),
)
_KIMI_NUM_RESERVED_SPECIAL_TOKENS = 256
_KIMI_PAT_STR = "|".join(
[
r"[\p{Han}]+",
r"[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+(?i:'s|'t|'re|'ve|'m|'ll|'d)?",
r"[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]+[\p{Ll}\p{Lm}\p{Lo}\p{M}&&[^\p{Han}]]*(?i:'s|'t|'re|'ve|'m|'ll|'d)?",
r"\p{N}{1,3}",
r" ?[^\s\p{L}\p{N}]+[\r\n]*",
r"\s*[\r\n]+",
r"\s+(?!\S)",
r"\s+",
]
)
class _KimiTokenizer:
"""CPU-only implementation of Kimi's published tokenizer ``encode`` API."""
def __init__(self, encoding: Any) -> None:
self._encoding = encoding
@staticmethod
def _split_whitespace_runs(text: str, max_run: int):
current_length = 0
current_is_space = text[0].isspace() if text else False
start = 0
for index, character in enumerate(text):
is_space = character.isspace()
if current_is_space ^ is_space:
current_length = 1
current_is_space = is_space
else:
current_length += 1
if current_length > max_run:
yield text[start:index]
start = index
current_length = 1
yield text[start:]
def encode(self, text: str) -> list[int]:
if type(text) is not str:
raise TypeError("Kimi tokenizer input must be str")
token_ids: list[int] = []
for chunk_start in range(0, len(text), 400_000):
chunk = text[chunk_start : chunk_start + 400_000]
for substring in self._split_whitespace_runs(chunk, 25_000):
token_ids.extend(
self._encoding.encode(substring, allowed_special="all")
)
return token_ids
class _FastTokenizer:
"""Transformers-compatible ``encode`` facade over tokenizer.json."""
def __init__(self, tokenizer: Any) -> None:
self._tokenizer = tokenizer
def encode(self, text: str) -> list[int]:
return self._tokenizer.encode(text, add_special_tokens=True).ids
def _generate_sentencepiece_bpe_merges(
vocab: dict[str, int],
scores: dict[str, float],
) -> list[tuple[str, str]]:
"""Reconstruct the BPE merge order encoded by a SentencePiece model."""
ranked: list[tuple[str, str, float]] = []
for merged_piece, score in scores.items():
candidates: list[tuple[str, str, float]] = []
for index in range(1, len(merged_piece)):
left = merged_piece[:index]
right = merged_piece[index:]
if left in vocab and right in vocab:
candidates.append((left, right, score))
candidates.sort(key=lambda value: (vocab[value[0]], vocab[value[1]]))
ranked.extend(candidates)
ranked.sort(
key=lambda value: (value[2], len(value[0]), len(value[1])),
reverse=True,
)
return [(left, right) for left, right, _score in ranked]
def _parse_tiktoken_ranks(model_bytes: bytes) -> dict[bytes, int]:
"""Parse the public ``tiktoken.model`` format without synchronous I/O."""
ranks: dict[bytes, int] = {}
for raw_line in model_bytes.splitlines():
if not raw_line:
continue
token, rank = raw_line.split()
ranks[base64.b64decode(token)] = int(rank)
return ranks
def _build_kimi_tokenizer(config_bytes: bytes, model_bytes: bytes) -> _KimiTokenizer:
"""Construct the official Kimi BPE from already-loaded bytes."""
try:
import tiktoken
except ImportError as exc: # pragma: no cover - pinned core dependency
raise RuntimeError(
"Trajectory compression requires tiktoken. Reinstall "
"async-hermes-agent to restore its pinned dependencies."
) from exc
tokenizer_config = json.loads(config_bytes)
added_tokens = tokenizer_config.get("added_tokens_decoder") or {}
token_names = {
int(token_id): token_data["content"]
for token_id, token_data in added_tokens.items()
if isinstance(token_data, dict) and isinstance(token_data.get("content"), str)
}
mergeable_ranks = _parse_tiktoken_ranks(model_bytes)
base_token_count = len(mergeable_ranks)
special_tokens = {
token_names.get(token_id, f"<|reserved_token_{token_id}|>"): token_id
for token_id in range(
base_token_count,
base_token_count + _KIMI_NUM_RESERVED_SPECIAL_TOKENS,
)
}
encoding = tiktoken.Encoding(
name="tiktoken.model",
pat_str=_KIMI_PAT_STR,
mergeable_ranks=mergeable_ranks,
special_tokens=special_tokens,
)
return _KimiTokenizer(encoding)
def _tokenizer_cache_directory(tokenizer_name: str) -> Path:
digest = hashlib.sha256(tokenizer_name.encode("utf-8")).hexdigest()[:24]
return get_hermes_home() / "cache" / "tokenizers" / digest
async def _read_optional_bytes(path: Path) -> bytes | None:
try:
async with aiofiles.open(path, "rb") as source:
return await source.read()
except FileNotFoundError:
return None
async def _atomic_write_bytes(path: Path, content: bytes) -> None:
await aiofiles.os.makedirs(path.parent, exist_ok=True)
temporary = path.parent / f".{path.name}.{uuid.uuid4().hex}.tmp"
try:
async with aiofiles.open(temporary, "wb") as destination:
await destination.write(content)
await aiofiles.os.replace(temporary, path)
finally:
try:
await aiofiles.os.remove(temporary)
except FileNotFoundError:
pass
def _offline_mode_enabled() -> bool:
return os.getenv("HF_HUB_OFFLINE", "").strip().lower() in {
"1",
"true",
"yes",
"on",
}
def _complete_cached_assets(
cached: dict[str, bytes | None],
filenames: tuple[str, ...],
) -> dict[str, bytes] | None:
complete: dict[str, bytes] = {}
for name in filenames:
content = cached.get(name)
if content is None:
return None
complete[name] = content
return complete
def _validate_hf_repo_id(repo_id: str) -> None:
"""Apply Hugging Face's repository-id shape constraints before HTTP."""
if len(repo_id) > 96 or repo_id.endswith(".git"):
raise ValueError(f"Invalid Hugging Face tokenizer repository: {repo_id!r}")
parts = repo_id.split("/")
allowed = frozenset(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_."
)
if (
not 1 <= len(parts) <= 2
or any(
not part
or part[0] in "-."
or part[-1] in "-."
or "--" in part
or ".." in part
or any(character not in allowed for character in part)
for part in parts
)
):
raise ValueError(f"Invalid Hugging Face tokenizer repository: {repo_id!r}")
async def _load_hf_tokenizer_assets(
tokenizer_name: str,
filenames: tuple[str, ...],
*,
revision: str = "main",
) -> dict[str, bytes]:
"""Load tokenizer files through native async local or Hub I/O."""
local_directory = Path(tokenizer_name)
if await aiofiles.os.path.isdir(local_directory):
local_assets = {
name: await _read_optional_bytes(local_directory / name)
for name in filenames
}
complete_local = _complete_cached_assets(local_assets, filenames)
if complete_local is None:
missing = [name for name, content in local_assets.items() if content is None]
raise FileNotFoundError(
f"Tokenizer directory '{tokenizer_name}' is missing: "
+ ", ".join(missing)
)
return complete_local
_validate_hf_repo_id(tokenizer_name)
cache_directory = _tokenizer_cache_directory(tokenizer_name)
cached = {
name: await _read_optional_bytes(cache_directory / name)
for name in filenames
}
metadata_path = cache_directory / "metadata.json"
metadata_bytes = await _read_optional_bytes(metadata_path)
try:
metadata = json.loads(metadata_bytes) if metadata_bytes else {}
except (TypeError, ValueError):
metadata = {}
cached_assets = _complete_cached_assets(cached, filenames)
if _offline_mode_enabled():
if cached_assets is not None:
return cached_assets
raise RuntimeError(
f"Tokenizer '{tokenizer_name}' is not cached and "
"HF_HUB_OFFLINE is enabled."
)
token = get_secret("HF_TOKEN") or get_secret("HUGGING_FACE_HUB_TOKEN")
common_headers = {"User-Agent": "async-hermes-agent/trajectory-compressor"}
if token:
common_headers["Authorization"] = f"Bearer {token}"
refreshed: dict[str, bytes] = {}
etags: dict[str, str] = {}
try:
from agent.ssl_verify import _create_httpx_client
async with (await _create_httpx_client(
follow_redirects=True,
timeout=httpx.Timeout(60.0),
headers=common_headers,
)) as client:
for name in filenames:
headers = {}
previous_etag = (metadata.get("etags") or {}).get(name)
if cached[name] is not None and isinstance(previous_etag, str):
headers["If-None-Match"] = previous_etag
url = (
f"https://huggingface.co/{tokenizer_name}/resolve/"
f"{revision}/{name}"
)
response = await client.get(url, headers=headers)
if response.status_code == 304:
cached_content = cached[name]
if cached_content is None or not isinstance(previous_etag, str):
raise RuntimeError(
f"Invalid conditional response for tokenizer asset {name}"
)
refreshed[name] = cached_content
etags[name] = previous_etag
continue
response.raise_for_status()
refreshed[name] = response.content
response_etag = response.headers.get("etag")
if response_etag:
etags[name] = response_etag
except httpx.TransportError:
if cached_assets is not None:
return cached_assets
raise
for name, content in refreshed.items():
if content != cached[name]:
await _atomic_write_bytes(cache_directory / name, content)
await _atomic_write_bytes(
metadata_path,
json.dumps(
{
"tokenizer": tokenizer_name,
"revision": revision,
"etags": etags,
},
sort_keys=True,
).encode("utf-8"),
)
return refreshed
async def _load_kimi_tokenizer_assets() -> tuple[bytes, bytes]:
"""Load Kimi tokenizer files through an async, conditional HTTP cache."""
assets = await _load_hf_tokenizer_assets(
_KIMI_TOKENIZER_NAME,
_KIMI_TOKENIZER_FILES,
revision=_KIMI_TOKENIZER_REVISION,
)
return assets["tokenizer_config.json"], assets["tiktoken.model"]
async def _load_fast_tokenizer_assets(
tokenizer_name: str,
) -> tuple[bytes, bytes]:
"""Load a standard Hugging Face tokenizer.json and its configuration."""
assets = await _load_hf_tokenizer_assets(
tokenizer_name,
_FAST_TOKENIZER_FILES,
)
return assets["tokenizer_config.json"], assets["tokenizer.json"]
def _is_missing_tokenizer_asset(exc: BaseException) -> bool:
if isinstance(exc, FileNotFoundError):
return True
return (
isinstance(exc, httpx.HTTPStatusError)
and exc.response.status_code == 404
)
async def _load_custom_tokenizer_assets(
tokenizer_name: str,
) -> tuple[str, bytes, bytes]:
"""Load a tokenizer.json pipeline or a supported SentencePiece model."""
try:
config_bytes, tokenizer_bytes = await _load_fast_tokenizer_assets(
tokenizer_name
)
return "fast", config_bytes, tokenizer_bytes
except (FileNotFoundError, httpx.HTTPStatusError) as exc:
if not _is_missing_tokenizer_asset(exc):
raise
last_missing: BaseException | None = None
for filenames in _SENTENCEPIECE_TOKENIZER_FILES:
try:
assets = await _load_hf_tokenizer_assets(
tokenizer_name,
filenames,
)
return "sentencepiece", assets["tokenizer_config.json"], assets[
filenames[1]
]
except (FileNotFoundError, httpx.HTTPStatusError) as exc:
if not _is_missing_tokenizer_asset(exc):
raise
last_missing = exc
if last_missing is not None:
raise last_missing
raise RuntimeError(f"No tokenizer assets found for {tokenizer_name!r}")
def _build_fast_tokenizer(
config_bytes: bytes,
tokenizer_bytes: bytes,
) -> _FastTokenizer:
"""Construct the generic Rust tokenizer from already-loaded JSON bytes."""
tokenizer_config = json.loads(config_bytes)
if tokenizer_config.get("auto_map", {}).get("AutoTokenizer"):
raise ValueError(
"the configured tokenizer requires Python remote code, which has "
"no native-async file-loading contract"
)
try:
from tokenizers import Tokenizer
except ImportError as exc: # pragma: no cover - pinned core dependency
raise RuntimeError(
"Trajectory compression requires tokenizers. Reinstall "
"async-hermes-agent to restore its pinned dependencies."
) from exc
return _FastTokenizer(Tokenizer.from_str(tokenizer_bytes.decode("utf-8")))
def _build_sentencepiece_tokenizer(
config_bytes: bytes,
model_bytes: bytes,
) -> _FastTokenizer:
"""Build verified Llama/T5 SentencePiece families without file I/O."""
tokenizer_config = json.loads(config_bytes)
if tokenizer_config.get("auto_map", {}).get("AutoTokenizer"):
raise ValueError(
"the configured tokenizer requires Python remote code, which has "
"no native-async file-loading contract"
)
tokenizer_class = str(tokenizer_config.get("tokenizer_class") or "")
normalized_class = tokenizer_class.removesuffix("Fast")
if normalized_class.endswith("LlamaTokenizer"):
add_bos_token = bool(tokenizer_config.get("add_bos_token", True))
add_eos_token = bool(tokenizer_config.get("add_eos_token", False))
tokenizer_family = "llama"
elif normalized_class in {"T5Tokenizer", "MT5Tokenizer"} or (
not normalized_class and "extra_ids" in tokenizer_config
):
add_bos_token = False
add_eos_token = True
tokenizer_family = "t5"
else:
raise ValueError(
"unsupported SentencePiece tokenizer family: "
f"{tokenizer_class or 'unknown'}"
)
try:
from sentencepiece import sentencepiece_model_pb2
except ImportError as exc: # pragma: no cover - pinned core dependency
raise RuntimeError(
"Trajectory compression requires sentencepiece. Reinstall "
"async-hermes-agent to restore its pinned dependencies."
) from exc
try:
model_proto_type = getattr(sentencepiece_model_pb2, "ModelProto")
model_proto = model_proto_type.FromString(model_bytes)
except Exception as exc:
raise ValueError("invalid serialized SentencePiece model") from exc
trainer_spec = model_proto.trainer_spec
if add_bos_token and trainer_spec.bos_id < 0:
raise ValueError("SentencePiece tokenizer requires a BOS token")
if add_eos_token and trainer_spec.eos_id < 0:
raise ValueError("SentencePiece tokenizer requires an EOS token")
try:
from tokenizers import (
AddedToken,
Tokenizer,
decoders,
models,
pre_tokenizers,
processors,
)
except ImportError as exc: # pragma: no cover - pinned core dependency
raise RuntimeError(
"Trajectory compression requires tokenizers. Reinstall "
"async-hermes-agent to restore its pinned dependencies."
) from exc
vocab_scores = [
(piece.piece, piece.score)
for piece in model_proto.pieces
]
vocab = {
piece: index
for index, (piece, _score) in enumerate(vocab_scores)
}
if tokenizer_family == "llama":
scores = {
piece: score for piece, score in vocab_scores
}
tokenizer = Tokenizer(
models.BPE(
vocab=vocab,
merges=_generate_sentencepiece_bpe_merges(vocab, scores),
fuse_unk=True,
byte_fallback=True,
dropout=None,
)
)
tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(
replacement="▁",
prepend_scheme="first",
split=False,
)
decoder_steps: list[Any] = [
decoders.Replace("▁", " "),
decoders.ByteFallback(),
decoders.Fuse(),
]
if bool(tokenizer_config.get("add_prefix_space", True)):
decoder_steps.append(decoders.Strip(content=" ", left=1))
tokenizer.decoder = decoders.Sequence(decoder_steps)
special_tokens: list[AddedToken] = []
template_tokens: list[tuple[str, int]] = []
for key, fallback in (
("unk_token", "<unk>"),
("bos_token", "<s>"),
("eos_token", "</s>"),
):
value = tokenizer_config.get(key, fallback)
if isinstance(value, dict):
content = str(value.get("content") or fallback)
normalized = bool(value.get("normalized", key == "unk_token"))
else:
content = str(value or fallback)
normalized = key == "unk_token"
token_id = vocab.get(content)
if token_id is None:
raise ValueError(f"SentencePiece model is missing {key}")
special_tokens.append(
AddedToken(content, special=True, normalized=normalized)
)
if key != "unk_token":
template_tokens.append((content, token_id))
tokenizer.add_special_tokens(special_tokens)
bos_content, bos_id = template_tokens[0]
eos_content, eos_id = template_tokens[1]
single_parts = ["$A"]
pair_parts = ["$A"]
post_specials: list[tuple[str, int]] = []
if add_bos_token:
single_parts.insert(0, bos_content)
pair_parts.insert(0, bos_content)
post_specials.append((bos_content, bos_id))
if add_eos_token:
single_parts.append(eos_content)
pair_parts.append(eos_content)
post_specials.append((eos_content, eos_id))
if add_bos_token:
pair_parts.extend((f"{bos_content}:1", "$B:1"))
else:
pair_parts.append("$B:1")
if add_eos_token:
pair_parts.append(f"{eos_content}:1")
if post_specials:
tokenizer.post_processor = processors.TemplateProcessing(
single=" ".join(single_parts),
pair=" ".join(pair_parts),
special_tokens=post_specials,
)
return _FastTokenizer(tokenizer)
tokenizer = Tokenizer(
models.Unigram(
vocab=vocab_scores,
unk_id=trainer_spec.unk_id,
byte_fallback=False,
)
)
precompiled_charsmap = model_proto.normalizer_spec.precompiled_charsmap
if precompiled_charsmap:
from tokenizers import normalizers
tokenizer.normalizer = normalizers.Precompiled(precompiled_charsmap)
tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
[
pre_tokenizers.WhitespaceSplit(),
pre_tokenizers.Metaspace(
replacement="▁",
prepend_scheme="always",
split=True,
),
]
)
tokenizer.decoder = decoders.Metaspace(
replacement="▁",
prepend_scheme="always",
split=True,
)
for key, fallback in (
("unk_token", "<unk>"),
("eos_token", "</s>"),
("pad_token", "<pad>"),
):
value = tokenizer_config.get(key, fallback)
content = str(value.get("content") or fallback) if isinstance(
value, dict
) else str(value or fallback)
if content in vocab:
tokenizer.add_special_tokens(
[AddedToken(content, special=True, normalized=False)]
)
eos_value = tokenizer_config.get("eos_token", "</s>")
eos_content = str(eos_value.get("content") or "</s>") if isinstance(
eos_value, dict
) else str(eos_value or "</s>")
eos_id = vocab.get(eos_content)
if eos_id is None:
raise ValueError("SentencePiece model is missing eos_token")
tokenizer.post_processor = processors.TemplateProcessing(
single=f"$A {eos_content}",
pair=f"$A {eos_content} $B {eos_content}",
special_tokens=[(eos_content, eos_id)],
)
return _FastTokenizer(tokenizer)
async def _finish_owned_task(task: asyncio.Task[Any]) -> Any:
"""Finish one compressor-owned task through repeated cancellation."""
cancellation: asyncio.CancelledError | None = None
while True:
try:
result = await asyncio.shield(task)
break
except asyncio.CancelledError as exc: # noqa: ASYNC103 - re-raised below
if task.cancelled():
raise
if cancellation is None:
cancellation = exc
except Exception as exc:
if cancellation is not None:
raise cancellation from exc
raise
if cancellation is not None:
raise cancellation
return result
async def _list_jsonl_files(directory: Path) -> list[Path]:
"""Return JSONL files without blocking the event loop on directory I/O."""
try:
names = await aiofiles.os.listdir(directory)
except OSError:
return []
paths: list[Path] = []
for name in names:
path = directory / name
if name.endswith(".jsonl") and await aiofiles.os.path.isfile(path):
paths.append(path)
return sorted(paths)
def _effective_temperature_for_model(
model: str,
requested_temperature: float,
base_url: str | None = None,
) -> float | None:
"""Apply fixed model temperature contracts to direct client calls.
Returns ``None`` when the model manages temperature server-side (Kimi);
callers must omit the ``temperature`` kwarg entirely in that case.
"""
try:
from agent.auxiliary_client import _fixed_temperature_for_model, OMIT_TEMPERATURE
except Exception:
return requested_temperature
fixed_temperature = _fixed_temperature_for_model(model, base_url)
if fixed_temperature is OMIT_TEMPERATURE:
return None # caller must omit temperature
if fixed_temperature is not None:
return fixed_temperature
return requested_temperature
@dataclass
class CompressionConfig:
"""Configuration for trajectory compression."""
# Tokenizer
tokenizer_name: str = "moonshotai/Kimi-K2-Thinking"
trust_remote_code: bool = True
# Compression targets
target_max_tokens: int = 15250
summary_target_tokens: int = 750
# Protected turns
protect_first_system: bool = True
protect_first_human: bool = True
protect_first_gpt: bool = True
protect_first_tool: bool = True
protect_last_n_turns: int = 4
# Summarization (OpenRouter)
summarization_model: str = "google/gemini-3-flash-preview"
base_url: str = OPENROUTER_BASE_URL
api_key_env: str = "OPENROUTER_API_KEY"
temperature: float = 0.3
max_retries: int = 3
retry_delay: int = 2
# Output
add_summary_notice: bool = True
summary_notice_text: str = "\n\nSome of your previous tool responses may be summarized to preserve context."
output_suffix: str = "_compressed"
# Processing
num_workers: int = 4
max_concurrent_requests: int = 50 # Max concurrent API calls for summarization
skip_under_target: bool = True
save_over_limit: bool = True
per_trajectory_timeout: int = 300 # Timeout per trajectory in seconds (default: 5 min)
# Metrics
metrics_enabled: bool = True
metrics_per_trajectory: bool = True
metrics_output_file: str = "compression_metrics.json"
@classmethod
async def from_yaml(cls, yaml_path: str) -> "CompressionConfig":
"""Load configuration from YAML file."""
async with aiofiles.open(yaml_path, encoding="utf-8") as source:
data = yaml.safe_load(await source.read()) or {}
config = cls()
# Tokenizer
if 'tokenizer' in data:
config.tokenizer_name = data['tokenizer'].get('name', config.tokenizer_name)
config.trust_remote_code = data['tokenizer'].get('trust_remote_code', config.trust_remote_code)
# Compression
if 'compression' in data:
config.target_max_tokens = data['compression'].get('target_max_tokens', config.target_max_tokens)
config.summary_target_tokens = data['compression'].get('summary_target_tokens', config.summary_target_tokens)
# Protected turns
if 'protected_turns' in data:
config.protect_first_system = data['protected_turns'].get('first_system', config.protect_first_system)
config.protect_first_human = data['protected_turns'].get('first_human', config.protect_first_human)
config.protect_first_gpt = data['protected_turns'].get('first_gpt', config.protect_first_gpt)
config.protect_first_tool = data['protected_turns'].get('first_tool', config.protect_first_tool)
config.protect_last_n_turns = data['protected_turns'].get('last_n_turns', config.protect_last_n_turns)
# Summarization
if 'summarization' in data:
config.summarization_model = data['summarization'].get('model', config.summarization_model)
config.base_url = data['summarization'].get('base_url') or config.base_url
config.api_key_env = data['summarization'].get('api_key_env', config.api_key_env)
config.temperature = data['summarization'].get('temperature', config.temperature)
config.max_retries = data['summarization'].get('max_retries', config.max_retries)
config.retry_delay = data['summarization'].get('retry_delay', config.retry_delay)
# Output
if 'output' in data:
config.add_summary_notice = data['output'].get('add_summary_notice', config.add_summary_notice)
config.summary_notice_text = data['output'].get('summary_notice_text', config.summary_notice_text)
config.output_suffix = data['output'].get('output_suffix', config.output_suffix)
# Processing
if 'processing' in data:
config.num_workers = data['processing'].get('num_workers', config.num_workers)
config.max_concurrent_requests = data['processing'].get('max_concurrent_requests', config.max_concurrent_requests)
config.skip_under_target = data['processing'].get('skip_under_target', config.skip_under_target)
config.save_over_limit = data['processing'].get('save_over_limit', config.save_over_limit)
# Metrics
if 'metrics' in data:
config.metrics_enabled = data['metrics'].get('enabled', config.metrics_enabled)
config.metrics_per_trajectory = data['metrics'].get('per_trajectory', config.metrics_per_trajectory)
config.metrics_output_file = data['metrics'].get('output_file', config.metrics_output_file)
return config
@dataclass
class TrajectoryMetrics:
"""Metrics for a single trajectory compression."""
original_tokens: int = 0
compressed_tokens: int = 0
tokens_saved: int = 0
compression_ratio: float = 1.0
original_turns: int = 0
compressed_turns: int = 0
turns_removed: int = 0
turns_compressed_start_idx: int = -1
turns_compressed_end_idx: int = -1
turns_in_compressed_region: int = 0
was_compressed: bool = False
still_over_limit: bool = False
skipped_under_target: bool = False
summarization_api_calls: int = 0
summarization_errors: int = 0
def to_dict(self) -> dict[str, Any]:
return {
"original_tokens": self.original_tokens,
"compressed_tokens": self.compressed_tokens,
"tokens_saved": self.tokens_saved,
"compression_ratio": round(self.compression_ratio, 4),
"original_turns": self.original_turns,
"compressed_turns": self.compressed_turns,
"turns_removed": self.turns_removed,
"compression_region": {
"start_idx": self.turns_compressed_start_idx,
"end_idx": self.turns_compressed_end_idx,
"turns_count": self.turns_in_compressed_region,
},
"was_compressed": self.was_compressed,
"still_over_limit": self.still_over_limit,
"skipped_under_target": self.skipped_under_target,
"summarization_api_calls": self.summarization_api_calls,
"summarization_errors": self.summarization_errors,
}
@dataclass
class AggregateMetrics:
"""Aggregate metrics across all trajectories."""
total_trajectories: int = 0
trajectories_compressed: int = 0
trajectories_skipped_under_target: int = 0
trajectories_still_over_limit: int = 0
trajectories_failed: int = 0
total_tokens_before: int = 0
total_tokens_after: int = 0
total_tokens_saved: int = 0
total_turns_before: int = 0
total_turns_after: int = 0
total_turns_removed: int = 0
total_summarization_calls: int = 0
total_summarization_errors: int = 0
# Distribution stats
compression_ratios: list[float] = field(default_factory=list)
tokens_saved_list: list[int] = field(default_factory=list)
turns_removed_list: list[int] = field(default_factory=list)
processing_start_time: str = ""
processing_end_time: str = ""
processing_duration_seconds: float = 0.0
def add_trajectory_metrics(self, metrics: TrajectoryMetrics):
"""Add a trajectory's metrics to the aggregate."""
self.total_trajectories += 1
self.total_tokens_before += metrics.original_tokens
self.total_tokens_after += metrics.compressed_tokens
self.total_tokens_saved += metrics.tokens_saved
self.total_turns_before += metrics.original_turns
self.total_turns_after += metrics.compressed_turns
self.total_turns_removed += metrics.turns_removed
self.total_summarization_calls += metrics.summarization_api_calls
self.total_summarization_errors += metrics.summarization_errors
if metrics.was_compressed:
self.trajectories_compressed += 1
self.compression_ratios.append(metrics.compression_ratio)
self.tokens_saved_list.append(metrics.tokens_saved)
self.turns_removed_list.append(metrics.turns_removed)
if metrics.skipped_under_target:
self.trajectories_skipped_under_target += 1
if metrics.still_over_limit:
self.trajectories_still_over_limit += 1
def to_dict(self) -> dict[str, Any]:
avg_compression_ratio = (
sum(self.compression_ratios) / len(self.compression_ratios)
if self.compression_ratios else 1.0
)
avg_tokens_saved = (
sum(self.tokens_saved_list) / len(self.tokens_saved_list)
if self.tokens_saved_list else 0
)
avg_turns_removed = (
sum(self.turns_removed_list) / len(self.turns_removed_list)
if self.turns_removed_list else 0
)
return {
"summary": {
"total_trajectories": self.total_trajectories,
"trajectories_compressed": self.trajectories_compressed,
"trajectories_skipped_under_target": self.trajectories_skipped_under_target,
"trajectories_still_over_limit": self.trajectories_still_over_limit,
"trajectories_failed": self.trajectories_failed,
"compression_rate": round(self.trajectories_compressed / max(self.total_trajectories, 1), 4),
},
"tokens": {
"total_before": self.total_tokens_before,
"total_after": self.total_tokens_after,
"total_saved": self.total_tokens_saved,
"overall_compression_ratio": round(self.total_tokens_after / max(self.total_tokens_before, 1), 4),
},
"turns": {
"total_before": self.total_turns_before,
"total_after": self.total_turns_after,
"total_removed": self.total_turns_removed,
},
"averages": {
"avg_compression_ratio": round(avg_compression_ratio, 4),
"avg_tokens_saved_per_compressed": round(avg_tokens_saved, 1),
"avg_turns_removed_per_compressed": round(avg_turns_removed, 2),
},
"summarization": {
"total_api_calls": self.total_summarization_calls,
"total_errors": self.total_summarization_errors,
"success_rate": round(1 - (self.total_summarization_errors / max(self.total_summarization_calls, 1)), 4),
},
"processing": {
"start_time": self.processing_start_time,
"end_time": self.processing_end_time,
"duration_seconds": round(self.processing_duration_seconds, 2),
},
}
class TrajectoryCompressor:
"""
Compresses agent trajectories to fit within a target token budget.
Compression strategy:
1. Keep protected head turns (system, human, first gpt+tool)
2. Keep protected tail turns (last N turns)
3. From the compressible middle region, compress only as much as needed
4. Replace compressed turns with a single human summary message
5. Keep remaining middle turns intact (model continues with tools)
"""
def __init__(self, config: CompressionConfig):
"""Initialize the compressor."""
self.config = config
self.aggregate_metrics = AggregateMetrics()
self.tokenizer = None
self._tokenizer_init_lock = asyncio.Lock()
self._initialization_lock = asyncio.Lock()
self._client_init_lock = asyncio.Lock()
self._summarizer_initialized = False
self.client = None
self.logger = logging.getLogger(__name__)
async def _initialize(self) -> None:
"""Initialize retained resources in their upstream order."""
if self.tokenizer is not None and self._summarizer_initialized:
return
async with self._initialization_lock:
if self.tokenizer is None:
await self._init_tokenizer()
if not self._summarizer_initialized: