ws-bom-robot-app 0.0.64__py3-none-any.whl → 0.0.65__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.
@@ -1,317 +1,317 @@
1
- from asyncio import Queue
2
- import aiohttp
3
- from typing import Optional, Type, Callable
4
- from ws_bom_robot_app.config import config
5
- from ws_bom_robot_app.llm.models.api import LlmApp,LlmAppTool
6
- from ws_bom_robot_app.llm.providers.llm_manager import LlmInterface
7
- from ws_bom_robot_app.llm.utils.cms import CmsApp, get_app_by_id
8
- from ws_bom_robot_app.llm.vector_store.db.manager import VectorDbManager
9
- from ws_bom_robot_app.llm.tools.utils import getRandomWaitingMessage, translate_text
10
- from ws_bom_robot_app.llm.tools.models.main import NoopInput,DocumentRetrieverInput,ImageGeneratorInput,LlmChainInput,SearchOnlineInput,EmailSenderInput
11
- from pydantic import BaseModel, ConfigDict
12
-
13
- class ToolConfig(BaseModel):
14
- function: Callable
15
- model: Optional[Type[BaseModel]] = NoopInput
16
- model_config = ConfigDict(
17
- arbitrary_types_allowed=True
18
- )
19
-
20
- class ToolManager:
21
- """
22
- ToolManager is responsible for managing various tools used in the application.
23
-
24
- Attributes:
25
- app_tool (LlmAppTool): The application tool configuration.
26
- api_key (str): The API key for accessing external services.
27
- callbacks (list): A list of callback functions to be executed.
28
-
29
- Methods:
30
- document_retriever(query: str): Asynchronously retrieves documents based on the query.
31
- image_generator(query: str, language: str = "it"): Asynchronously generates an image based on the query.
32
- get_coroutine(): Retrieves the coroutine function based on the tool configuration.
33
- """
34
-
35
- def __init__(
36
- self,
37
- llm: LlmInterface,
38
- app_tool: LlmAppTool,
39
- callbacks: list,
40
- queue: Optional[Queue] = None
41
- ):
42
- self.llm = llm
43
- self.app_tool = app_tool
44
- self.callbacks = callbacks
45
- self.queue = queue
46
-
47
- async def __extract_documents(self, query: str, app_tool: LlmAppTool):
48
- search_type = "similarity"
49
- search_kwargs = {"k": 4}
50
- if app_tool.search_settings:
51
- search_settings = app_tool.search_settings # type: ignore
52
- if search_settings.search_type == "similarityScoreThreshold":
53
- search_type = "similarity_score_threshold"
54
- search_kwargs = {
55
- "score_threshold": search_settings.score_threshold_id if search_settings.score_threshold_id else 0.5,
56
- "k": search_settings.search_k if search_settings.search_k else 100
57
- }
58
- elif search_settings.search_type == "mmr":
59
- search_type = "mmr"
60
- search_kwargs = {"k": search_settings.search_k if search_settings.search_k else 4}
61
- elif search_settings.search_type == "default":
62
- search_type = "similarity"
63
- search_kwargs = {"k": search_settings.search_k if search_settings.search_k else 4}
64
- else:
65
- search_type = "mixed"
66
- search_kwargs = {"k": search_settings.search_k if search_settings.search_k else 4}
67
- if self.queue:
68
- await self.queue.put(getRandomWaitingMessage(app_tool.waiting_message, traduction=False))
69
-
70
- return await VectorDbManager.get_strategy(app_tool.vector_type).invoke(
71
- self.llm.get_embeddings(),
72
- app_tool.vector_db,
73
- query,
74
- search_type,
75
- search_kwargs,
76
- app_tool=app_tool,
77
- llm=self.llm.get_llm(),
78
- source=app_tool.function_id,
79
- )
80
-
81
- #region functions
82
- async def document_retriever(self, query: str) -> list:
83
- """
84
- Asynchronously retrieves documents based on the provided query using the specified search settings.
85
-
86
- Args:
87
- query (str): The search query string.
88
-
89
- Returns:
90
- list: A list of retrieved documents based on the search criteria.
91
-
92
- Raises:
93
- ValueError: If the configuration for the tool is invalid or the vector database is not found.
94
-
95
- Notes:
96
- - The function supports different search types such as "similarity", "similarity_score_threshold", "mmr", and "mixed".
97
- - The search settings can be customized through the `app_tool.search_settings` attribute.
98
- - If a queue is provided, a waiting message is put into the queue before invoking the search.
99
- """
100
- if (
101
- self.app_tool.type == "function" and self.app_tool.vector_db
102
- #and self.settings.get("dataSource") == "knowledgebase"
103
- ):
104
- return await self.__extract_documents(query, self.app_tool)
105
-
106
- async def image_generator(self, query: str, language: str = "it"):
107
- """
108
- Asynchronously generates an image based on the query.
109
- set OPENAI_API_KEY in your environment variables
110
- """
111
- from langchain_community.utilities.dalle_image_generator import DallEAPIWrapper
112
- model = self.app_tool.model or "dall-e-3"
113
- random_waiting_message = getRandomWaitingMessage(self.app_tool.waiting_message, traduction=False)
114
- if not language:
115
- language = "it"
116
- await translate_text(
117
- self.llm, language, random_waiting_message, self.callbacks
118
- )
119
- try:
120
- #set os.environ.get("OPENAI_API_KEY")!
121
- image_url = DallEAPIWrapper(model=model).run(query) # type: ignore
122
- return image_url
123
- except Exception as e:
124
- return f"Error: {str(e)}"
125
-
126
- async def llm_chain(self, input: str):
127
- if self.app_tool.type == "llmChain":
128
- from langchain_core.prompts import ChatPromptTemplate
129
- from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
130
- from pydantic import create_model
131
- system_message = self.app_tool.llm_chain_settings.prompt
132
- context = []
133
- if self.app_tool.data_source == "knowledgebase":
134
- context = await self.__extract_documents(input, self.app_tool)
135
- if len(context) > 0:
136
- for doc in context:
137
- system_message += f"\n\nContext:\n{doc.metadata.get("source", "")}: {doc.page_content}"
138
- # Determine output parser and format based on output type
139
- output_type = self.app_tool.llm_chain_settings.outputStructure.get("outputType")
140
- is_json_output = output_type == "json"
141
-
142
- if is_json_output:
143
- output_format = self.app_tool.llm_chain_settings.outputStructure.get("outputFormat", {})
144
- json_schema = create_model('json_schema', **{k: (type(v), ...) for k, v in output_format.items()})
145
- output_parser = JsonOutputParser(pydantic_object=json_schema)
146
- system_message += "\n\nFormat instructions:\n{format_instructions}".strip()
147
- else:
148
- output_parser = StrOutputParser()
149
- # Create prompt template with or without format instructions
150
- base_messages = [
151
- ("system", system_message),
152
- ("user", "{input}")
153
- ]
154
- if is_json_output:
155
- prompt = ChatPromptTemplate.from_messages(base_messages).partial(
156
- format_instructions=output_parser.get_format_instructions()
157
- )
158
- else:
159
- prompt = ChatPromptTemplate.from_messages(base_messages)
160
- model = self.app_tool.llm_chain_settings.model
161
- self.llm.config.model = model
162
- llm = self.llm.get_llm()
163
- llm.tags = ["llm_chain"]
164
- chain = prompt | llm | output_parser
165
- result = await chain.ainvoke({"input": input})
166
- return result
167
-
168
- async def proxy_app_chat(self, query: str) -> str | None:
169
- secrets = self.app_tool.secrets_to_dict()
170
- app_id = secrets.get("appId")
171
- if not app_id:
172
- raise ValueError("Tool configuration is invalid. 'appId' is required.")
173
- app: CmsApp = await get_app_by_id(app_id)
174
- if not app:
175
- raise ValueError(f"App with id {app_id} not found.")
176
- url = f"{config.robot_cms_host}/api/llm/message?locale=en&raw=true"
177
- auth = config.robot_cms_auth
178
- headers = {"Authorization": auth} if auth else {}
179
- async with aiohttp.ClientSession() as session:
180
- data = {
181
- "appKey": app.credentials.app_key,
182
- "apiKey": app.credentials.api_key,
183
- "messages": [
184
- {
185
- "role": "user",
186
- "content": query
187
- }
188
- ]
189
- }
190
- async with session.post(url, json=data, headers=headers) as response:
191
- if response.status == 200:
192
- return await response.text()
193
- else:
194
- raise ValueError(f"Error fetching chat response: {response.status}")
195
- return None
196
-
197
- async def proxy_app_tool(self) -> None:
198
- return None
199
-
200
- async def _fetch_urls(self, urls: list[str]) -> list[dict]:
201
- import aiohttp, asyncio
202
- from ws_bom_robot_app.llm.tools.utils import fetch_page, extract_content_with_trafilatura
203
- if not urls:
204
- return []
205
- async with aiohttp.ClientSession() as session:
206
- tasks = [fetch_page(session, url) for url in urls]
207
- responses = await asyncio.gather(*tasks, return_exceptions=True)
208
- final_results = []
209
- for item in responses:
210
- if isinstance(item, Exception):
211
- continue
212
- url = item["url"]
213
- html = item["html"]
214
- if html:
215
- content = await extract_content_with_trafilatura(html)
216
- if content:
217
- final_results.append({"url": url, "content": content})
218
- else:
219
- final_results.append({"url": url, "content": "No content found"})
220
- else:
221
- final_results.append({"url": url, "content": "Page not found"})
222
- return final_results
223
-
224
- async def search_online(self, query: str) -> list[dict]:
225
- from langchain_community.utilities import DuckDuckGoSearchAPIWrapper
226
- # Wrapper DuckDuckGo
227
- search = DuckDuckGoSearchAPIWrapper(max_results=10)
228
- try:
229
- raw_results = search.results(query, max_results=10)
230
- except Exception as e:
231
- return f"[!] Errore ricerca: {e}"
232
- urls = [r["link"] for r in raw_results]
233
- return await self._fetch_urls(urls)
234
-
235
- async def search_online_google(self, query: str) -> list[dict]:
236
- from langchain_google_community import GoogleSearchAPIWrapper
237
- secrets = self.app_tool.secrets_to_dict()
238
- search_type = secrets.get("searchType")
239
- if search_type:
240
- search_kwargs = {"searchType" : search_type}
241
- search = GoogleSearchAPIWrapper(
242
- google_api_key=secrets.get("GOOGLE_API_KEY"),
243
- google_cse_id=secrets.get("GOOGLE_CSE_ID"),
244
- )
245
- if search_type:
246
- raw_results = search.results(query=query,
247
- num_results=secrets.get("num_results", 5),
248
- search_params=search_kwargs)
249
- return raw_results
250
- raw_results = search.results(
251
- query=query,
252
- num_results=secrets.get("num_results", 5)
253
- )
254
- urls = [r["link"] for r in raw_results]
255
- return await self._fetch_urls(urls)
256
-
257
- async def send_email(self, email_subject: str, body: str, to_email:str):
258
- import smtplib
259
- from email.mime.multipart import MIMEMultipart
260
- from email.mime.text import MIMEText
261
- secrets = self.app_tool.secrets
262
- secrets = {item["secretId"]: item["secretValue"] for item in secrets}
263
- import urllib.parse as urlparse
264
- url_preview = secrets.get("url_preview", "")
265
- if url_preview and url_preview != "":
266
- message_tread = "Puoi visualizzare la chat su questo indirizzo: " + urlparse.urljoin(url_preview, f"?llmThreadId={self.app_tool.thread_id}")
267
- body = body.replace("##url_preview##", message_tread)
268
- # Email configuration
269
- smtp_server = secrets.get("smtp_server")
270
- smtp_port = secrets.get("smtp_port")
271
- smtp_user = secrets.get("smtp_user")
272
- smtp_password = secrets.get("smtp_password")
273
- from_email = secrets.get("from_email")
274
- if not to_email or to_email == "":
275
- return "No recipient email provided"
276
- if not email_subject or email_subject == "":
277
- return "No email object provided"
278
- # Create the email content
279
- msg = MIMEMultipart()
280
- msg['From'] = from_email
281
- msg['To'] = to_email
282
- msg['Subject'] = email_subject
283
-
284
- # Create the email body
285
- msg.attach(MIMEText(body, 'plain'))
286
-
287
- # Send the email
288
- try:
289
- with smtplib.SMTP(smtp_server, smtp_port) as server:
290
- # Use authentication and SSL only if password is provided
291
- if smtp_password:
292
- server.starttls()
293
- server.login(smtp_user, smtp_password)
294
- server.send_message(msg)
295
- except Exception as e:
296
- return f"Failed to send email: {str(e)}"
297
- return "Email sent successfully"
298
-
299
- #endregion
300
-
301
- #class variables (static)
302
- _list: dict[str,ToolConfig] = {
303
- f"{document_retriever.__name__}": ToolConfig(function=document_retriever, model=DocumentRetrieverInput),
304
- f"{image_generator.__name__}": ToolConfig(function=image_generator, model=ImageGeneratorInput),
305
- f"{llm_chain.__name__}": ToolConfig(function=llm_chain, model=LlmChainInput),
306
- f"{search_online.__name__}": ToolConfig(function=search_online, model=SearchOnlineInput),
307
- f"{search_online_google.__name__}": ToolConfig(function=search_online_google, model=SearchOnlineInput),
308
- f"{send_email.__name__}": ToolConfig(function=send_email, model=EmailSenderInput),
309
- f"{proxy_app_chat.__name__}": ToolConfig(function=proxy_app_chat, model=DocumentRetrieverInput),
310
- f"{proxy_app_tool.__name__}": ToolConfig(function=proxy_app_tool, model=NoopInput),
311
-
312
- }
313
-
314
- #instance methods
315
- def get_coroutine(self):
316
- tool_cfg = self._list.get(self.app_tool.function_name)
317
- return getattr(self, tool_cfg.function.__name__) # type: ignore
1
+ from asyncio import Queue
2
+ import aiohttp
3
+ from typing import Optional, Type, Callable
4
+ from ws_bom_robot_app.config import config
5
+ from ws_bom_robot_app.llm.models.api import LlmApp,LlmAppTool
6
+ from ws_bom_robot_app.llm.providers.llm_manager import LlmInterface
7
+ from ws_bom_robot_app.llm.utils.cms import CmsApp, get_app_by_id
8
+ from ws_bom_robot_app.llm.vector_store.db.manager import VectorDbManager
9
+ from ws_bom_robot_app.llm.tools.utils import getRandomWaitingMessage, translate_text
10
+ from ws_bom_robot_app.llm.tools.models.main import NoopInput,DocumentRetrieverInput,ImageGeneratorInput,LlmChainInput,SearchOnlineInput,EmailSenderInput
11
+ from pydantic import BaseModel, ConfigDict
12
+
13
+ class ToolConfig(BaseModel):
14
+ function: Callable
15
+ model: Optional[Type[BaseModel]] = NoopInput
16
+ model_config = ConfigDict(
17
+ arbitrary_types_allowed=True
18
+ )
19
+
20
+ class ToolManager:
21
+ """
22
+ ToolManager is responsible for managing various tools used in the application.
23
+
24
+ Attributes:
25
+ app_tool (LlmAppTool): The application tool configuration.
26
+ api_key (str): The API key for accessing external services.
27
+ callbacks (list): A list of callback functions to be executed.
28
+
29
+ Methods:
30
+ document_retriever(query: str): Asynchronously retrieves documents based on the query.
31
+ image_generator(query: str, language: str = "it"): Asynchronously generates an image based on the query.
32
+ get_coroutine(): Retrieves the coroutine function based on the tool configuration.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ llm: LlmInterface,
38
+ app_tool: LlmAppTool,
39
+ callbacks: list,
40
+ queue: Optional[Queue] = None
41
+ ):
42
+ self.llm = llm
43
+ self.app_tool = app_tool
44
+ self.callbacks = callbacks
45
+ self.queue = queue
46
+
47
+ async def __extract_documents(self, query: str, app_tool: LlmAppTool):
48
+ search_type = "similarity"
49
+ search_kwargs = {"k": 4}
50
+ if app_tool.search_settings:
51
+ search_settings = app_tool.search_settings # type: ignore
52
+ if search_settings.search_type == "similarityScoreThreshold":
53
+ search_type = "similarity_score_threshold"
54
+ search_kwargs = {
55
+ "score_threshold": search_settings.score_threshold_id if search_settings.score_threshold_id else 0.5,
56
+ "k": search_settings.search_k if search_settings.search_k else 100
57
+ }
58
+ elif search_settings.search_type == "mmr":
59
+ search_type = "mmr"
60
+ search_kwargs = {"k": search_settings.search_k if search_settings.search_k else 4}
61
+ elif search_settings.search_type == "default":
62
+ search_type = "similarity"
63
+ search_kwargs = {"k": search_settings.search_k if search_settings.search_k else 4}
64
+ else:
65
+ search_type = "mixed"
66
+ search_kwargs = {"k": search_settings.search_k if search_settings.search_k else 4}
67
+ if self.queue:
68
+ await self.queue.put(getRandomWaitingMessage(app_tool.waiting_message, traduction=False))
69
+
70
+ return await VectorDbManager.get_strategy(app_tool.vector_type).invoke(
71
+ self.llm.get_embeddings(),
72
+ app_tool.vector_db,
73
+ query,
74
+ search_type,
75
+ search_kwargs,
76
+ app_tool=app_tool,
77
+ llm=self.llm.get_llm(),
78
+ source=app_tool.function_id,
79
+ )
80
+
81
+ #region functions
82
+ async def document_retriever(self, query: str) -> list:
83
+ """
84
+ Asynchronously retrieves documents based on the provided query using the specified search settings.
85
+
86
+ Args:
87
+ query (str): The search query string.
88
+
89
+ Returns:
90
+ list: A list of retrieved documents based on the search criteria.
91
+
92
+ Raises:
93
+ ValueError: If the configuration for the tool is invalid or the vector database is not found.
94
+
95
+ Notes:
96
+ - The function supports different search types such as "similarity", "similarity_score_threshold", "mmr", and "mixed".
97
+ - The search settings can be customized through the `app_tool.search_settings` attribute.
98
+ - If a queue is provided, a waiting message is put into the queue before invoking the search.
99
+ """
100
+ if (
101
+ self.app_tool.type == "function" and self.app_tool.vector_db
102
+ #and self.settings.get("dataSource") == "knowledgebase"
103
+ ):
104
+ return await self.__extract_documents(query, self.app_tool)
105
+
106
+ async def image_generator(self, query: str, language: str = "it"):
107
+ """
108
+ Asynchronously generates an image based on the query.
109
+ set OPENAI_API_KEY in your environment variables
110
+ """
111
+ from langchain_community.utilities.dalle_image_generator import DallEAPIWrapper
112
+ model = self.app_tool.model or "dall-e-3"
113
+ random_waiting_message = getRandomWaitingMessage(self.app_tool.waiting_message, traduction=False)
114
+ if not language:
115
+ language = "it"
116
+ await translate_text(
117
+ self.llm, language, random_waiting_message, self.callbacks
118
+ )
119
+ try:
120
+ #set os.environ.get("OPENAI_API_KEY")!
121
+ image_url = DallEAPIWrapper(model=model).run(query) # type: ignore
122
+ return image_url
123
+ except Exception as e:
124
+ return f"Error: {str(e)}"
125
+
126
+ async def llm_chain(self, input: str):
127
+ if self.app_tool.type == "llmChain":
128
+ from langchain_core.prompts import ChatPromptTemplate
129
+ from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
130
+ from pydantic import create_model
131
+ system_message = self.app_tool.llm_chain_settings.prompt
132
+ context = []
133
+ if self.app_tool.data_source == "knowledgebase":
134
+ context = await self.__extract_documents(input, self.app_tool)
135
+ if len(context) > 0:
136
+ for doc in context:
137
+ system_message += f"\n\nContext:\n{doc.metadata.get("source", "")}: {doc.page_content}"
138
+ # Determine output parser and format based on output type
139
+ output_type = self.app_tool.llm_chain_settings.outputStructure.get("outputType")
140
+ is_json_output = output_type == "json"
141
+
142
+ if is_json_output:
143
+ output_format = self.app_tool.llm_chain_settings.outputStructure.get("outputFormat", {})
144
+ json_schema = create_model('json_schema', **{k: (type(v), ...) for k, v in output_format.items()})
145
+ output_parser = JsonOutputParser(pydantic_object=json_schema)
146
+ system_message += "\n\nFormat instructions:\n{format_instructions}".strip()
147
+ else:
148
+ output_parser = StrOutputParser()
149
+ # Create prompt template with or without format instructions
150
+ base_messages = [
151
+ ("system", system_message),
152
+ ("user", "{input}")
153
+ ]
154
+ if is_json_output:
155
+ prompt = ChatPromptTemplate.from_messages(base_messages).partial(
156
+ format_instructions=output_parser.get_format_instructions()
157
+ )
158
+ else:
159
+ prompt = ChatPromptTemplate.from_messages(base_messages)
160
+ model = self.app_tool.llm_chain_settings.model
161
+ self.llm.config.model = model
162
+ llm = self.llm.get_llm()
163
+ llm.tags = ["llm_chain"]
164
+ chain = prompt | llm | output_parser
165
+ result = await chain.ainvoke({"input": input})
166
+ return result
167
+
168
+ async def proxy_app_chat(self, query: str) -> str | None:
169
+ secrets = self.app_tool.secrets_to_dict()
170
+ app_id = secrets.get("appId")
171
+ if not app_id:
172
+ raise ValueError("Tool configuration is invalid. 'appId' is required.")
173
+ app: CmsApp = await get_app_by_id(app_id)
174
+ if not app:
175
+ raise ValueError(f"App with id {app_id} not found.")
176
+ url = f"{config.robot_cms_host}/api/llm/message?locale=en&raw=true"
177
+ auth = config.robot_cms_auth
178
+ headers = {"Authorization": auth} if auth else {}
179
+ async with aiohttp.ClientSession() as session:
180
+ data = {
181
+ "appKey": app.credentials.app_key,
182
+ "apiKey": app.credentials.api_key,
183
+ "messages": [
184
+ {
185
+ "role": "user",
186
+ "content": query
187
+ }
188
+ ]
189
+ }
190
+ async with session.post(url, json=data, headers=headers) as response:
191
+ if response.status == 200:
192
+ return await response.text()
193
+ else:
194
+ raise ValueError(f"Error fetching chat response: {response.status}")
195
+ return None
196
+
197
+ async def proxy_app_tool(self) -> None:
198
+ return None
199
+
200
+ async def _fetch_urls(self, urls: list[str]) -> list[dict]:
201
+ import aiohttp, asyncio
202
+ from ws_bom_robot_app.llm.tools.utils import fetch_page, extract_content_with_trafilatura
203
+ if not urls:
204
+ return []
205
+ async with aiohttp.ClientSession() as session:
206
+ tasks = [fetch_page(session, url) for url in urls]
207
+ responses = await asyncio.gather(*tasks, return_exceptions=True)
208
+ final_results = []
209
+ for item in responses:
210
+ if isinstance(item, Exception):
211
+ continue
212
+ url = item["url"]
213
+ html = item["html"]
214
+ if html:
215
+ content = await extract_content_with_trafilatura(html)
216
+ if content:
217
+ final_results.append({"url": url, "content": content})
218
+ else:
219
+ final_results.append({"url": url, "content": "No content found"})
220
+ else:
221
+ final_results.append({"url": url, "content": "Page not found"})
222
+ return final_results
223
+
224
+ async def search_online(self, query: str) -> list[dict]:
225
+ from langchain_community.utilities import DuckDuckGoSearchAPIWrapper
226
+ # Wrapper DuckDuckGo
227
+ search = DuckDuckGoSearchAPIWrapper(max_results=10)
228
+ try:
229
+ raw_results = search.results(query, max_results=10)
230
+ except Exception as e:
231
+ return f"[!] Errore ricerca: {e}"
232
+ urls = [r["link"] for r in raw_results]
233
+ return await self._fetch_urls(urls)
234
+
235
+ async def search_online_google(self, query: str) -> list[dict]:
236
+ from langchain_google_community import GoogleSearchAPIWrapper
237
+ secrets = self.app_tool.secrets_to_dict()
238
+ search_type = secrets.get("searchType")
239
+ if search_type:
240
+ search_kwargs = {"searchType" : search_type}
241
+ search = GoogleSearchAPIWrapper(
242
+ google_api_key=secrets.get("GOOGLE_API_KEY"),
243
+ google_cse_id=secrets.get("GOOGLE_CSE_ID"),
244
+ )
245
+ if search_type:
246
+ raw_results = search.results(query=query,
247
+ num_results=secrets.get("num_results", 5),
248
+ search_params=search_kwargs)
249
+ return raw_results
250
+ raw_results = search.results(
251
+ query=query,
252
+ num_results=secrets.get("num_results", 5)
253
+ )
254
+ urls = [r["link"] for r in raw_results]
255
+ return await self._fetch_urls(urls)
256
+
257
+ async def send_email(self, email_subject: str, body: str, to_email:str):
258
+ import smtplib
259
+ from email.mime.multipart import MIMEMultipart
260
+ from email.mime.text import MIMEText
261
+ secrets = self.app_tool.secrets
262
+ secrets = {item["secretId"]: item["secretValue"] for item in secrets}
263
+ import urllib.parse as urlparse
264
+ url_preview = secrets.get("url_preview", "")
265
+ if url_preview and url_preview != "":
266
+ message_tread = "Puoi visualizzare la chat su questo indirizzo: " + urlparse.urljoin(url_preview, f"?llmThreadId={self.app_tool.thread_id}")
267
+ body = body.replace("##url_preview##", message_tread)
268
+ # Email configuration
269
+ smtp_server = secrets.get("smtp_server")
270
+ smtp_port = secrets.get("smtp_port")
271
+ smtp_user = secrets.get("smtp_user")
272
+ smtp_password = secrets.get("smtp_password")
273
+ from_email = secrets.get("from_email")
274
+ if not to_email or to_email == "":
275
+ return "No recipient email provided"
276
+ if not email_subject or email_subject == "":
277
+ return "No email object provided"
278
+ # Create the email content
279
+ msg = MIMEMultipart()
280
+ msg['From'] = from_email
281
+ msg['To'] = to_email
282
+ msg['Subject'] = email_subject
283
+
284
+ # Create the email body
285
+ msg.attach(MIMEText(body, 'plain'))
286
+
287
+ # Send the email
288
+ try:
289
+ with smtplib.SMTP(smtp_server, smtp_port) as server:
290
+ # Use authentication and SSL only if password is provided
291
+ if smtp_password:
292
+ server.starttls()
293
+ server.login(smtp_user, smtp_password)
294
+ server.send_message(msg)
295
+ except Exception as e:
296
+ return f"Failed to send email: {str(e)}"
297
+ return "Email sent successfully"
298
+
299
+ #endregion
300
+
301
+ #class variables (static)
302
+ _list: dict[str,ToolConfig] = {
303
+ f"{document_retriever.__name__}": ToolConfig(function=document_retriever, model=DocumentRetrieverInput),
304
+ f"{image_generator.__name__}": ToolConfig(function=image_generator, model=ImageGeneratorInput),
305
+ f"{llm_chain.__name__}": ToolConfig(function=llm_chain, model=LlmChainInput),
306
+ f"{search_online.__name__}": ToolConfig(function=search_online, model=SearchOnlineInput),
307
+ f"{search_online_google.__name__}": ToolConfig(function=search_online_google, model=SearchOnlineInput),
308
+ f"{send_email.__name__}": ToolConfig(function=send_email, model=EmailSenderInput),
309
+ f"{proxy_app_chat.__name__}": ToolConfig(function=proxy_app_chat, model=DocumentRetrieverInput),
310
+ f"{proxy_app_tool.__name__}": ToolConfig(function=proxy_app_tool, model=NoopInput),
311
+
312
+ }
313
+
314
+ #instance methods
315
+ def get_coroutine(self):
316
+ tool_cfg = self._list.get(self.app_tool.function_name)
317
+ return getattr(self, tool_cfg.function.__name__) # type: ignore