zrb 1.8.10__py3-none-any.whl → 1.21.29__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 (147) hide show
  1. zrb/__init__.py +126 -113
  2. zrb/__main__.py +1 -1
  3. zrb/attr/type.py +10 -7
  4. zrb/builtin/__init__.py +2 -50
  5. zrb/builtin/git.py +12 -1
  6. zrb/builtin/group.py +31 -15
  7. zrb/builtin/http.py +7 -8
  8. zrb/builtin/llm/attachment.py +40 -0
  9. zrb/builtin/llm/chat_completion.py +274 -0
  10. zrb/builtin/llm/chat_session.py +152 -85
  11. zrb/builtin/llm/chat_session_cmd.py +288 -0
  12. zrb/builtin/llm/chat_trigger.py +79 -0
  13. zrb/builtin/llm/history.py +7 -9
  14. zrb/builtin/llm/llm_ask.py +221 -98
  15. zrb/builtin/llm/tool/api.py +74 -52
  16. zrb/builtin/llm/tool/cli.py +46 -17
  17. zrb/builtin/llm/tool/code.py +71 -90
  18. zrb/builtin/llm/tool/file.py +301 -241
  19. zrb/builtin/llm/tool/note.py +84 -0
  20. zrb/builtin/llm/tool/rag.py +38 -8
  21. zrb/builtin/llm/tool/sub_agent.py +67 -50
  22. zrb/builtin/llm/tool/web.py +146 -122
  23. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/_zrb/entity/add_entity_util.py +7 -7
  24. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/_zrb/module/add_module_util.py +5 -5
  25. zrb/builtin/project/add/fastapp/fastapp_util.py +1 -1
  26. zrb/builtin/searxng/config/settings.yml +5671 -0
  27. zrb/builtin/searxng/start.py +21 -0
  28. zrb/builtin/setup/latex/ubuntu.py +1 -0
  29. zrb/builtin/setup/ubuntu.py +1 -1
  30. zrb/builtin/shell/autocomplete/bash.py +4 -3
  31. zrb/builtin/shell/autocomplete/zsh.py +4 -3
  32. zrb/builtin/todo.py +13 -2
  33. zrb/config/config.py +614 -0
  34. zrb/config/default_prompt/file_extractor_system_prompt.md +112 -0
  35. zrb/config/default_prompt/interactive_system_prompt.md +29 -0
  36. zrb/config/default_prompt/persona.md +1 -0
  37. zrb/config/default_prompt/repo_extractor_system_prompt.md +112 -0
  38. zrb/config/default_prompt/repo_summarizer_system_prompt.md +29 -0
  39. zrb/config/default_prompt/summarization_prompt.md +57 -0
  40. zrb/config/default_prompt/system_prompt.md +38 -0
  41. zrb/config/llm_config.py +339 -0
  42. zrb/config/llm_context/config.py +166 -0
  43. zrb/config/llm_context/config_parser.py +40 -0
  44. zrb/config/llm_context/workflow.py +81 -0
  45. zrb/config/llm_rate_limitter.py +190 -0
  46. zrb/{runner → config}/web_auth_config.py +17 -22
  47. zrb/context/any_shared_context.py +17 -1
  48. zrb/context/context.py +16 -2
  49. zrb/context/shared_context.py +18 -8
  50. zrb/group/any_group.py +12 -5
  51. zrb/group/group.py +67 -3
  52. zrb/input/any_input.py +5 -1
  53. zrb/input/base_input.py +18 -6
  54. zrb/input/option_input.py +13 -1
  55. zrb/input/text_input.py +8 -25
  56. zrb/runner/cli.py +25 -23
  57. zrb/runner/common_util.py +24 -19
  58. zrb/runner/web_app.py +3 -3
  59. zrb/runner/web_route/docs_route.py +1 -1
  60. zrb/runner/web_route/error_page/serve_default_404.py +1 -1
  61. zrb/runner/web_route/error_page/show_error_page.py +1 -1
  62. zrb/runner/web_route/home_page/home_page_route.py +2 -2
  63. zrb/runner/web_route/login_api_route.py +1 -1
  64. zrb/runner/web_route/login_page/login_page_route.py +2 -2
  65. zrb/runner/web_route/logout_api_route.py +1 -1
  66. zrb/runner/web_route/logout_page/logout_page_route.py +2 -2
  67. zrb/runner/web_route/node_page/group/show_group_page.py +1 -1
  68. zrb/runner/web_route/node_page/node_page_route.py +1 -1
  69. zrb/runner/web_route/node_page/task/show_task_page.py +1 -1
  70. zrb/runner/web_route/refresh_token_api_route.py +1 -1
  71. zrb/runner/web_route/static/static_route.py +1 -1
  72. zrb/runner/web_route/task_input_api_route.py +6 -6
  73. zrb/runner/web_route/task_session_api_route.py +20 -12
  74. zrb/runner/web_util/cookie.py +1 -1
  75. zrb/runner/web_util/token.py +1 -1
  76. zrb/runner/web_util/user.py +8 -4
  77. zrb/session/any_session.py +24 -17
  78. zrb/session/session.py +50 -25
  79. zrb/session_state_logger/any_session_state_logger.py +9 -4
  80. zrb/session_state_logger/file_session_state_logger.py +16 -6
  81. zrb/session_state_logger/session_state_logger_factory.py +1 -1
  82. zrb/task/any_task.py +30 -9
  83. zrb/task/base/context.py +17 -9
  84. zrb/task/base/execution.py +15 -8
  85. zrb/task/base/lifecycle.py +8 -4
  86. zrb/task/base/monitoring.py +12 -7
  87. zrb/task/base_task.py +69 -5
  88. zrb/task/base_trigger.py +12 -5
  89. zrb/task/cmd_task.py +1 -1
  90. zrb/task/llm/agent.py +154 -161
  91. zrb/task/llm/agent_runner.py +152 -0
  92. zrb/task/llm/config.py +47 -18
  93. zrb/task/llm/conversation_history.py +209 -0
  94. zrb/task/llm/conversation_history_model.py +67 -0
  95. zrb/task/llm/default_workflow/coding/workflow.md +41 -0
  96. zrb/task/llm/default_workflow/copywriting/workflow.md +68 -0
  97. zrb/task/llm/default_workflow/git/workflow.md +118 -0
  98. zrb/task/llm/default_workflow/golang/workflow.md +128 -0
  99. zrb/task/llm/default_workflow/html-css/workflow.md +135 -0
  100. zrb/task/llm/default_workflow/java/workflow.md +146 -0
  101. zrb/task/llm/default_workflow/javascript/workflow.md +158 -0
  102. zrb/task/llm/default_workflow/python/workflow.md +160 -0
  103. zrb/task/llm/default_workflow/researching/workflow.md +153 -0
  104. zrb/task/llm/default_workflow/rust/workflow.md +162 -0
  105. zrb/task/llm/default_workflow/shell/workflow.md +299 -0
  106. zrb/task/llm/error.py +24 -10
  107. zrb/task/llm/file_replacement.py +206 -0
  108. zrb/task/llm/file_tool_model.py +57 -0
  109. zrb/task/llm/history_processor.py +206 -0
  110. zrb/task/llm/history_summarization.py +11 -166
  111. zrb/task/llm/print_node.py +193 -69
  112. zrb/task/llm/prompt.py +242 -45
  113. zrb/task/llm/subagent_conversation_history.py +41 -0
  114. zrb/task/llm/tool_wrapper.py +260 -57
  115. zrb/task/llm/workflow.py +76 -0
  116. zrb/task/llm_task.py +182 -171
  117. zrb/task/make_task.py +2 -3
  118. zrb/task/rsync_task.py +26 -11
  119. zrb/task/scheduler.py +4 -4
  120. zrb/util/attr.py +54 -39
  121. zrb/util/callable.py +23 -0
  122. zrb/util/cli/markdown.py +12 -0
  123. zrb/util/cli/text.py +30 -0
  124. zrb/util/file.py +29 -11
  125. zrb/util/git.py +8 -11
  126. zrb/util/git_diff_model.py +10 -0
  127. zrb/util/git_subtree.py +9 -14
  128. zrb/util/git_subtree_model.py +32 -0
  129. zrb/util/init_path.py +1 -1
  130. zrb/util/markdown.py +62 -0
  131. zrb/util/string/conversion.py +2 -2
  132. zrb/util/todo.py +17 -50
  133. zrb/util/todo_model.py +46 -0
  134. zrb/util/truncate.py +23 -0
  135. zrb/util/yaml.py +204 -0
  136. zrb/xcom/xcom.py +10 -0
  137. zrb-1.21.29.dist-info/METADATA +270 -0
  138. {zrb-1.8.10.dist-info → zrb-1.21.29.dist-info}/RECORD +140 -98
  139. {zrb-1.8.10.dist-info → zrb-1.21.29.dist-info}/WHEEL +1 -1
  140. zrb/config.py +0 -335
  141. zrb/llm_config.py +0 -411
  142. zrb/llm_rate_limitter.py +0 -125
  143. zrb/task/llm/context.py +0 -102
  144. zrb/task/llm/context_enrichment.py +0 -199
  145. zrb/task/llm/history.py +0 -211
  146. zrb-1.8.10.dist-info/METADATA +0 -264
  147. {zrb-1.8.10.dist-info → zrb-1.21.29.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,288 @@
1
+ import os
2
+ import subprocess
3
+
4
+ from zrb.context.any_context import AnyContext
5
+ from zrb.task.llm.workflow import get_available_workflows
6
+ from zrb.util.cli.markdown import render_markdown
7
+ from zrb.util.cli.style import (
8
+ stylize_blue,
9
+ stylize_bold_yellow,
10
+ stylize_error,
11
+ stylize_faint,
12
+ )
13
+ from zrb.util.file import write_file
14
+ from zrb.util.markdown import make_markdown_section
15
+ from zrb.util.string.conversion import FALSE_STRS, TRUE_STRS, to_boolean
16
+
17
+ MULTILINE_START_CMD = ["/multi", "/multiline"]
18
+ MULTILINE_END_CMD = ["/end"]
19
+ QUIT_CMD = ["/bye", "/quit", "/q", "/exit"]
20
+ WORKFLOW_CMD = ["/workflow", "/workflows", "/skill", "/skills", "/w"]
21
+ SAVE_CMD = ["/save", "/s"]
22
+ ATTACHMENT_CMD = ["/attachment", "/attachments", "/attach"]
23
+ YOLO_CMD = ["/yolo"]
24
+ HELP_CMD = ["/help", "/info"]
25
+ ADD_SUB_CMD = ["add"]
26
+ SET_SUB_CMD = ["set"]
27
+ CLEAR_SUB_CMD = ["clear"]
28
+ RUN_CLI_CMD = ["/run", "/exec", "/execute", "/cmd", "/cli", "!"]
29
+
30
+ # Command display constants
31
+ MULTILINE_START_CMD_DESC = "Start multiline input"
32
+ MULTILINE_END_CMD_DESC = "End multiline input"
33
+ QUIT_CMD_DESC = "Quit from chat session"
34
+ WORKFLOW_CMD_DESC = "Show active workflows"
35
+ WORKFLOW_ADD_SUB_CMD_DESC = (
36
+ "Add active workflow "
37
+ f"(e.g., `{WORKFLOW_CMD[0]} {ADD_SUB_CMD[0]} coding,researching`)"
38
+ )
39
+ WORKFLOW_SET_SUB_CMD_DESC = (
40
+ "Set active workflows " f"(e.g., `{WORKFLOW_CMD[0]} {SET_SUB_CMD[0]} coding,`)"
41
+ )
42
+ WORKFLOW_CLEAR_SUB_CMD_DESC = "Deactivate all workflows"
43
+ SAVE_CMD_DESC = f"Save last response to a file (e.g., `{SAVE_CMD[0]} conclusion.md`)"
44
+ ATTACHMENT_CMD_DESC = "Show current attachment"
45
+ ATTACHMENT_ADD_SUB_CMD_DESC = (
46
+ "Attach a file " f"(e.g., `{ATTACHMENT_CMD[0]} {ADD_SUB_CMD[0]} ./logo.png`)"
47
+ )
48
+ ATTACHMENT_SET_SUB_CMD_DESC = (
49
+ "Set attachments "
50
+ f"(e.g., `{ATTACHMENT_CMD[0]} {SET_SUB_CMD[0]} ./logo.png,./diagram.png`)"
51
+ )
52
+ ATTACHMENT_CLEAR_SUB_CMD_DESC = "Clear attachment"
53
+ YOLO_CMD_DESC = "Show/manipulate current YOLO mode"
54
+ YOLO_SET_CMD_DESC = (
55
+ "Assign YOLO tools "
56
+ f"(e.g., `{YOLO_CMD[0]} {SET_SUB_CMD[0]} read_from_file,analyze_file`)"
57
+ )
58
+ YOLO_SET_TRUE_CMD_DESC = "Activate YOLO mode for all tools"
59
+ YOLO_SET_FALSE_CMD_DESC = "Deactivate YOLO mode for all tools"
60
+ RUN_CLI_CMD_DESC = "Run a non-interactive CLI command"
61
+ HELP_CMD_DESC = "Show info/help"
62
+
63
+
64
+ def print_current_yolo_mode(
65
+ ctx: AnyContext, current_yolo_mode_value: str | bool
66
+ ) -> None:
67
+ yolo_mode_str = (
68
+ current_yolo_mode_value if current_yolo_mode_value != "" else "*Not Set*"
69
+ )
70
+ ctx.print(render_markdown(f"🎲 Current YOLO mode: {yolo_mode_str}"), plain=True)
71
+ ctx.print("", plain=True)
72
+
73
+
74
+ def print_current_attachments(ctx: AnyContext, current_attachments_value: str) -> None:
75
+ attachments_str = (
76
+ current_attachments_value if current_attachments_value != "" else "*Not Set*"
77
+ )
78
+ ctx.print(render_markdown(f"📎 Current attachments: {attachments_str}"), plain=True)
79
+ ctx.print("", plain=True)
80
+
81
+
82
+ def print_current_workflows(ctx: AnyContext, current_workflows_value: str) -> None:
83
+ available_workflows = get_available_workflows()
84
+ available_workflows_str = (
85
+ ", ".join(sorted([workflow_name for workflow_name in available_workflows]))
86
+ if len(available_workflows) > 0
87
+ else "*No Available Workflow*"
88
+ )
89
+ current_workflows_str = (
90
+ current_workflows_value
91
+ if current_workflows_value != ""
92
+ else "*No Active Workflow*"
93
+ )
94
+ ctx.print(
95
+ render_markdown(
96
+ "\n".join(
97
+ [
98
+ f"- 🔄 Current workflows : {current_workflows_str}",
99
+ f"- 📚 Available workflows : {available_workflows_str}",
100
+ ]
101
+ )
102
+ ),
103
+ plain=True,
104
+ )
105
+ ctx.print("", plain=True)
106
+
107
+
108
+ def save_final_result(ctx: AnyContext, user_input: str, final_result: str) -> None:
109
+ save_path = get_command_param(user_input, SAVE_CMD)
110
+ save_path = os.path.expanduser(save_path)
111
+ if os.path.exists(save_path):
112
+ ctx.print(
113
+ stylize_error(f"Cannot save to existing file: {save_path}"),
114
+ plain=True,
115
+ )
116
+ return
117
+ write_file(save_path, final_result)
118
+ ctx.print(f"Response saved to {save_path}", plain=True)
119
+
120
+
121
+ def run_cli_command(ctx: AnyContext, user_input: str) -> None:
122
+ command = get_command_param(user_input, RUN_CLI_CMD)
123
+ result = subprocess.run(
124
+ command,
125
+ shell=True,
126
+ capture_output=True,
127
+ text=True,
128
+ )
129
+ ctx.print(
130
+ render_markdown(
131
+ make_markdown_section(
132
+ f"`{command}`",
133
+ "\n".join(
134
+ [
135
+ make_markdown_section("📤 Stdout", result.stdout, as_code=True),
136
+ make_markdown_section("🚫 Stderr", result.stderr, as_code=True),
137
+ make_markdown_section(
138
+ "🎯 Return code", f"Return Code: {result.returncode}"
139
+ ),
140
+ ]
141
+ ),
142
+ )
143
+ ),
144
+ plain=True,
145
+ )
146
+ ctx.print("", plain=True)
147
+
148
+
149
+ def get_new_yolo_mode(old_yolo_mode: str | bool, user_input: str) -> str | bool:
150
+ new_yolo_mode = get_command_param(user_input, YOLO_CMD)
151
+ if new_yolo_mode != "":
152
+ if new_yolo_mode in TRUE_STRS or new_yolo_mode in FALSE_STRS:
153
+ return to_boolean(new_yolo_mode)
154
+ return new_yolo_mode
155
+ if isinstance(old_yolo_mode, bool):
156
+ return old_yolo_mode
157
+ return _normalize_comma_separated_str(old_yolo_mode)
158
+
159
+
160
+ def get_new_attachments(old_attachment: str, user_input: str) -> str:
161
+ if not is_command_match(user_input, ATTACHMENT_CMD):
162
+ return _normalize_comma_separated_str(old_attachment)
163
+ if is_command_match(user_input, ATTACHMENT_CMD, SET_SUB_CMD):
164
+ return _normalize_comma_separated_str(
165
+ get_command_param(user_input, ATTACHMENT_CMD, SET_SUB_CMD)
166
+ )
167
+ if is_command_match(user_input, ATTACHMENT_CMD, CLEAR_SUB_CMD):
168
+ return ""
169
+ if is_command_match(user_input, ATTACHMENT_CMD, ADD_SUB_CMD):
170
+ new_attachment = get_command_param(user_input, ATTACHMENT_CMD, ADD_SUB_CMD)
171
+ return _normalize_comma_separated_str(
172
+ ",".join([old_attachment, new_attachment])
173
+ )
174
+ return old_attachment
175
+
176
+
177
+ def get_new_workflows(old_workflow: str, user_input: str) -> str:
178
+ if not is_command_match(user_input, WORKFLOW_CMD):
179
+ return _normalize_comma_separated_str(old_workflow)
180
+ if is_command_match(user_input, WORKFLOW_CMD, SET_SUB_CMD):
181
+ return _normalize_comma_separated_str(
182
+ get_command_param(user_input, WORKFLOW_CMD, SET_SUB_CMD)
183
+ )
184
+ if is_command_match(user_input, WORKFLOW_CMD, CLEAR_SUB_CMD):
185
+ return ""
186
+ if is_command_match(user_input, WORKFLOW_CMD, ADD_SUB_CMD):
187
+ new_workflow = get_command_param(user_input, WORKFLOW_CMD, ADD_SUB_CMD)
188
+ return _normalize_comma_separated_str(",".join([old_workflow, new_workflow]))
189
+ return _normalize_comma_separated_str(old_workflow)
190
+
191
+
192
+ def _normalize_comma_separated_str(comma_separated_str: str) -> str:
193
+ return ",".join(
194
+ [
195
+ workflow_name.strip()
196
+ for workflow_name in comma_separated_str.split(",")
197
+ if workflow_name.strip() != ""
198
+ ]
199
+ )
200
+
201
+
202
+ def get_command_param(user_input: str, *cmd_patterns: list[str]) -> str:
203
+ if not is_command_match(user_input, *cmd_patterns):
204
+ return ""
205
+ parts = [part for part in user_input.split(" ") if part.strip() != ""]
206
+ if len(parts) <= len(cmd_patterns):
207
+ return ""
208
+ params = parts[len(cmd_patterns) :]
209
+ return " ".join(params)
210
+
211
+
212
+ def is_command_match(user_input: str, *cmd_patterns: list[str]) -> bool:
213
+ parts = [part for part in user_input.split(" ") if part.strip() != ""]
214
+ if len(cmd_patterns) > len(parts):
215
+ return False
216
+ for index, cmd_pattern in enumerate(cmd_patterns):
217
+ part = parts[index]
218
+ if part.lower() not in cmd_pattern:
219
+ return False
220
+ return True
221
+
222
+
223
+ def print_commands(ctx: AnyContext):
224
+ """
225
+ Displays the available chat session commands to the user.
226
+ Args:
227
+ ctx: The context object for the task.
228
+ """
229
+ ctx.print(
230
+ "\n".join(
231
+ [
232
+ _show_command(QUIT_CMD[0], QUIT_CMD_DESC),
233
+ _show_command(MULTILINE_START_CMD[0], MULTILINE_START_CMD_DESC),
234
+ _show_command(MULTILINE_END_CMD[0], MULTILINE_END_CMD_DESC),
235
+ _show_command(ATTACHMENT_CMD[0], ATTACHMENT_CMD_DESC),
236
+ _show_subcommand(
237
+ ADD_SUB_CMD[0], "<file-path>", ATTACHMENT_ADD_SUB_CMD_DESC
238
+ ),
239
+ _show_subcommand(
240
+ SET_SUB_CMD[0],
241
+ "<file1-path,file2-path,...>",
242
+ ATTACHMENT_SET_SUB_CMD_DESC,
243
+ ),
244
+ _show_subcommand(CLEAR_SUB_CMD[0], "", ATTACHMENT_CLEAR_SUB_CMD_DESC),
245
+ _show_command(WORKFLOW_CMD[0], WORKFLOW_CMD_DESC),
246
+ _show_subcommand(
247
+ ADD_SUB_CMD[0], "<workflow>", WORKFLOW_ADD_SUB_CMD_DESC
248
+ ),
249
+ _show_subcommand(
250
+ SET_SUB_CMD[0],
251
+ "<workflow1,workflow2,..>",
252
+ WORKFLOW_SET_SUB_CMD_DESC,
253
+ ),
254
+ _show_subcommand(CLEAR_SUB_CMD[0], "", WORKFLOW_CLEAR_SUB_CMD_DESC),
255
+ _show_command(f"{SAVE_CMD[0]}", SAVE_CMD_DESC),
256
+ _show_command(YOLO_CMD[0], YOLO_CMD_DESC),
257
+ _show_subcommand(SET_SUB_CMD[0], "true", YOLO_SET_TRUE_CMD_DESC),
258
+ _show_subcommand(SET_SUB_CMD[0], "false", YOLO_SET_FALSE_CMD_DESC),
259
+ _show_subcommand(
260
+ SET_SUB_CMD[0], "<tool1,tool2,tool2>", YOLO_SET_CMD_DESC
261
+ ),
262
+ _show_command(RUN_CLI_CMD[0], ""),
263
+ _show_command_param("<cli-command>", RUN_CLI_CMD_DESC),
264
+ _show_command(HELP_CMD[0], HELP_CMD_DESC),
265
+ ]
266
+ ),
267
+ plain=True,
268
+ )
269
+ ctx.print("", plain=True)
270
+
271
+
272
+ def _show_command(command: str, description: str) -> str:
273
+ styled_command = stylize_bold_yellow(command.ljust(37))
274
+ styled_description = stylize_faint(description)
275
+ return f" {styled_command} {styled_description}"
276
+
277
+
278
+ def _show_subcommand(subcommand: str, param: str, description: str) -> str:
279
+ styled_subcommand = stylize_bold_yellow(f" {subcommand}")
280
+ styled_param = stylize_blue(param.ljust(32 - len(subcommand)))
281
+ styled_description = stylize_faint(description)
282
+ return f" {styled_subcommand} {styled_param} {styled_description}"
283
+
284
+
285
+ def _show_command_param(param: str, description: str) -> str:
286
+ styled_param = stylize_blue(f" {param}".ljust(37))
287
+ styled_description = stylize_faint(description)
288
+ return f" {styled_param} {styled_description}"
@@ -0,0 +1,79 @@
1
+ import asyncio
2
+ import os
3
+ from asyncio import StreamReader
4
+ from typing import TYPE_CHECKING, Any, Callable, Coroutine
5
+
6
+ from zrb.context.any_context import AnyContext
7
+ from zrb.util.run import run_async
8
+
9
+ if TYPE_CHECKING:
10
+ from prompt_toolkit import PromptSession
11
+
12
+
13
+ ChatTrigger = Callable[[AnyContext], Coroutine[Any, Any, str] | str]
14
+
15
+
16
+ class LLMChatTrigger:
17
+
18
+ def __init__(self):
19
+ self._triggers: list[ChatTrigger] = []
20
+
21
+ def add_trigger(self, *trigger: ChatTrigger):
22
+ self.append_trigger(*trigger)
23
+
24
+ def append_trigger(self, *trigger: ChatTrigger):
25
+ for single_trigger in trigger:
26
+ self._triggers.append(single_trigger)
27
+
28
+ async def wait(
29
+ self, reader: "PromptSession[Any] | StreamReader", ctx: AnyContext
30
+ ) -> str:
31
+ trigger_tasks = [
32
+ asyncio.create_task(run_async(self._read_next_line(reader, ctx)))
33
+ ] + [asyncio.create_task(run_async(trigger(ctx))) for trigger in self._triggers]
34
+ final_result: str = ""
35
+ try:
36
+ done, pending = await asyncio.wait(
37
+ trigger_tasks, return_when=asyncio.FIRST_COMPLETED
38
+ )
39
+ for task in done:
40
+ final_result = await task
41
+ if pending:
42
+ for task in pending:
43
+ task.cancel()
44
+ for task in done:
45
+ break
46
+ except asyncio.CancelledError:
47
+ ctx.print("Task cancelled.", plain=True)
48
+ final_result = "/bye"
49
+ except KeyboardInterrupt:
50
+ ctx.print("KeyboardInterrupt detected. Exiting...", plain=True)
51
+ final_result = "/bye"
52
+ return final_result
53
+
54
+ async def _read_next_line(
55
+ self, reader: "PromptSession[Any] | StreamReader", ctx: AnyContext
56
+ ) -> str:
57
+ """Reads one line of input using the provided reader."""
58
+ from prompt_toolkit import PromptSession
59
+
60
+ from zrb.builtin.llm.chat_completion import ChatCompleter
61
+
62
+ try:
63
+ if isinstance(reader, PromptSession):
64
+ bottom_toolbar = f"📁 Current directory: {os.getcwd()}"
65
+ return await reader.prompt_async(
66
+ completer=ChatCompleter(), bottom_toolbar=bottom_toolbar
67
+ )
68
+ line_bytes = await reader.readline()
69
+ if not line_bytes:
70
+ return "/bye" # Signal to exit
71
+ user_input = line_bytes.decode().strip()
72
+ ctx.print(user_input, plain=True)
73
+ return user_input
74
+ except KeyboardInterrupt:
75
+ ctx.print("KeyboardInterrupt detected. Exiting...", plain=True)
76
+ return "/bye"
77
+
78
+
79
+ llm_chat_trigger = LLMChatTrigger()
@@ -2,16 +2,16 @@ import json
2
2
  import os
3
3
  from typing import Any
4
4
 
5
- from zrb.config import CFG
6
- from zrb.context.any_shared_context import AnySharedContext
7
- from zrb.task.llm.history import ConversationHistoryData
5
+ from zrb.config.config import CFG
6
+ from zrb.context.any_context import AnyContext
7
+ from zrb.task.llm.conversation_history_model import ConversationHistory
8
8
  from zrb.util.file import read_file, write_file
9
9
 
10
10
 
11
- def read_chat_conversation(ctx: AnySharedContext) -> dict[str, Any] | list | None:
11
+ def read_chat_conversation(ctx: AnyContext) -> dict[str, Any] | list | None:
12
12
  """Reads conversation history from the session file.
13
13
  Returns the raw dictionary or list loaded from JSON, or None if not found/empty.
14
- The LLMTask will handle parsing this into ConversationHistoryData.
14
+ The LLMTask will handle parsing this into ConversationHistory.
15
15
  """
16
16
  if ctx.input.start_new:
17
17
  return None # Indicate no history to load
@@ -51,12 +51,10 @@ def read_chat_conversation(ctx: AnySharedContext) -> dict[str, Any] | list | Non
51
51
  return None
52
52
 
53
53
 
54
- def write_chat_conversation(
55
- ctx: AnySharedContext, history_data: ConversationHistoryData
56
- ):
54
+ def write_chat_conversation(ctx: AnyContext, history_data: ConversationHistory):
57
55
  """Writes the conversation history data (including context) to a session file."""
58
56
  os.makedirs(CFG.LLM_HISTORY_DIR, exist_ok=True)
59
- current_session_name = ctx.session.name
57
+ current_session_name = ctx.session.name if ctx.session is not None else None
60
58
  if not current_session_name:
61
59
  ctx.log_warning("Cannot write history: Session name is empty.")
62
60
  return