youcom-haystack 0.0.1__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.
@@ -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,60 @@
1
+ Metadata-Version: 2.5
2
+ Name: youcom-haystack
3
+ Version: 0.0.1
4
+ Summary: Haystack integration for the You.com Search API
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/youcom#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/youcom
8
+ Author-email: deepset GmbH <info@deepset.ai>, "You.com" <developers@you.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Keywords: AI Search,Haystack,Web Search,You.com
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
+ # youcom-haystack
28
+
29
+ [![PyPI - Version](https://img.shields.io/pypi/v/youcom-haystack.svg)](https://pypi.org/project/youcom-haystack)
30
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/youcom-haystack.svg)](https://pypi.org/project/youcom-haystack)
31
+
32
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/youcom/CHANGELOG.md)
33
+
34
+ ---
35
+
36
+ ## Usage
37
+
38
+ `YouComWebSearch` runs without any configuration: with no API key available it uses the You.com
39
+ [keyless free tier](https://you.com/docs/api-reference/search/v1-agents-search) (rate limited per IP).
40
+ Set the `YOUDOTCOM_API_KEY` environment variable to use the keyed
41
+ [You.com Search API](https://you.com/docs/api-reference/search/v1-search) with higher limits.
42
+
43
+ ```python
44
+ from haystack_integrations.components.websearch.youcom import YouComWebSearch
45
+
46
+ websearch = YouComWebSearch(top_k=5)
47
+ result = websearch.run(query="What is Haystack by deepset?")
48
+ result["documents"] # list[Document]
49
+ result["links"] # list[str]
50
+ ```
51
+
52
+ To require a key instead of silently degrading to the keyless tier, pass `keyless_fallback=False`;
53
+ the component then raises `YouComError` when no key resolves.
54
+
55
+ ## Contributing
56
+
57
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
58
+
59
+ The unit tests are fully mocked and need no credentials. The integration tests include one live keyless
60
+ search that needs no key; to also run the keyed tests, export the `YOUDOTCOM_API_KEY` environment variable.
@@ -0,0 +1,34 @@
1
+ # youcom-haystack
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/youcom-haystack.svg)](https://pypi.org/project/youcom-haystack)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/youcom-haystack.svg)](https://pypi.org/project/youcom-haystack)
5
+
6
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/youcom/CHANGELOG.md)
7
+
8
+ ---
9
+
10
+ ## Usage
11
+
12
+ `YouComWebSearch` runs without any configuration: with no API key available it uses the You.com
13
+ [keyless free tier](https://you.com/docs/api-reference/search/v1-agents-search) (rate limited per IP).
14
+ Set the `YOUDOTCOM_API_KEY` environment variable to use the keyed
15
+ [You.com Search API](https://you.com/docs/api-reference/search/v1-search) with higher limits.
16
+
17
+ ```python
18
+ from haystack_integrations.components.websearch.youcom import YouComWebSearch
19
+
20
+ websearch = YouComWebSearch(top_k=5)
21
+ result = websearch.run(query="What is Haystack by deepset?")
22
+ result["documents"] # list[Document]
23
+ result["links"] # list[str]
24
+ ```
25
+
26
+ To require a key instead of silently degrading to the keyless tier, pass `keyless_fallback=False`;
27
+ the component then raises `YouComError` when no key resolves.
28
+
29
+ ## Contributing
30
+
31
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
32
+
33
+ The unit tests are fully mocked and need no credentials. The integration tests include one live keyless
34
+ search that needs no key; to also run the keyed tests, export the `YOUDOTCOM_API_KEY` environment variable.
@@ -0,0 +1,13 @@
1
+ loaders:
2
+ - modules:
3
+ - haystack_integrations.components.websearch.youcom.youcom_websearch
4
+ search_path: [../src]
5
+ processors:
6
+ - type: filter
7
+ documented_only: true
8
+ skip_empty_modules: true
9
+ renderer:
10
+ description: You.com Search integration for Haystack
11
+ id: integrations-youcom
12
+ filename: youcom.md
13
+ title: You.com Search
@@ -0,0 +1,170 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "youcom-haystack"
7
+ dynamic = ["version"]
8
+ description = "Haystack integration for the You.com Search API"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ keywords = ["Haystack", "You.com", "Web Search", "AI Search"]
13
+ authors = [
14
+ { name = "deepset GmbH", email = "info@deepset.ai" },
15
+ { name = "You.com", email = "developers@you.com" },
16
+ ]
17
+ classifiers = [
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Development Status :: 4 - Beta",
20
+ "Programming Language :: Python",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Programming Language :: Python :: Implementation :: CPython",
27
+ "Programming Language :: Python :: Implementation :: PyPy",
28
+ ]
29
+ dependencies = ["haystack-ai>=2.24.1", "httpx>=0.27.0"]
30
+
31
+ [project.urls]
32
+ Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/youcom#readme"
33
+ Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
34
+ Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/youcom"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/haystack_integrations"]
38
+
39
+ [tool.hatch.version]
40
+ source = "vcs"
41
+ tag-pattern = 'integrations\/youcom-v(?P<version>.*)'
42
+
43
+ [tool.hatch.version.raw-options]
44
+ root = "../.."
45
+ git_describe_command = 'git describe --tags --match="integrations/youcom-v[0-9]*"'
46
+
47
+ [tool.hatch.envs.default]
48
+ installer = "uv"
49
+ dependencies = ["haystack-pydoc-tools", "ruff"]
50
+
51
+ [tool.hatch.envs.default.scripts]
52
+ docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
53
+ fmt = "ruff check --fix {args}; ruff format {args}"
54
+ fmt-check = "ruff check {args} && ruff format --check {args}"
55
+
56
+ [tool.hatch.envs.test]
57
+ dependencies = [
58
+ "pytest",
59
+ "pytest-asyncio",
60
+ "pytest-cov",
61
+ "pytest-rerunfailures",
62
+ "mypy",
63
+ "pip",
64
+ ]
65
+
66
+ [tool.hatch.envs.test.scripts]
67
+ unit = 'pytest -m "not integration" {args:tests}'
68
+ integration = 'pytest -m "integration" {args:tests}'
69
+ all = 'pytest {args:tests}'
70
+ unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}'
71
+ integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}'
72
+ types = "mypy -p haystack_integrations.components.websearch.youcom {args}"
73
+
74
+ [tool.mypy]
75
+ install_types = true
76
+ non_interactive = true
77
+ check_untyped_defs = true
78
+ disallow_incomplete_defs = true
79
+
80
+ [[tool.mypy.overrides]]
81
+ module = ["httpx.*"]
82
+ ignore_missing_imports = true
83
+
84
+ [tool.ruff]
85
+ line-length = 120
86
+
87
+ [tool.ruff.lint]
88
+ select = [
89
+ "A",
90
+ "ANN",
91
+ "ARG",
92
+ "B",
93
+ "C",
94
+ "D102", # Missing docstring in public method
95
+ "D103", # Missing docstring in public function
96
+ "D205", # 1 blank line required between summary line and description
97
+ "D209", # Closing triple quotes go to new line
98
+ "D213", # summary lines must be positioned on the second physical line of the docstring
99
+ "D417", # Missing argument descriptions in the docstring
100
+ "D419", # Docstring is empty
101
+ "DTZ",
102
+ "E",
103
+ "EM",
104
+ "F",
105
+ "I",
106
+ "ICN",
107
+ "ISC",
108
+ "N",
109
+ "PLC",
110
+ "PLE",
111
+ "PLR",
112
+ "PLW",
113
+ "Q",
114
+ "RUF",
115
+ "S",
116
+ "T",
117
+ "TID",
118
+ "UP",
119
+ "W",
120
+ "YTT",
121
+ ]
122
+ ignore = [
123
+ # Allow non-abstract empty methods in abstract base classes
124
+ "B027",
125
+ # Allow function calls in argument defaults (common Haystack pattern for Secret.from_env_var)
126
+ "B008",
127
+ # Ignore checks for possible passwords
128
+ "S105",
129
+ "S106",
130
+ "S107",
131
+ # Ignore complexity
132
+ "C901",
133
+ "PLR0911",
134
+ "PLR0912",
135
+ "PLR0913",
136
+ "PLR0915",
137
+ "PLR0917",
138
+ # Allow `Any` type - used legitimately for dynamic types and SDK boundaries
139
+ "ANN401",
140
+ ]
141
+
142
+ [tool.ruff.lint.isort]
143
+ known-first-party = ["haystack_integrations"]
144
+
145
+ [tool.ruff.lint.flake8-tidy-imports]
146
+ ban-relative-imports = "parents"
147
+
148
+ [tool.ruff.lint.per-file-ignores]
149
+ # Tests can use magic values, assertions, relative imports, and don't need type annotations
150
+ "tests/**/*" = ["PLR2004", "S101", "TID252", "D", "ANN"]
151
+
152
+ [tool.coverage.run]
153
+ source = ["haystack_integrations"]
154
+ branch = true
155
+ parallel = false
156
+ relative_files = true
157
+
158
+ [tool.coverage.report]
159
+ omit = ["*/tests/*", "*/__init__.py"]
160
+ show_missing = true
161
+ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
162
+
163
+ [tool.pytest.ini_options]
164
+ addopts = "--strict-markers"
165
+ markers = [
166
+ "integration: integration tests",
167
+ ]
168
+ log_cli = true
169
+ asyncio_mode = "auto"
170
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,7 @@
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.youcom.youcom_websearch import YouComError, YouComWebSearch
6
+
7
+ __all__ = ["YouComError", "YouComWebSearch"]
@@ -0,0 +1,283 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+ from typing import Any
7
+
8
+ import httpx
9
+ from haystack import ComponentError, Document, component, logging
10
+ from haystack.utils import Secret
11
+ from haystack.utils.requests_utils import async_request_with_retry, request_with_retry
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ YOUCOM_KEYED_SEARCH_URL = "https://api.you.com/v1/search"
16
+ YOUCOM_KEYLESS_SEARCH_URL = "https://api.you.com/v1/agents/search"
17
+
18
+ API_KEY_ENV_VAR = "YOUDOTCOM_API_KEY"
19
+
20
+ try:
21
+ _VERSION = version("youcom-haystack")
22
+ except PackageNotFoundError: # pragma: no cover
23
+ _VERSION = "0.0.0-dev"
24
+
25
+ USER_AGENT = f"youcom-haystack/{_VERSION} youdotcom-integration/deepset-ai-haystack-core-integrations"
26
+
27
+ _RATE_LIMIT_STATUSES = (402, 429)
28
+ _UPGRADE_HINT = (
29
+ "You.com keyless free-tier limit reached. Set the YOUDOTCOM_API_KEY environment variable "
30
+ "(or pass api_key) for higher limits — get a free API key at https://you.com/platform."
31
+ )
32
+
33
+
34
+ class YouComError(ComponentError):
35
+ """An error occurred while querying the You.com Search API."""
36
+
37
+
38
+ @component
39
+ class YouComWebSearch:
40
+ """
41
+ A component that uses the You.com Search API to search the web and return results as Haystack Documents.
42
+
43
+ Works with zero configuration: when no API key is available, searches use You.com's
44
+ [keyless free tier](https://you.com/docs/api-reference/search/v1-agents-search) (rate limited
45
+ per IP), so getting-started pipelines run without any setup. Set the `YOUDOTCOM_API_KEY`
46
+ environment variable (or pass `api_key`) to use the keyed
47
+ [You.com Search API](https://you.com/docs/api-reference/search/v1-search) with higher limits.
48
+
49
+ Pass `keyless_fallback=False` to require a key and fail fast instead of degrading to the
50
+ keyless tier — useful in production pipelines where a missing key should surface as an error.
51
+
52
+ ### Usage example
53
+
54
+ ```python
55
+ from haystack_integrations.components.websearch.youcom import YouComWebSearch
56
+
57
+ websearch = YouComWebSearch(top_k=5) # no API key needed to get started
58
+ result = websearch.run(query="What is Haystack by deepset?")
59
+ documents = result["documents"]
60
+ links = result["links"]
61
+ ```
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ api_key: Secret = Secret.from_env_var(API_KEY_ENV_VAR, strict=False),
67
+ keyless_fallback: bool = True,
68
+ top_k: int | None = 10,
69
+ freshness: str | None = None,
70
+ country: str | None = None,
71
+ search_lang: str | None = None,
72
+ safesearch: str | None = None,
73
+ extra_params: dict[str, Any] | None = None,
74
+ timeout: int = 10,
75
+ max_retries: int = 3,
76
+ ) -> None:
77
+ """
78
+ Initialize the YouComWebSearch component.
79
+
80
+ :param api_key:
81
+ You.com API key. Defaults to the `YOUDOTCOM_API_KEY` environment variable. Resolved
82
+ leniently, so an unset key is not an error — see `keyless_fallback` for what happens then.
83
+ :param keyless_fallback:
84
+ What to do when no API key resolves. When `True` (the default), search the
85
+ [keyless free tier](https://you.com/docs/api-reference/search/v1-agents-search),
86
+ which needs no credentials but is rate limited per IP; the component logs which
87
+ endpoint it selected. When `False`, raise `YouComError` instead, so a missing key
88
+ fails fast rather than silently degrading.
89
+ :param top_k:
90
+ Maximum number of results to return per section (web, news). Maps to the
91
+ `count` parameter in the You.com API (1-100).
92
+ :param freshness:
93
+ Only return results from within the given window: `"day"`, `"week"`, `"month"`,
94
+ `"year"`, or a date range in the format `"YYYY-MM-DDtoYYYY-MM-DD"`.
95
+ :param country:
96
+ 2-letter country code determining the geographical focus of web results (e.g. `"US"`, `"DE"`).
97
+ :param search_lang:
98
+ Language of the returned web results in BCP 47 format (e.g. `"EN"`, `"PT-BR"`).
99
+ Maps to the `language` parameter in the You.com API.
100
+ :param safesearch:
101
+ Content moderation level: `"off"`, `"moderate"`, or `"strict"`.
102
+ :param extra_params:
103
+ Additional query parameters passed directly to the You.com Search API
104
+ (e.g. `{"include_domains": "nytimes.com,bbc.com"}`).
105
+ :param timeout:
106
+ Timeout in seconds for the HTTP request. Defaults to 10.
107
+ :param max_retries:
108
+ Maximum number of retry attempts on transient failures. Defaults to 3.
109
+ """
110
+ self.api_key = api_key
111
+ self.keyless_fallback = keyless_fallback
112
+ self.top_k = top_k
113
+ self.freshness = freshness
114
+ self.country = country
115
+ self.search_lang = search_lang
116
+ self.safesearch = safesearch
117
+ self.extra_params = extra_params
118
+ self.timeout = timeout
119
+ self.max_retries = max_retries
120
+
121
+ @component.output_types(documents=list[Document], links=list[str])
122
+ def run(
123
+ self,
124
+ query: str,
125
+ top_k: int | None = None,
126
+ ) -> dict[str, Any]:
127
+ """
128
+ Search the web using the You.com Search API and return results as Documents.
129
+
130
+ :param query: Search query string.
131
+ :param top_k:
132
+ Optional per-run override of the maximum number of results.
133
+ If not provided, the init-time `top_k` is used.
134
+ :returns: A dictionary with:
135
+ - `documents`: List of Documents containing search result content.
136
+ - `links`: List of URLs from the search results.
137
+ :raises YouComError: If the You.com Search API request fails.
138
+ """
139
+ url, headers = self._build_request()
140
+ params = self._build_params(query=query, top_k=top_k)
141
+
142
+ try:
143
+ response = request_with_retry(
144
+ attempts=self.max_retries,
145
+ method="GET",
146
+ url=url,
147
+ params=params,
148
+ headers=headers,
149
+ timeout=self.timeout,
150
+ )
151
+ except httpx.HTTPError as error:
152
+ raise YouComError(self._error_message(error, headers)) from error
153
+ return self._parse_response(response.json())
154
+
155
+ @component.output_types(documents=list[Document], links=list[str])
156
+ async def run_async(
157
+ self,
158
+ query: str,
159
+ top_k: int | None = None,
160
+ ) -> dict[str, Any]:
161
+ """
162
+ Asynchronously search the web using the You.com Search API and return results as Documents.
163
+
164
+ :param query: Search query string.
165
+ :param top_k:
166
+ Optional per-run override of the maximum number of results.
167
+ If not provided, the init-time `top_k` is used.
168
+ :returns: A dictionary with:
169
+ - `documents`: List of Documents containing search result content.
170
+ - `links`: List of URLs from the search results.
171
+ :raises YouComError: If the You.com Search API request fails.
172
+ """
173
+ url, headers = self._build_request()
174
+ params = self._build_params(query=query, top_k=top_k)
175
+
176
+ try:
177
+ response = await async_request_with_retry(
178
+ attempts=self.max_retries,
179
+ method="GET",
180
+ url=url,
181
+ params=params,
182
+ headers=headers,
183
+ timeout=self.timeout,
184
+ )
185
+ except httpx.HTTPError as error:
186
+ raise YouComError(self._error_message(error, headers)) from error
187
+ return self._parse_response(response.json())
188
+
189
+ def _build_request(self) -> tuple[str, dict[str, str]]:
190
+ """
191
+ Select the endpoint and headers based on API key availability.
192
+
193
+ With a resolvable API key, requests go to the keyed You.com Search API. Without one,
194
+ requests fall back to the keyless free tier, unless `keyless_fallback` is disabled.
195
+
196
+ :raises YouComError: If no API key resolves and `keyless_fallback` is `False`.
197
+ """
198
+ headers = {
199
+ "Accept": "application/json",
200
+ "User-Agent": USER_AGENT,
201
+ }
202
+ api_key = self.api_key.resolve_value() if self.api_key else None
203
+ if api_key:
204
+ headers["X-API-Key"] = api_key
205
+ return YOUCOM_KEYED_SEARCH_URL, headers
206
+
207
+ if not self.keyless_fallback:
208
+ msg = (
209
+ "No You.com API key resolved and keyless_fallback is disabled. Set the "
210
+ f"{API_KEY_ENV_VAR} environment variable, pass api_key explicitly, "
211
+ "or enable keyless_fallback to use the rate-limited keyless tier."
212
+ )
213
+ raise YouComError(msg)
214
+
215
+ logger.debug(
216
+ "No You.com API key resolved; using the keyless free tier at {url}, which is rate "
217
+ "limited per IP. Set keyless_fallback=False to require a key instead.",
218
+ url=YOUCOM_KEYLESS_SEARCH_URL,
219
+ )
220
+ return YOUCOM_KEYLESS_SEARCH_URL, headers
221
+
222
+ def _build_params(self, query: str, top_k: int | None) -> dict[str, Any]:
223
+ effective_top_k = top_k if top_k is not None else self.top_k
224
+ params: dict[str, Any] = {"query": query}
225
+ if effective_top_k is not None:
226
+ params["count"] = effective_top_k
227
+ if self.freshness is not None:
228
+ params["freshness"] = self.freshness
229
+ if self.country is not None:
230
+ params["country"] = self.country
231
+ if self.search_lang is not None:
232
+ params["language"] = self.search_lang
233
+ if self.safesearch is not None:
234
+ params["safesearch"] = self.safesearch
235
+ if self.extra_params:
236
+ params.update(self.extra_params)
237
+ return params
238
+
239
+ @staticmethod
240
+ def _error_message(error: httpx.HTTPError, headers: dict[str, str]) -> str:
241
+ """
242
+ Build the `YouComError` message, adding upgrade guidance for keyless rate-limit responses.
243
+ """
244
+ message = f"An error occurred while querying the You.com Search API. Error: {error}"
245
+ if not isinstance(error, httpx.HTTPStatusError):
246
+ return message
247
+
248
+ message = f"{message}, Response: {error.response.text}"
249
+ if error.response.status_code in _RATE_LIMIT_STATUSES and "X-API-Key" not in headers:
250
+ message = f"{message} — {_UPGRADE_HINT}"
251
+ return message
252
+
253
+ @staticmethod
254
+ def _parse_response(response: dict[str, Any]) -> dict[str, Any]:
255
+ """
256
+ Convert a You.com Search API response to Haystack Documents and links.
257
+
258
+ Web results come first, then news results. Document content is the joined
259
+ text snippets when available, falling back to the result description.
260
+
261
+ :param response: You.com Search API response dictionary.
262
+ :returns: Dictionary with `documents` and `links` keys.
263
+ """
264
+ documents: list[Document] = []
265
+ links: list[str] = []
266
+
267
+ results = response.get("results", {})
268
+ for section in ("web", "news"):
269
+ for result in results.get(section) or []:
270
+ url = result.get("url", "")
271
+ title = result.get("title", "")
272
+ snippets = result.get("snippets") or []
273
+ content = "\n".join(snippets) if snippets else result.get("description", "")
274
+
275
+ meta: dict[str, Any] = {"title": title, "url": url, "source": section}
276
+ if result.get("page_age"):
277
+ meta["page_age"] = result["page_age"]
278
+
279
+ documents.append(Document(content=content, meta=meta))
280
+ if url:
281
+ links.append(url)
282
+
283
+ return {"documents": documents, "links": links}
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,350 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import os
6
+ from unittest.mock import AsyncMock, MagicMock, patch
7
+
8
+ import httpx
9
+ import pytest
10
+ from haystack import Document
11
+ from haystack.core.serialization import component_from_dict, component_to_dict
12
+ from haystack.utils import Secret
13
+
14
+ from haystack_integrations.components.websearch.youcom import YouComError, YouComWebSearch
15
+ from haystack_integrations.components.websearch.youcom.youcom_websearch import (
16
+ API_KEY_ENV_VAR,
17
+ USER_AGENT,
18
+ YOUCOM_KEYED_SEARCH_URL,
19
+ YOUCOM_KEYLESS_SEARCH_URL,
20
+ )
21
+
22
+ SAMPLE_RESPONSE = {
23
+ "results": {
24
+ "web": [
25
+ {
26
+ "url": "https://haystack.deepset.ai",
27
+ "title": "Haystack | Haystack",
28
+ "description": "Open-source AI framework",
29
+ "snippets": ["Haystack is an open-source framework", "for building production-ready AI pipelines"],
30
+ "page_age": "2026-07-01T00:00:00",
31
+ },
32
+ ],
33
+ "news": [
34
+ {
35
+ "url": "https://example.com/news",
36
+ "title": "AI news item",
37
+ "description": "A news description",
38
+ "page_age": "2026-07-20T00:00:00",
39
+ },
40
+ ],
41
+ },
42
+ "metadata": {"query": "test", "latency": 0.1},
43
+ }
44
+
45
+
46
+ def mock_response(json_body, status_code=200):
47
+ response = MagicMock()
48
+ response.status_code = status_code
49
+ response.json.return_value = json_body
50
+ return response
51
+
52
+
53
+ def _keyed_env():
54
+ """True when the API key env var holds a value, so the keyed live tests can run."""
55
+ return bool(os.environ.get(API_KEY_ENV_VAR))
56
+
57
+
58
+ def http_status_error(status_code, message="Client Error"):
59
+ """Build the `httpx.HTTPStatusError` that `request_with_retry` raises for an error response."""
60
+ request = httpx.Request("GET", YOUCOM_KEYLESS_SEARCH_URL)
61
+ response = httpx.Response(status_code, request=request)
62
+ return httpx.HTTPStatusError(f"{status_code} {message}", request=request, response=response)
63
+
64
+
65
+ class TestYouComWebSearch:
66
+ @pytest.fixture(autouse=True)
67
+ def clean_env(self, monkeypatch):
68
+ monkeypatch.delenv(API_KEY_ENV_VAR, raising=False)
69
+
70
+ def test_init_defaults(self):
71
+ component = YouComWebSearch()
72
+ assert component.api_key == Secret.from_env_var(API_KEY_ENV_VAR, strict=False)
73
+ assert component.keyless_fallback is True
74
+ assert component.top_k == 10
75
+ assert component.freshness is None
76
+ assert component.country is None
77
+ assert component.search_lang is None
78
+ assert component.safesearch is None
79
+ assert component.extra_params is None
80
+ assert component.timeout == 10
81
+ assert component.max_retries == 3
82
+
83
+ def test_init_without_env_var_does_not_raise(self):
84
+ component = YouComWebSearch()
85
+ assert component.api_key.resolve_value() is None
86
+
87
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
88
+ def test_run_keyless_when_no_api_key(self, mock_request):
89
+ mock_request.return_value = mock_response(SAMPLE_RESPONSE)
90
+
91
+ component = YouComWebSearch()
92
+ component.run(query="test")
93
+
94
+ kwargs = mock_request.call_args.kwargs
95
+ assert kwargs["url"] == YOUCOM_KEYLESS_SEARCH_URL
96
+ assert "X-API-Key" not in kwargs["headers"]
97
+
98
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
99
+ def test_run_keyed_when_env_var_set(self, mock_request, monkeypatch):
100
+ monkeypatch.setenv("YOUDOTCOM_API_KEY", "env-key")
101
+ mock_request.return_value = mock_response(SAMPLE_RESPONSE)
102
+
103
+ component = YouComWebSearch()
104
+ component.run(query="test")
105
+
106
+ kwargs = mock_request.call_args.kwargs
107
+ assert kwargs["url"] == YOUCOM_KEYED_SEARCH_URL
108
+ assert kwargs["headers"]["X-API-Key"] == "env-key"
109
+
110
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
111
+ def test_keyless_fallback_disabled_raises_without_key(self, mock_request):
112
+ component = YouComWebSearch(keyless_fallback=False)
113
+
114
+ with pytest.raises(YouComError, match="keyless_fallback"):
115
+ component.run(query="test")
116
+ mock_request.assert_not_called()
117
+
118
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
119
+ def test_keyless_fallback_disabled_still_searches_with_key(self, mock_request, monkeypatch):
120
+ monkeypatch.setenv("YOUDOTCOM_API_KEY", "env-key")
121
+ mock_request.return_value = mock_response(SAMPLE_RESPONSE)
122
+
123
+ component = YouComWebSearch(keyless_fallback=False)
124
+ component.run(query="test")
125
+
126
+ assert mock_request.call_args.kwargs["url"] == YOUCOM_KEYED_SEARCH_URL
127
+
128
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.async_request_with_retry")
129
+ async def test_keyless_fallback_disabled_raises_without_key_async(self, mock_request):
130
+ component = YouComWebSearch(keyless_fallback=False)
131
+
132
+ with pytest.raises(YouComError, match="keyless_fallback"):
133
+ await component.run_async(query="test")
134
+ mock_request.assert_not_called()
135
+
136
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
137
+ def test_run_keyed_with_explicit_token(self, mock_request):
138
+ mock_request.return_value = mock_response(SAMPLE_RESPONSE)
139
+
140
+ component = YouComWebSearch(api_key=Secret.from_token("explicit-key"))
141
+ component.run(query="test")
142
+
143
+ kwargs = mock_request.call_args.kwargs
144
+ assert kwargs["url"] == YOUCOM_KEYED_SEARCH_URL
145
+ assert kwargs["headers"]["X-API-Key"] == "explicit-key"
146
+
147
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
148
+ def test_run_sends_user_agent(self, mock_request):
149
+ mock_request.return_value = mock_response(SAMPLE_RESPONSE)
150
+
151
+ component = YouComWebSearch()
152
+ component.run(query="test")
153
+
154
+ headers = mock_request.call_args.kwargs["headers"]
155
+ assert headers["User-Agent"] == USER_AGENT
156
+ assert USER_AGENT.startswith("youcom-haystack/")
157
+ assert USER_AGENT.endswith(" youdotcom-integration/deepset-ai-haystack-core-integrations")
158
+
159
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
160
+ def test_run_builds_params(self, mock_request):
161
+ mock_request.return_value = mock_response(SAMPLE_RESPONSE)
162
+
163
+ component = YouComWebSearch(
164
+ top_k=5,
165
+ freshness="week",
166
+ country="US",
167
+ search_lang="EN",
168
+ safesearch="moderate",
169
+ extra_params={"include_domains": "nytimes.com,bbc.com"},
170
+ )
171
+ component.run(query="climate news")
172
+
173
+ params = mock_request.call_args.kwargs["params"]
174
+ assert params == {
175
+ "query": "climate news",
176
+ "count": 5,
177
+ "freshness": "week",
178
+ "country": "US",
179
+ "language": "EN",
180
+ "safesearch": "moderate",
181
+ "include_domains": "nytimes.com,bbc.com",
182
+ }
183
+
184
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
185
+ def test_run_top_k_override(self, mock_request):
186
+ mock_request.return_value = mock_response(SAMPLE_RESPONSE)
187
+
188
+ component = YouComWebSearch(top_k=10)
189
+ component.run(query="q", top_k=3)
190
+
191
+ assert mock_request.call_args.kwargs["params"]["count"] == 3
192
+
193
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
194
+ def test_run_parses_documents_and_links(self, mock_request):
195
+ mock_request.return_value = mock_response(SAMPLE_RESPONSE)
196
+
197
+ component = YouComWebSearch()
198
+ result = component.run(query="test")
199
+
200
+ documents = result["documents"]
201
+ links = result["links"]
202
+ assert len(documents) == 2
203
+ assert all(isinstance(doc, Document) for doc in documents)
204
+
205
+ web_doc = documents[0]
206
+ assert web_doc.content == "Haystack is an open-source framework\nfor building production-ready AI pipelines"
207
+ assert web_doc.meta == {
208
+ "title": "Haystack | Haystack",
209
+ "url": "https://haystack.deepset.ai",
210
+ "source": "web",
211
+ "page_age": "2026-07-01T00:00:00",
212
+ }
213
+
214
+ news_doc = documents[1]
215
+ assert news_doc.content == "A news description"
216
+ assert news_doc.meta["source"] == "news"
217
+
218
+ assert links == ["https://haystack.deepset.ai", "https://example.com/news"]
219
+
220
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
221
+ def test_run_empty_results(self, mock_request):
222
+ mock_request.return_value = mock_response({"results": {"web": [], "news": []}})
223
+
224
+ component = YouComWebSearch()
225
+ result = component.run(query="test")
226
+
227
+ assert result == {"documents": [], "links": []}
228
+
229
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
230
+ def test_run_missing_sections(self, mock_request):
231
+ mock_request.return_value = mock_response({"metadata": {}})
232
+
233
+ component = YouComWebSearch()
234
+ result = component.run(query="test")
235
+
236
+ assert result == {"documents": [], "links": []}
237
+
238
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
239
+ def test_run_null_sections(self, mock_request):
240
+ mock_request.return_value = mock_response({"results": {"web": None, "news": None}})
241
+
242
+ component = YouComWebSearch()
243
+ result = component.run(query="test")
244
+
245
+ assert result == {"documents": [], "links": []}
246
+
247
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
248
+ def test_keyless_rate_limit_error_includes_upgrade_hint(self, mock_request):
249
+ mock_request.side_effect = http_status_error(402)
250
+
251
+ component = YouComWebSearch()
252
+ with pytest.raises(YouComError, match="YOUDOTCOM_API_KEY"):
253
+ component.run(query="test")
254
+
255
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
256
+ def test_keyed_error_is_not_rewritten(self, mock_request):
257
+ mock_request.side_effect = http_status_error(401, "Unauthorized")
258
+
259
+ component = YouComWebSearch(api_key=Secret.from_token("bad-key"))
260
+ with pytest.raises(YouComError, match="401") as excinfo:
261
+ component.run(query="test")
262
+ assert "YOUDOTCOM_API_KEY" not in str(excinfo.value)
263
+
264
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.request_with_retry")
265
+ def test_network_error_is_wrapped(self, mock_request):
266
+ """Transport-level failures have no response, so they are reported without one."""
267
+ mock_request.side_effect = httpx.ConnectError("connection refused")
268
+
269
+ component = YouComWebSearch()
270
+ with pytest.raises(YouComError, match="connection refused") as excinfo:
271
+ component.run(query="test")
272
+ assert "Response:" not in str(excinfo.value)
273
+ assert isinstance(excinfo.value.__cause__, httpx.ConnectError)
274
+
275
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.async_request_with_retry")
276
+ async def test_run_async(self, mock_request):
277
+ mock_request.side_effect = AsyncMock(return_value=mock_response(SAMPLE_RESPONSE))
278
+
279
+ component = YouComWebSearch()
280
+ result = await component.run_async(query="test")
281
+
282
+ assert len(result["documents"]) == 2
283
+ assert mock_request.call_args.kwargs["url"] == YOUCOM_KEYLESS_SEARCH_URL
284
+
285
+ @patch("haystack_integrations.components.websearch.youcom.youcom_websearch.async_request_with_retry")
286
+ async def test_run_async_keyless_rate_limit_error_includes_upgrade_hint(self, mock_request):
287
+ mock_request.side_effect = AsyncMock(side_effect=http_status_error(429, "Too Many Requests"))
288
+
289
+ component = YouComWebSearch()
290
+ with pytest.raises(YouComError, match="YOUDOTCOM_API_KEY"):
291
+ await component.run_async(query="test")
292
+
293
+ def test_serialization_roundtrip_without_env_var(self):
294
+ component = YouComWebSearch(top_k=7, freshness="month", keyless_fallback=False)
295
+ data = component_to_dict(component, name="websearch")
296
+ restored = component_from_dict(YouComWebSearch, data, name="websearch")
297
+
298
+ assert data["init_parameters"]["keyless_fallback"] is False
299
+ assert restored.top_k == 7
300
+ assert restored.freshness == "month"
301
+ assert restored.keyless_fallback is False
302
+ assert restored.api_key == Secret.from_env_var(API_KEY_ENV_VAR, strict=False)
303
+
304
+ def test_serialization_roundtrip_with_env_var(self, monkeypatch):
305
+ monkeypatch.setenv("YOUDOTCOM_API_KEY", "env-key")
306
+ component = YouComWebSearch()
307
+ data = component_to_dict(component, name="websearch")
308
+ restored = component_from_dict(YouComWebSearch, data, name="websearch")
309
+
310
+ assert restored.api_key.resolve_value() == "env-key"
311
+
312
+ def test_serialization_does_not_leak_token_secret(self):
313
+ component = YouComWebSearch(api_key=Secret.from_token("super-secret"))
314
+ with pytest.raises(ValueError, match="Cannot serialize token-based secret"):
315
+ component_to_dict(component, name="websearch")
316
+
317
+
318
+ @pytest.mark.integration
319
+ class TestYouComWebSearchIntegration:
320
+ def test_keyless_live_search(self, monkeypatch):
321
+ """The keyless free tier is rate limited per IP, so a shared CI runner may legitimately hit the limit."""
322
+ monkeypatch.delenv(API_KEY_ENV_VAR, raising=False)
323
+ component = YouComWebSearch(top_k=2)
324
+ try:
325
+ result = component.run(query="What is Haystack by deepset?")
326
+ except YouComError as error:
327
+ cause = error.__cause__
328
+ status = cause.response.status_code if isinstance(cause, httpx.HTTPStatusError) else None
329
+ if status in (402, 429):
330
+ pytest.skip(f"keyless free-tier rate limit hit: {status}")
331
+ raise
332
+
333
+ assert len(result["documents"]) > 0
334
+ assert len(result["links"]) > 0
335
+ assert result["documents"][0].content
336
+
337
+ @pytest.mark.skipif(not _keyed_env(), reason="no You.com API key in the environment")
338
+ def test_keyed_live_search(self):
339
+ component = YouComWebSearch(top_k=2)
340
+ result = component.run(query="What is Haystack by deepset?")
341
+
342
+ assert len(result["documents"]) > 0
343
+ assert len(result["links"]) > 0
344
+
345
+ @pytest.mark.skipif(not _keyed_env(), reason="no You.com API key in the environment")
346
+ async def test_keyed_live_search_async(self):
347
+ component = YouComWebSearch(top_k=2)
348
+ result = await component.run_async(query="What is Haystack by deepset?")
349
+
350
+ assert len(result["documents"]) > 0