quantalogic 0.59.3__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 (41) 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/tools_prompt.j2 +2 -4
  11. quantalogic/prompts.py +23 -4
  12. quantalogic/server/agent_server.py +1 -1
  13. quantalogic/tools/__init__.py +2 -0
  14. quantalogic/tools/duckduckgo_search_tool.py +1 -0
  15. quantalogic/tools/execute_bash_command_tool.py +114 -57
  16. quantalogic/tools/file_tracker_tool.py +49 -0
  17. quantalogic/tools/google_packages/google_news_tool.py +3 -0
  18. quantalogic/tools/image_generation/dalle_e.py +89 -137
  19. quantalogic/tools/rag_tool/__init__.py +2 -9
  20. quantalogic/tools/rag_tool/document_rag_sources_.py +728 -0
  21. quantalogic/tools/rag_tool/ocr_pdf_markdown.py +144 -0
  22. quantalogic/tools/replace_in_file_tool.py +1 -1
  23. quantalogic/tools/terminal_capture_tool.py +293 -0
  24. quantalogic/tools/tool.py +4 -0
  25. quantalogic/tools/utilities/__init__.py +2 -0
  26. quantalogic/tools/utilities/download_file_tool.py +3 -5
  27. quantalogic/tools/utilities/llm_tool.py +283 -0
  28. quantalogic/tools/utilities/selenium_tool.py +296 -0
  29. quantalogic/tools/utilities/vscode_tool.py +1 -1
  30. quantalogic/tools/web_navigation/__init__.py +5 -0
  31. quantalogic/tools/web_navigation/web_tool.py +145 -0
  32. quantalogic/tools/write_file_tool.py +72 -36
  33. {quantalogic-0.59.3.dist-info → quantalogic-0.60.0.dist-info}/METADATA +1 -1
  34. {quantalogic-0.59.3.dist-info → quantalogic-0.60.0.dist-info}/RECORD +37 -28
  35. quantalogic/tools/rag_tool/document_metadata.py +0 -15
  36. quantalogic/tools/rag_tool/query_response.py +0 -20
  37. quantalogic/tools/rag_tool/rag_tool.py +0 -566
  38. quantalogic/tools/rag_tool/rag_tool_beta.py +0 -264
  39. {quantalogic-0.59.3.dist-info → quantalogic-0.60.0.dist-info}/LICENSE +0 -0
  40. {quantalogic-0.59.3.dist-info → quantalogic-0.60.0.dist-info}/WHEEL +0 -0
  41. {quantalogic-0.59.3.dist-info → quantalogic-0.60.0.dist-info}/entry_points.txt +0 -0
@@ -1,264 +0,0 @@
1
- """RAG (Retrieval Augmented Generation) Tool using LlamaIndex.
2
-
3
- This tool provides a flexible RAG implementation supporting multiple vector stores
4
- and embedding models, with configurable document processing options.
5
- """
6
-
7
- import os
8
- from enum import Enum
9
- from typing import Any, List, Optional
10
-
11
- import chromadb
12
- from llama_index.core import (
13
- SimpleDirectoryReader,
14
- StorageContext,
15
- VectorStoreIndex,
16
- load_index_from_storage,
17
- )
18
- from llama_index.core.settings import Settings
19
- from llama_index.embeddings.bedrock import BedrockEmbedding
20
- from llama_index.embeddings.huggingface import HuggingFaceEmbedding
21
- from llama_index.embeddings.instructor import InstructorEmbedding
22
- from llama_index.embeddings.openai import OpenAIEmbedding
23
- from llama_index.vector_stores.chroma import ChromaVectorStore
24
- from llama_index.vector_stores.faiss import FaissVectorStore
25
- from loguru import logger
26
-
27
- from quantalogic.tools.tool import Tool, ToolArgument
28
-
29
-
30
- class VectorStoreType(str, Enum):
31
- """Supported vector store types."""
32
- CHROMA = "chroma"
33
- FAISS = "faiss"
34
-
35
- class EmbeddingType(str, Enum):
36
- """Supported embedding model types."""
37
- OPENAI = "openai"
38
- HUGGINGFACE = "huggingface"
39
- INSTRUCTOR = "instructor"
40
- BEDROCK = "bedrock"
41
-
42
- class RagTool(Tool):
43
- """Tool for performing RAG operations using LlamaIndex."""
44
-
45
- name: str = "rag_tool"
46
- description: str = (
47
- "Retrieval Augmented Generation (RAG) tool for querying indexed documents "
48
- "using vector stores and embedding models."
49
- )
50
- arguments: List[ToolArgument] = [
51
- ToolArgument(
52
- name="query",
53
- arg_type="string",
54
- description="Query string for searching the index",
55
- required=True,
56
- example="What is the main topic?",
57
- ),
58
- ]
59
-
60
- def __init__(
61
- self,
62
- vector_store: str = "chroma",
63
- embedding_model: str = "openai",
64
- persist_dir: str = "./storage/rag",
65
- document_paths: Optional[List[str]] = None,
66
- ):
67
- """Initialize the RAG tool with vector store, embedding model, and optional documents.
68
-
69
- Args:
70
- vector_store: Vector store type (chroma, faiss)
71
- embedding_model: Embedding model type (openai, huggingface, instructor, bedrock)
72
- persist_dir: Directory for persistence
73
- document_paths: Optional list of paths to documents or directories to index
74
- """
75
- super().__init__()
76
- self.persist_dir = os.path.abspath(persist_dir)
77
- self.embed_model = self._setup_embedding_model(embedding_model)
78
- self.vector_store = self._setup_vector_store(vector_store, self.persist_dir)
79
-
80
- # Configure llama-index settings with the embedding model
81
- Settings.embed_model = self.embed_model
82
- self.storage_context = StorageContext.from_defaults(vector_store=self.vector_store)
83
-
84
- # Initialize index
85
- self.index = None
86
-
87
- # Check if we have documents to initialize with
88
- if document_paths:
89
- self._initialize_with_documents(document_paths)
90
- else:
91
- # Only try to load existing index if no documents were provided
92
- index_exists = os.path.exists(os.path.join(self.persist_dir, "docstore.json"))
93
- if index_exists:
94
- try:
95
- self.index = load_index_from_storage(
96
- storage_context=self.storage_context,
97
- )
98
- logger.info(f"Loaded existing index from {self.persist_dir}")
99
- except Exception as e:
100
- logger.error(f"Failed to load existing index: {str(e)}")
101
- self.index = None
102
- else:
103
- logger.warning("No existing index found and no documents provided")
104
-
105
- def _initialize_with_documents(self, document_paths: List[str]) -> None:
106
- """Initialize the index with the given documents.
107
-
108
- Args:
109
- document_paths: List of paths to documents or directories
110
- """
111
- try:
112
- all_documents = []
113
- for path in document_paths:
114
- if not os.path.exists(path):
115
- logger.warning(f"Document path does not exist: {path}")
116
- continue
117
-
118
- documents = SimpleDirectoryReader(
119
- input_files=[path] if os.path.isfile(path) else None,
120
- input_dir=path if os.path.isdir(path) else None,
121
- ).load_data()
122
- all_documents.extend(documents)
123
-
124
- if all_documents:
125
- self.index = VectorStoreIndex.from_documents(
126
- all_documents,
127
- storage_context=self.storage_context,
128
- )
129
- # Persist the index after creation
130
- self.storage_context.persist(persist_dir=self.persist_dir)
131
- logger.info(f"Created and persisted new index with {len(all_documents)} documents")
132
- else:
133
- logger.warning("No valid documents found in provided paths")
134
-
135
- except Exception as e:
136
- logger.error(f"Error initializing with documents: {str(e)}")
137
- raise RuntimeError(f"Failed to initialize with documents: {str(e)}")
138
-
139
- def _setup_embedding_model(self, model_type: str) -> Any:
140
- """Set up the embedding model based on type.
141
-
142
- Args:
143
- model_type: Type of embedding model to use
144
-
145
- Returns:
146
- Configured embedding model instance
147
- """
148
- model_type = EmbeddingType(model_type.lower())
149
- if model_type == EmbeddingType.OPENAI:
150
- return OpenAIEmbedding()
151
- elif model_type == EmbeddingType.HUGGINGFACE:
152
- return HuggingFaceEmbedding()
153
- elif model_type == EmbeddingType.INSTRUCTOR:
154
- return InstructorEmbedding()
155
- elif model_type == EmbeddingType.BEDROCK:
156
- return BedrockEmbedding()
157
- else:
158
- raise ValueError(f"Unsupported embedding model type: {model_type}")
159
-
160
- def _setup_vector_store(self, store_type: str, persist_dir: str) -> Any:
161
- """Set up the vector store based on type.
162
-
163
- Args:
164
- store_type: Type of vector store to use
165
- persist_dir: Directory for persistence
166
-
167
- Returns:
168
- Configured vector store instance
169
- """
170
- store_type = VectorStoreType(store_type.lower())
171
-
172
- # Ensure the persist directory exists
173
- os.makedirs(persist_dir, exist_ok=True)
174
-
175
- if store_type == VectorStoreType.CHROMA:
176
- # Use PersistentClient with explicit settings
177
- chroma_persist_dir = os.path.join(persist_dir, "chroma")
178
- os.makedirs(chroma_persist_dir, exist_ok=True)
179
-
180
- chroma_client = chromadb.PersistentClient(
181
- path=chroma_persist_dir,
182
- )
183
- collection = chroma_client.create_collection(
184
- name="default_collection",
185
- get_or_create=True
186
- )
187
- return ChromaVectorStore(
188
- chroma_collection=collection,
189
- )
190
- elif store_type == VectorStoreType.FAISS:
191
- return FaissVectorStore()
192
- else:
193
- raise ValueError(f"Unsupported vector store type: {store_type}")
194
-
195
- def add_documents(self, document_path: str) -> bool:
196
- """Add documents to the RAG system.
197
-
198
- Args:
199
- document_path: Path to document or directory of documents
200
-
201
- Returns:
202
- bool: True if documents were added successfully
203
- """
204
- try:
205
- if not os.path.exists(document_path):
206
- logger.error(f"Document path does not exist: {document_path}")
207
- return False
208
-
209
- documents = SimpleDirectoryReader(
210
- input_files=[document_path] if os.path.isfile(document_path) else None,
211
- input_dir=document_path if os.path.isdir(document_path) else None,
212
- ).load_data()
213
-
214
- # Create index with configured settings and storage context
215
- self.index = VectorStoreIndex.from_documents(
216
- documents,
217
- storage_context=self.storage_context,
218
- )
219
-
220
- return True
221
- except Exception as e:
222
- logger.error(f"Error adding documents: {str(e)}")
223
- return False
224
-
225
- def execute(self, query: str) -> str:
226
- """Execute a query against the indexed documents.
227
-
228
- Args:
229
- query: Query string for searching
230
-
231
- Returns:
232
- Query response
233
-
234
- Raises:
235
- ValueError: If no index is available
236
- """
237
- try:
238
- if not self.index:
239
- raise ValueError("No index available. Please add documents first using add_documents()")
240
-
241
- # Query the index
242
- query_engine = self.index.as_query_engine()
243
- response = query_engine.query(query)
244
- return str(response)
245
-
246
- except Exception as e:
247
- logger.error(f"Error in RAG query: {str(e)}")
248
- raise RuntimeError(f"Query failed: {str(e)}")
249
-
250
-
251
- if __name__ == "__main__":
252
- # Example usage
253
- tool = RagTool(
254
- vector_store="chroma",
255
- embedding_model="openai",
256
- persist_dir="./storage/rag",
257
- document_paths=[
258
- "./docs/file1.pdf",
259
- "./docs/directory1"
260
- ]
261
- )
262
-
263
- # Query
264
- print(tool.execute("What is the main topic?"))