forked from iLenakh/arabic-storm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rm.py
883 lines (757 loc) · 33.2 KB
/
rm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
import logging
import os
from typing import Callable, Union, List
import backoff
import dspy
import requests
from dsp import backoff_hdlr, giveup_hdlr
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_qdrant import Qdrant
from qdrant_client import QdrantClient
from .utils import WebPageHelper
class YouRM(dspy.Retrieve):
def __init__(self, ydc_api_key=None, k=3, is_valid_source: Callable = None):
super().__init__(k=k)
if not ydc_api_key and not os.environ.get("YDC_API_KEY"):
raise RuntimeError(
"You must supply ydc_api_key or set environment variable YDC_API_KEY"
)
elif ydc_api_key:
self.ydc_api_key = ydc_api_key
else:
self.ydc_api_key = os.environ["YDC_API_KEY"]
self.usage = 0
# If not None, is_valid_source shall be a function that takes a URL and returns a boolean.
if is_valid_source:
self.is_valid_source = is_valid_source
else:
self.is_valid_source = lambda x: True
def get_usage_and_reset(self):
usage = self.usage
self.usage = 0
return {"YouRM": usage}
def forward(
self, query_or_queries: Union[str, List[str]], exclude_urls: List[str] = []
):
"""Search with You.com for self.k top passages for query or queries
Args:
query_or_queries (Union[str, List[str]]): The query or queries to search for.
exclude_urls (List[str]): A list of urls to exclude from the search results.
Returns:
a list of Dicts, each dict has keys of 'description', 'snippets' (list of strings), 'title', 'url'
"""
queries = (
[query_or_queries]
if isinstance(query_or_queries, str)
else query_or_queries
)
self.usage += len(queries)
collected_results = []
for query in queries:
try:
headers = {"X-API-Key": self.ydc_api_key}
results = requests.get(
f"https://api.ydc-index.io/search?query={query}",
headers=headers,
).json()
authoritative_results = []
for r in results["hits"]:
if self.is_valid_source(r["url"]) and r["url"] not in exclude_urls:
authoritative_results.append(r)
if "hits" in results:
collected_results.extend(authoritative_results[: self.k])
except Exception as e:
logging.error(f"Error occurs when searching query {query}: {e}")
return collected_results
class BingSearch(dspy.Retrieve):
def __init__(
self,
bing_search_api_key=None,
k=3,
is_valid_source: Callable = None,
min_char_count: int = 150,
snippet_chunk_size: int = 1000,
webpage_helper_max_threads=10,
mkt="en-US",
language="en",
**kwargs,
):
"""
Params:
min_char_count: Minimum character count for the article to be considered valid.
snippet_chunk_size: Maximum character count for each snippet.
webpage_helper_max_threads: Maximum number of threads to use for webpage helper.
mkt, language, **kwargs: Bing search API parameters.
- Reference: https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/reference/query-parameters
"""
super().__init__(k=k)
if not bing_search_api_key and not os.environ.get("BING_SEARCH_API_KEY"):
raise RuntimeError(
"You must supply bing_search_subscription_key or set environment variable BING_SEARCH_API_KEY"
)
elif bing_search_api_key:
self.bing_api_key = bing_search_api_key
else:
self.bing_api_key = os.environ["BING_SEARCH_API_KEY"]
self.endpoint = "https://api.bing.microsoft.com/v7.0/search"
self.params = {"mkt": mkt, "setLang": language, "count": k, **kwargs}
self.webpage_helper = WebPageHelper(
min_char_count=min_char_count,
snippet_chunk_size=snippet_chunk_size,
max_thread_num=webpage_helper_max_threads,
)
self.usage = 0
# If not None, is_valid_source shall be a function that takes a URL and returns a boolean.
if is_valid_source:
self.is_valid_source = is_valid_source
else:
self.is_valid_source = lambda x: True
def get_usage_and_reset(self):
usage = self.usage
self.usage = 0
return {"BingSearch": usage}
def forward(
self, query_or_queries: Union[str, List[str]], exclude_urls: List[str] = []
):
"""Search with Bing for self.k top passages for query or queries
Args:
query_or_queries (Union[str, List[str]]): The query or queries to search for.
exclude_urls (List[str]): A list of urls to exclude from the search results.
Returns:
a list of Dicts, each dict has keys of 'description', 'snippets' (list of strings), 'title', 'url'
"""
queries = (
[query_or_queries]
if isinstance(query_or_queries, str)
else query_or_queries
)
self.usage += len(queries)
url_to_results = {}
headers = {"Ocp-Apim-Subscription-Key": self.bing_api_key}
for query in queries:
try:
results = requests.get(
self.endpoint, headers=headers, params={**self.params, "q": query}
).json()
for d in results["webPages"]["value"]:
if self.is_valid_source(d["url"]) and d["url"] not in exclude_urls:
url_to_results[d["url"]] = {
"url": d["url"],
"title": d["name"],
"description": d["snippet"],
}
except Exception as e:
logging.error(f"Error occurs when searching query {query}: {e}")
valid_url_to_snippets = self.webpage_helper.urls_to_snippets(
list(url_to_results.keys())
)
collected_results = []
for url in valid_url_to_snippets:
r = url_to_results[url]
r["snippets"] = valid_url_to_snippets[url]["snippets"]
collected_results.append(r)
return collected_results
class VectorRM(dspy.Retrieve):
"""Retrieve information from custom documents using Qdrant.
To be compatible with STORM, the custom documents should have the following fields:
- content: The main text content of the document.
- title: The title of the document.
- url: The URL of the document. STORM use url as the unique identifier of the document, so ensure different
documents have different urls.
- description (optional): The description of the document.
The documents should be stored in a CSV file.
"""
def __init__(
self,
collection_name: str,
embedding_model: str,
device: str = "mps",
k: int = 3,
):
"""
Params:
collection_name: Name of the Qdrant collection.
embedding_model: Name of the Hugging Face embedding model.
device: Device to run the embeddings model on, can be "mps", "cuda", "cpu".
k: Number of top chunks to retrieve.
"""
super().__init__(k=k)
self.usage = 0
# check if the collection is provided
if not collection_name:
raise ValueError("Please provide a collection name.")
# check if the embedding model is provided
if not embedding_model:
raise ValueError("Please provide an embedding model.")
model_kwargs = {"device": device}
encode_kwargs = {"normalize_embeddings": True}
self.model = HuggingFaceEmbeddings(
model_name=embedding_model,
model_kwargs=model_kwargs,
encode_kwargs=encode_kwargs,
)
self.collection_name = collection_name
self.client = None
self.qdrant = None
def _check_collection(self):
"""
Check if the Qdrant collection exists and create it if it does not.
"""
if self.client is None:
raise ValueError("Qdrant client is not initialized.")
if self.client.collection_exists(collection_name=f"{self.collection_name}"):
print(
f"Collection {self.collection_name} exists. Loading the collection..."
)
self.qdrant = Qdrant(
client=self.client,
collection_name=self.collection_name,
embeddings=self.model,
)
else:
raise ValueError(
f"Collection {self.collection_name} does not exist. Please create the collection first."
)
def init_online_vector_db(self, url: str, api_key: str):
"""
Initialize the Qdrant client that is connected to an online vector store with the given URL and API key.
Args:
url (str): URL of the Qdrant server.
api_key (str): API key for the Qdrant server.
"""
if api_key is None:
if not os.getenv("QDRANT_API_KEY"):
raise ValueError("Please provide an api key.")
api_key = os.getenv("QDRANT_API_KEY")
if url is None:
raise ValueError("Please provide a url for the Qdrant server.")
try:
self.client = QdrantClient(url=url, api_key=api_key)
self._check_collection()
except Exception as e:
raise ValueError(f"Error occurs when connecting to the server: {e}")
def init_offline_vector_db(self, vector_store_path: str):
"""
Initialize the Qdrant client that is connected to an offline vector store with the given vector store folder path.
Args:
vector_store_path (str): Path to the vector store.
"""
if vector_store_path is None:
raise ValueError("Please provide a folder path.")
try:
self.client = QdrantClient(path=vector_store_path)
self._check_collection()
except Exception as e:
raise ValueError(f"Error occurs when loading the vector store: {e}")
def get_usage_and_reset(self):
usage = self.usage
self.usage = 0
return {"VectorRM": usage}
def get_vector_count(self):
"""
Get the count of vectors in the collection.
Returns:
int: Number of vectors in the collection.
"""
return self.qdrant.client.count(collection_name=self.collection_name)
def forward(self, query_or_queries: Union[str, List[str]], exclude_urls: List[str]):
"""
Search in your data for self.k top passages for query or queries.
Args:
query_or_queries (Union[str, List[str]]): The query or queries to search for.
exclude_urls (List[str]): Dummy parameter to match the interface. Does not have any effect.
Returns:
a list of Dicts, each dict has keys of 'description', 'snippets' (list of strings), 'title', 'url'
"""
queries = (
[query_or_queries]
if isinstance(query_or_queries, str)
else query_or_queries
)
self.usage += len(queries)
collected_results = []
for query in queries:
related_docs = self.qdrant.similarity_search_with_score(query, k=self.k)
for i in range(len(related_docs)):
doc = related_docs[i][0]
collected_results.append(
{
"description": doc.metadata["description"],
"snippets": [doc.page_content],
"title": doc.metadata["title"],
"url": doc.metadata["url"],
}
)
return collected_results
class SerperRM(dspy.Retrieve):
"""Retrieve information from custom queries using Serper.dev."""
def __init__(self, serper_search_api_key=None, query_params=None):
"""Args:
serper_search_api_key str: API key to run serper, can be found by creating an account on https://serper.dev/
query_params (dict or list of dict): parameters in dictionary or list of dictionaries that has a max size of 100 that will be used to query.
Commonly used fields are as follows (see more information in https://serper.dev/playground):
q str: query that will be used with google search
type str: type that will be used for browsing google. Types are search, images, video, maps, places, etc.
gl str: Country that will be focused on for the search
location str: Country where the search will originate from. All locates can be found here: https://api.serper.dev/locations.
autocorrect bool: Enable autocorrect on the queries while searching, if query is misspelled, will be updated.
results int: Max number of results per page.
page int: Max number of pages per call.
tbs str: date time range, automatically set to any time by default.
qdr:h str: Date time range for the past hour.
qdr:d str: Date time range for the past 24 hours.
qdr:w str: Date time range for past week.
qdr:m str: Date time range for past month.
qdr:y str: Date time range for past year.
"""
super().__init__()
self.usage = 0
self.query_params = query_params
self.serper_search_api_key = serper_search_api_key
if not self.serper_search_api_key and not os.environ.get("SERPER_API_KEY"):
raise RuntimeError(
"You must supply a serper_search_api_key param or set environment variable SERPER_API_KEY"
)
elif self.serper_search_api_key:
self.serper_search_api_key = serper_search_api_key
else:
self.serper_search_api_key = os.environ["SERPER_API_KEY"]
self.base_url = "https://google.serper.dev"
def serper_runner(self, query_params):
self.search_url = f"{self.base_url}/search"
headers = {
"X-API-KEY": self.serper_search_api_key,
"Content-Type": "application/json",
}
response = requests.request(
"POST", self.search_url, headers=headers, json=query_params
)
if response == None:
raise RuntimeError(
f"Error had occured while running the search process.\n Error is {response.reason}, had failed with status code {response.status_code}"
)
return response.json()
def get_usage_and_reset(self):
usage = self.usage
self.usage = 0
return {"SerperRM": usage}
def forward(self, query_or_queries: Union[str, List[str]], exclude_urls: List[str]):
"""
Calls the API and searches for the query passed in.
Args:
query_or_queries (Union[str, List[str]]): The query or queries to search for.
exclude_urls (List[str]): Dummy parameter to match the interface. Does not have any effect.
Returns:
a list of dictionaries, each dictionary has keys of 'description', 'snippets' (list of strings), 'title', 'url'
"""
queries = (
[query_or_queries]
if isinstance(query_or_queries, str)
else query_or_queries
)
self.usage += len(queries)
self.results = []
collected_results = []
for query in queries:
if query == "Queries:":
continue
query_params = self.query_params
# All available parameters can be found in the playground: https://serper.dev/playground
# Sets the json value for query to be the query that is being parsed.
query_params["q"] = query
# Sets the type to be search, can be images, video, places, maps etc that Google provides.
query_params["type"] = "search"
self.result = self.serper_runner(query_params)
self.results.append(self.result)
# Array of dictionaries that will be used by Storm to create the jsons
collected_results = []
for result in self.results:
try:
# An array of dictionaries that contains the snippets, title of the document and url that will be used.
organic_results = result.get("organic")
knowledge_graph = result.get("knowledgeGraph")
for organic in organic_results:
snippets = []
snippets.append(organic.get("snippet"))
if knowledge_graph != None:
collected_results.append(
{
"snippets": snippets,
"title": organic.get("title"),
"url": organic.get("link"),
"description": knowledge_graph.get("description"),
}
)
else:
# Common for knowledge graph to be None, set description to empty string
collected_results.append(
{
"snippets": snippets,
"title": organic.get("title"),
"url": organic.get("link"),
"description": "",
}
)
except:
continue
return collected_results
class BraveRM(dspy.Retrieve):
def __init__(
self, brave_search_api_key=None, k=3, is_valid_source: Callable = None
):
super().__init__(k=k)
if not brave_search_api_key and not os.environ.get("BRAVE_API_KEY"):
raise RuntimeError(
"You must supply brave_search_api_key or set environment variable BRAVE_API_KEY"
)
elif brave_search_api_key:
self.brave_search_api_key = brave_search_api_key
else:
self.brave_search_api_key = os.environ["BRAVE_API_KEY"]
self.usage = 0
# If not None, is_valid_source shall be a function that takes a URL and returns a boolean.
if is_valid_source:
self.is_valid_source = is_valid_source
else:
self.is_valid_source = lambda x: True
def get_usage_and_reset(self):
usage = self.usage
self.usage = 0
return {"BraveRM": usage}
def forward(
self, query_or_queries: Union[str, List[str]], exclude_urls: List[str] = []
):
"""Search with api.search.brave.com for self.k top passages for query or queries
Args:
query_or_queries (Union[str, List[str]]): The query or queries to search for.
exclude_urls (List[str]): A list of urls to exclude from the search results.
Returns:
a list of Dicts, each dict has keys of 'description', 'snippets' (list of strings), 'title', 'url'
"""
queries = (
[query_or_queries]
if isinstance(query_or_queries, str)
else query_or_queries
)
self.usage += len(queries)
collected_results = []
for query in queries:
try:
headers = {
"Accept": "application/json",
"Accept-Encoding": "gzip",
"X-Subscription-Token": self.brave_search_api_key,
}
response = requests.get(
f"https://api.search.brave.com/res/v1/web/search?result_filter=web&q={query}",
headers=headers,
).json()
results = response.get("web", {}).get("results", [])
for result in results:
collected_results.append(
{
"snippets": result.get("extra_snippets", []),
"title": result.get("title"),
"url": result.get("url"),
"description": result.get("description"),
}
)
except Exception as e:
logging.error(f"Error occurs when searching query {query}: {e}")
return collected_results
class SearXNG(dspy.Retrieve):
def __init__(
self,
searxng_api_url,
searxng_api_key=None,
k=3,
is_valid_source: Callable = None,
):
"""Initialize the SearXNG search retriever.
Please set up SearXNG according to https://docs.searxng.org/index.html.
Args:
searxng_api_url (str): The URL of the SearXNG API. Consult SearXNG documentation for details.
searxng_api_key (str, optional): The API key for the SearXNG API. Defaults to None. Consult SearXNG documentation for details.
k (int, optional): The number of top passages to retrieve. Defaults to 3.
is_valid_source (Callable, optional): A function that takes a URL and returns a boolean indicating if the
source is valid. Defaults to None.
"""
super().__init__(k=k)
if not searxng_api_url:
raise RuntimeError("You must supply searxng_api_url")
self.searxng_api_url = searxng_api_url
self.searxng_api_key = searxng_api_key
self.usage = 0
if is_valid_source:
self.is_valid_source = is_valid_source
else:
self.is_valid_source = lambda x: True
def get_usage_and_reset(self):
usage = self.usage
self.usage = 0
return {"SearXNG": usage}
def forward(
self, query_or_queries: Union[str, List[str]], exclude_urls: List[str] = []
):
"""Search with SearxNG for self.k top passages for query or queries
Args:
query_or_queries (Union[str, List[str]]): The query or queries to search for.
exclude_urls (List[str]): A list of urls to exclude from the search results.
Returns:
a list of Dicts, each dict has keys of 'description', 'snippets' (list of strings), 'title', 'url'
"""
queries = (
[query_or_queries]
if isinstance(query_or_queries, str)
else query_or_queries
)
self.usage += len(queries)
collected_results = []
headers = (
{"Authorization": f"Bearer {self.searxng_api_key}"}
if self.searxng_api_key
else {}
)
for query in queries:
try:
params = {"q": query, "format": "json"}
response = requests.get(
self.searxng_api_url, headers=headers, params=params
)
results = response.json()
for r in results["results"]:
if self.is_valid_source(r["url"]) and r["url"] not in exclude_urls:
collected_results.append(
{
"description": r.get("content", ""),
"snippets": [r.get("content", "")],
"title": r.get("title", ""),
"url": r["url"],
}
)
except Exception as e:
logging.error(f"Error occurs when searching query {query}: {e}")
return collected_results
class DuckDuckGoSearchRM(dspy.Retrieve):
"""Retrieve information from custom queries using DuckDuckGo."""
def __init__(
self,
k: int = 3,
is_valid_source: Callable = None,
min_char_count: int = 150,
snippet_chunk_size: int = 1000,
webpage_helper_max_threads=10,
safe_search: str = "On",
region: str = "us-en",
):
"""
Params:
min_char_count: Minimum character count for the article to be considered valid.
snippet_chunk_size: Maximum character count for each snippet.
webpage_helper_max_threads: Maximum number of threads to use for webpage helper.
**kwargs: Additional parameters for the OpenAI API.
"""
super().__init__(k=k)
try:
from duckduckgo_search import DDGS
except ImportError as err:
raise ImportError(
"Duckduckgo requires `pip install duckduckgo_search`."
) from err
self.k = k
self.webpage_helper = WebPageHelper(
min_char_count=min_char_count,
snippet_chunk_size=snippet_chunk_size,
max_thread_num=webpage_helper_max_threads,
)
self.usage = 0
# All params for search can be found here:
# https://duckduckgo.com/duckduckgo-help-pages/settings/params/
# Sets the backend to be api
self.duck_duck_go_backend = "api"
# Only gets safe search results
self.duck_duck_go_safe_search = safe_search
# Specifies the region that the search will use
self.duck_duck_go_region = region
# If not None, is_valid_source shall be a function that takes a URL and returns a boolean.
if is_valid_source:
self.is_valid_source = is_valid_source
else:
self.is_valid_source = lambda x: True
# Import the duckduckgo search library found here: https://github.com/deedy5/duckduckgo_search
self.ddgs = DDGS()
def get_usage_and_reset(self):
usage = self.usage
self.usage = 0
return {"DuckDuckGoRM": usage}
@backoff.on_exception(
backoff.expo,
(Exception,),
max_time=1000,
max_tries=8,
on_backoff=backoff_hdlr,
giveup=giveup_hdlr,
)
def request(self, query: str):
results = self.ddgs.text(
query, max_results=self.k, backend=self.duck_duck_go_backend
)
return results
def forward(
self, query_or_queries: Union[str, List[str]], exclude_urls: List[str] = []
):
"""Search with DuckDuckGoSearch for self.k top passages for query or queries
Args:
query_or_queries (Union[str, List[str]]): The query or queries to search for.
exclude_urls (List[str]): A list of urls to exclude from the search results.
Returns:
a list of Dicts, each dict has keys of 'description', 'snippets' (list of strings), 'title', 'url'
"""
queries = (
[query_or_queries]
if isinstance(query_or_queries, str)
else query_or_queries
)
self.usage += len(queries)
collected_results = []
for query in queries:
# list of dicts that will be parsed to return
results = self.request(query)
for d in results:
# assert d is dict
if not isinstance(d, dict):
print(f"Invalid result: {d}\n")
continue
try:
# ensure keys are present
url = d.get("href", None)
title = d.get("title", None)
description = d.get("description", title)
snippets = [d.get("body", None)]
# raise exception of missing key(s)
if not all([url, title, description, snippets]):
raise ValueError(f"Missing key(s) in result: {d}")
if self.is_valid_source(url) and url not in exclude_urls:
result = {
"url": url,
"title": title,
"description": description,
"snippets": snippets,
}
collected_results.append(result)
else:
print(f"invalid source {url} or url in exclude_urls")
except Exception as e:
print(f"Error occurs when processing {result=}: {e}\n")
print(f"Error occurs when searching query {query}: {e}")
return collected_results
class TavilySearchRM(dspy.Retrieve):
"""Retrieve information from custom queries using Tavily. Documentation and examples can be found at https://docs.tavily.com/docs/python-sdk/tavily-search/examples"""
def __init__(
self,
tavily_search_api_key=None,
k: int = 3,
is_valid_source: Callable = None,
min_char_count: int = 150,
snippet_chunk_size: int = 1000,
webpage_helper_max_threads=10,
include_raw_content=False,
):
"""
Params:
tavily_search_api_key str: API key for tavily that can be retrieved from https://tavily.com/
min_char_count: Minimum character count for the article to be considered valid.
snippet_chunk_size: Maximum character count for each snippet.
webpage_helper_max_threads: Maximum number of threads to use for webpage helper.
include_raw_content bool: Boolean that is used to determine if the full text should be returned.
"""
super().__init__(k=k)
try:
from tavily import TavilyClient
except ImportError as err:
raise ImportError("Tavily requires `pip install tavily-python`.") from err
if not tavily_search_api_key and not os.environ.get("TAVILY_API_KEY"):
raise RuntimeError(
"You must supply tavily_search_api_key or set environment variable TAVILY_API_KEY"
)
elif tavily_search_api_key:
self.tavily_search_api_key = tavily_search_api_key
else:
self.tavily_search_api_key = os.environ["TAVILY_API_KEY"]
self.k = k
self.webpage_helper = WebPageHelper(
min_char_count=min_char_count,
snippet_chunk_size=snippet_chunk_size,
max_thread_num=webpage_helper_max_threads,
)
self.usage = 0
# Creates client instance that will use search. Full search params are here:
# https://docs.tavily.com/docs/python-sdk/tavily-search/examples
self.tavily_client = TavilyClient(api_key=self.tavily_search_api_key)
self.include_raw_content = include_raw_content
# If not None, is_valid_source shall be a function that takes a URL and returns a boolean.
if is_valid_source:
self.is_valid_source = is_valid_source
else:
self.is_valid_source = lambda x: True
def get_usage_and_reset(self):
usage = self.usage
self.usage = 0
return {"TavilySearchRM": usage}
def forward(
self, query_or_queries: Union[str, List[str]], exclude_urls: List[str] = []
):
"""Search with TavilySearch for self.k top passages for query or queries
Args:
query_or_queries (Union[str, List[str]]): The query or queries to search for.
exclude_urls (List[str]): A list of urls to exclude from the search results.
Returns:
a list of Dicts, each dict has keys of 'description', 'snippets' (list of strings), 'title', 'url'
"""
queries = (
[query_or_queries]
if isinstance(query_or_queries, str)
else query_or_queries
)
self.usage += len(queries)
collected_results = []
for query in queries:
args = {
"max_results": self.k,
"include_raw_contents": self.include_raw_content,
}
# list of dicts that will be parsed to return
responseData = self.tavily_client.search(query)
results = responseData.get("results")
for d in results:
# assert d is dict
if not isinstance(d, dict):
print(f"Invalid result: {d}\n")
continue
try:
# ensure keys are present
url = d.get("url", None)
title = d.get("title", None)
description = d.get("content", None)
snippets = []
if d.get("raw_body_content"):
snippets.append(d.get("raw_body_content"))
else:
snippets.append(d.get("content"))
# raise exception of missing key(s)
if not all([url, title, description, snippets]):
raise ValueError(f"Missing key(s) in result: {d}")
if self.is_valid_source(url) and url not in exclude_urls:
result = {
"url": url,
"title": title,
"description": description,
"snippets": snippets,
}
collected_results.append(result)
else:
print(f"invalid source {url} or url in exclude_urls")
except Exception as e:
print(f"Error occurs when processing {result=}: {e}\n")
print(f"Error occurs when searching query {query}: {e}")
return collected_results