google-drive-haystack 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: google-drive-haystack
3
+ Version: 1.0.0
4
+ Summary: Haystack integration for google_drive
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/google_drive#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/google_drive
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Keywords: drive,google,haystack,retriever
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
24
+ Requires-Dist: httpx>=0.28.0
25
+ Requires-Dist: tenacity>=8.2.3
26
+ Description-Content-Type: text/markdown
27
+
28
+ # google-drive-haystack
29
+
30
+ [![PyPI - Version](https://img.shields.io/pypi/v/google-drive-haystack.svg)](https://pypi.org/project/google-drive-haystack)
31
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/google-drive-haystack.svg)](https://pypi.org/project/google-drive-haystack)
32
+
33
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/google_drive/CHANGELOG.md)
34
+
35
+ ---
36
+
37
+ ## Contributing
38
+
39
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,8 @@
1
+ haystack_integrations/components/retrievers/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ haystack_integrations/components/retrievers/google_drive/__init__.py,sha256=xRiZoC0xfhhuMJCy9P8tz55E_Ou0VGOnhFnckI5rw5I,368
3
+ haystack_integrations/components/retrievers/google_drive/errors.py,sha256=hWMYJTnuer1la1_Vw792qqypjHTm8WEujA_7Shibj1k,595
4
+ haystack_integrations/components/retrievers/google_drive/retriever.py,sha256=8VkVcIdHc0x136GZieZx1hDDA1mGNDrcVLCiFOSS1tQ,22637
5
+ google_drive_haystack-1.0.0.dist-info/METADATA,sha256=XDjA8N1JOcdTG13Kv7fjA55tQFubA6MvRS--Hd37iiA,1848
6
+ google_drive_haystack-1.0.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
7
+ google_drive_haystack-1.0.0.dist-info/licenses/LICENSE.txt,sha256=OrAtTu4aPmrTjKDSTzkSPgo_ji6NOMWO2N9JOTFyAzM,11350
8
+ google_drive_haystack-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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,12 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ from .errors import GoogleDriveConfigError, GoogleDriveError, GoogleDriveRequestError
5
+ from .retriever import GoogleDriveRetriever
6
+
7
+ __all__ = [
8
+ "GoogleDriveConfigError",
9
+ "GoogleDriveError",
10
+ "GoogleDriveRequestError",
11
+ "GoogleDriveRetriever",
12
+ ]
@@ -0,0 +1,19 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+
6
+ class GoogleDriveError(Exception):
7
+ """Base class for errors raised by the Google Drive integration."""
8
+
9
+
10
+ class GoogleDriveConfigError(GoogleDriveError):
11
+ """Raised when the Google Drive retriever is misconfigured."""
12
+
13
+
14
+ class GoogleDriveRequestError(GoogleDriveError):
15
+ """Raised when a Google Drive API request fails."""
16
+
17
+ def __init__(self, message: str, status_code: int | None = None) -> None:
18
+ super().__init__(message)
19
+ self.status_code = status_code
@@ -0,0 +1,499 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ import httpx
9
+ from haystack import Document, component, default_from_dict, default_to_dict, logging
10
+ from haystack.utils import Secret
11
+ from tenacity import AsyncRetrying, RetryCallState, Retrying, retry_if_result, stop_after_attempt, wait_exponential
12
+
13
+ from .errors import GoogleDriveConfigError, GoogleDriveRequestError
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ _DEFAULT_API_BASE_URL = "https://www.googleapis.com/drive/v3"
18
+ # The Drive `files.list` endpoint caps a single page at 1000 results; larger `top_k` values are paginated.
19
+ _MAX_PAGE_SIZE = 1000
20
+ _RETRYABLE_STATUS = frozenset({429, 500, 502, 503, 504})
21
+ # Fallback backoff when a throttled response carries no `Retry-After` header: 1s, 2s, 4s, ...
22
+ _EXPONENTIAL_BACKOFF = wait_exponential()
23
+
24
+ # The file properties requested via the Drive `fields` selection.
25
+ _DEFAULT_FILE_FIELDS = (
26
+ "id",
27
+ "name",
28
+ "mimeType",
29
+ "webViewLink",
30
+ "description",
31
+ "fileExtension",
32
+ "createdTime",
33
+ "modifiedTime",
34
+ "owners(displayName)",
35
+ "lastModifyingUser(displayName)",
36
+ )
37
+
38
+ # The mime types that support content exporting: application/vnd.google-apps.*
39
+ _EXPORT_MIME_TYPES = {
40
+ "application/vnd.google-apps.document": "text/plain",
41
+ "application/vnd.google-apps.spreadsheet": "text/csv",
42
+ "application/vnd.google-apps.presentation": "text/plain",
43
+ }
44
+
45
+
46
+ def _retry_response(retry_state: RetryCallState) -> httpx.Response | None:
47
+ """Return the `httpx.Response` recorded for a retry attempt, or `None` if the attempt raised."""
48
+ outcome = retry_state.outcome
49
+ if outcome is None or outcome.failed:
50
+ return None
51
+ return outcome.result()
52
+
53
+
54
+ def _is_retryable_response(response: httpx.Response) -> bool:
55
+ """Return whether a Google Drive API response should trigger a retry."""
56
+ return response.status_code in _RETRYABLE_STATUS
57
+
58
+
59
+ def _wait_with_retry_after(retry_state: RetryCallState) -> float:
60
+ """Wait strategy honoring a numeric `Retry-After` header, falling back to exponential backoff."""
61
+ response = _retry_response(retry_state)
62
+ if response is not None:
63
+ retry_after = response.headers.get("Retry-After")
64
+ if retry_after:
65
+ try:
66
+ return float(retry_after)
67
+ except ValueError:
68
+ pass
69
+
70
+ return _EXPONENTIAL_BACKOFF(retry_state)
71
+
72
+
73
+ def _last_response(retry_state: RetryCallState) -> httpx.Response:
74
+ """Return the final response once retries are exhausted, so the caller can raise a typed error."""
75
+ response = _retry_response(retry_state)
76
+ if response is None:
77
+ msg = "Google Drive API retries were exhausted without a recorded response."
78
+ raise GoogleDriveRequestError(msg)
79
+ return response
80
+
81
+
82
+ def _log_retry(retry_state: RetryCallState) -> None:
83
+ """Log a warning before sleeping between Google Drive API retries."""
84
+ response = _retry_response(retry_state)
85
+ next_action = retry_state.next_action
86
+ if response is None or next_action is None:
87
+ return
88
+ logger.warning(
89
+ "Google Drive API returned status {status}; retrying in {delay}s (attempt {attempt}).",
90
+ status=response.status_code,
91
+ delay=next_action.sleep,
92
+ attempt=retry_state.attempt_number,
93
+ )
94
+
95
+
96
+ @component
97
+ class GoogleDriveRetriever:
98
+ """
99
+ Retrieves files from Google Drive via the Drive API v3 search (`files.list`) endpoint.
100
+
101
+ Given a query, the retriever runs a full-text search over the user's Drive (and optionally shared
102
+ drives) and maps each matching file to a Haystack `Document`. By default, each `Document` carries
103
+ resource metadata (`file_name`, `file_id`, `web_url`, `mime_type`, `file_extension`, author, and
104
+ timestamps) and uses the file `description` or `name` as `content`, because the Drive search API does
105
+ not return a text snippet. Set `include_content=True` to additionally export native Google
106
+ Docs/Sheets/Slides to text and use that as the `Document` content. Binary files (PDF, DOCX, ...) are
107
+ never downloaded. Compose a downstream fetcher/converter on the returned `web_url`/`file_id` when full
108
+ file content is needed.
109
+
110
+ The retriever takes a per-user `access_token` as a run input, typically wired from an upstream
111
+ `OAuthResolver`. The token must carry a delegated Google OAuth scope that allows search
112
+ (for example `https://www.googleapis.com/auth/drive.readonly`). The metadata-only
113
+ `drive.metadata.readonly` scope cannot search file content or export documents.
114
+
115
+ ### Usage example
116
+ ```python
117
+ from haystack import Pipeline
118
+ from haystack.utils import Secret
119
+ from haystack_integrations.components.connectors.oauth import OAuthResolver
120
+ from haystack_integrations.utils.oauth import RefreshTokenSource
121
+ from haystack_integrations.components.retrievers.google_drive import GoogleDriveRetriever
122
+
123
+ pipeline = Pipeline()
124
+ pipeline.add_component(
125
+ "resolver",
126
+ OAuthResolver(
127
+ token_source=RefreshTokenSource(
128
+ token_url="https://oauth2.googleapis.com/token",
129
+ client_id="aaa-bbb-ccc",
130
+ refresh_token=Secret.from_env_var("GOOGLE_REFRESH_TOKEN"),
131
+ scopes=["https://www.googleapis.com/auth/drive.readonly"],
132
+ ),
133
+ ),
134
+ )
135
+ pipeline.add_component("retriever", GoogleDriveRetriever(top_k=5))
136
+ pipeline.connect("resolver.access_token", "retriever.access_token")
137
+
138
+ result = pipeline.run({"retriever": {"query": "quarterly roadmap"}})
139
+ documents = result["retriever"]["documents"]
140
+ ```
141
+ """
142
+
143
+ def __init__(
144
+ self,
145
+ *,
146
+ include_content: bool = False,
147
+ top_k: int = 10,
148
+ query_filter: str | None = None,
149
+ include_shared_drives: bool = False,
150
+ order_by: str | None = None,
151
+ fields: list[str] | None = None,
152
+ api_base_url: str = _DEFAULT_API_BASE_URL,
153
+ timeout: float = 30.0,
154
+ max_retries: int = 3,
155
+ ) -> None:
156
+ """
157
+ Initialize the retriever.
158
+
159
+ :param include_content: When `True`, native Google Docs/Sheets/Slides are exported to text and the
160
+ result becomes the `Document` content. Binary files are never downloaded. When `False` (the
161
+ default), `content` is the file `description` or `name` and no export request is made.
162
+ :param top_k: The maximum number of documents to return. Maps to the Drive `pageSize` and is
163
+ paginated when it exceeds a single page.
164
+ :param query_filter: Optional Drive query clause AND-ed with the full-text search term, for example
165
+ `"mimeType != 'application/vnd.google-apps.folder'"` or `"'<folderId>' in parents"`.
166
+ :param include_shared_drives: When `True`, the search spans shared drives as well as the user's My
167
+ Drive (sets `includeItemsFromAllDrives`, `supportsAllDrives`, and `corpora=allDrives`).
168
+ :param order_by: Optional Drive `orderBy` expression, for example `"modifiedTime desc"`.
169
+ :param fields: Optional list of file properties to request via the Drive `fields` selection.
170
+ Defaults to a standard set covering the returned metadata.
171
+ :param api_base_url: The Drive API base URL. Defaults to `https://www.googleapis.com/drive/v3`.
172
+ :param timeout: The HTTP timeout in seconds for each request to the Drive API.
173
+ :param max_retries: The maximum number of retries on HTTP 429 (rate limit), 500, 502, 503,
174
+ or 504 responses. Set to 0 to disable retries.
175
+ :raises GoogleDriveConfigError: If `top_k` is not positive or `max_retries` is negative.
176
+ """
177
+ if top_k <= 0:
178
+ msg = "top_k must be a positive integer."
179
+ raise GoogleDriveConfigError(msg)
180
+ if max_retries < 0:
181
+ msg = "max_retries must be zero or a positive integer."
182
+ raise GoogleDriveConfigError(msg)
183
+
184
+ self.include_content = include_content
185
+ self.top_k = top_k
186
+ self.query_filter = query_filter
187
+ self.include_shared_drives = include_shared_drives
188
+ self.order_by = order_by
189
+ self.fields = fields
190
+ self.api_base_url = api_base_url.rstrip("/")
191
+ self.timeout = timeout
192
+ self.max_retries = max_retries
193
+
194
+ @component.output_types(documents=list[Document])
195
+ def run(self, query: str, access_token: str | Secret, top_k: int | None = None) -> dict[str, list[Document]]:
196
+ """
197
+ Search Google Drive and return the matching documents.
198
+
199
+ :param query: The search query string, matched against the full text of files via
200
+ `fullText contains`.
201
+ :param access_token: A delegated Google OAuth bearer token for the user whose Drive is searched,
202
+ typically wired from an upstream `OAuthResolver` (which emits a plain `str`). A `Secret` is also
203
+ accepted and resolved internally.
204
+ :param top_k: Overrides the `top_k` configured at initialization for this run.
205
+ :returns: A dictionary with a `documents` key holding the list of retrieved `Document` objects.
206
+ :raises GoogleDriveConfigError: If `access_token` is a `Secret` that does not resolve to a string.
207
+ :raises GoogleDriveRequestError: If the Drive API returns an error response.
208
+ :raises httpx.HTTPError: If a network-level error occurs (for example a timeout or connection failure).
209
+ """
210
+ token = self._resolve_access_token(access_token)
211
+ limit = top_k or self.top_k
212
+ documents: list[Document] = []
213
+ page_token: str | None = None
214
+ with httpx.Client(timeout=self.timeout) as client:
215
+ while len(documents) < limit:
216
+ size = min(_MAX_PAGE_SIZE, limit - len(documents))
217
+ params = self._build_params(query, page_token, size)
218
+ payload = self._get(client, token, params)
219
+ files = payload.get("files") or []
220
+ for file in files:
221
+ content = self._content_for(client, token, file)
222
+ documents.append(self._file_to_document(file, content))
223
+ page_token = payload.get("nextPageToken")
224
+ if not files or not page_token:
225
+ break
226
+
227
+ return {"documents": documents[:limit]}
228
+
229
+ @component.output_types(documents=list[Document])
230
+ async def run_async(
231
+ self, query: str, access_token: str | Secret, top_k: int | None = None
232
+ ) -> dict[str, list[Document]]:
233
+ """
234
+ Asynchronously search Google Drive and return the matching documents.
235
+
236
+ :param query: The search query string, matched against the full text of files via
237
+ `fullText contains`.
238
+ :param access_token: A delegated Google OAuth bearer token for the user whose Drive is searched,
239
+ typically wired from an upstream `OAuthResolver` (which emits a plain `str`). A `Secret` is also
240
+ accepted and resolved internally.
241
+ :param top_k: Overrides the `top_k` configured at initialization for this run.
242
+ :returns: A dictionary with a `documents` key holding the list of retrieved `Document` objects.
243
+ :raises GoogleDriveConfigError: If `access_token` is a `Secret` that does not resolve to a string.
244
+ :raises GoogleDriveRequestError: If the Drive API returns an error response.
245
+ :raises httpx.HTTPError: If a network-level error occurs (for example a timeout or connection failure).
246
+ """
247
+ token = self._resolve_access_token(access_token)
248
+ limit = top_k or self.top_k
249
+ documents: list[Document] = []
250
+ page_token: str | None = None
251
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
252
+ while len(documents) < limit:
253
+ size = min(_MAX_PAGE_SIZE, limit - len(documents))
254
+ params = self._build_params(query, page_token, size)
255
+ payload = await self._get_async(client, token, params)
256
+ files = payload.get("files") or []
257
+ for file in files:
258
+ content = await self._content_for_async(client, token, file)
259
+ documents.append(self._file_to_document(file, content))
260
+ page_token = payload.get("nextPageToken")
261
+ if not files or not page_token:
262
+ break
263
+
264
+ return {"documents": documents[:limit]}
265
+
266
+ @staticmethod
267
+ def _resolve_access_token(access_token: str | Secret) -> str:
268
+ """Return the bearer token string, resolving it if a `Secret` was passed."""
269
+ if not isinstance(access_token, Secret):
270
+ return access_token
271
+ resolved = access_token.resolve_value()
272
+ if not isinstance(resolved, str):
273
+ msg = "The access_token Secret did not resolve to a string value."
274
+ raise GoogleDriveConfigError(msg)
275
+ return resolved
276
+
277
+ def _build_params(self, query: str, page_token: str | None, size: int) -> dict[str, Any]:
278
+ """Build the Drive `files.list` query parameters for one page."""
279
+ q = f"fullText contains '{self._escape_query(query)}'"
280
+ if self.query_filter:
281
+ q = f"{q} and ({self.query_filter})"
282
+ fields = tuple(self.fields) if self.fields else _DEFAULT_FILE_FIELDS
283
+ params: dict[str, Any] = {
284
+ "q": q,
285
+ "pageSize": size,
286
+ "fields": f"nextPageToken, files({', '.join(fields)})",
287
+ }
288
+ if page_token:
289
+ params["pageToken"] = page_token
290
+ if self.order_by:
291
+ params["orderBy"] = self.order_by
292
+ if self.include_shared_drives:
293
+ params["includeItemsFromAllDrives"] = True
294
+ params["supportsAllDrives"] = True
295
+ params["corpora"] = "allDrives"
296
+
297
+ return params
298
+
299
+ @staticmethod
300
+ def _escape_query(query: str) -> str:
301
+ """Escape backslashes and single quotes so the query is safe inside a Drive `q` string literal."""
302
+ return query.replace("\\", "\\\\").replace("'", "\\'")
303
+
304
+ def _content_for(self, client: httpx.Client, access_token: str, file: dict[str, Any]) -> str | None:
305
+ """Return the exported text for a native Google file when `include_content` is set, else `None`."""
306
+ if not self.include_content:
307
+ return None
308
+ mime_type = file.get("mimeType")
309
+ file_id = file.get("id")
310
+ if not mime_type or not file_id:
311
+ return None
312
+ export_mime = _EXPORT_MIME_TYPES.get(mime_type)
313
+ if not export_mime:
314
+ return None
315
+ return self._export_content(client, access_token, file_id, export_mime)
316
+
317
+ async def _content_for_async(
318
+ self, client: httpx.AsyncClient, access_token: str, file: dict[str, Any]
319
+ ) -> str | None:
320
+ """Async variant of `_content_for`."""
321
+ if not self.include_content:
322
+ return None
323
+ mime_type = file.get("mimeType")
324
+ file_id = file.get("id")
325
+ if not mime_type or not file_id:
326
+ return None
327
+ export_mime = _EXPORT_MIME_TYPES.get(mime_type)
328
+ if not export_mime:
329
+ return None
330
+ return await self._export_content_async(client, access_token, file_id, export_mime)
331
+
332
+ def _export_content(self, client: httpx.Client, access_token: str, file_id: str, export_mime: str) -> str | None:
333
+ """Export a native Google file to text. On any failure, log a warning and return `None`."""
334
+ url = f"{self.api_base_url}/files/{file_id}/export"
335
+ headers = {"Authorization": f"Bearer {access_token}"}
336
+ try:
337
+ response = client.get(url, headers=headers, params={"mimeType": export_mime})
338
+ except httpx.HTTPError as error:
339
+ logger.warning(
340
+ "Could not export Google Drive file {file_id} as {export_mime}: {error}. "
341
+ "Falling back to metadata content.",
342
+ file_id=file_id,
343
+ export_mime=export_mime,
344
+ error=str(error),
345
+ )
346
+ return None
347
+ if response.is_error:
348
+ logger.warning(
349
+ "Could not export Google Drive file {file_id} as {export_mime} (status {status}). "
350
+ "Falling back to metadata content.",
351
+ file_id=file_id,
352
+ export_mime=export_mime,
353
+ status=response.status_code,
354
+ )
355
+ return None
356
+
357
+ return response.text
358
+
359
+ async def _export_content_async(
360
+ self, client: httpx.AsyncClient, access_token: str, file_id: str, export_mime: str
361
+ ) -> str | None:
362
+ """Async variant of `_export_content`."""
363
+ url = f"{self.api_base_url}/files/{file_id}/export"
364
+ headers = {"Authorization": f"Bearer {access_token}"}
365
+ try:
366
+ response = await client.get(url, headers=headers, params={"mimeType": export_mime})
367
+ except httpx.HTTPError as error:
368
+ logger.warning(
369
+ "Could not export Google Drive file {file_id} as {export_mime}: {error}. "
370
+ "Falling back to metadata content.",
371
+ file_id=file_id,
372
+ export_mime=export_mime,
373
+ error=str(error),
374
+ )
375
+ return None
376
+ if response.is_error:
377
+ logger.warning(
378
+ "Could not export Google Drive file {file_id} as {export_mime} (status {status}). "
379
+ "Falling back to metadata content.",
380
+ file_id=file_id,
381
+ export_mime=export_mime,
382
+ status=response.status_code,
383
+ )
384
+ return None
385
+
386
+ return response.text
387
+
388
+ def _get(self, client: httpx.Client, access_token: str, params: dict[str, Any]) -> dict[str, Any]:
389
+ """Send a `files.list` request, retrying on throttling/transient errors, and return the parsed JSON."""
390
+ url = f"{self.api_base_url}/files"
391
+ headers = {"Authorization": f"Bearer {access_token}"}
392
+ retrying = Retrying(
393
+ stop=stop_after_attempt(self.max_retries + 1),
394
+ wait=_wait_with_retry_after,
395
+ retry=retry_if_result(_is_retryable_response),
396
+ before_sleep=_log_retry,
397
+ retry_error_callback=_last_response,
398
+ )
399
+ response: httpx.Response = retrying(client.get, url, headers=headers, params=params)
400
+
401
+ return self._parse_response(response)
402
+
403
+ async def _get_async(self, client: httpx.AsyncClient, access_token: str, params: dict[str, Any]) -> dict[str, Any]:
404
+ """Async variant of `_get`."""
405
+ url = f"{self.api_base_url}/files"
406
+ headers = {"Authorization": f"Bearer {access_token}"}
407
+ retrying = AsyncRetrying(
408
+ stop=stop_after_attempt(self.max_retries + 1),
409
+ wait=_wait_with_retry_after,
410
+ retry=retry_if_result(_is_retryable_response),
411
+ before_sleep=_log_retry,
412
+ retry_error_callback=_last_response,
413
+ )
414
+ response: httpx.Response = await retrying(client.get, url, headers=headers, params=params)
415
+
416
+ return self._parse_response(response)
417
+
418
+ @staticmethod
419
+ def _parse_response(response: httpx.Response) -> dict[str, Any]:
420
+ """Return the parsed JSON for a successful response, or raise a descriptive error."""
421
+ if not response.is_error:
422
+ return response.json()
423
+
424
+ status = response.status_code
425
+ if status == httpx.codes.UNAUTHORIZED:
426
+ msg = (
427
+ "Google Drive rejected the access token (401 Unauthorized). The token may be expired, invalid, "
428
+ "or missing a required scope (for example https://www.googleapis.com/auth/drive.readonly). The "
429
+ "metadata-only drive.metadata.readonly scope cannot search file content or export documents."
430
+ )
431
+ elif status == httpx.codes.FORBIDDEN:
432
+ msg = f"Google Drive denied the request (403 Forbidden): {response.text}"
433
+ else:
434
+ msg = f"Google Drive API request failed with status {status}: {response.text}"
435
+
436
+ raise GoogleDriveRequestError(msg, status_code=status)
437
+
438
+ @staticmethod
439
+ def _display_name(identity: dict[str, Any] | None) -> str | None:
440
+ """Extract the display name from a Drive user object (`owners[i]` / `lastModifyingUser`), if present."""
441
+ if not identity:
442
+ return None
443
+ return identity.get("displayName")
444
+
445
+ @staticmethod
446
+ def _file_to_document(file: dict[str, Any], content: str | None = None) -> Document:
447
+ """Map a single Drive file resource to a Haystack Document (content + resource metadata)."""
448
+ name = file.get("name")
449
+ text = content or file.get("description") or name or ""
450
+
451
+ # Drive usually returns `fileExtension`; derive it from the name when absent (e.g. native Google docs).
452
+ extension = file.get("fileExtension")
453
+ if not extension and name:
454
+ extension = os.path.splitext(name)[1].lstrip(".").lower() or None
455
+
456
+ owners = file.get("owners") or []
457
+ created_by = GoogleDriveRetriever._display_name(owners[0]) if owners else None
458
+
459
+ meta = {
460
+ "file_name": name,
461
+ "file_id": file.get("id"),
462
+ "web_url": file.get("webViewLink"),
463
+ "mime_type": file.get("mimeType"),
464
+ "file_extension": extension,
465
+ "created_date_time": file.get("createdTime"),
466
+ "last_modified_date_time": file.get("modifiedTime"),
467
+ "created_by": created_by,
468
+ "last_modified_by": GoogleDriveRetriever._display_name(file.get("lastModifyingUser")),
469
+ }
470
+ return Document(content=text, meta={key: value for key, value in meta.items() if value is not None})
471
+
472
+ def to_dict(self) -> dict[str, Any]:
473
+ """
474
+ Serialize this component to a dictionary.
475
+
476
+ :returns: The serialized component as a dictionary.
477
+ """
478
+ return default_to_dict(
479
+ self,
480
+ include_content=self.include_content,
481
+ top_k=self.top_k,
482
+ query_filter=self.query_filter,
483
+ include_shared_drives=self.include_shared_drives,
484
+ order_by=self.order_by,
485
+ fields=self.fields,
486
+ api_base_url=self.api_base_url,
487
+ timeout=self.timeout,
488
+ max_retries=self.max_retries,
489
+ )
490
+
491
+ @classmethod
492
+ def from_dict(cls, data: dict[str, Any]) -> "GoogleDriveRetriever":
493
+ """
494
+ Deserialize this component from a dictionary.
495
+
496
+ :param data: The dictionary representation of this component.
497
+ :returns: The deserialized component instance.
498
+ """
499
+ return default_from_dict(cls, data)
File without changes