quantalogic 0.59.2__py3-none-any.whl → 0.60.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 (42) hide show
  1. quantalogic/agent.py +268 -24
  2. quantalogic/create_custom_agent.py +26 -78
  3. quantalogic/prompts/chat_system_prompt.j2 +10 -7
  4. quantalogic/prompts/code_2_system_prompt.j2 +190 -0
  5. quantalogic/prompts/code_system_prompt.j2 +142 -0
  6. quantalogic/prompts/doc_system_prompt.j2 +178 -0
  7. quantalogic/prompts/legal_2_system_prompt.j2 +218 -0
  8. quantalogic/prompts/legal_system_prompt.j2 +140 -0
  9. quantalogic/prompts/system_prompt.j2 +6 -2
  10. quantalogic/prompts/task_prompt.j2 +1 -1
  11. quantalogic/prompts/tools_prompt.j2 +2 -4
  12. quantalogic/prompts.py +23 -4
  13. quantalogic/server/agent_server.py +1 -1
  14. quantalogic/tools/__init__.py +2 -0
  15. quantalogic/tools/duckduckgo_search_tool.py +1 -0
  16. quantalogic/tools/execute_bash_command_tool.py +114 -57
  17. quantalogic/tools/file_tracker_tool.py +49 -0
  18. quantalogic/tools/google_packages/google_news_tool.py +3 -0
  19. quantalogic/tools/image_generation/dalle_e.py +89 -137
  20. quantalogic/tools/rag_tool/__init__.py +2 -9
  21. quantalogic/tools/rag_tool/document_rag_sources_.py +728 -0
  22. quantalogic/tools/rag_tool/ocr_pdf_markdown.py +144 -0
  23. quantalogic/tools/replace_in_file_tool.py +1 -1
  24. quantalogic/tools/terminal_capture_tool.py +293 -0
  25. quantalogic/tools/tool.py +4 -0
  26. quantalogic/tools/utilities/__init__.py +2 -0
  27. quantalogic/tools/utilities/download_file_tool.py +3 -5
  28. quantalogic/tools/utilities/llm_tool.py +283 -0
  29. quantalogic/tools/utilities/selenium_tool.py +296 -0
  30. quantalogic/tools/utilities/vscode_tool.py +1 -1
  31. quantalogic/tools/web_navigation/__init__.py +5 -0
  32. quantalogic/tools/web_navigation/web_tool.py +145 -0
  33. quantalogic/tools/write_file_tool.py +72 -36
  34. {quantalogic-0.59.2.dist-info → quantalogic-0.60.0.dist-info}/METADATA +2 -2
  35. {quantalogic-0.59.2.dist-info → quantalogic-0.60.0.dist-info}/RECORD +38 -29
  36. quantalogic/tools/rag_tool/document_metadata.py +0 -15
  37. quantalogic/tools/rag_tool/query_response.py +0 -20
  38. quantalogic/tools/rag_tool/rag_tool.py +0 -566
  39. quantalogic/tools/rag_tool/rag_tool_beta.py +0 -264
  40. {quantalogic-0.59.2.dist-info → quantalogic-0.60.0.dist-info}/LICENSE +0 -0
  41. {quantalogic-0.59.2.dist-info → quantalogic-0.60.0.dist-info}/WHEEL +0 -0
  42. {quantalogic-0.59.2.dist-info → quantalogic-0.60.0.dist-info}/entry_points.txt +0 -0
@@ -6,6 +6,10 @@ import signal
6
6
  import subprocess
7
7
  import sys
8
8
  from typing import Dict, Optional, Union
9
+ from pathlib import Path
10
+ from datetime import datetime
11
+ import shutil
12
+ import re
9
13
 
10
14
  from loguru import logger
11
15
 
@@ -24,7 +28,7 @@ class ExecuteBashCommandTool(Tool):
24
28
  """Tool for executing bash commands with real-time I/O handling."""
25
29
 
26
30
  name: str = "execute_bash_tool"
27
- description: str = "Executes a bash command and returns its output."
31
+ description: str = "Executes a bash command and returns its output. All commands are executed in /tmp for security."
28
32
  need_validation: bool = True
29
33
  arguments: list = [
30
34
  ToolArgument(
@@ -34,14 +38,6 @@ class ExecuteBashCommandTool(Tool):
34
38
  required=True,
35
39
  example="ls -la",
36
40
  ),
37
- ToolArgument(
38
- name="working_dir",
39
- arg_type="string",
40
- description="The working directory where the command will be executed. Defaults to the current directory.",
41
- required=False,
42
- example="/path/to/directory",
43
- default=os.getcwd(),
44
- ),
45
41
  ToolArgument(
46
42
  name="timeout",
47
43
  arg_type="int",
@@ -52,15 +48,67 @@ class ExecuteBashCommandTool(Tool):
52
48
  ),
53
49
  ]
54
50
 
51
+ def _validate_command(self, command: str) -> None:
52
+ """Validate the command for potential security risks."""
53
+ forbidden_commands = ["rm -rf /", "mkfs", "dd", ":(){ :|:& };:"]
54
+ for cmd in forbidden_commands:
55
+ if cmd in command.lower():
56
+ raise ValueError(f"Command '{command}' contains forbidden operation")
57
+
58
+ def _handle_mkdir_command(self, command: str) -> str:
59
+ """Handle mkdir command with automatic cleanup and date suffix.
60
+
61
+ Args:
62
+ command: The original mkdir command
63
+
64
+ Returns:
65
+ Modified command that handles existing directories and adds date suffix
66
+ """
67
+ try:
68
+ # Extract directory name from mkdir command
69
+ mkdir_pattern = r'mkdir\s+(?:-p\s+)?["\']?([^"\'>\n]+)["\']?'
70
+ match = re.search(mkdir_pattern, command)
71
+ if not match:
72
+ return command
73
+
74
+ dir_name = match.group(1)
75
+ # Add timestamp suffix
76
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
77
+ new_dir_name = f"{dir_name}_{timestamp}"
78
+
79
+ # Create cleanup and mkdir commands
80
+ cleanup_cmd = f'rm -rf "{dir_name}" 2>/dev/null; '
81
+ mkdir_cmd = command.replace(dir_name, new_dir_name)
82
+
83
+ return cleanup_cmd + mkdir_cmd
84
+
85
+ except Exception as e:
86
+ logger.warning(f"Error processing mkdir command: {e}")
87
+ return command
88
+
89
+ def _format_output(self, stdout: str, return_code: int, error: Optional[str] = None) -> str:
90
+ """Format command output with stdout, return code, and optional error."""
91
+ formatted_result = "<command_output>\n"
92
+ formatted_result += f" <stdout>{stdout.strip()}</stdout>\n"
93
+ formatted_result += f" <returncode>{return_code}</returncode>\n"
94
+ if error:
95
+ formatted_result += f" <error>{error}</error>\n"
96
+ formatted_result += "</command_output>"
97
+ return formatted_result
98
+
55
99
  def _execute_windows(
56
100
  self,
57
101
  command: str,
58
- cwd: str,
59
102
  timeout_seconds: int,
60
103
  env_vars: Dict[str, str],
104
+ cwd: Optional[str] = None,
61
105
  ) -> str:
62
106
  """Execute command on Windows platform."""
63
107
  try:
108
+ # Handle mkdir commands
109
+ if "mkdir" in command:
110
+ command = self._handle_mkdir_command(command)
111
+
64
112
  # On Windows, use subprocess with pipes
65
113
  process = subprocess.Popen(
66
114
  command,
@@ -68,7 +116,7 @@ class ExecuteBashCommandTool(Tool):
68
116
  stdin=subprocess.PIPE,
69
117
  stdout=subprocess.PIPE,
70
118
  stderr=subprocess.PIPE,
71
- cwd=cwd,
119
+ cwd="/tmp", # cwd, Force /tmp directory
72
120
  env=env_vars,
73
121
  text=True,
74
122
  encoding="utf-8",
@@ -77,34 +125,27 @@ class ExecuteBashCommandTool(Tool):
77
125
  try:
78
126
  stdout, stderr = process.communicate(timeout=timeout_seconds)
79
127
  return_code = process.returncode
80
-
81
- if return_code != 0 and stderr:
82
- logger.warning(f"Command failed with error: {stderr}")
83
-
84
- formatted_result = (
85
- "<command_output>"
86
- f" <stdout>{stdout.strip()}</stdout>"
87
- f" <returncode>{return_code}</returncode>"
88
- f"</command_output>"
89
- )
90
- return formatted_result
128
+ return self._format_output(stdout, return_code, stderr if stderr else None)
91
129
 
92
130
  except subprocess.TimeoutExpired:
93
131
  process.kill()
94
- return f"Command timed out after {timeout_seconds} seconds."
132
+ return self._format_output("", 1, f"Command timed out after {timeout_seconds} seconds")
95
133
 
96
134
  except Exception as e:
97
- return f"Unexpected error executing command: {str(e)}"
135
+ return self._format_output("", 1, f"Unexpected error executing command: {str(e)}")
98
136
 
99
137
  def _execute_unix(
100
138
  self,
101
139
  command: str,
102
- cwd: str,
103
140
  timeout_seconds: int,
104
141
  env_vars: Dict[str, str],
105
142
  ) -> str:
106
143
  """Execute command on Unix platform."""
107
144
  try:
145
+ # Handle mkdir commands
146
+ if "mkdir" in command:
147
+ command = self._handle_mkdir_command(command)
148
+
108
149
  master, slave = pty.openpty()
109
150
  proc = subprocess.Popen(
110
151
  command,
@@ -112,7 +153,7 @@ class ExecuteBashCommandTool(Tool):
112
153
  stdin=slave,
113
154
  stdout=slave,
114
155
  stderr=subprocess.STDOUT,
115
- cwd=cwd,
156
+ cwd="/tmp", # cwd=cwd, # Force /tmp directory
116
157
  env=env_vars,
117
158
  preexec_fn=os.setsid,
118
159
  close_fds=True,
@@ -127,74 +168,90 @@ class ExecuteBashCommandTool(Tool):
127
168
  rlist, _, _ = select.select([master, sys.stdin], [], [], timeout_seconds)
128
169
  if not rlist:
129
170
  if proc.poll() is not None:
130
- break # Process completed but select timed out
171
+ break
131
172
  raise subprocess.TimeoutExpired(command, timeout_seconds)
132
173
 
133
174
  for fd in rlist:
134
175
  if fd == master:
135
- data = os.read(master, 1024).decode()
136
- if not data:
176
+ try:
177
+ data = os.read(master, 1024).decode()
178
+ if not data:
179
+ break_loop = True
180
+ break
181
+ stdout_buffer.append(data)
182
+ sys.stdout.write(data)
183
+ sys.stdout.flush()
184
+ except (OSError, UnicodeDecodeError) as e:
185
+ logger.warning(f"Error reading output: {e}")
137
186
  break_loop = True
138
187
  break
139
- stdout_buffer.append(data)
140
- sys.stdout.write(data)
141
- sys.stdout.flush()
142
188
  elif fd == sys.stdin:
143
- user_input = os.read(sys.stdin.fileno(), 1024)
144
- os.write(master, user_input)
189
+ try:
190
+ user_input = os.read(sys.stdin.fileno(), 1024)
191
+ os.write(master, user_input)
192
+ except OSError as e:
193
+ logger.warning(f"Error handling input: {e}")
145
194
 
146
195
  if break_loop or proc.poll() is not None:
147
- while True:
148
- data = os.read(master, 1024).decode()
149
- if not data:
150
- break
151
- stdout_buffer.append(data)
152
- sys.stdout.write(data)
153
- sys.stdout.flush()
196
+ try:
197
+ while True:
198
+ data = os.read(master, 1024).decode()
199
+ if not data:
200
+ break
201
+ stdout_buffer.append(data)
202
+ sys.stdout.write(data)
203
+ sys.stdout.flush()
204
+ except (OSError, UnicodeDecodeError):
205
+ pass
154
206
  break
155
207
 
156
208
  except subprocess.TimeoutExpired:
157
209
  os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
158
- return f"Command timed out after {timeout_seconds} seconds."
210
+ return self._format_output("", 1, f"Command timed out after {timeout_seconds} seconds")
159
211
  except EOFError:
160
- pass # Process exited normally
212
+ pass
161
213
  finally:
162
214
  os.close(master)
163
215
  proc.wait()
164
216
 
165
217
  stdout_content = "".join(stdout_buffer)
166
218
  return_code = proc.returncode
167
- formatted_result = (
168
- "<command_output>"
169
- f" <stdout>{stdout_content.strip()}</stdout>"
170
- f" <returncode>{return_code}</returncode>"
171
- f"</command_output>"
172
- )
173
- return formatted_result
219
+ return self._format_output(stdout_content, return_code)
220
+
174
221
  except Exception as e:
175
- return f"Unexpected error executing command: {str(e)}"
222
+ return self._format_output("", 1, f"Unexpected error executing command: {str(e)}")
176
223
 
177
224
  def execute(
178
225
  self,
179
226
  command: str,
180
- working_dir: Optional[str] = None,
227
+ working_dir: Optional[str] = None, # Kept for backward compatibility but ignored
181
228
  timeout: Union[int, str, None] = 60,
182
229
  env: Optional[Dict[str, str]] = None,
183
230
  ) -> str:
184
- """Executes a bash command with interactive input handling."""
231
+ """Executes a bash command with interactive input handling in /tmp directory."""
232
+ # Ensure /tmp exists and is writable
233
+ tmp_dir = Path("/tmp")
234
+ if not (tmp_dir.exists() and os.access(tmp_dir, os.W_OK)):
235
+ return self._format_output("", 1, "Error: /tmp directory is not accessible")
236
+
237
+ # Validate command
238
+ try:
239
+ self._validate_command(command)
240
+ except ValueError as e:
241
+ return self._format_output("", 1, str(e))
242
+
185
243
  timeout_seconds = int(timeout) if timeout else 60
186
- cwd = working_dir or os.getcwd()
187
244
  env_vars = os.environ.copy()
188
245
  if env:
189
246
  env_vars.update(env)
190
247
 
191
248
  if sys.platform == "win32":
192
- return self._execute_windows(command, cwd, timeout_seconds, env_vars)
249
+ return self._execute_windows(command, timeout_seconds, env_vars)
193
250
  else:
194
251
  if not pty:
195
252
  logger.warning("PTY module not available, falling back to Windows-style execution")
196
- return self._execute_windows(command, cwd, timeout_seconds, env_vars)
197
- return self._execute_unix(command, cwd, timeout_seconds, env_vars)
253
+ return self._execute_windows(command, timeout_seconds, env_vars)
254
+ return self._execute_unix(command, timeout_seconds, env_vars)
198
255
 
199
256
 
200
257
  if __name__ == "__main__":
@@ -0,0 +1,49 @@
1
+ """Tool for tracking and returning paths of files created during a process."""
2
+
3
+ from typing import List
4
+ from pydantic import Field
5
+
6
+ from quantalogic.tools.tool import Tool, ToolArgument
7
+
8
+
9
+ class FileTrackerTool(Tool):
10
+ """Tool for tracking and returning file paths created during a process."""
11
+ name: str = "file_tracker_tool"
12
+ description: str = "Tracks and returns file paths created during a process."
13
+ need_validation: bool = False
14
+ arguments: list = [
15
+ ToolArgument(
16
+ name="file_path",
17
+ arg_type="string",
18
+ description="The path to the file to write. Using an absolute path is recommended.",
19
+ required=True,
20
+ example="/path/to/file.txt",
21
+ ),
22
+ ToolArgument(
23
+ name="content",
24
+ arg_type="string",
25
+ description="""
26
+ The content to write to the file. Use CDATA to escape special characters.
27
+ Don't add newlines at the beginning or end of the content.
28
+ """,
29
+ required=True,
30
+ example="Hello, world!",
31
+ ),
32
+ ToolArgument(
33
+ name="append_mode",
34
+ arg_type="string",
35
+ description="""Append mode. If true, the content will be appended to the end of the file.
36
+ """,
37
+ required=False,
38
+ example="False",
39
+ ),
40
+ ToolArgument(
41
+ name="overwrite",
42
+ arg_type="string",
43
+ description="Overwrite mode. If true, existing files can be overwritten. Defaults to False.",
44
+ required=False,
45
+ example="False",
46
+ default="False",
47
+ ),
48
+ ]
49
+ execute = lambda self, file_path: file_path
@@ -95,6 +95,7 @@ class GoogleNewsTool(Tool):
95
95
  """
96
96
 
97
97
  name: str = "google_news_tool"
98
+ need_post_process: bool = False
98
99
  description: str = (
99
100
  "Advanced news retrieval and analysis tool with support for sentiment analysis, "
100
101
  "keyword extraction, and article summarization."
@@ -295,6 +296,8 @@ class GoogleNewsTool(Tool):
295
296
  }
296
297
  processed_articles.append(processed_article)
297
298
 
299
+
300
+ logger.info(f"Fetched {len(processed_articles)} articles for query: {query}")
298
301
  # Return pretty-printed JSON string, matching DuckDuckGo tool format
299
302
  return json.dumps(processed_articles, indent=4, ensure_ascii=False)
300
303