zrb 1.21.9__py3-none-any.whl → 1.21.28__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.

Potentially problematic release.


This version of zrb might be problematic. Click here for more details.

Files changed (41) hide show
  1. zrb/attr/type.py +10 -7
  2. zrb/builtin/git.py +12 -1
  3. zrb/builtin/llm/chat_completion.py +274 -0
  4. zrb/builtin/llm/chat_session_cmd.py +90 -28
  5. zrb/builtin/llm/chat_trigger.py +7 -1
  6. zrb/builtin/llm/history.py +4 -4
  7. zrb/builtin/llm/tool/code.py +4 -1
  8. zrb/builtin/llm/tool/file.py +36 -81
  9. zrb/builtin/llm/tool/note.py +36 -16
  10. zrb/builtin/llm/tool/sub_agent.py +30 -10
  11. zrb/config/config.py +108 -13
  12. zrb/config/default_prompt/interactive_system_prompt.md +1 -1
  13. zrb/config/default_prompt/summarization_prompt.md +54 -8
  14. zrb/config/default_prompt/system_prompt.md +1 -1
  15. zrb/config/llm_rate_limitter.py +24 -5
  16. zrb/input/option_input.py +13 -1
  17. zrb/task/llm/agent.py +42 -144
  18. zrb/task/llm/agent_runner.py +152 -0
  19. zrb/task/llm/config.py +7 -5
  20. zrb/task/llm/conversation_history.py +35 -24
  21. zrb/task/llm/conversation_history_model.py +4 -11
  22. zrb/task/llm/default_workflow/coding/workflow.md +2 -3
  23. zrb/task/llm/file_replacement.py +206 -0
  24. zrb/task/llm/file_tool_model.py +57 -0
  25. zrb/task/llm/history_processor.py +206 -0
  26. zrb/task/llm/history_summarization.py +2 -179
  27. zrb/task/llm/print_node.py +14 -5
  28. zrb/task/llm/prompt.py +7 -18
  29. zrb/task/llm/subagent_conversation_history.py +41 -0
  30. zrb/task/llm/tool_wrapper.py +27 -12
  31. zrb/task/llm_task.py +55 -47
  32. zrb/util/attr.py +17 -10
  33. zrb/util/cli/text.py +6 -4
  34. zrb/util/git.py +2 -2
  35. zrb/util/yaml.py +1 -0
  36. zrb/xcom/xcom.py +10 -0
  37. {zrb-1.21.9.dist-info → zrb-1.21.28.dist-info}/METADATA +5 -5
  38. {zrb-1.21.9.dist-info → zrb-1.21.28.dist-info}/RECORD +40 -35
  39. zrb/task/llm/history_summarization_tool.py +0 -24
  40. {zrb-1.21.9.dist-info → zrb-1.21.28.dist-info}/WHEEL +0 -0
  41. {zrb-1.21.9.dist-info → zrb-1.21.28.dist-info}/entry_points.txt +0 -0
@@ -1,7 +1,6 @@
1
1
  import json
2
2
  import os
3
3
  from collections.abc import Callable
4
- from copy import deepcopy
5
4
  from typing import Any
6
5
 
7
6
  from zrb.attr.type import StrAttr
@@ -13,6 +12,37 @@ from zrb.util.attr import get_str_attr
13
12
  from zrb.util.file import read_file, write_file
14
13
  from zrb.util.markdown import make_markdown_section
15
14
  from zrb.util.run import run_async
15
+ from zrb.xcom.xcom import Xcom
16
+
17
+
18
+ def _get_global_subagent_messages_xcom(ctx: AnyContext) -> Xcom:
19
+ if "_global_subagents" not in ctx.xcom:
20
+ ctx.xcom["_global_subagents"] = Xcom([{}])
21
+ if not isinstance(ctx.xcom["_global_subagents"], Xcom):
22
+ raise ValueError("ctx.xcom._global_subagents must be an Xcom")
23
+ return ctx.xcom["_global_subagents"]
24
+
25
+
26
+ def inject_subagent_history_into_ctx(
27
+ ctx: AnyContext, conversation_history: ConversationHistory
28
+ ):
29
+ subagent_messages_xcom = _get_global_subagent_messages_xcom(ctx)
30
+ existing_subagent_history = subagent_messages_xcom.get({})
31
+ subagent_messages_xcom.set(
32
+ {**existing_subagent_history, **conversation_history.subagent_history}
33
+ )
34
+
35
+
36
+ def set_ctx_subagent_history(ctx: AnyContext, subagent_name: str, messages: ListOfDict):
37
+ subagent_messages_xcom = _get_global_subagent_messages_xcom(ctx)
38
+ subagent_history = subagent_messages_xcom.get({})
39
+ subagent_history[subagent_name] = messages
40
+ subagent_messages_xcom.set(subagent_history)
41
+
42
+
43
+ def get_subagent_histories_from_ctx(ctx: AnyContext) -> dict[str, ListOfDict]:
44
+ subagent_messsages_xcom = _get_global_subagent_messages_xcom(ctx)
45
+ return subagent_messsages_xcom.get({})
16
46
 
17
47
 
18
48
  def inject_conversation_history_notes(conversation_history: ConversationHistory):
@@ -56,7 +86,10 @@ def get_history_file(
56
86
 
57
87
  async def _read_from_source(
58
88
  ctx: AnyContext,
59
- reader: Callable[[AnyContext], dict[str, Any] | list | None] | None,
89
+ reader: (
90
+ Callable[[AnyContext], ConversationHistory | dict[str, Any] | list | None]
91
+ | None
92
+ ),
60
93
  file_path: str | None,
61
94
  ) -> "ConversationHistory | None":
62
95
  # Priority 1: Reader function
@@ -165,28 +198,6 @@ async def write_conversation_history(
165
198
  write_file(history_file, json.dumps(history_data.to_dict(), indent=2))
166
199
 
167
200
 
168
- def replace_system_prompt_in_history(
169
- history_list: ListOfDict, replacement: str = "<main LLM system prompt>"
170
- ) -> ListOfDict:
171
- """
172
- Returns a new history list where any part with part_kind 'system-prompt'
173
- has its 'content' replaced with the given replacement string.
174
- Args:
175
- history: List of history items (each item is a dict with a 'parts' list).
176
- replacement: The string to use in place of system-prompt content.
177
-
178
- Returns:
179
- A deep-copied list of history items with system-prompt content replaced.
180
- """
181
- new_history = deepcopy(history_list)
182
- for item in new_history:
183
- parts = item.get("parts", [])
184
- for part in parts:
185
- if part.get("part_kind") == "system-prompt":
186
- part["content"] = replacement
187
- return new_history
188
-
189
-
190
201
  def count_part_in_history_list(history_list: ListOfDict) -> int:
191
202
  """Calculates the total number of 'parts' in a history list."""
192
203
  history_part_len = 0
@@ -10,27 +10,24 @@ class ConversationHistory:
10
10
 
11
11
  def __init__(
12
12
  self,
13
- past_conversation_summary: str = "",
14
- past_conversation_transcript: str = "",
15
13
  history: ListOfDict | None = None,
16
14
  contextual_note: str | None = None,
17
15
  long_term_note: str | None = None,
18
16
  project_path: str | None = None,
17
+ subagent_history: dict[str, ListOfDict] | None = None,
19
18
  ):
20
- self.past_conversation_transcript = past_conversation_transcript
21
- self.past_conversation_summary = past_conversation_summary
22
19
  self.history = history if history is not None else []
23
20
  self.contextual_note = contextual_note if contextual_note is not None else ""
24
21
  self.long_term_note = long_term_note if long_term_note is not None else ""
25
22
  self.project_path = project_path if project_path is not None else os.getcwd()
23
+ self.subagent_history = subagent_history if subagent_history is not None else {}
26
24
 
27
25
  def to_dict(self) -> dict[str, Any]:
28
26
  return {
29
- "past_conversation_summary": self.past_conversation_summary,
30
- "past_conversation_transcript": self.past_conversation_transcript,
31
27
  "history": self.history,
32
28
  "contextual_note": self.contextual_note,
33
29
  "long_term_note": self.long_term_note,
30
+ "subagent_history": self.subagent_history,
34
31
  }
35
32
 
36
33
  def model_dump_json(self, indent: int = 2) -> str:
@@ -44,15 +41,11 @@ class ConversationHistory:
44
41
  if isinstance(data, cls):
45
42
  return data # Already a valid instance
46
43
  if isinstance(data, dict):
47
- # This handles both the new format and the old {'context': ..., 'history': ...}
48
44
  return cls(
49
- past_conversation_summary=data.get("past_conversation_summary", ""),
50
- past_conversation_transcript=data.get(
51
- "past_conversation_transcript", ""
52
- ),
53
45
  history=data.get("history", data.get("messages", [])),
54
46
  contextual_note=data.get("contextual_note", ""),
55
47
  long_term_note=data.get("long_term_note", ""),
48
+ subagent_history=data.get("subagent_history", {}),
56
49
  )
57
50
  elif isinstance(data, list):
58
51
  # Handle very old format (just a list) - wrap it
@@ -1,5 +1,5 @@
1
1
  ---
2
- description: "A comprehensive workflow for software engineering tasks, including writing, modifying, and debugging code, as well as creating new applications."
2
+ description: "A comprehensive workflow for software engineering tasks, including writing, modifying, and debugging code, as well as creating new applications. ALWAYS activate this workflow whenever you need to deal with software engineering tasks."
3
3
  ---
4
4
 
5
5
  This workflow provides a structured approach to software engineering tasks. Adhere to these guidelines to deliver high-quality, idiomatic code that respects the project's existing patterns and conventions.
@@ -35,8 +35,7 @@ Always consider if a more specific workflow is available and appropriate for the
35
35
  When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this sequence:
36
36
  1. **Understand & Strategize:** Think about the user's request and the relevant codebase context. When the task involves **complex refactoring, codebase exploration or system-wide analysis**, your **first and primary tool** must be 'codebase_investigator'. Use it to build a comprehensive understanding of the code, its structure, and dependencies. For **simple, targeted searches** (like finding a specific function name, file path, or variable declaration), you should use 'search_file_content' or 'glob' directly.
37
37
  2. **Plan:** Build a coherent and grounded (based on the understanding in step 1) plan for how you intend to resolve the user's task. Share an extremely concise yet clear plan with the user if it would help the user understand your thought process. As part of the plan, you should use an iterative development process that includes writing unit tests to verify your changes. Use output logs or debug statements as part of this process to arrive at a solution.
38
- 3. **Implement:** Use the available tools (e.g., 'replace', 'write_file' 'run_shell_command' ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core
39
- Mandates').
38
+ 3. **Implement:** Use the available tools (e.g., 'replace_in_file', 'write_to_file' 'run_shell_command' ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core Mandates').
40
39
  4. **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands.
41
40
  5. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to.
42
41
  6. **Finalize:** After all verification passes, consider the task complete. Do not remove or revert any changes or created files (like tests). Await the user's next instruction.
@@ -0,0 +1,206 @@
1
+ import difflib
2
+ import os
3
+ import shlex
4
+ import subprocess
5
+ import tempfile
6
+ from typing import Any
7
+
8
+ from zrb.config.config import CFG
9
+ from zrb.task.llm.file_tool_model import FileReplacement
10
+ from zrb.util.file import read_file
11
+
12
+
13
+ def is_single_path_replacement(param: Any):
14
+ if isinstance(param, dict):
15
+ return _dict_has_exact_keys(
16
+ param, {"path", "old_text", "new_text"}
17
+ ) or _dict_has_exact_keys(param, {"path", "old_text", "new_text", "count"})
18
+ if isinstance(param, list):
19
+ current_path = None
20
+ for single_replacement in param:
21
+ if not is_single_path_replacement(single_replacement):
22
+ return False
23
+ if current_path is not None and current_path != single_replacement["path"]:
24
+ return False
25
+ current_path = single_replacement["path"]
26
+ return True
27
+ return False
28
+
29
+
30
+ def _dict_has_exact_keys(dictionary: dict, required_keys: set) -> bool:
31
+ """
32
+ Check if a dictionary contains exactly the specified keys.
33
+ More efficient for large dictionaries.
34
+ """
35
+ if len(dictionary) != len(required_keys):
36
+ return False
37
+ return all(key in dictionary for key in required_keys)
38
+
39
+
40
+ def edit_replacement(
41
+ replacement: list[FileReplacement] | FileReplacement,
42
+ diff_edit_command_tpl: str | None = None,
43
+ ) -> tuple[list[FileReplacement] | FileReplacement, bool]:
44
+ # Normalize input to list
45
+ replacement_list = [replacement] if isinstance(replacement, dict) else replacement
46
+ if not replacement_list:
47
+ return replacement, False
48
+ path = replacement_list[0]["path"]
49
+ original_content = read_file(path)
50
+ # Calculate initial proposed content based on AI's suggestion
51
+ proposed_content = _apply_initial_replacements(original_content, replacement_list)
52
+ # Open external editor for user modification
53
+ edited_content = _open_diff_editor(
54
+ path, original_content, proposed_content, diff_edit_command_tpl
55
+ )
56
+ # If content hasn't changed from proposal, return original replacement
57
+ if edited_content == proposed_content:
58
+ return replacement, False
59
+ # Calculate optimized replacements based on user's final edit
60
+ optimized_replacements = _generate_optimized_replacements(
61
+ path, original_content, edited_content
62
+ )
63
+ return optimized_replacements, True
64
+
65
+
66
+ def _apply_initial_replacements(
67
+ content: str, replacement_list: list[FileReplacement]
68
+ ) -> str:
69
+ new_content = content
70
+ for single_replacement in replacement_list:
71
+ old_text = single_replacement["old_text"]
72
+ new_text = single_replacement["new_text"]
73
+ count = single_replacement.get("count", -1)
74
+ new_content = new_content.replace(old_text, new_text, count)
75
+ return new_content
76
+
77
+
78
+ def _open_diff_editor(
79
+ original_path: str,
80
+ original_content: str,
81
+ proposed_content: str,
82
+ diff_edit_command_tpl: str | None,
83
+ ) -> str:
84
+ if diff_edit_command_tpl is None:
85
+ diff_edit_command_tpl = CFG.DEFAULT_DIFF_EDIT_COMMAND_TPL
86
+ _, extension = os.path.splitext(original_path)
87
+ with tempfile.NamedTemporaryFile(delete=False, suffix=extension) as old_file:
88
+ old_file_name = old_file.name
89
+ old_file.write(original_content.encode())
90
+ old_file.flush()
91
+ with tempfile.NamedTemporaryFile(delete=False, suffix=extension) as new_file:
92
+ new_file_name = new_file.name
93
+ new_file.write(proposed_content.encode())
94
+ new_file.flush()
95
+ diff_edit_command = diff_edit_command_tpl.format(
96
+ old=old_file_name, new=new_file_name
97
+ )
98
+ subprocess.call(shlex.split(diff_edit_command))
99
+ edited_content = read_file(new_file_name)
100
+ if os.path.exists(old_file_name):
101
+ os.remove(old_file_name)
102
+ if os.path.exists(new_file_name):
103
+ os.remove(new_file_name)
104
+ return edited_content
105
+
106
+
107
+ def _generate_optimized_replacements(
108
+ path: str, original_content: str, edited_content: str
109
+ ) -> list[FileReplacement]:
110
+ matcher = difflib.SequenceMatcher(None, original_content, edited_content)
111
+ hunks = _group_opcodes_into_hunks(matcher.get_opcodes())
112
+ replacements = []
113
+ for hunk in hunks:
114
+ replacement = _create_replacement_from_hunk(
115
+ path, original_content, edited_content, hunk
116
+ )
117
+ if replacement:
118
+ replacements.append(replacement)
119
+ return replacements
120
+
121
+
122
+ def _group_opcodes_into_hunks(opcodes, merge_threshold=200):
123
+ """
124
+ Groups opcodes into hunks.
125
+ 'equal' blocks smaller than merge_threshold are treated as context (glue) within a hunk.
126
+ """
127
+ hunks = []
128
+ current_hunk = []
129
+ for tag, i1, i2, j1, j2 in opcodes:
130
+ if tag == "equal":
131
+ if i2 - i1 < merge_threshold:
132
+ if current_hunk:
133
+ current_hunk.append((tag, i1, i2, j1, j2))
134
+ else:
135
+ if current_hunk:
136
+ hunks.append(current_hunk)
137
+ current_hunk = []
138
+ else:
139
+ current_hunk.append((tag, i1, i2, j1, j2))
140
+ if current_hunk:
141
+ hunks.append(current_hunk)
142
+ return hunks
143
+
144
+
145
+ def _create_replacement_from_hunk(
146
+ path: str, original_content: str, edited_content: str, hunk: list
147
+ ) -> FileReplacement | None:
148
+ # Trim leading/trailing 'equal' opcodes
149
+ while hunk and hunk[0][0] == "equal":
150
+ hunk.pop(0)
151
+ while hunk and hunk[-1][0] == "equal":
152
+ hunk.pop()
153
+ if not hunk:
154
+ return None
155
+ # Determine range of modification
156
+ i_start = hunk[0][1]
157
+ i_end = hunk[-1][2]
158
+ j_start = hunk[0][3]
159
+ j_end = hunk[-1][4]
160
+ base_old_text = original_content[i_start:i_end]
161
+ base_new_text = edited_content[j_start:j_end]
162
+ if base_old_text == base_new_text:
163
+ return None
164
+ # Expand context
165
+ start, end = _expand_context_for_uniqueness(original_content, i_start, i_end)
166
+ start, end = _expand_to_word_boundary(original_content, start, end)
167
+ final_old_text = original_content[start:end]
168
+ # Reconstruct new text
169
+ prefix = original_content[start:i_start]
170
+ suffix = original_content[i_end:end]
171
+ final_new_text = prefix + base_new_text + suffix
172
+ if final_old_text == final_new_text:
173
+ return None
174
+ return {
175
+ "path": path,
176
+ "old_text": final_old_text,
177
+ "new_text": final_new_text,
178
+ "count": 1,
179
+ }
180
+
181
+
182
+ def _expand_context_for_uniqueness(
183
+ content: str, start: int, end: int
184
+ ) -> tuple[int, int]:
185
+ """Expands the range [start, end] until the substring content[start:end] is unique."""
186
+ while content.count(content[start:end]) > 1:
187
+ if start == 0 and end == len(content):
188
+ break
189
+ if start > 0:
190
+ start -= 1
191
+ if end < len(content):
192
+ end += 1
193
+ return start, end
194
+
195
+
196
+ def _expand_to_word_boundary(content: str, start: int, end: int) -> tuple[int, int]:
197
+ """Expands the range [start, end] outwards to the nearest whitespace boundaries."""
198
+
199
+ def is_boundary(char):
200
+ return char.isspace()
201
+
202
+ while start > 0 and not is_boundary(content[start - 1]):
203
+ start -= 1
204
+ while end < len(content) and not is_boundary(content[end]):
205
+ end += 1
206
+ return start, end
@@ -0,0 +1,57 @@
1
+ import sys
2
+ from typing import Literal
3
+
4
+ if sys.version_info >= (3, 12):
5
+ from typing import NotRequired, TypedDict
6
+ else:
7
+ from typing_extensions import NotRequired, TypedDict
8
+
9
+
10
+ class FileToRead(TypedDict):
11
+ """
12
+ Configuration for reading a file or file section.
13
+
14
+ Attributes:
15
+ path (str): Absolute or relative path to the file
16
+ start_line (int | None): Starting line number (1-based, inclusive).
17
+ If None, reads from beginning.
18
+ end_line (int | None): Ending line number (1-based, exclusive). If None, reads to end.
19
+ """
20
+
21
+ path: str
22
+ start_line: NotRequired[int | None]
23
+ end_line: NotRequired[int | None]
24
+
25
+
26
+ class FileToWrite(TypedDict):
27
+ """
28
+ Configuration for writing content to a file.
29
+
30
+ Attributes:
31
+ path (str): Absolute or relative path where file will be written.
32
+ content (str): Content to write. CRITICAL: For JSON, ensure all special characters
33
+ in this string are properly escaped.
34
+ mode (str): Mode for writing:
35
+ 'w' (overwrite, default), 'a' (append), 'x' (create exclusively).
36
+ """
37
+
38
+ path: str
39
+ content: str
40
+ mode: NotRequired[Literal["w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"]]
41
+
42
+
43
+ class FileReplacement(TypedDict):
44
+ """
45
+ Configuration for a single text replacement operation in a file.
46
+
47
+ Attributes:
48
+ path (str): Absolute or relative path to the file
49
+ old_text (str): Exact text to find and replace (must match file content exactly)
50
+ new_text (str): New text to replace with
51
+ count (int): Optional. Number of occurrences to replace. Defaults to -1 (all).
52
+ """
53
+
54
+ path: str
55
+ old_text: str
56
+ new_text: str
57
+ count: NotRequired[int]
@@ -0,0 +1,206 @@
1
+ import json
2
+ import sys
3
+ import traceback
4
+ from typing import TYPE_CHECKING, Any, Callable, Coroutine
5
+
6
+ from zrb.config.llm_config import llm_config
7
+ from zrb.config.llm_rate_limitter import LLMRateLimitter
8
+ from zrb.config.llm_rate_limitter import llm_rate_limitter as default_llm_rate_limitter
9
+ from zrb.context.any_context import AnyContext
10
+ from zrb.task.llm.agent_runner import run_agent_iteration
11
+ from zrb.util.cli.style import stylize_faint
12
+ from zrb.util.markdown import make_markdown_section
13
+
14
+ if sys.version_info >= (3, 12):
15
+ from typing import TypedDict
16
+ else:
17
+ from typing_extensions import TypedDict
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from pydantic_ai import ModelMessage
22
+ from pydantic_ai.models import Model
23
+ from pydantic_ai.settings import ModelSettings
24
+
25
+
26
+ class SingleMessage(TypedDict):
27
+ """
28
+ SingleConversation
29
+
30
+ Attributes:
31
+ role: Either AI, User, Tool Call, or Tool Result
32
+ time: yyyy-mm-ddTHH:MM:SSZ:
33
+ content: The content of the message (summarize if too long)
34
+ """
35
+
36
+ role: str
37
+ time: str
38
+ content: str
39
+
40
+
41
+ class ConversationSummary(TypedDict):
42
+ """
43
+ Conversation history
44
+
45
+ Attributes:
46
+ transcript: Several last transcript of the conversation
47
+ summary: Descriptive conversation summary
48
+ """
49
+
50
+ transcript: list[SingleMessage]
51
+ summary: str
52
+
53
+
54
+ def save_conversation_summary(conversation_summary: ConversationSummary):
55
+ """
56
+ Write conversation summary for main assistant to continue conversation.
57
+ """
58
+ return conversation_summary
59
+
60
+
61
+ def create_summarize_history_processor(
62
+ ctx: AnyContext,
63
+ system_prompt: str,
64
+ rate_limitter: LLMRateLimitter | None = None,
65
+ summarization_model: "Model | str | None" = None,
66
+ summarization_model_settings: "ModelSettings | None" = None,
67
+ summarization_system_prompt: str | None = None,
68
+ summarization_token_threshold: int | None = None,
69
+ summarization_retries: int = 2,
70
+ ) -> Callable[[list["ModelMessage"]], Coroutine[None, None, list["ModelMessage"]]]:
71
+ from pydantic_ai import Agent, ModelMessage, ModelRequest
72
+ from pydantic_ai.messages import ModelMessagesTypeAdapter, UserPromptPart
73
+
74
+ if rate_limitter is None:
75
+ rate_limitter = default_llm_rate_limitter
76
+ if summarization_model is None:
77
+ summarization_model = llm_config.default_small_model
78
+ if summarization_model_settings is None:
79
+ summarization_model_settings = llm_config.default_small_model_settings
80
+ if summarization_system_prompt is None:
81
+ summarization_system_prompt = llm_config.default_summarization_prompt
82
+ if summarization_token_threshold is None:
83
+ summarization_token_threshold = (
84
+ llm_config.default_history_summarization_token_threshold
85
+ )
86
+
87
+ async def maybe_summarize_history(
88
+ messages: list[ModelMessage],
89
+ ) -> list[ModelMessage]:
90
+ history_list = json.loads(ModelMessagesTypeAdapter.dump_json(messages))
91
+ history_json_str = json.dumps(history_list)
92
+ # Estimate token usage
93
+ # Note: Pydantic ai has run context parameter
94
+ # (https://ai.pydantic.dev/message-history/#runcontext-parameter)
95
+ # But we cannot use run_ctx.usage.total_tokens because total token keep increasing
96
+ # even after summariztion.
97
+ estimated_token_usage = rate_limitter.count_token(history_json_str)
98
+ _print_request_info(
99
+ ctx, estimated_token_usage, summarization_token_threshold, messages
100
+ )
101
+ if estimated_token_usage < summarization_token_threshold or len(messages) == 1:
102
+ return messages
103
+ history_list_without_instruction = [
104
+ {
105
+ key: obj[key]
106
+ for key in obj
107
+ if index == len(history_list) - 1 or key != "instructions"
108
+ }
109
+ for index, obj in enumerate(history_list)
110
+ ]
111
+ history_json_str_without_instruction = json.dumps(
112
+ history_list_without_instruction
113
+ )
114
+ summarization_message = f"Summarize the following conversation: {history_json_str_without_instruction}"
115
+ summarization_agent = Agent[None, ConversationSummary](
116
+ model=summarization_model,
117
+ output_type=save_conversation_summary,
118
+ instructions=summarization_system_prompt,
119
+ model_settings=summarization_model_settings,
120
+ retries=summarization_retries,
121
+ )
122
+ try:
123
+ _print_info(ctx, "📝 Rollup Conversation", 2)
124
+ summary_run = await run_agent_iteration(
125
+ ctx=ctx,
126
+ agent=summarization_agent,
127
+ user_prompt=summarization_message,
128
+ attachments=[],
129
+ history_list=[],
130
+ rate_limitter=rate_limitter,
131
+ log_indent_level=2,
132
+ )
133
+ if summary_run and summary_run.result and summary_run.result.output:
134
+ usage = summary_run.result.usage()
135
+ _print_info(ctx, f"📝 Rollup Conversation Token: {usage}", 2)
136
+ ctx.print(plain=True)
137
+ ctx.log_info("History summarized and updated.")
138
+ condensed_message = make_markdown_section(
139
+ header="Past Conversation",
140
+ content="\n".join(
141
+ [
142
+ make_markdown_section(
143
+ "Summary", _extract_summary(summary_run.result.output)
144
+ ),
145
+ make_markdown_section(
146
+ "Past Trancript",
147
+ _extract_transcript(summary_run.result.output),
148
+ ),
149
+ ]
150
+ ),
151
+ )
152
+ return [
153
+ ModelRequest(
154
+ instructions=system_prompt,
155
+ parts=[UserPromptPart(condensed_message)],
156
+ )
157
+ ]
158
+ ctx.log_warning("History summarization failed or returned no data.")
159
+ except BaseException as e:
160
+ ctx.log_warning(f"Error during history summarization: {e}")
161
+ traceback.print_exc()
162
+ return messages
163
+
164
+ return maybe_summarize_history
165
+
166
+
167
+ def _print_request_info(
168
+ ctx: AnyContext,
169
+ estimated_token_usage: int,
170
+ summarization_token_threshold: int,
171
+ messages: list["ModelMessage"],
172
+ ):
173
+ _print_info(ctx, f"Current request token (estimated): {estimated_token_usage}")
174
+ _print_info(ctx, f"Summarization token threshold: {summarization_token_threshold}")
175
+ _print_info(ctx, f"History length: {len(messages)}")
176
+
177
+
178
+ def _print_info(ctx: AnyContext, text: str, log_indent_level: int = 0):
179
+ log_prefix = (2 * (log_indent_level + 1)) * " "
180
+ ctx.print(stylize_faint(f"{log_prefix}{text}"), plain=True)
181
+
182
+
183
+ def _extract_summary(summary_result_output: dict[str, Any] | str) -> str:
184
+ summary = (
185
+ summary_result_output.get("summary", "")
186
+ if isinstance(summary_result_output, dict)
187
+ else ""
188
+ )
189
+ return summary
190
+
191
+
192
+ def _extract_transcript(summary_result_output: dict[str, Any] | str) -> str:
193
+ transcript_list = (
194
+ summary_result_output.get("transcript", [])
195
+ if isinstance(summary_result_output, dict)
196
+ else []
197
+ )
198
+ transcript_list = [] if not isinstance(transcript_list, list) else transcript_list
199
+ return "\n".join(_format_transcript_message(message) for message in transcript_list)
200
+
201
+
202
+ def _format_transcript_message(message: dict[str, str]) -> str:
203
+ role = message.get("role", "Message")
204
+ time = message.get("time", "<unknown>")
205
+ content = message.get("content", "<empty>")
206
+ return f"{role} ({time}): {content}"