serperdev-haystack 1.0.0__tar.gz
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.
- serperdev_haystack-1.0.0/.gitignore +146 -0
- serperdev_haystack-1.0.0/LICENSE.txt +201 -0
- serperdev_haystack-1.0.0/PKG-INFO +40 -0
- serperdev_haystack-1.0.0/README.md +14 -0
- serperdev_haystack-1.0.0/pydoc/config_docusaurus.yml +13 -0
- serperdev_haystack-1.0.0/pyproject.toml +165 -0
- serperdev_haystack-1.0.0/src/haystack_integrations/components/websearch/py.typed +0 -0
- serperdev_haystack-1.0.0/src/haystack_integrations/components/websearch/serperdev/__init__.py +10 -0
- serperdev_haystack-1.0.0/src/haystack_integrations/components/websearch/serperdev/websearch.py +280 -0
- serperdev_haystack-1.0.0/tests/__init__.py +3 -0
- serperdev_haystack-1.0.0/tests/test_websearch.py +441 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
pip-wheel-metadata/
|
|
24
|
+
share/python-wheels/
|
|
25
|
+
*.egg-info/
|
|
26
|
+
.installed.cfg
|
|
27
|
+
*.egg
|
|
28
|
+
MANIFEST
|
|
29
|
+
|
|
30
|
+
# PyInstaller
|
|
31
|
+
# Usually these files are written by a python script from a template
|
|
32
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
33
|
+
*.manifest
|
|
34
|
+
*.spec
|
|
35
|
+
|
|
36
|
+
# Installer logs
|
|
37
|
+
pip-log.txt
|
|
38
|
+
pip-delete-this-directory.txt
|
|
39
|
+
|
|
40
|
+
# Unit test / coverage reports
|
|
41
|
+
htmlcov/
|
|
42
|
+
.tox/
|
|
43
|
+
.nox/
|
|
44
|
+
.coverage
|
|
45
|
+
.coverage.*
|
|
46
|
+
.cache
|
|
47
|
+
nosetests.xml
|
|
48
|
+
coverage.xml
|
|
49
|
+
*.cover
|
|
50
|
+
*.py,cover
|
|
51
|
+
.hypothesis/
|
|
52
|
+
.pytest_cache/
|
|
53
|
+
volumes/
|
|
54
|
+
|
|
55
|
+
# Translations
|
|
56
|
+
*.mo
|
|
57
|
+
*.pot
|
|
58
|
+
|
|
59
|
+
# Django stuff:
|
|
60
|
+
*.log
|
|
61
|
+
local_settings.py
|
|
62
|
+
db.sqlite3
|
|
63
|
+
db.sqlite3-journal
|
|
64
|
+
|
|
65
|
+
# Flask stuff:
|
|
66
|
+
instance/
|
|
67
|
+
.webassets-cache
|
|
68
|
+
|
|
69
|
+
# Scrapy stuff:
|
|
70
|
+
.scrapy
|
|
71
|
+
|
|
72
|
+
# Sphinx documentation
|
|
73
|
+
docs/_build/
|
|
74
|
+
|
|
75
|
+
# PyBuilder
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
.python-version
|
|
87
|
+
|
|
88
|
+
# pipenv
|
|
89
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
90
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
91
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
92
|
+
# install all needed dependencies.
|
|
93
|
+
#Pipfile.lock
|
|
94
|
+
|
|
95
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
|
96
|
+
__pypackages__/
|
|
97
|
+
|
|
98
|
+
# Celery stuff
|
|
99
|
+
celerybeat-schedule
|
|
100
|
+
celerybeat.pid
|
|
101
|
+
|
|
102
|
+
# SageMath parsed files
|
|
103
|
+
*.sage.py
|
|
104
|
+
|
|
105
|
+
# Environments
|
|
106
|
+
.env
|
|
107
|
+
.venv
|
|
108
|
+
env/
|
|
109
|
+
venv/
|
|
110
|
+
ENV/
|
|
111
|
+
env.bak/
|
|
112
|
+
venv.bak/
|
|
113
|
+
|
|
114
|
+
# Spyder project settings
|
|
115
|
+
.spyderproject
|
|
116
|
+
.spyproject
|
|
117
|
+
|
|
118
|
+
# Rope project settings
|
|
119
|
+
.ropeproject
|
|
120
|
+
|
|
121
|
+
# mkdocs documentation
|
|
122
|
+
/site
|
|
123
|
+
|
|
124
|
+
# mypy
|
|
125
|
+
.mypy_cache/
|
|
126
|
+
.dmypy.json
|
|
127
|
+
dmypy.json
|
|
128
|
+
|
|
129
|
+
# Pyre type checker
|
|
130
|
+
.pyre/
|
|
131
|
+
|
|
132
|
+
# IDEs
|
|
133
|
+
.vscode
|
|
134
|
+
|
|
135
|
+
# Docs generation artifacts
|
|
136
|
+
_readme_*.md
|
|
137
|
+
.idea
|
|
138
|
+
|
|
139
|
+
# macOS
|
|
140
|
+
.DS_Store
|
|
141
|
+
|
|
142
|
+
# http cache (requests-cache)
|
|
143
|
+
**/http_cache.sqlite
|
|
144
|
+
|
|
145
|
+
# ruff
|
|
146
|
+
.ruff_cache
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2023-present deepset GmbH
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: serperdev-haystack
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Haystack integration for SerperDev Web Search
|
|
5
|
+
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/serperdev#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
7
|
+
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/serperdev
|
|
8
|
+
Author-email: deepset GmbH <info@deepset.ai>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE.txt
|
|
11
|
+
Keywords: AI Search,Haystack,Serper,SerperDev,Web Search
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Programming Language :: Python
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
21
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Requires-Dist: haystack-ai>=2.24.1
|
|
24
|
+
Requires-Dist: httpx>=0.27.0
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# serperdev-haystack
|
|
28
|
+
|
|
29
|
+
[](https://pypi.org/project/serperdev-haystack)
|
|
30
|
+
[](https://pypi.org/project/serperdev-haystack)
|
|
31
|
+
|
|
32
|
+
- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/serperdev/CHANGELOG.md)
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## Contributing
|
|
37
|
+
|
|
38
|
+
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
|
|
39
|
+
|
|
40
|
+
To run integration tests locally, you need to export the `SERPERDEV_API_KEY` environment variable.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# serperdev-haystack
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/serperdev-haystack)
|
|
4
|
+
[](https://pypi.org/project/serperdev-haystack)
|
|
5
|
+
|
|
6
|
+
- [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/serperdev/CHANGELOG.md)
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## Contributing
|
|
11
|
+
|
|
12
|
+
Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
|
|
13
|
+
|
|
14
|
+
To run integration tests locally, you need to export the `SERPERDEV_API_KEY` environment variable.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
loaders:
|
|
2
|
+
- modules:
|
|
3
|
+
- haystack_integrations.components.websearch.serperdev.websearch
|
|
4
|
+
search_path: [../src]
|
|
5
|
+
processors:
|
|
6
|
+
- type: filter
|
|
7
|
+
documented_only: true
|
|
8
|
+
skip_empty_modules: true
|
|
9
|
+
renderer:
|
|
10
|
+
description: SerperDev integration for Haystack
|
|
11
|
+
id: integrations-serperdev
|
|
12
|
+
filename: serperdev.md
|
|
13
|
+
title: SerperDev
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling", "hatch-vcs"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "serperdev-haystack"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Haystack integration for SerperDev Web Search"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
keywords = ["Haystack", "SerperDev", "Serper", "Web Search", "AI Search"]
|
|
13
|
+
authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"License :: OSI Approved :: Apache Software License",
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Programming Language :: Python",
|
|
18
|
+
"Programming Language :: Python :: 3.10",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"Programming Language :: Python :: 3.12",
|
|
21
|
+
"Programming Language :: Python :: 3.13",
|
|
22
|
+
"Programming Language :: Python :: 3.14",
|
|
23
|
+
"Programming Language :: Python :: Implementation :: CPython",
|
|
24
|
+
"Programming Language :: Python :: Implementation :: PyPy",
|
|
25
|
+
]
|
|
26
|
+
dependencies = ["haystack-ai>=2.24.1", "httpx>=0.27.0"]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/serperdev#readme"
|
|
30
|
+
Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
|
|
31
|
+
Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/serperdev"
|
|
32
|
+
|
|
33
|
+
[tool.hatch.build.targets.wheel]
|
|
34
|
+
packages = ["src/haystack_integrations"]
|
|
35
|
+
|
|
36
|
+
[tool.hatch.version]
|
|
37
|
+
source = "vcs"
|
|
38
|
+
tag-pattern = 'integrations\/serperdev-v(?P<version>.*)'
|
|
39
|
+
|
|
40
|
+
[tool.hatch.version.raw-options]
|
|
41
|
+
root = "../.."
|
|
42
|
+
git_describe_command = 'git describe --tags --match="integrations/serperdev-v[0-9]*"'
|
|
43
|
+
|
|
44
|
+
[tool.hatch.envs.default]
|
|
45
|
+
installer = "uv"
|
|
46
|
+
dependencies = ["haystack-pydoc-tools", "ruff"]
|
|
47
|
+
|
|
48
|
+
[tool.hatch.envs.default.scripts]
|
|
49
|
+
docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
|
|
50
|
+
fmt = "ruff check --fix {args}; ruff format {args}"
|
|
51
|
+
fmt-check = "ruff check {args} && ruff format --check {args}"
|
|
52
|
+
|
|
53
|
+
[tool.hatch.envs.test]
|
|
54
|
+
dependencies = [
|
|
55
|
+
"pytest",
|
|
56
|
+
"pytest-asyncio",
|
|
57
|
+
"pytest-cov",
|
|
58
|
+
"pytest-rerunfailures",
|
|
59
|
+
"mypy",
|
|
60
|
+
"pip",
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
[tool.hatch.envs.test.scripts]
|
|
64
|
+
unit = 'pytest -m "not integration" {args:tests}'
|
|
65
|
+
integration = 'pytest -m "integration" {args:tests}'
|
|
66
|
+
all = 'pytest {args:tests}'
|
|
67
|
+
unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}'
|
|
68
|
+
integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}'
|
|
69
|
+
types = "mypy -p haystack_integrations.components.websearch.serperdev {args}"
|
|
70
|
+
|
|
71
|
+
[tool.mypy]
|
|
72
|
+
install_types = true
|
|
73
|
+
non_interactive = true
|
|
74
|
+
check_untyped_defs = true
|
|
75
|
+
disallow_incomplete_defs = true
|
|
76
|
+
|
|
77
|
+
[[tool.mypy.overrides]]
|
|
78
|
+
module = ["httpx.*"]
|
|
79
|
+
ignore_missing_imports = true
|
|
80
|
+
|
|
81
|
+
[tool.ruff]
|
|
82
|
+
line-length = 120
|
|
83
|
+
|
|
84
|
+
[tool.ruff.lint]
|
|
85
|
+
select = [
|
|
86
|
+
"A",
|
|
87
|
+
"ANN",
|
|
88
|
+
"ARG",
|
|
89
|
+
"B",
|
|
90
|
+
"C",
|
|
91
|
+
"D102", # Missing docstring in public method
|
|
92
|
+
"D103", # Missing docstring in public function
|
|
93
|
+
"D205", # 1 blank line required between summary line and description
|
|
94
|
+
"D209", # Closing triple quotes go to new line
|
|
95
|
+
"D213", # summary lines must be positioned on the second physical line of the docstring
|
|
96
|
+
"D417", # Missing argument descriptions in the docstring
|
|
97
|
+
"D419", # Docstring is empty
|
|
98
|
+
"DTZ",
|
|
99
|
+
"E",
|
|
100
|
+
"EM",
|
|
101
|
+
"F",
|
|
102
|
+
"I",
|
|
103
|
+
"ICN",
|
|
104
|
+
"ISC",
|
|
105
|
+
"N",
|
|
106
|
+
"PLC",
|
|
107
|
+
"PLE",
|
|
108
|
+
"PLR",
|
|
109
|
+
"PLW",
|
|
110
|
+
"Q",
|
|
111
|
+
"RUF",
|
|
112
|
+
"S",
|
|
113
|
+
"T",
|
|
114
|
+
"TID",
|
|
115
|
+
"UP",
|
|
116
|
+
"W",
|
|
117
|
+
"YTT",
|
|
118
|
+
]
|
|
119
|
+
ignore = [
|
|
120
|
+
# Allow non-abstract empty methods in abstract base classes
|
|
121
|
+
"B027",
|
|
122
|
+
# Allow function calls in argument defaults (common Haystack pattern for Secret.from_env_var)
|
|
123
|
+
"B008",
|
|
124
|
+
# Ignore checks for possible passwords
|
|
125
|
+
"S105",
|
|
126
|
+
"S106",
|
|
127
|
+
"S107",
|
|
128
|
+
# Ignore complexity
|
|
129
|
+
"C901",
|
|
130
|
+
"PLR0911",
|
|
131
|
+
"PLR0912",
|
|
132
|
+
"PLR0913",
|
|
133
|
+
"PLR0915",
|
|
134
|
+
# Allow `Any` type - used legitimately for dynamic types and SDK boundaries
|
|
135
|
+
"ANN401",
|
|
136
|
+
]
|
|
137
|
+
|
|
138
|
+
[tool.ruff.lint.isort]
|
|
139
|
+
known-first-party = ["haystack_integrations"]
|
|
140
|
+
|
|
141
|
+
[tool.ruff.lint.flake8-tidy-imports]
|
|
142
|
+
ban-relative-imports = "parents"
|
|
143
|
+
|
|
144
|
+
[tool.ruff.lint.per-file-ignores]
|
|
145
|
+
# Tests can use magic values, assertions, relative imports, and don't need type annotations
|
|
146
|
+
"tests/**/*" = ["PLR2004", "S101", "TID252", "D", "ANN"]
|
|
147
|
+
|
|
148
|
+
[tool.coverage.run]
|
|
149
|
+
source = ["haystack_integrations"]
|
|
150
|
+
branch = true
|
|
151
|
+
relative_files = true
|
|
152
|
+
parallel = false
|
|
153
|
+
|
|
154
|
+
[tool.coverage.report]
|
|
155
|
+
omit = ["*/tests/*", "*/__init__.py"]
|
|
156
|
+
show_missing = true
|
|
157
|
+
exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
|
|
158
|
+
|
|
159
|
+
[tool.pytest.ini_options]
|
|
160
|
+
addopts = "--strict-markers"
|
|
161
|
+
markers = [
|
|
162
|
+
"integration: integration tests",
|
|
163
|
+
]
|
|
164
|
+
log_cli = true
|
|
165
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
File without changes
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
from haystack_integrations.components.websearch.serperdev.websearch import (
|
|
6
|
+
SerperDevError,
|
|
7
|
+
SerperDevWebSearch,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
__all__ = ["SerperDevError", "SerperDevWebSearch"]
|
serperdev_haystack-1.0.0/src/haystack_integrations/components/websearch/serperdev/websearch.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
from urllib.parse import urlparse
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
from haystack import ComponentError, Document, component, default_from_dict, default_to_dict, logging
|
|
10
|
+
from haystack.utils import Secret, deserialize_secrets_inplace
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
SERPERDEV_BASE_URL = "https://google.serper.dev/search"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SerperDevError(ComponentError): ...
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@component
|
|
22
|
+
class SerperDevWebSearch:
|
|
23
|
+
"""
|
|
24
|
+
Uses [Serper](https://serper.dev/) to search the web for relevant documents.
|
|
25
|
+
|
|
26
|
+
See the [Serper Dev website](https://serper.dev/) for more details.
|
|
27
|
+
|
|
28
|
+
Usage example:
|
|
29
|
+
```python
|
|
30
|
+
from haystack.utils import Secret
|
|
31
|
+
|
|
32
|
+
from haystack_integrations.components.websearch.serperdev import SerperDevWebSearch
|
|
33
|
+
|
|
34
|
+
serper_dev_api = Secret.from_env_var("SERPERDEV_API_KEY")
|
|
35
|
+
|
|
36
|
+
websearch = SerperDevWebSearch(top_k=10, api_key=serper_dev_api)
|
|
37
|
+
results = websearch.run(query="Who is the boyfriend of Olivia Wilde?")
|
|
38
|
+
|
|
39
|
+
assert results["documents"]
|
|
40
|
+
assert results["links"]
|
|
41
|
+
|
|
42
|
+
# Example with domain filtering - exclude subdomains
|
|
43
|
+
websearch_filtered = SerperDevWebSearch(
|
|
44
|
+
top_k=10,
|
|
45
|
+
allowed_domains=["example.com"],
|
|
46
|
+
exclude_subdomains=True, # Only results from example.com, not blog.example.com
|
|
47
|
+
api_key=serper_dev_api,
|
|
48
|
+
)
|
|
49
|
+
results_filtered = websearch_filtered.run(query="search query")
|
|
50
|
+
```
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
api_key: Secret = Secret.from_env_var("SERPERDEV_API_KEY"),
|
|
56
|
+
top_k: int | None = 10,
|
|
57
|
+
allowed_domains: list[str] | None = None,
|
|
58
|
+
search_params: dict[str, Any] | None = None,
|
|
59
|
+
*,
|
|
60
|
+
exclude_subdomains: bool = False,
|
|
61
|
+
) -> None:
|
|
62
|
+
"""
|
|
63
|
+
Initialize the SerperDevWebSearch component.
|
|
64
|
+
|
|
65
|
+
:param api_key: API key for the Serper API.
|
|
66
|
+
:param top_k: Number of documents to return.
|
|
67
|
+
:param allowed_domains: List of domains to limit the search to.
|
|
68
|
+
:param exclude_subdomains: Whether to exclude subdomains when filtering by allowed_domains.
|
|
69
|
+
If True, only results from the exact domains in allowed_domains will be returned.
|
|
70
|
+
If False, results from subdomains will also be included. Defaults to False.
|
|
71
|
+
:param search_params: Additional parameters passed to the Serper API.
|
|
72
|
+
For example, you can set 'num' to 20 to increase the number of search results.
|
|
73
|
+
See the [Serper website](https://serper.dev/) for more details.
|
|
74
|
+
"""
|
|
75
|
+
self.api_key = api_key
|
|
76
|
+
self.top_k = top_k
|
|
77
|
+
self.allowed_domains = allowed_domains
|
|
78
|
+
self.exclude_subdomains = exclude_subdomains
|
|
79
|
+
self.search_params = search_params or {}
|
|
80
|
+
|
|
81
|
+
# Ensure that the API key is resolved.
|
|
82
|
+
_ = self.api_key.resolve_value()
|
|
83
|
+
|
|
84
|
+
def to_dict(self) -> dict[str, Any]:
|
|
85
|
+
"""
|
|
86
|
+
Serializes the component to a dictionary.
|
|
87
|
+
|
|
88
|
+
:returns:
|
|
89
|
+
Dictionary with serialized data.
|
|
90
|
+
"""
|
|
91
|
+
return default_to_dict(
|
|
92
|
+
self,
|
|
93
|
+
top_k=self.top_k,
|
|
94
|
+
allowed_domains=self.allowed_domains,
|
|
95
|
+
exclude_subdomains=self.exclude_subdomains,
|
|
96
|
+
search_params=self.search_params,
|
|
97
|
+
api_key=self.api_key.to_dict(),
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
@classmethod
|
|
101
|
+
def from_dict(cls, data: dict[str, Any]) -> "SerperDevWebSearch":
|
|
102
|
+
"""
|
|
103
|
+
Deserializes the component from a dictionary.
|
|
104
|
+
|
|
105
|
+
:param data:
|
|
106
|
+
The dictionary to deserialize from.
|
|
107
|
+
:returns:
|
|
108
|
+
The deserialized component.
|
|
109
|
+
"""
|
|
110
|
+
deserialize_secrets_inplace(data["init_parameters"], keys=["api_key"])
|
|
111
|
+
return default_from_dict(cls, data)
|
|
112
|
+
|
|
113
|
+
def _is_domain_allowed(self, url: str) -> bool:
|
|
114
|
+
"""
|
|
115
|
+
Check if a URL's domain is allowed based on allowed_domains and exclude_subdomains settings.
|
|
116
|
+
|
|
117
|
+
:param url: The URL to check.
|
|
118
|
+
:returns: True if the domain is allowed, False otherwise.
|
|
119
|
+
"""
|
|
120
|
+
if not self.allowed_domains:
|
|
121
|
+
return True
|
|
122
|
+
|
|
123
|
+
try:
|
|
124
|
+
parsed = urlparse(url)
|
|
125
|
+
domain = parsed.netloc.lower()
|
|
126
|
+
|
|
127
|
+
for allowed_domain in self.allowed_domains:
|
|
128
|
+
allowed_domain_lower = allowed_domain.lower()
|
|
129
|
+
|
|
130
|
+
if self.exclude_subdomains:
|
|
131
|
+
# Exact domain match only
|
|
132
|
+
if domain == allowed_domain_lower:
|
|
133
|
+
return True
|
|
134
|
+
# Allow subdomains (current behavior)
|
|
135
|
+
elif domain == allowed_domain_lower or domain.endswith("." + allowed_domain_lower):
|
|
136
|
+
return True
|
|
137
|
+
|
|
138
|
+
return False
|
|
139
|
+
except Exception:
|
|
140
|
+
# If URL parsing fails, allow the result to be safe
|
|
141
|
+
return True
|
|
142
|
+
|
|
143
|
+
@component.output_types(documents=list[Document], links=list[str])
|
|
144
|
+
def run(self, query: str) -> dict[str, list[Document] | list[str]]:
|
|
145
|
+
"""
|
|
146
|
+
Use [Serper](https://serper.dev/) to search the web.
|
|
147
|
+
|
|
148
|
+
:param query: Search query.
|
|
149
|
+
:returns: A dictionary with the following keys:
|
|
150
|
+
- "documents": List of documents returned by the search engine.
|
|
151
|
+
- "links": List of links returned by the search engine.
|
|
152
|
+
:raises SerperDevError: If an error occurs while querying the SerperDev API.
|
|
153
|
+
:raises TimeoutError: If the request to the SerperDev API times out.
|
|
154
|
+
"""
|
|
155
|
+
payload, headers = self._prepare_request(query)
|
|
156
|
+
try:
|
|
157
|
+
response = httpx.post(SERPERDEV_BASE_URL, headers=headers, json=payload, timeout=30)
|
|
158
|
+
response.raise_for_status() # Will raise an HTTPError for bad responses
|
|
159
|
+
except httpx.TimeoutException as error:
|
|
160
|
+
msg = f"Request to {self.__class__.__name__} timed out."
|
|
161
|
+
raise TimeoutError(msg) from error
|
|
162
|
+
|
|
163
|
+
except httpx.HTTPStatusError as e:
|
|
164
|
+
msg = f"An error occurred while querying {self.__class__.__name__}. Error: {e}, Response: {e.response.text}"
|
|
165
|
+
raise SerperDevError(msg) from e
|
|
166
|
+
|
|
167
|
+
except httpx.HTTPError as e:
|
|
168
|
+
msg = f"An error occurred while querying {self.__class__.__name__}. Error: {e}"
|
|
169
|
+
raise SerperDevError(msg) from e
|
|
170
|
+
|
|
171
|
+
documents, links = self._parse_response(response)
|
|
172
|
+
|
|
173
|
+
logger.debug(
|
|
174
|
+
"Serper Dev returned {number_documents} documents for the query '{query}'",
|
|
175
|
+
number_documents=len(documents),
|
|
176
|
+
query=query,
|
|
177
|
+
)
|
|
178
|
+
return {"documents": documents[: self.top_k], "links": links[: self.top_k]}
|
|
179
|
+
|
|
180
|
+
@component.output_types(documents=list[Document], links=list[str])
|
|
181
|
+
async def run_async(self, query: str) -> dict[str, list[Document] | list[str]]:
|
|
182
|
+
"""
|
|
183
|
+
Asynchronously uses [Serper](https://serper.dev/) to search the web.
|
|
184
|
+
|
|
185
|
+
This is the asynchronous version of the `run` method with the same parameters and return values.
|
|
186
|
+
|
|
187
|
+
:param query: Search query.
|
|
188
|
+
:returns: A dictionary with the following keys:
|
|
189
|
+
- "documents": List of documents returned by the search engine.
|
|
190
|
+
- "links": List of links returned by the search engine.
|
|
191
|
+
:raises SerperDevError: If an error occurs while querying the SerperDev API.
|
|
192
|
+
:raises TimeoutError: If the request to the SerperDev API times out.
|
|
193
|
+
"""
|
|
194
|
+
payload, headers = self._prepare_request(query)
|
|
195
|
+
try:
|
|
196
|
+
async with httpx.AsyncClient() as client:
|
|
197
|
+
response = await client.post(SERPERDEV_BASE_URL, headers=headers, json=payload, timeout=30)
|
|
198
|
+
response.raise_for_status() # Will raise an HTTPError for bad responses
|
|
199
|
+
except httpx.TimeoutException as error:
|
|
200
|
+
msg = f"Request to {self.__class__.__name__} timed out."
|
|
201
|
+
raise TimeoutError(msg) from error
|
|
202
|
+
|
|
203
|
+
except httpx.HTTPStatusError as e:
|
|
204
|
+
msg = f"An error occurred while querying {self.__class__.__name__}. Error: {e}, Response: {e.response.text}"
|
|
205
|
+
raise SerperDevError(msg) from e
|
|
206
|
+
|
|
207
|
+
except httpx.HTTPError as e:
|
|
208
|
+
msg = f"An error occurred while querying {self.__class__.__name__}. Error: {e}"
|
|
209
|
+
raise SerperDevError(msg) from e
|
|
210
|
+
|
|
211
|
+
documents, links = self._parse_response(response)
|
|
212
|
+
|
|
213
|
+
logger.debug(
|
|
214
|
+
"Serper Dev returned {number_documents} documents for the query '{query}'",
|
|
215
|
+
number_documents=len(documents),
|
|
216
|
+
query=query,
|
|
217
|
+
)
|
|
218
|
+
return {"documents": documents[: self.top_k], "links": links[: self.top_k]}
|
|
219
|
+
|
|
220
|
+
def _prepare_request(self, query: str) -> tuple[dict[str, Any], dict[str, str]]:
|
|
221
|
+
query_prepend = "OR ".join(f"site:{domain} " for domain in self.allowed_domains) if self.allowed_domains else ""
|
|
222
|
+
payload = {"q": query_prepend + query, "gl": "us", "hl": "en", "autocorrect": True, **self.search_params}
|
|
223
|
+
if (api_key := self.api_key.resolve_value()) is None:
|
|
224
|
+
msg = "API key cannot be `None`."
|
|
225
|
+
raise ValueError(msg)
|
|
226
|
+
headers = {"X-API-KEY": api_key}
|
|
227
|
+
return payload, headers
|
|
228
|
+
|
|
229
|
+
def _parse_response(self, response: httpx.Response) -> tuple[list[Document], list[str]]:
|
|
230
|
+
# If we reached this point, it means the request was successful and we can proceed
|
|
231
|
+
json_result = response.json()
|
|
232
|
+
|
|
233
|
+
# we get the snippet from the json result and put it in the content field of the document
|
|
234
|
+
organic = [
|
|
235
|
+
Document(meta={k: v for k, v in d.items() if k != "snippet"}, content=d.get("snippet"))
|
|
236
|
+
for d in json_result["organic"]
|
|
237
|
+
if self._is_domain_allowed(d.get("link", ""))
|
|
238
|
+
]
|
|
239
|
+
|
|
240
|
+
# answer box is what search engine shows as a direct answer to the query
|
|
241
|
+
answer_box = []
|
|
242
|
+
if "answerBox" in json_result:
|
|
243
|
+
answer_dict = json_result["answerBox"]
|
|
244
|
+
highlighted_answers = answer_dict.get("snippetHighlighted")
|
|
245
|
+
answer_box_content = None
|
|
246
|
+
# Check if highlighted_answers is a list and has at least one element
|
|
247
|
+
if isinstance(highlighted_answers, list) and len(highlighted_answers) > 0:
|
|
248
|
+
answer_box_content = highlighted_answers[0]
|
|
249
|
+
elif isinstance(highlighted_answers, str):
|
|
250
|
+
answer_box_content = highlighted_answers
|
|
251
|
+
if not answer_box_content:
|
|
252
|
+
for key in ["snippet", "answer", "title"]:
|
|
253
|
+
if key in answer_dict:
|
|
254
|
+
answer_box_content = answer_dict[key]
|
|
255
|
+
break
|
|
256
|
+
if answer_box_content and self._is_domain_allowed(answer_dict.get("link", "")):
|
|
257
|
+
answer_box = [
|
|
258
|
+
Document(
|
|
259
|
+
content=answer_box_content,
|
|
260
|
+
meta={"title": answer_dict.get("title", ""), "link": answer_dict.get("link", "")},
|
|
261
|
+
)
|
|
262
|
+
]
|
|
263
|
+
|
|
264
|
+
# these are related questions that search engine shows
|
|
265
|
+
people_also_ask = []
|
|
266
|
+
if "peopleAlsoAsk" in json_result:
|
|
267
|
+
for result in json_result["peopleAlsoAsk"]:
|
|
268
|
+
if self._is_domain_allowed(result.get("link", "")):
|
|
269
|
+
title = result.get("title", "")
|
|
270
|
+
people_also_ask.append(
|
|
271
|
+
Document(
|
|
272
|
+
content=result["snippet"] if result.get("snippet") else title,
|
|
273
|
+
meta={"title": title, "link": result.get("link", None)},
|
|
274
|
+
)
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
documents = answer_box + organic + people_also_ask
|
|
278
|
+
|
|
279
|
+
links = [result["link"] for result in json_result["organic"] if self._is_domain_allowed(result.get("link", ""))]
|
|
280
|
+
return documents, links
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Generator
|
|
8
|
+
from unittest.mock import AsyncMock, MagicMock, Mock, patch
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
from haystack import Document
|
|
12
|
+
from haystack.utils.auth import Secret
|
|
13
|
+
from httpx import ConnectTimeout, HTTPStatusError, ReadTimeout, Request, RequestError, Response
|
|
14
|
+
|
|
15
|
+
from haystack_integrations.components.websearch.serperdev import SerperDevError, SerperDevWebSearch
|
|
16
|
+
|
|
17
|
+
EXAMPLE_SERPERDEV_RESPONSE = {
|
|
18
|
+
"searchParameters": {
|
|
19
|
+
"q": "Who is the boyfriend of Olivia Wilde?",
|
|
20
|
+
"gl": "us",
|
|
21
|
+
"hl": "en",
|
|
22
|
+
"autocorrect": True,
|
|
23
|
+
"type": "search",
|
|
24
|
+
},
|
|
25
|
+
"organic": [
|
|
26
|
+
{
|
|
27
|
+
"title": "Olivia Wilde embraces Jason Sudeikis amid custody battle, Harry Styles split - Page Six",
|
|
28
|
+
"link": "https://pagesix.com/2023/01/29/olivia-wilde-hugs-it-out-with-jason-sudeikis-after-harry-styles-split/",
|
|
29
|
+
"snippet": "Looks like Olivia Wilde and Jason Sudeikis are starting 2023 on good terms. Amid their highly "
|
|
30
|
+
"publicized custody battle - and the actress' ...",
|
|
31
|
+
"date": "Jan 29, 2023",
|
|
32
|
+
"position": 1,
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
"title": "Olivia Wilde Is 'Quietly Dating' Again Following Harry Styles Split: 'He Makes Her Happy'",
|
|
36
|
+
"link": "https://www.yahoo.com/now/olivia-wilde-quietly-dating-again-183844364.html",
|
|
37
|
+
"snippet": "Olivia Wilde is “quietly dating again” following her November 2022 split from Harry Styles, "
|
|
38
|
+
"a source exclusively tells Life & Style.",
|
|
39
|
+
"date": "Feb 10, 2023",
|
|
40
|
+
"position": 2,
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"title": "Olivia Wilde and Harry Styles' Relationship Timeline: The Way They Were - Us Weekly",
|
|
44
|
+
"link": "https://www.usmagazine.com/celebrity-news/pictures/olivia-wilde-and-harry-styles-relationship-timeline/",
|
|
45
|
+
"snippet": "Olivia Wilde started dating Harry Styles after ending her years-long engagement to Jason "
|
|
46
|
+
"Sudeikis — see their relationship timeline.",
|
|
47
|
+
"date": "Mar 10, 2023",
|
|
48
|
+
"imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSgTcalNFvptTbYBiDXX55s8yCGfn6F1qbed9DAN16LvynTr9GayK5SPmY&s",
|
|
49
|
+
"position": 3,
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
"title": "Olivia Wilde Is 'Ready to Date Again' After Harry Styles Split - Us Weekly",
|
|
53
|
+
"link": "https://www.usmagazine.com/celebrity-news/news/olivia-wilde-is-ready-to-date-again-after-harry-styles-split/",
|
|
54
|
+
"snippet": "Ready for love! Olivia Wilde is officially back on the dating scene following her split from "
|
|
55
|
+
"her ex-boyfriend, Harry Styles.",
|
|
56
|
+
"date": "Mar 1, 2023",
|
|
57
|
+
"imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRCRAeRy5sVE631ZctzbzuOF70xkIOHaTvh2K7dYvdiVBwALiKrIjpscok&s",
|
|
58
|
+
"position": 4,
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
"title": "Harry Styles and Olivia Wilde's Definitive Relationship Timeline - Harper's Bazaar",
|
|
62
|
+
"link": "https://www.harpersbazaar.com/celebrity/latest/a35172115/harry-styles-olivia-wilde-relationship-timeline/",
|
|
63
|
+
"snippet": "November 2020: News breaks about Olivia splitting from fiancé Jason Sudeikis. ... "
|
|
64
|
+
"In mid-November, news breaks of Olivia Wilde's split from Jason ...",
|
|
65
|
+
"date": "Feb 23, 2023",
|
|
66
|
+
"imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRRqw3fvZOIGHEepxCc7yFAWYsS_v_1H6X-4nxyFJxdfRuFQw_BrI6JVzI&s",
|
|
67
|
+
"position": 5,
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
"title": "Harry Styles and Olivia Wilde's Relationship Timeline - People",
|
|
71
|
+
"link": "https://people.com/music/harry-styles-olivia-wilde-relationship-timeline/",
|
|
72
|
+
"snippet": "Harry Styles and Olivia Wilde first met on the set of Don't Worry Darling and stepped out as "
|
|
73
|
+
"a couple in January 2021. Relive all their biggest relationship ...",
|
|
74
|
+
"position": 6,
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
"title": "Jason Sudeikis and Olivia Wilde's Relationship Timeline - People",
|
|
78
|
+
"link": "https://people.com/movies/jason-sudeikis-olivia-wilde-relationship-timeline/",
|
|
79
|
+
"snippet": "Jason Sudeikis and Olivia Wilde ended their engagement of seven years in 2020. Here's a "
|
|
80
|
+
"complete timeline of their relationship.",
|
|
81
|
+
"date": "Mar 24, 2023",
|
|
82
|
+
"imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSleZoXusQyJJe2WMgIuck_cVaJ8AE0_hU2QxsXzYvKANi55UQlv82yAVI&s",
|
|
83
|
+
"position": 7,
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
"title": "Olivia Wilde's anger at ex-boyfriend Harry Styles: She resents him and thinks he was using her "
|
|
87
|
+
"| Marca",
|
|
88
|
+
"link": "https://www.marca.com/en/lifestyle/celebrities/2023/02/23/63f779a4e2704e8d988b4624.html",
|
|
89
|
+
"snippet": "The two started dating after Wilde split up with actor Jason Sudeikisin 2020. However, their "
|
|
90
|
+
"relationship came to an end last November.",
|
|
91
|
+
"date": "Feb 23, 2023",
|
|
92
|
+
"imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQBgJF2mSnIWCvPrqUqM4WTI9xPNWPyLvHuune85swpB1yE_G8cy_7KRh0&s",
|
|
93
|
+
"position": 8,
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
"title": "Olivia Wilde's dating history: Who has the actress dated? | The US Sun",
|
|
97
|
+
"link": "https://www.the-sun.com/entertainment/5221040/olivia-wildes-dating-history/",
|
|
98
|
+
"snippet": "AMERICAN actress Olivia Wilde started dating Harry Styles in January 2021 after breaking off "
|
|
99
|
+
"her engagement the year prior.",
|
|
100
|
+
"date": "Nov 19, 2022",
|
|
101
|
+
"imageUrl": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTpm8BToVFHJoH6yRggg0fLocLT9mt6lwsnRxFFDNdDGhDydzQiSKZ9__g&s",
|
|
102
|
+
"position": 9,
|
|
103
|
+
},
|
|
104
|
+
],
|
|
105
|
+
"relatedSearches": [
|
|
106
|
+
{"query": "Harry Styles girlfriends in order"},
|
|
107
|
+
{"query": "Harry Styles and Olivia Wilde engaged"},
|
|
108
|
+
{"query": "Harry Styles and Olivia Wilde wedding"},
|
|
109
|
+
{"query": "Who is Harry Styles married to"},
|
|
110
|
+
{"query": "Jason Sudeikis Olivia Wilde relationship"},
|
|
111
|
+
{"query": "Olivia Wilde and Jason Sudeikis kids"},
|
|
112
|
+
{"query": "Olivia Wilde children"},
|
|
113
|
+
{"query": "Harry Styles and Olivia Wilde age difference"},
|
|
114
|
+
{"query": "Jason Sudeikis Olivia Wilde, Harry Styles"},
|
|
115
|
+
],
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
HTTPX_PATH = "haystack_integrations.components.websearch.serperdev.websearch.httpx"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@pytest.fixture
|
|
122
|
+
def mock_serper_dev_search_result() -> Generator[MagicMock, None, None]:
|
|
123
|
+
with patch(HTTPX_PATH) as mock_run:
|
|
124
|
+
mock_run.post.return_value = Mock(status_code=200, json=lambda: EXAMPLE_SERPERDEV_RESPONSE)
|
|
125
|
+
yield mock_run
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@pytest.fixture
|
|
129
|
+
def mock_serper_dev_search_result_async() -> Generator[MagicMock, None, None]:
|
|
130
|
+
with patch(f"{HTTPX_PATH}.AsyncClient") as mock_run:
|
|
131
|
+
mock_client = AsyncMock()
|
|
132
|
+
mock_client.post.return_value = Mock(status_code=200, json=lambda: EXAMPLE_SERPERDEV_RESPONSE)
|
|
133
|
+
mock_client.__aenter__.return_value = mock_client
|
|
134
|
+
mock_run.return_value = mock_client
|
|
135
|
+
yield mock_run
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@pytest.fixture
|
|
139
|
+
def mock_serper_dev_search_result_no_snippet() -> Generator[MagicMock, None, None]:
|
|
140
|
+
resp = copy.deepcopy(EXAMPLE_SERPERDEV_RESPONSE)
|
|
141
|
+
del resp["organic"][0]["snippet"]
|
|
142
|
+
with patch(HTTPX_PATH) as mock_run:
|
|
143
|
+
mock_run.post.return_value = Mock(status_code=200, json=lambda: resp)
|
|
144
|
+
yield mock_run
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@pytest.fixture
|
|
148
|
+
def mock_serper_dev_search_result_no_snippet_async() -> Generator[MagicMock, None, None]:
|
|
149
|
+
resp = copy.deepcopy(EXAMPLE_SERPERDEV_RESPONSE)
|
|
150
|
+
del resp["organic"][0]["snippet"]
|
|
151
|
+
with patch(f"{HTTPX_PATH}.AsyncClient") as mock_run:
|
|
152
|
+
mock_client = AsyncMock()
|
|
153
|
+
mock_client.post.return_value = Mock(status_code=200, json=lambda: resp)
|
|
154
|
+
mock_client.__aenter__.return_value = mock_client
|
|
155
|
+
mock_run.return_value = mock_client
|
|
156
|
+
yield mock_run
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class TestSerperDevSearchAPI:
|
|
160
|
+
def test_init_fail_wo_api_key(self, monkeypatch):
|
|
161
|
+
monkeypatch.delenv("SERPERDEV_API_KEY", raising=False)
|
|
162
|
+
with pytest.raises(ValueError, match=r"None of the .* environment variables are set"):
|
|
163
|
+
SerperDevWebSearch()
|
|
164
|
+
|
|
165
|
+
def test_to_dict(self, monkeypatch):
|
|
166
|
+
monkeypatch.setenv("SERPERDEV_API_KEY", "test-api-key")
|
|
167
|
+
component = SerperDevWebSearch(top_k=10, allowed_domains=["test.com"], search_params={"param": "test"})
|
|
168
|
+
data = component.to_dict()
|
|
169
|
+
assert data == {
|
|
170
|
+
"type": ("haystack_integrations.components.websearch.serperdev.websearch.SerperDevWebSearch"),
|
|
171
|
+
"init_parameters": {
|
|
172
|
+
"api_key": {"env_vars": ["SERPERDEV_API_KEY"], "strict": True, "type": "env_var"},
|
|
173
|
+
"top_k": 10,
|
|
174
|
+
"allowed_domains": ["test.com"],
|
|
175
|
+
"exclude_subdomains": False,
|
|
176
|
+
"search_params": {"param": "test"},
|
|
177
|
+
},
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
def test_from_dict(self, monkeypatch):
|
|
181
|
+
monkeypatch.setenv("SERPERDEV_API_KEY", "test-api-key")
|
|
182
|
+
data = {
|
|
183
|
+
"type": ("haystack_integrations.components.websearch.serperdev.websearch.SerperDevWebSearch"),
|
|
184
|
+
"init_parameters": {
|
|
185
|
+
"api_key": {"env_vars": ["SERPERDEV_API_KEY"], "strict": True, "type": "env_var"},
|
|
186
|
+
"top_k": 10,
|
|
187
|
+
"allowed_domains": ["test.com"],
|
|
188
|
+
"exclude_subdomains": True,
|
|
189
|
+
"search_params": {"param": "test"},
|
|
190
|
+
},
|
|
191
|
+
}
|
|
192
|
+
component = SerperDevWebSearch.from_dict(data)
|
|
193
|
+
assert component.api_key == Secret.from_env_var("SERPERDEV_API_KEY")
|
|
194
|
+
assert component.top_k == 10
|
|
195
|
+
assert component.allowed_domains == ["test.com"]
|
|
196
|
+
assert component.exclude_subdomains is True
|
|
197
|
+
assert component.search_params == {"param": "test"}
|
|
198
|
+
|
|
199
|
+
@pytest.mark.parametrize("top_k", [1, 5, 7])
|
|
200
|
+
@pytest.mark.usefixtures("mock_serper_dev_search_result")
|
|
201
|
+
def test_web_search_top_k(self, top_k: int) -> None:
|
|
202
|
+
ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"), top_k=top_k)
|
|
203
|
+
results = ws.run(query="Who is the boyfriend of Olivia Wilde?")
|
|
204
|
+
documents = results["documents"]
|
|
205
|
+
links = results["links"]
|
|
206
|
+
assert len(documents) == len(links) == top_k
|
|
207
|
+
assert all(isinstance(doc, Document) for doc in documents)
|
|
208
|
+
assert all(isinstance(link, str) for link in links)
|
|
209
|
+
assert all(link.startswith("http") for link in links)
|
|
210
|
+
|
|
211
|
+
@pytest.mark.parametrize("top_k", [1, 5, 7])
|
|
212
|
+
@pytest.mark.asyncio
|
|
213
|
+
@pytest.mark.usefixtures("mock_serper_dev_search_result_async")
|
|
214
|
+
async def test_web_search_top_k_async(self, top_k: int) -> None:
|
|
215
|
+
ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"), top_k=top_k)
|
|
216
|
+
results = await ws.run_async(query="Who is the boyfriend of Olivia Wilde?")
|
|
217
|
+
documents = results["documents"]
|
|
218
|
+
links = results["links"]
|
|
219
|
+
assert len(documents) == len(links) == top_k
|
|
220
|
+
assert all(isinstance(doc, Document) for doc in documents)
|
|
221
|
+
assert all(isinstance(link, str) for link in links)
|
|
222
|
+
assert all(link.startswith("http") for link in links)
|
|
223
|
+
|
|
224
|
+
@pytest.mark.usefixtures("mock_serper_dev_search_result_no_snippet")
|
|
225
|
+
def test_no_snippet(self) -> None:
|
|
226
|
+
ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"), top_k=1)
|
|
227
|
+
ws.run(query="Who is the boyfriend of Olivia Wilde?")
|
|
228
|
+
|
|
229
|
+
@pytest.mark.asyncio
|
|
230
|
+
@pytest.mark.usefixtures("mock_serper_dev_search_result_no_snippet_async")
|
|
231
|
+
async def test_no_snippet_async(self) -> None:
|
|
232
|
+
ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"), top_k=1)
|
|
233
|
+
await ws.run_async(query="Who is the boyfriend of Olivia Wilde?")
|
|
234
|
+
|
|
235
|
+
@pytest.mark.parametrize("timeout_exception", [ConnectTimeout, ReadTimeout])
|
|
236
|
+
@patch("httpx.post")
|
|
237
|
+
def test_timeout_error(self, mock_post: MagicMock, timeout_exception: type[Exception]) -> None:
|
|
238
|
+
mock_post.side_effect = timeout_exception("Request has timed out.")
|
|
239
|
+
ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"))
|
|
240
|
+
|
|
241
|
+
with pytest.raises(TimeoutError):
|
|
242
|
+
ws.run(query="Who is the boyfriend of Olivia Wilde?")
|
|
243
|
+
|
|
244
|
+
@pytest.mark.parametrize("timeout_exception", [ConnectTimeout, ReadTimeout])
|
|
245
|
+
@pytest.mark.asyncio
|
|
246
|
+
@patch("httpx.AsyncClient.post")
|
|
247
|
+
async def test_timeout_error_async(self, mock_post: AsyncMock, timeout_exception: type[Exception]) -> None:
|
|
248
|
+
mock_post.side_effect = timeout_exception("Request has timed out.")
|
|
249
|
+
ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"))
|
|
250
|
+
|
|
251
|
+
with pytest.raises(TimeoutError):
|
|
252
|
+
await ws.run_async(query="Who is the boyfriend of Olivia Wilde?")
|
|
253
|
+
|
|
254
|
+
@patch("httpx.post")
|
|
255
|
+
def test_request_exception(self, mock_post: MagicMock) -> None:
|
|
256
|
+
mock_post.side_effect = RequestError("An errors has occurred in the request.")
|
|
257
|
+
ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"))
|
|
258
|
+
|
|
259
|
+
with pytest.raises(SerperDevError):
|
|
260
|
+
ws.run(query="Who is the boyfriend of Olivia Wilde?")
|
|
261
|
+
|
|
262
|
+
@pytest.mark.asyncio
|
|
263
|
+
@patch("httpx.AsyncClient.post")
|
|
264
|
+
async def test_request_exception_async(self, mock_post: MagicMock) -> None:
|
|
265
|
+
mock_post.side_effect = RequestError("An errors has occurred in the request.")
|
|
266
|
+
ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"))
|
|
267
|
+
|
|
268
|
+
with pytest.raises(SerperDevError):
|
|
269
|
+
await ws.run_async(query="Who is the boyfriend of Olivia Wilde?")
|
|
270
|
+
|
|
271
|
+
@patch("httpx.post")
|
|
272
|
+
def test_bad_response_code(self, mock_post: MagicMock) -> None:
|
|
273
|
+
mock_response = mock_post.return_value
|
|
274
|
+
mock_response.status_code = 404
|
|
275
|
+
mock_error_request = Request("POST", "https://example.com")
|
|
276
|
+
mock_error_response = Response(404)
|
|
277
|
+
mock_response.raise_for_status.side_effect = HTTPStatusError(
|
|
278
|
+
"404 Not Found.", request=mock_error_request, response=mock_error_response
|
|
279
|
+
)
|
|
280
|
+
ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"))
|
|
281
|
+
|
|
282
|
+
with pytest.raises(SerperDevError):
|
|
283
|
+
ws.run(query="Who is the boyfriend of Olivia Wilde?")
|
|
284
|
+
|
|
285
|
+
@pytest.mark.asyncio
|
|
286
|
+
@patch("httpx.AsyncClient")
|
|
287
|
+
async def test_bad_response_code_async(self, mock_run: MagicMock) -> None:
|
|
288
|
+
mock_client = AsyncMock()
|
|
289
|
+
mock_response = Mock(status_code=404)
|
|
290
|
+
mock_error_request = Request("POST", "https://example.com")
|
|
291
|
+
mock_error_response = Response(404)
|
|
292
|
+
mock_response.raise_for_status.side_effect = HTTPStatusError(
|
|
293
|
+
"404 Not Found.", request=mock_error_request, response=mock_error_response
|
|
294
|
+
)
|
|
295
|
+
mock_client.post.return_value = mock_response
|
|
296
|
+
mock_client.__aenter__.return_value = mock_client
|
|
297
|
+
mock_run.return_value = mock_client
|
|
298
|
+
ws = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"))
|
|
299
|
+
|
|
300
|
+
with pytest.raises(SerperDevError):
|
|
301
|
+
await ws.run_async(query="Who is the boyfriend of Olivia Wilde?")
|
|
302
|
+
|
|
303
|
+
@pytest.mark.skipif(
|
|
304
|
+
not os.environ.get("SERPERDEV_API_KEY", None),
|
|
305
|
+
reason="Export an env var called SERPERDEV_API_KEY containing the SerperDev API key to run this test.",
|
|
306
|
+
)
|
|
307
|
+
@pytest.mark.integration
|
|
308
|
+
def test_web_search(self) -> None:
|
|
309
|
+
ws = SerperDevWebSearch(top_k=10)
|
|
310
|
+
results = ws.run(query="Who is the boyfriend of Olivia Wilde?")
|
|
311
|
+
documents = results["documents"]
|
|
312
|
+
links = results["links"]
|
|
313
|
+
# documents can also include answer box and "people also ask" results, so only links
|
|
314
|
+
# (which come from organic results) are guaranteed to be at most top_k
|
|
315
|
+
assert 0 < len(documents) <= 10
|
|
316
|
+
assert 0 < len(links) <= 10
|
|
317
|
+
assert all(isinstance(doc, Document) for doc in documents)
|
|
318
|
+
assert all(isinstance(link, str) for link in links)
|
|
319
|
+
assert all(link.startswith("http") for link in links)
|
|
320
|
+
|
|
321
|
+
@pytest.mark.asyncio
|
|
322
|
+
@pytest.mark.skipif(
|
|
323
|
+
not os.environ.get("SERPERDEV_API_KEY", None),
|
|
324
|
+
reason="Export an env var called SERPERDEV_API_KEY containing the SerperDev API key to run this test.",
|
|
325
|
+
)
|
|
326
|
+
@pytest.mark.integration
|
|
327
|
+
async def test_web_search_async(self) -> None:
|
|
328
|
+
ws = SerperDevWebSearch(top_k=10)
|
|
329
|
+
results = await ws.run_async(query="Who is the boyfriend of Olivia Wilde?")
|
|
330
|
+
documents = results["documents"]
|
|
331
|
+
links = results["links"]
|
|
332
|
+
# documents can also include answer box and "people also ask" results, so only links
|
|
333
|
+
# (which come from organic results) are guaranteed to be at most top_k
|
|
334
|
+
assert 0 < len(documents) <= 10
|
|
335
|
+
assert 0 < len(links) <= 10
|
|
336
|
+
assert all(isinstance(doc, Document) for doc in documents)
|
|
337
|
+
assert all(isinstance(link, str) for link in links)
|
|
338
|
+
assert all(link.startswith("http") for link in links)
|
|
339
|
+
|
|
340
|
+
def test_exclude_subdomains_filtering(self, monkeypatch):
|
|
341
|
+
"""Test that exclude_subdomains parameter properly filters results."""
|
|
342
|
+
monkeypatch.setenv("SERPERDEV_API_KEY", "test-api-key")
|
|
343
|
+
|
|
344
|
+
# Mock response with mixed domains and subdomains
|
|
345
|
+
mock_response = {
|
|
346
|
+
"organic": [
|
|
347
|
+
{
|
|
348
|
+
"title": "Main domain result",
|
|
349
|
+
"link": "https://example.com/page1",
|
|
350
|
+
"snippet": "Content from main domain",
|
|
351
|
+
},
|
|
352
|
+
{
|
|
353
|
+
"title": "Subdomain result 1",
|
|
354
|
+
"link": "https://blog.example.com/post1",
|
|
355
|
+
"snippet": "Content from blog subdomain",
|
|
356
|
+
},
|
|
357
|
+
{
|
|
358
|
+
"title": "Subdomain result 2",
|
|
359
|
+
"link": "https://shop.example.com/product1",
|
|
360
|
+
"snippet": "Content from shop subdomain",
|
|
361
|
+
},
|
|
362
|
+
{
|
|
363
|
+
"title": "Different domain result",
|
|
364
|
+
"link": "https://other.com/page1",
|
|
365
|
+
"snippet": "Content from different domain",
|
|
366
|
+
},
|
|
367
|
+
]
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
with patch(HTTPX_PATH) as mock_requests:
|
|
371
|
+
mock_requests.post.return_value = Mock(status_code=200, json=lambda: mock_response)
|
|
372
|
+
|
|
373
|
+
# Test with exclude_subdomains=False (default behavior)
|
|
374
|
+
ws_include = SerperDevWebSearch(
|
|
375
|
+
api_key=Secret.from_token("test-api-key"), allowed_domains=["example.com"], exclude_subdomains=False
|
|
376
|
+
)
|
|
377
|
+
results_include = ws_include.run(query="test query")
|
|
378
|
+
|
|
379
|
+
# Should include main domain and subdomains but exclude other domains
|
|
380
|
+
assert len(results_include["documents"]) == 3 # example.com + 2 subdomains
|
|
381
|
+
assert len(results_include["links"]) == 3
|
|
382
|
+
|
|
383
|
+
included_links = results_include["links"]
|
|
384
|
+
assert "https://example.com/page1" in included_links
|
|
385
|
+
assert "https://blog.example.com/post1" in included_links
|
|
386
|
+
assert "https://shop.example.com/product1" in included_links
|
|
387
|
+
assert "https://other.com/page1" not in included_links
|
|
388
|
+
|
|
389
|
+
# Test with exclude_subdomains=True
|
|
390
|
+
ws_exclude = SerperDevWebSearch(
|
|
391
|
+
api_key=Secret.from_token("test-api-key"), allowed_domains=["example.com"], exclude_subdomains=True
|
|
392
|
+
)
|
|
393
|
+
results_exclude = ws_exclude.run(query="test query")
|
|
394
|
+
|
|
395
|
+
# Should only include main domain, exclude subdomains and other domains
|
|
396
|
+
assert len(results_exclude["documents"]) == 1 # only example.com
|
|
397
|
+
assert len(results_exclude["links"]) == 1
|
|
398
|
+
|
|
399
|
+
excluded_links = results_exclude["links"]
|
|
400
|
+
assert "https://example.com/page1" in excluded_links
|
|
401
|
+
assert "https://blog.example.com/post1" not in excluded_links
|
|
402
|
+
assert "https://shop.example.com/product1" not in excluded_links
|
|
403
|
+
assert "https://other.com/page1" not in excluded_links
|
|
404
|
+
|
|
405
|
+
def test_is_domain_allowed_helper_method(self, monkeypatch):
|
|
406
|
+
"""Test the _is_domain_allowed helper method directly."""
|
|
407
|
+
monkeypatch.setenv("SERPERDEV_API_KEY", "test-api-key")
|
|
408
|
+
|
|
409
|
+
# Test with exclude_subdomains=False
|
|
410
|
+
ws_include = SerperDevWebSearch(
|
|
411
|
+
api_key=Secret.from_token("test-api-key"),
|
|
412
|
+
allowed_domains=["example.com", "test.org"],
|
|
413
|
+
exclude_subdomains=False,
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
# Should allow main domains and subdomains
|
|
417
|
+
assert ws_include._is_domain_allowed("https://example.com/page") is True
|
|
418
|
+
assert ws_include._is_domain_allowed("https://blog.example.com/post") is True
|
|
419
|
+
assert ws_include._is_domain_allowed("https://shop.example.com/product") is True
|
|
420
|
+
assert ws_include._is_domain_allowed("https://test.org/page") is True
|
|
421
|
+
assert ws_include._is_domain_allowed("https://sub.test.org/page") is True
|
|
422
|
+
assert ws_include._is_domain_allowed("https://other.com/page") is False
|
|
423
|
+
|
|
424
|
+
# Test with exclude_subdomains=True
|
|
425
|
+
ws_exclude = SerperDevWebSearch(
|
|
426
|
+
api_key=Secret.from_token("test-api-key"),
|
|
427
|
+
allowed_domains=["example.com", "test.org"],
|
|
428
|
+
exclude_subdomains=True,
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
# Should only allow exact domain matches
|
|
432
|
+
assert ws_exclude._is_domain_allowed("https://example.com/page") is True
|
|
433
|
+
assert ws_exclude._is_domain_allowed("https://blog.example.com/post") is False
|
|
434
|
+
assert ws_exclude._is_domain_allowed("https://shop.example.com/product") is False
|
|
435
|
+
assert ws_exclude._is_domain_allowed("https://test.org/page") is True
|
|
436
|
+
assert ws_exclude._is_domain_allowed("https://sub.test.org/page") is False
|
|
437
|
+
assert ws_exclude._is_domain_allowed("https://other.com/page") is False
|
|
438
|
+
|
|
439
|
+
# Test with no allowed_domains (should allow all)
|
|
440
|
+
ws_no_filter = SerperDevWebSearch(api_key=Secret.from_token("test-api-key"), allowed_domains=None)
|
|
441
|
+
assert ws_no_filter._is_domain_allowed("https://any.domain.com/page") is True
|