compaction
zocrates.agents.common.compaction ¶
Google ADK 2.8+ session context compaction utilities for Zocrates.
Provides fail-open event summarization, pipeline isolation scope filtering, and thought-stripped markdown formatting for dialogue history.
DEFAULT_ADAPTIVE_COMPACTION_RETENTION_TURNS
module-attribute
¶
DEFAULT_COMPACTION_SUMMARIZER_MODEL
module-attribute
¶
ZOCRATES_COMPACTION_PROMPT_TEMPLATE
module-attribute
¶
ZOCRATES_COMPACTION_PROMPT_TEMPLATE = '## OBJECTIVE\nYou are compacting the prior research dialogue history between a researcher and Zocrates (an AI academic research assistant).\n\nYour objective is to generate an accurate, dense, and grounded synthesis/summary of past dialogue turns so future research turns maintain complete context.\n\n## INSTRUCTIONS\n\n### Sections\nYou summary must include the following sections:\n- Sources: List all papers, studies, and documents discussed in the conversation using unnumbered bullet points with authors, publication year, paper title, and journal/source (e.g. "- Smith et al. (2021) — Mechanisms of BRCA-mediated repair (Nature Genetics)"). Do NOT use numeric citation brackets ([1], [2]) or numbered lists for sources.\n- Key Findings & Established Decisions: Summarize core findings, established facts, methodologies, and user decisions in dense bullet points. Attribute findings directly to the authors (e.g. "Petersen et al. (2022) showed...").\n- Unresolved Questions & Next Steps: Note any explicit knowledge gaps, ongoing literature inquiries, user preferences, or next steps identified in the conversation.\n\n### Critical Guidelines:\n- Exclude Internal Mechanics: Do not describe internal tool calls, retrieval loops, or intermediate system steps; focus strictly on final evidence obtained and conceptual conclusions.\n- Conciseness & Dense Structure: Keep the summary dense, direct, and under 400 words. Use structured bullet points rather than verbose paragraphs.\n- Do NOT include conversational pleasantries, greeting filler, or language declarations. \n- Do NOT attempt to answer any user questions found in the history. Your task is strictly to summarize the past dialogue into the sections above.\n\n## CONVERSATION HISTORY TO SUMMARIZE\n\n<dialogue_history>\n\n{conversation_history}\n\n</dialogue_history>\n\n## SUMMARY\nNow, provide the dense, structured academic compaction summary of the dialogue history above:\n'
__all__
module-attribute
¶
__all__ = ['ZOCRATES_COMPACTION_PROMPT_TEMPLATE', 'FailOpenLlmEventSummarizer', 'build_compaction_llm', 'build_events_compaction_config', 'compact_session_adaptive', 'run_adaptive_post_invocation_compaction']
FailOpenLlmEventSummarizer ¶
Bases: LlmEventSummarizer
Event summarizer with fail-open resilience and pipeline isolation scope filtering.
Initialize fail-open LLM event summarizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Any
|
Positional arguments forwarded to |
()
|
**kwargs
|
Any
|
Keyword arguments forwarded to |
{}
|
Source code in zocrates/agents/common/compaction.py
maybe_summarize_events
async
¶
Summarize conversation events with scope filtering and fail-open resilience.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
events
|
list[Event]
|
List of session events to consider for compaction summarization. |
required |
Returns:
| Type | Description |
|---|---|
Event | None
|
Compaction event containing the generated summary, or None if skipped or on failure. |
Source code in zocrates/agents/common/compaction.py
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 | |
_extract_compacted_text ¶
Extract clean summary text from compacted_content (Content, str, or dict).
Source code in zocrates/agents/common/compaction.py
_get_active_turn_invocation_id ¶
Find the invocation_id of the active turn (the latest non-compaction invocation).
Source code in zocrates/agents/common/compaction.py
_get_completed_turn_groups ¶
Group unscoped, non-compaction events into chronological completed turns.
Returns a list of (invocation_id, turn_events) pairs for turns that have an assistant completion. Incomplete turns (e.g. unanswered user queries or open tool calls) are excluded.
Source code in zocrates/agents/common/compaction.py
_is_compaction_event ¶
Check if event is an ADK compaction event.
_prepare_compaction_slice ¶
Prepares the conversation history prompt, timestamps, and metadata for adaptive compaction.
Returns (prompt, start_timestamp, end_timestamp, slice_turns_count, k) or None. Fails open to None on any error without raising.
Source code in zocrates/agents/common/compaction.py
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 | |
_safe_apply_rewinds ¶
Safely apply rewinds to events list, failing open to original list if unneeded.
Source code in zocrates/agents/common/adaptive_decision.py
_safe_set ¶
Safely set an attribute on an active OpenTelemetry span, no-oping on error or None.
Source code in zocrates/agents/common/compaction.py
_start_compaction_span ¶
Return a context manager yielding an OpenTelemetry span for Phoenix observability, or None on fallback.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the OpenTelemetry span. |
'compact_session_history'
|
Yields:
| Type | Description |
|---|---|
Any
|
Active span if tracing is available, otherwise None. |
Source code in zocrates/agents/common/compaction.py
_suppress_reasoning_effort ¶
Safely suppress reasoning/thinking effort on LLM instances without raising Pydantic field errors.
Source code in zocrates/agents/common/compaction.py
_trim_to_completed_turns ¶
Ensure events to compact only contain fully completed turns.
In conversational agent workflows, a turn may have 2 events (chat), 3 events (tool call + tool response), or more. If raw event slicing leaves an incomplete turn at the tail (such as an unanswered user question or open tool call), drop that turn completely from the compaction slice so the summarizer prompt always terminates cleanly on an Assistant completion.
Source code in zocrates/agents/common/compaction.py
build_agent_llm ¶
Build a dedicated LiteLlm instance for an agent role.
Resolves configuration according to precedence
agent_cfg > global_cfg > defaults
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_cfg
|
dict[str, Any]
|
Role-specific override dict (e.g. from override_agent_models). |
required |
global_cfg
|
dict[str, Any] | None
|
Optional global configuration dictionary (loaded if None). |
None
|
zotero_data_dir
|
Path | str | None
|
Optional Zotero data directory path. |
None
|
Returns:
| Type | Description |
|---|---|
BaseLlm
|
Configured ADK BaseLlm (LiteLlm) instance. |
Source code in zocrates/llm.py
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 | |
build_compaction_llm ¶
Build a fast, dedicated LiteLlm instance for context compaction with suppressed reasoning effort.
Source code in zocrates/agents/common/compaction.py
build_events_compaction_config ¶
Deactivated: native ADK pre-invocation triggers are replaced by post-turn adaptive compaction.
Source code in zocrates/agents/common/compaction.py
compact_session_adaptive
async
¶
Compact session history using adaptive retention slicing and rolling consolidation.
- Slices history into candidate turns covering Turns 1 .. N-K, retaining the latest K turns verbatim.
- If a previous compaction event exists: Consolidates the previous summary with new completed turns up to Turn N-K, preserving start_timestamp = previous_compaction.start_timestamp and setting end_timestamp = new_slice_events[-1].timestamp.
- If no previous compaction event exists: Summarizes all events from Turns 1 .. N-K spanning [slice_events[0].ts, slice_events[-1].ts].
- Wraps LLM invocation in OpenTelemetry span
compact_session_history(kind=LLM) with full attributes. - Fails open to None on any error or timeout without raising.
Source code in zocrates/agents/common/compaction.py
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 | |
load_zocrates_config ¶
Load the Zocrates config from the data directory.
If zotero_data_dir is None, attempts to obtain it from the active
LibrarySyncer service or the ZOTERO_DATA_DIR environment variable.
Returns config merged with standard defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zotero_data_dir
|
Path | str | None
|
Root Zotero data directory. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Parsed JSON config dict merged with defaults. |
Source code in zocrates/config.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 | |
run_adaptive_post_invocation_compaction
async
¶
Execute post-turn adaptive compaction check and compaction event append.
Returns True if a compaction event was generated and appended to the session, False otherwise. Fails open defensively without raising exceptions.
Source code in zocrates/agents/common/compaction.py
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 | |
should_trigger_adaptive_compaction ¶
Evaluate whether adaptive compaction should trigger post-turn for the given session.
Enforces:
1. Global enable toggle (enable_adaptive_compaction).
2. Minimum completed turns invariant: effective_min_turns = max(configured_min_turns, k + 1).
3. Coordinator prompt token envelope (token floor and ceiling):
- If tokens >= token_ceiling (default 100k): forces COMPRESS immediately without probing.
- If tokens < token_floor (default 30k): skips compaction without probing.
4. Fast decision model rubric probe on state (Returns COMPRESS if p >= threshold, else CONTINUE).
Fails open to CONTINUE on any probe error or timeout.
Source code in zocrates/agents/common/adaptive_decision.py
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 | |