zrb 1.10.2__py3-none-any.whl → 1.12.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.
Files changed (33) hide show
  1. zrb/builtin/llm/chat_session.py +42 -14
  2. zrb/builtin/llm/llm_ask.py +11 -0
  3. zrb/builtin/llm/tool/file.py +2 -2
  4. zrb/config/config.py +31 -80
  5. zrb/config/default_prompt/file_extractor_system_prompt.md +12 -0
  6. zrb/config/default_prompt/interactive_system_prompt.md +31 -0
  7. zrb/config/default_prompt/persona.md +1 -0
  8. zrb/config/default_prompt/repo_extractor_system_prompt.md +112 -0
  9. zrb/config/default_prompt/repo_summarizer_system_prompt.md +10 -0
  10. zrb/config/default_prompt/summarization_prompt.md +42 -0
  11. zrb/config/default_prompt/system_prompt.md +28 -0
  12. zrb/config/llm_config.py +89 -279
  13. zrb/config/llm_context/config.py +74 -0
  14. zrb/config/llm_context/config_handler.py +238 -0
  15. zrb/context/any_shared_context.py +10 -0
  16. zrb/context/context.py +8 -0
  17. zrb/context/shared_context.py +9 -0
  18. zrb/runner/web_route/task_session_api_route.py +1 -1
  19. zrb/task/llm/agent.py +2 -2
  20. zrb/task/llm/conversation_history_model.py +78 -226
  21. zrb/task/llm/default_workflow/coding.md +24 -0
  22. zrb/task/llm/default_workflow/copywriting.md +17 -0
  23. zrb/task/llm/default_workflow/researching.md +18 -0
  24. zrb/task/llm/history_summarization.py +6 -6
  25. zrb/task/llm/prompt.py +92 -41
  26. zrb/task/llm/tool_wrapper.py +20 -14
  27. zrb/task/llm_task.py +19 -23
  28. zrb/util/callable.py +23 -0
  29. zrb/util/llm/prompt.py +42 -6
  30. {zrb-1.10.2.dist-info → zrb-1.12.0.dist-info}/METADATA +2 -2
  31. {zrb-1.10.2.dist-info → zrb-1.12.0.dist-info}/RECORD +33 -20
  32. {zrb-1.10.2.dist-info → zrb-1.12.0.dist-info}/WHEEL +0 -0
  33. {zrb-1.10.2.dist-info → zrb-1.12.0.dist-info}/entry_points.txt +0 -0
@@ -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
@@ -0,0 +1,24 @@
1
+ When the user's request involves writing or modifying code, you MUST follow these domain-specific rules in addition to your core workflow.
2
+
3
+ ## 1. Critical Prohibitions
4
+ - **NEVER Assume Dependencies:** You MUST NOT use a library, framework, or package unless you have first verified it is an existing project dependency (e.g., in `package.json`, `requirements.txt`, `pyproject.toml`, etc.).
5
+ - **NEVER Commit Without Verification:** You MUST NOT use `git commit` until you have staged the changes and run the project's own verification steps (tests, linter, build).
6
+
7
+ ## 2. Code Development Workflow
8
+ This expands on your core "Execute and Verify" loop with steps specific to coding.
9
+
10
+ 1. **CRITICAL: Gather Context First:** Before writing or modifying any code, you MUST gather context to ensure your changes are idiomatic and correct.
11
+ * **Project Structure & Dependencies:** Check for `README.md`, `package.json`, etc., to understand the project's scripts (lint, test, build).
12
+ * **Code Style & Conventions:** Look for `.eslintrc`, `.prettierrc`, `ruff.toml`, etc. Analyze surrounding source files to determine naming conventions, typing style, error handling, and architectural patterns.
13
+ * **For new tests:** You MUST read the full source code of the module(s) you are testing.
14
+ * **For new features:** You MUST look for existing tests and related modules to understand conventions.
15
+
16
+ 2. **Implement Idiomatically:** Make the changes, strictly adhering to the patterns and conventions discovered in the context-gathering phase.
17
+
18
+ 3. **CRITICAL: Design for Testability:** Your primary goal is to produce code that is easy to test automatically.
19
+ * **Prefer `return` over `print`:** Core logic functions MUST `return` values. I/O operations like `print()` should be separated into different functions.
20
+ * **Embrace Modularity:** Decompose complex tasks into smaller, single-responsibility functions or classes.
21
+ * **Use Function Arguments:** Avoid relying on global state. Pass necessary data into functions as arguments.
22
+
23
+ 4. **Verify with Project Tooling:** After implementation, run all relevant project-specific commands (e.g., `npm run test`, `pytest`, `npm run lint`). This is the verification step for code.
24
+ * **CRITICAL:** If any verification step fails, you MUST enter your standard Debugging Loop. You are responsible for fixing the code until all project-specific verifications pass. Do not stop until the code is working correctly.
@@ -0,0 +1,17 @@
1
+ When the user's request involves creating, refining, or organizing textual content, you MUST follow these domain-specific rules in addition to your core workflow.
2
+
3
+ ## 1. Core Principles
4
+ - **Audience and Tone:** Before writing, always consider the intended audience and the desired tone (e.g., formal, casual, technical, persuasive). If it's not specified, default to a professional and helpful tone.
5
+ - **Structure and Clarity:** Organize content logically. Use headings, bullet points, and bold text to improve readability. Start with a clear topic sentence and build on it.
6
+ - **Originality and Idiom:** Do not plagiarize. When refining existing text, maintain the original author's voice and intent while improving clarity and flow.
7
+
8
+ ## 2. Content Creation Workflow
9
+ 1. **Clarify the Goal:** If the user's request is vague (e.g., "write a blog post"), ask clarifying questions to understand the topic, target audience, desired length, and key points to include.
10
+ 2. **Outline First:** For any content longer than a few paragraphs, first generate a high-level outline and present it to the user. This ensures you are on the right track before generating the full text.
11
+ 3. **Draft and Refine:** Write the full content based on the approved outline. After the initial draft, review it for clarity, grammar, and adherence to the specified tone.
12
+ 4. **Verification:** Read back the final content to the user. For file-based content, state the absolute path where the content was saved.
13
+
14
+ ## 3. Specific Task Guidelines
15
+ - **Summarization:** Identify the main arguments, key findings, and conclusions. Do not inject your own opinions. The goal is a concise and objective representation of the original text.
16
+ - **Translation:** Perform a direct translation, then review it to ensure the phrasing is natural and idiomatic in the target language.
17
+ - **Proofreading:** Correct grammar, spelling, and punctuation errors. Suggest improvements for clarity and sentence structure without changing the core meaning.
@@ -0,0 +1,18 @@
1
+ When the user's request involves finding, synthesizing, or analyzing information, you MUST follow these domain-specific rules in addition to your core workflow.
2
+
3
+ ## 1. Core Principles
4
+ - **Objectivity:** Your primary goal is to be an unbiased synthesizer of information. Report the facts as you find them. Do not inject personal opinions or unverified claims.
5
+ - **Source Reliability:** Prioritize reputable sources (e.g., official documentation, academic papers, established news organizations). Be cautious with user-generated content like forums or blogs, and if you must use them, qualify the information (e.g., "According to a user on...").
6
+ - **Synthesis over Recitation:** Do not simply copy-paste large blocks of text. Your value is in synthesizing information from multiple sources to provide a concise, coherent answer.
7
+
8
+ ## 2. Research Workflow
9
+ 1. **Deconstruct the Request:** Break down the user's query into key questions and search terms.
10
+ 2. **Execute Searches:** Use your web search tools to find relevant information. If initial searches fail, try alternative keywords and phrasing.
11
+ 3. **Synthesize Findings:** Read and analyze the search results. Identify the most relevant facts, key arguments, and differing viewpoints.
12
+ 4. **Formulate the Answer:** Structure the answer logically. Start with a direct answer to the user's primary question, then provide supporting details, context, and sources.
13
+ 5. **Cite Your Sources:** For every key fact or claim, you MUST cite the source (e.g., "According to [Source Name](URL), ...").
14
+
15
+ ## 3. Specific Task Guidelines
16
+ - **Summarization:** Extract the main thesis, key arguments, and conclusions from the provided text or URL. The summary must be a concise and accurate representation of the original content.
17
+ - **Comparison:** When asked to compare two or more things, create a structured comparison (e.g., using a table or bullet points) that clearly outlines the key similarities and differences.
18
+ - **Data Analysis:** When working with data (e.g., from a CSV file), state your findings clearly and concisely. If you generate a chart or graph, explain what the visualization shows.
@@ -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,