zrb 1.10.2__py3-none-any.whl → 1.11.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,10 +3,11 @@ import os
3
3
  from collections.abc import Callable
4
4
  from typing import Any
5
5
 
6
- from zrb.config.config import CFG
6
+ from zrb.config.llm_context.config import llm_context_config
7
7
  from zrb.context.any_context import AnyContext
8
8
  from zrb.task.llm.typing import ListOfDict
9
- from zrb.util.file import read_file, read_file_with_line_numbers, write_file
9
+ from zrb.util.file import read_file
10
+ from zrb.util.llm.prompt import make_prompt_section
10
11
  from zrb.util.run import run_async
11
12
 
12
13
 
@@ -81,14 +82,8 @@ class ConversationHistory:
81
82
  return None
82
83
 
83
84
  def fetch_newest_notes(self):
84
- self.long_term_note = ""
85
- long_term_note_path = self._get_long_term_note_path()
86
- if os.path.isfile(long_term_note_path):
87
- self.long_term_note = read_file(long_term_note_path)
88
- self.contextual_note = ""
89
- contextual_note_path = self._get_contextual_note_path()
90
- if os.path.isfile(contextual_note_path):
91
- self.contextual_note = read_file(contextual_note_path)
85
+ self._fetch_long_term_note()
86
+ self._fetch_contextual_note()
92
87
 
93
88
  @classmethod
94
89
  def parse_and_validate(
@@ -139,12 +134,13 @@ class ConversationHistory:
139
134
  past_conversation_summary (str): The summary text to store.
140
135
 
141
136
  Returns:
142
- None
137
+ str: A JSON object indicating the success or failure of the operation.
143
138
 
144
139
  Raises:
145
140
  Exception: If the summary cannot be written.
146
141
  """
147
142
  self.past_conversation_summary = past_conversation_summary
143
+ return json.dumps({"success": True})
148
144
 
149
145
  def write_past_conversation_transcript(self, past_conversation_transcript: str):
150
146
  """
@@ -157,284 +153,140 @@ class ConversationHistory:
157
153
  past_conversation_transcript (str): The transcript text to store.
158
154
 
159
155
  Returns:
160
- None
156
+ str: A JSON object indicating the success or failure of the operation.
161
157
 
162
158
  Raises:
163
159
  Exception: If the transcript cannot be written.
164
160
  """
165
161
  self.past_conversation_transcript = past_conversation_transcript
162
+ return json.dumps({"success": True})
166
163
 
167
- def read_long_term_note(
168
- self,
169
- start_line: int | None = None,
170
- end_line: int | None = None,
171
- ) -> str:
164
+ def read_long_term_note(self) -> str:
172
165
  """
173
- Read the content of the long-term note, optionally for a specific line range.
166
+ Read the content of the long-term references.
174
167
 
175
168
  This tool helps you retrieve knowledge or notes stored for long-term reference.
176
169
  If the note does not exist, you may want to create it using the write tool.
177
170
 
178
- Args:
179
- start_line (int, optional): 1-based line number to start reading from.
180
- end_line (int, optional): 1-based line number to stop reading at (inclusive).
181
-
182
171
  Returns:
183
- str: JSON with file path, content (with line numbers), start/end lines,
184
- and total lines.
172
+ str: JSON with content of the notes.
185
173
 
186
174
  Raises:
187
175
  Exception: If the note cannot be read.
188
- Suggests writing the note if it does not exist.
189
176
  """
190
- return self._read_note(
191
- self._get_long_term_note_path(),
192
- start_line,
193
- end_line,
194
- note_type="long-term note",
195
- )
177
+ return json.dumps({"content": self._fetch_long_term_note()})
196
178
 
197
- def write_long_term_note(self, content: str) -> str:
179
+ def add_long_term_info(self, new_info: str) -> str:
198
180
  """
199
- Write or overwrite the content of the long-term note.
200
-
201
- Use this tool to create a new long-term note or replace its entire content.
202
- Always read the note first to avoid accidental data loss, unless you are sure
203
- you want to overwrite.
181
+ Add new info for long-term reference.
204
182
 
205
183
  Args:
206
- content (str): The full content to write to the note.
184
+ new_info (str): New info to be added into long-term references.
207
185
 
208
186
  Returns:
209
- str: JSON indicating success and the note path.
187
+ str: JSON with new content of the notes.
210
188
 
211
189
  Raises:
212
- Exception: If the note cannot be written. Suggests checking permissions or path.
190
+ Exception: If the note cannot be read.
213
191
  """
214
- self.long_term_note = content
215
- return self._write_note(
216
- self._get_long_term_note_path(), content, note_type="long-term note"
217
- )
192
+ llm_context_config.add_to_context(new_info, cwd="/")
193
+ return json.dumps({"success": True, "content": self._fetch_long_term_note()})
218
194
 
219
- def replace_in_long_term_note(
220
- self,
221
- old_string: str,
222
- new_string: str,
223
- ) -> str:
195
+ def remove_long_term_info(self, irrelevant_info: str) -> str:
224
196
  """
225
- Replace the first occurrence of a string in the long-term note.
226
-
227
- Use this tool to update a specific part of the long-term note without
228
- overwriting the entire content. If the note does not exist, consider writing it
229
- first. If the string is not found, check your input or read the note to verify.
197
+ Remove irrelevant info from long-term reference.
230
198
 
231
199
  Args:
232
- old_string (str): The exact string to search for and replace.
233
- new_string (str): The string to replace with.
200
+ irrelevant_info (str): Irrelevant info to be removed from long-term references.
234
201
 
235
202
  Returns:
236
- str: JSON indicating success and the note path.
203
+ str: JSON with new content of the notes and deletion status.
237
204
 
238
205
  Raises:
239
- Exception: If the note does not exist or the string is not found.
240
- Suggests writing or reading the note.
206
+ Exception: If the note cannot be read.
241
207
  """
242
- result = self._replace_in_note(
243
- self._get_long_term_note_path(),
244
- old_string,
245
- new_string,
246
- note_type="long-term note",
208
+ was_removed = llm_context_config.remove_from_context(irrelevant_info, cwd="/")
209
+ return json.dumps(
210
+ {
211
+ "success": was_removed,
212
+ "content": self._fetch_long_term_note(),
213
+ }
247
214
  )
248
- self.long_term_note = new_string
249
- return result
250
215
 
251
- def read_contextual_note(
252
- self,
253
- start_line: int | None = None,
254
- end_line: int | None = None,
255
- ) -> str:
216
+ def read_contextual_note(self) -> str:
256
217
  """
257
- Read the content of the contextual note, optionally for a specific line range.
218
+ Read the content of the contextual references.
258
219
 
259
- This tool helps you retrieve project-specific or session-specific notes.
220
+ This tool helps you retrieve knowledge or notes stored for contextual reference.
260
221
  If the note does not exist, you may want to create it using the write tool.
261
222
 
262
- Args:
263
- start_line (int, optional): 1-based line number to start reading from.
264
- end_line (int, optional): 1-based line number to stop reading at (inclusive).
265
-
266
223
  Returns:
267
- str: JSON with file path, content (with line numbers), start/end lines,
268
- and total lines.
224
+ str: JSON with content of the notes.
269
225
 
270
226
  Raises:
271
227
  Exception: If the note cannot be read.
272
- Suggests writing the note if it does not exist.
273
228
  """
274
- return self._read_note(
275
- self._get_contextual_note_path(),
276
- start_line,
277
- end_line,
278
- note_type="contextual note",
279
- )
229
+ return json.dumps({"content": self._fetch_contextual_note()})
280
230
 
281
- def write_contextual_note(self, content: str) -> str:
231
+ def add_contextual_info(self, new_info: str, context_path: str | None) -> str:
282
232
  """
283
- Write or overwrite the content of the contextual note.
284
-
285
- Use this tool to create a new contextual note or replace its entire content.
286
- Always read the note first to avoid accidental data loss, unless you are sure
287
- you want to overwrite.
233
+ Add new info for contextual reference.
288
234
 
289
235
  Args:
290
- content (str): The full content to write to the note.
236
+ new_info (str): New info to be added into contextual references.
237
+ context_path (str, optional): contextual directory path for new info
291
238
 
292
239
  Returns:
293
- str: JSON indicating success and the note path.
240
+ str: JSON with new content of the notes.
294
241
 
295
242
  Raises:
296
- Exception: If the note cannot be written. Suggests checking permissions or path.
243
+ Exception: If the note cannot be read.
297
244
  """
298
- self.contextual_note = content
299
- return self._write_note(
300
- self._get_contextual_note_path(), content, note_type="contextual note"
301
- )
245
+ if context_path is None:
246
+ context_path = self.project_path
247
+ llm_context_config.add_to_context(new_info, context_path=context_path)
248
+ return json.dumps({"success": True, "content": self._fetch_contextual_note()})
302
249
 
303
- def replace_in_contextual_note(
304
- self,
305
- old_string: str,
306
- new_string: str,
250
+ def remove_contextual_info(
251
+ self, irrelevant_info: str, context_path: str | None
307
252
  ) -> str:
308
253
  """
309
- Replace the first occurrence of a string in the contextual note.
310
-
311
- Use this tool to update a specific part of the contextual note without
312
- overwriting the entire content. If the note does not exist, consider writing it
313
- first. If the string is not found, check your input or read the note to verify.
254
+ Remove irrelevant info from contextual reference.
314
255
 
315
256
  Args:
316
- old_string (str): The exact string to search for and replace.
317
- new_string (str): The string to replace with.
257
+ irrelevant_info (str): Irrelevant info to be removed from contextual references.
258
+ context_path (str, optional): contextual directory path of the irrelevant info
318
259
 
319
260
  Returns:
320
- str: JSON indicating success and the note path.
261
+ str: JSON with new content of the notes and deletion status.
321
262
 
322
263
  Raises:
323
- Exception: If the note does not exist or the string is not found.
324
- Suggests writing or reading the note.
264
+ Exception: If the note cannot be read.
325
265
  """
326
- result = self._replace_in_note(
327
- self._get_contextual_note_path(),
328
- old_string,
329
- new_string,
330
- note_type="contextual note",
266
+ if context_path is None:
267
+ context_path = self.project_path
268
+ was_removed = llm_context_config.remove_from_context(
269
+ irrelevant_info, context_path=context_path
270
+ )
271
+ return json.dumps(
272
+ {
273
+ "success": was_removed,
274
+ "content": self._fetch_contextual_note(),
275
+ }
331
276
  )
332
- self.contextual_note = new_string
333
- return result
334
-
335
- def _get_long_term_note_path(self) -> str:
336
- return os.path.abspath(os.path.expanduser(CFG.LLM_LONG_TERM_NOTE_PATH))
337
-
338
- def _get_contextual_note_path(self) -> str:
339
- return os.path.join(self.project_path, CFG.LLM_CONTEXTUAL_NOTE_FILE)
340
-
341
- def _read_note(
342
- self,
343
- path: str,
344
- start_line: int | None = None,
345
- end_line: int | None = None,
346
- note_type: str = "note",
347
- ) -> str:
348
- """
349
- Internal helper to read a note file with line numbers and error handling.
350
- """
351
- if not os.path.exists(path):
352
- return json.dumps(
353
- {
354
- "path": path,
355
- "content": "",
356
- "start_line": 0,
357
- "end_line": 0,
358
- "total_lines": 0,
359
- }
360
- )
361
- try:
362
- content = read_file_with_line_numbers(path)
363
- lines = content.splitlines()
364
- total_lines = len(lines)
365
- start_idx = (start_line - 1) if start_line is not None else 0
366
- end_idx = end_line if end_line is not None else total_lines
367
- if start_idx < 0:
368
- start_idx = 0
369
- if end_idx > total_lines:
370
- end_idx = total_lines
371
- if start_idx > end_idx:
372
- start_idx = end_idx
373
- selected_lines = lines[start_idx:end_idx]
374
- content_result = "\n".join(selected_lines)
375
- return json.dumps(
376
- {
377
- "path": path,
378
- "content": content_result,
379
- "start_line": start_idx + 1,
380
- "end_line": end_idx,
381
- "total_lines": total_lines,
382
- }
383
- )
384
- except Exception:
385
- raise Exception(
386
- f"Failed to read the {note_type}. "
387
- f"If the {note_type} does not exist, try writing it first."
388
- )
389
-
390
- def _write_note(self, path: str, content: str, note_type: str = "note") -> str:
391
- """
392
- Internal helper to write a note file with error handling.
393
- """
394
- try:
395
- directory = os.path.dirname(path)
396
- if directory and not os.path.exists(directory):
397
- os.makedirs(directory, exist_ok=True)
398
- write_file(path, content)
399
- return json.dumps({"success": True, "path": path})
400
- except (OSError, IOError):
401
- raise Exception(
402
- f"Failed to write the {note_type}. "
403
- "Please check if the path is correct and you have write permissions."
404
- )
405
- except Exception:
406
- raise Exception(
407
- f"Unexpected error while writing the {note_type}. "
408
- "Please check your input and try again."
409
- )
410
277
 
411
- def _replace_in_note(
412
- self, path: str, old_string: str, new_string: str, note_type: str = "note"
413
- ) -> str:
414
- """
415
- Internal helper to replace a string in a note file with error handling.
416
- """
417
- if not os.path.exists(path):
418
- raise Exception(
419
- (
420
- f"{note_type.capitalize()} not found. "
421
- f"Consider writing a new {note_type} first."
422
- )
423
- )
424
- try:
425
- content = read_file(path)
426
- if old_string not in content:
427
- raise Exception(
428
- f"The specified string to replace was not found in the {note_type}. ("
429
- f"Try reading the {note_type} to verify its content or "
430
- f"write a new one if needed)."
431
- )
432
- new_content = content.replace(old_string, new_string, 1)
433
- write_file(path, new_content)
434
- return json.dumps({"success": True, "path": path})
435
- except Exception:
436
- raise Exception(
437
- f"Failed to replace content in the {note_type}. ("
438
- f"Try reading the {note_type} to verify its content or "
439
- "write a new one if needed)."
440
- )
278
+ def _fetch_long_term_note(self):
279
+ contexts = llm_context_config.get_contexts(cwd=self.project_path)
280
+ self.long_term_note = contexts.get("/", "")
281
+ return self.long_term_note
282
+
283
+ def _fetch_contextual_note(self):
284
+ contexts = llm_context_config.get_contexts(cwd=self.project_path)
285
+ self.contextual_note = "\n".join(
286
+ [
287
+ make_prompt_section(header, content)
288
+ for header, content in contexts.items()
289
+ if header != "/"
290
+ ]
291
+ )
292
+ return self.contextual_note
@@ -145,16 +145,16 @@ async def summarize_history(
145
145
  tools=[
146
146
  conversation_history.write_past_conversation_summary,
147
147
  conversation_history.write_past_conversation_transcript,
148
- conversation_history.read_contextual_note,
149
- conversation_history.write_contextual_note,
150
- conversation_history.replace_in_contextual_note,
151
148
  conversation_history.read_long_term_note,
152
- conversation_history.write_long_term_note,
153
- conversation_history.replace_in_long_term_note,
149
+ conversation_history.add_long_term_info,
150
+ conversation_history.remove_long_term_info,
151
+ conversation_history.read_contextual_note,
152
+ conversation_history.add_contextual_info,
153
+ conversation_history.remove_contextual_info,
154
154
  ],
155
155
  )
156
156
  try:
157
- ctx.print(stylize_faint("📝 Summarize"), plain=True)
157
+ ctx.print(stylize_faint("📝 Summarize Conversation >>>"), plain=True)
158
158
  summary_run = await run_agent_iteration(
159
159
  ctx=ctx,
160
160
  agent=summarization_agent,
zrb/task/llm/prompt.py CHANGED
@@ -125,38 +125,37 @@ def get_system_and_user_prompt(
125
125
  def extract_conversation_context(user_message: str) -> tuple[str, str]:
126
126
  modified_user_message = user_message
127
127
  # Match “@” + any non-space/comma sequence that contains at least one “/”
128
- pattern = r"(?<!\w)@(?=[^,\s]*/)([^,\s]+)"
128
+ pattern = r"(?<!\w)@(?=[^,\s]*\/)([^,\s]+)"
129
129
  potential_resource_path = re.findall(pattern, user_message)
130
130
  apendixes = []
131
- for ref in potential_resource_path:
131
+ for i, ref in enumerate(potential_resource_path):
132
132
  resource_path = os.path.abspath(os.path.expanduser(ref))
133
- print("RESOURCE PATH", resource_path)
133
+ content = ""
134
+ ref_type = ""
134
135
  if os.path.isfile(resource_path):
135
136
  content = read_file_with_line_numbers(resource_path)
136
- apendixes.append(
137
- make_prompt_section(
138
- f"`{ref}` (file path: `{resource_path}`)", content, as_code=True
139
- )
140
- )
141
- # Remove the '@' from the modified user message for valid file paths
142
- modified_user_message = modified_user_message.replace(f"@{ref}", ref, 1)
137
+ ref_type = "file"
143
138
  elif os.path.isdir(resource_path):
144
139
  content = read_dir(resource_path)
140
+ ref_type = "directory"
141
+ if content != "":
142
+ # Replace the @-reference in the user message with the placeholder
143
+ placeholder = f"[Reference {i+1}: {os.path.basename(ref)}]"
144
+ modified_user_message = modified_user_message.replace(
145
+ f"@{ref}", placeholder, 1
146
+ )
145
147
  apendixes.append(
146
148
  make_prompt_section(
147
- f"`{ref}` (directory path: `{resource_path}`)",
149
+ f"{placeholder} ({ref_type} path: `{resource_path}`)",
148
150
  content,
149
151
  as_code=True,
150
152
  )
151
153
  )
152
- # Remove the '@' from the modified user message for valid directory paths
153
- modified_user_message = modified_user_message.replace(f"@{ref}", ref, 1)
154
154
  conversation_context = "\n".join(
155
155
  [
156
156
  make_prompt_section("Current OS", platform.system()),
157
157
  make_prompt_section("OS Version", platform.version()),
158
158
  make_prompt_section("Python Version", platform.python_version()),
159
- make_prompt_section("Apendixes", "\n".join(apendixes)),
160
159
  ]
161
160
  )
162
161
  iso_date = datetime.now(timezone.utc).astimezone().isoformat()
@@ -172,6 +171,7 @@ def extract_conversation_context(user_message: str) -> tuple[str, str]:
172
171
  "Current working directory", current_directory
173
172
  ),
174
173
  make_prompt_section("Current time", iso_date),
174
+ make_prompt_section("Apendixes", "\n".join(apendixes)),
175
175
  ]
176
176
  ),
177
177
  ),
zrb/util/llm/prompt.py CHANGED
@@ -2,17 +2,53 @@ import re
2
2
 
3
3
 
4
4
  def _demote_markdown_headers(md: str) -> str:
5
- def demote(match):
6
- hashes = match.group(1)
7
- return "#" + hashes + match.group(2) # add one `#`
5
+ lines = md.split("\n")
6
+ new_lines = []
7
+ fence_stack = []
8
+ for line in lines:
9
+ stripped_line = line.strip()
10
+ fence_match = re.match(r"^([`~]{3,})", stripped_line)
8
11
 
9
- # Replace headers at the beginning of a line
10
- return re.sub(r"^(#{1,6})(\s)", demote, md, flags=re.MULTILINE)
12
+ if fence_match:
13
+ current_fence = fence_match.group(1)
14
+ # If stack is not empty and we found a closing fence
15
+ if (
16
+ fence_stack
17
+ and fence_stack[-1][0] == current_fence[0]
18
+ and len(current_fence) >= len(fence_stack[-1])
19
+ ):
20
+ fence_stack.pop()
21
+ else:
22
+ fence_stack.append(current_fence)
23
+ new_lines.append(line)
24
+ else:
25
+ if fence_stack: # If we are inside a code block
26
+ new_lines.append(line)
27
+ else:
28
+ match = re.match(r"^(#{1,6})(\s)", line)
29
+ if match:
30
+ new_lines.append("#" + line)
31
+ else:
32
+ new_lines.append(line)
33
+ return "\n".join(new_lines)
11
34
 
12
35
 
13
36
  def make_prompt_section(header: str, content: str, as_code: bool = False) -> str:
14
37
  if content.strip() == "":
15
38
  return ""
16
39
  if as_code:
17
- return f"# {header}\n````\n{content.strip()}\n````\n"
40
+ # Find the longest sequence of backticks in the content
41
+ longest_backtick_sequence = 0
42
+ # Use finditer to find all occurrences of backticks
43
+ for match in re.finditer(r"`+", content):
44
+ longest_backtick_sequence = max(
45
+ longest_backtick_sequence, len(match.group(0))
46
+ )
47
+
48
+ # The fence should be one longer than the longest sequence found
49
+ fence_len = 4
50
+ if longest_backtick_sequence >= fence_len:
51
+ fence_len = longest_backtick_sequence + 1
52
+ fence = "`" * fence_len
53
+ return f"# {header}\n{fence}\n{content.strip()}\n{fence}\n"
18
54
  return f"# {header}\n{_demote_markdown_headers(content.strip())}\n"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: zrb
3
- Version: 1.10.2
3
+ Version: 1.11.0
4
4
  Summary: Your Automation Powerhouse
5
5
  Home-page: https://github.com/state-alchemists/zrb
6
6
  License: AGPL-3.0-or-later
@@ -27,7 +27,7 @@ Requires-Dist: pdfplumber (>=0.11.6,<0.12.0) ; extra == "rag" or extra == "all"
27
27
  Requires-Dist: playwright (>=1.53.0,<2.0.0) ; extra == "playwright" or extra == "all"
28
28
  Requires-Dist: prompt-toolkit (>=3.0.51,<4.0.0)
29
29
  Requires-Dist: psutil (>=7.0.0,<8.0.0)
30
- Requires-Dist: pydantic-ai (>=0.3.4,<0.4.0)
30
+ Requires-Dist: pydantic-ai (>=0.4.4,<0.5.0)
31
31
  Requires-Dist: pyjwt (>=2.10.1,<3.0.0)
32
32
  Requires-Dist: python-dotenv (>=1.1.1,<2.0.0)
33
33
  Requires-Dist: python-jose[cryptography] (>=3.4.0,<4.0.0)