decodo-adk 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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Decodo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,196 @@
1
+ Metadata-Version: 2.4
2
+ Name: decodo-adk
3
+ Version: 1.0.0
4
+ Summary: Decodo Web Data API tools for Google ADK agents.
5
+ Author-email: Decodo <support@decodo.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://decodo.com
8
+ Project-URL: Repository, https://github.com/Decodo/google-adk
9
+ Project-URL: Documentation, https://help.decodo.com/docs/introduction
10
+ Keywords: decodo,google-adk,gemini,web-scraping,agents,tools
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Internet :: WWW/HTTP
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: <3.14,>=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: decodo-sdk>=3.1.0
22
+ Requires-Dist: google-adk<3,>=2.14
23
+ Requires-Dist: httpx>=0.27
24
+ Provides-Extra: example
25
+ Requires-Dist: gspread>=6.2; extra == "example"
26
+ Provides-Extra: dev
27
+ Requires-Dist: decodo-adk[example]; extra == "dev"
28
+ Requires-Dist: pytest>=8; extra == "dev"
29
+ Requires-Dist: ruff>=0.4; extra == "dev"
30
+ Requires-Dist: mypy>=1.10; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # Decodo tools for Google ADK
34
+
35
+ `decodo-adk` gives [Google ADK](https://google.github.io/adk-docs/) agents search, scrape, map and
36
+ crawl on the Decodo Web Data API. This repository also holds `research_agent`, an example agent
37
+ that researches a topic end to end:
38
+
39
+ 1. **Decodo** searches the web and reads the pages (search, scrape, map and crawl on the Web Data API).
40
+ 2. **Gemini** analyses what was found.
41
+ 3. **Google Sheets** keeps a log of the search results and the analysis.
42
+
43
+ The Decodo tools are not written by hand. `decodo_adk` builds them when the agent starts, from what
44
+ Decodo publishes, so a new tool, field or limit reaches the agent without a code change.
45
+
46
+ ## Requirements
47
+
48
+ - Python 3.11 to 3.13
49
+ - A Decodo Web Data API key from the [playground](https://dashboard.decodo.com/web-data/playground)
50
+ - A Gemini API key from [Google AI Studio](https://aistudio.google.com/apikey)
51
+ - A Google Cloud project with the Google Sheets API enabled, a service account in it, and a sheet
52
+ shared with that account
53
+
54
+ ## Setup
55
+
56
+ ```bash
57
+ git clone https://github.com/Decodo/google-adk.git
58
+ cd google-adk
59
+ python -m venv .venv && source .venv/bin/activate
60
+ pip install -e ".[example]"
61
+ cp research_agent/.env.example research_agent/.env
62
+ ```
63
+
64
+ Fill in `research_agent/.env`. Nothing else holds credentials, and the file is git-ignored.
65
+
66
+ | Variable | What it is |
67
+ |---|---|
68
+ | `DECODO_API_KEY` | Decodo Web Data API key |
69
+ | `GOOGLE_API_KEY` | Gemini API key |
70
+ | `GOOGLE_SERVICE_ACCOUNT_FILE` | Path to the service account's JSON key file |
71
+ | `GOOGLE_SHEET_ID` | The id in the sheet's URL: `docs.google.com/spreadsheets/d/<id>/edit` |
72
+ | `GEMINI_MODEL` | Optional. A Gemini model id; defaults to the ADK default model |
73
+
74
+ `adk` reads this file when it starts the agent, and keeps variables already set in your shell over
75
+ the ones in the file. So if `GOOGLE_GENAI_USE_VERTEXAI` is true in your shell, the model goes to
76
+ Vertex AI and `GOOGLE_API_KEY` is ignored; unset it in the shell, not in `.env`.
77
+
78
+ ### Google Sheets access
79
+
80
+ 1. In your Google Cloud project, enable the **Google Sheets API** and create a service account.
81
+ 2. Create a JSON key for it and save the file outside the repository.
82
+ 3. Create a sheet and share it with the service account's email as **Editor**. Share only this
83
+ sheet: the agent asks for the Sheets scope alone and can reach nothing else.
84
+
85
+ An empty sheet is enough. The **Search results** and **Analysis** tabs are created, with their
86
+ headers, the first time the agent writes to each.
87
+
88
+ ### Check the Decodo key
89
+
90
+ ```bash
91
+ export DECODO_API_KEY=...
92
+ python -m decodo_adk.check
93
+ ```
94
+
95
+ ## Run
96
+
97
+ ```bash
98
+ adk run research_agent
99
+ ```
100
+
101
+ Then ask, for example:
102
+
103
+ > Research "best residential proxies 2026" and tell me what the top results have in common.
104
+
105
+ The agent searches, logs the results to the **Search results** tab, reads the top pages, writes an
106
+ analysis, logs it to the **Analysis** tab and shows it to you. `adk web` gives the same agent a
107
+ browser UI.
108
+
109
+ The agent is told that what the tools return is page content, never instructions to it. A scraped
110
+ page is untrusted input: keep that line in any agent you build from this one.
111
+
112
+ ## Tools
113
+
114
+ | Tool | What it does |
115
+ |---|---|
116
+ | `decodo_search` | Web search: ranked results with titles, links and snippets |
117
+ | `decodo_scrape` | Reads one page as markdown |
118
+ | `decodo_map` | Lists the URLs of a site |
119
+ | `decodo_crawl_start` | Starts reading many pages of a site; returns a `crawl_id` |
120
+ | `decodo_crawl_results` | Waits for a crawl and returns its pages as markdown |
121
+ | `decodo_crawl_cancel` | Stops a crawl |
122
+ | `log_search_results`, `log_analysis` | Append rows to the Google Sheet |
123
+
124
+ A crawl is billed per page. `decodo_crawl_start` reads 10 pages unless the agent asks for more, 50 at
125
+ most, and every crawl can be checked or stopped by its `crawl_id`.
126
+
127
+ ### Use the tools in your own agent
128
+
129
+ The toolset needs neither the example nor `gspread`, so install the package on its own, without
130
+ the `example` extra. It is not on PyPI yet, so install it from a clone of this repository:
131
+
132
+ ```bash
133
+ pip install /path/to/google-adk
134
+ ```
135
+
136
+ ```python
137
+ from google.adk.agents import LlmAgent
138
+ from decodo_adk import DecodoToolset
139
+
140
+ agent = LlmAgent(name="my_agent", tools=[DecodoToolset()])
141
+ ```
142
+
143
+ `DecodoToolset()` reads `DECODO_API_KEY`. Pass `api_key=...` to set it in code instead.
144
+
145
+ ### What Decodo controls without a release
146
+
147
+ This repository holds no list of tools, fields or endpoints. When the agent starts, the toolset
148
+ reads these from the schema Decodo publishes:
149
+
150
+ | Published | Controls |
151
+ |---|---|
152
+ | The `google-adk-python` surface | Which tools exist, their names and descriptions, the fields they show, fixed values, defaults and caps |
153
+ | Flows | How each tool runs: one request, a job that is started, waited for and read, or a batch of jobs, and which endpoints that uses |
154
+ | Result rules, in the surface | How each response is read: what counts as a failure inside a successful reply, and which fields the model gets |
155
+ | Limits, in the surface and the flows | How much of a result the model gets, how long a results tool waits for its job, and how often it polls |
156
+ | The API description | Field types, allowed values and limits |
157
+
158
+ So a new field, a new tool for another scrape target, or a tool for another job-style endpoint
159
+ reaches the agent within a day, with no update here. So does a change to how a response is read.
160
+ Code is needed only for a new way of running things. This repository keeps a fallback and a ceiling
161
+ for each limit, so a wrong published value cannot flood the model's context.
162
+
163
+ If the published schema cannot be fetched, or gives no usable tools, the copy bundled with
164
+ `decodo-sdk` is used. To define the tools yourself, import `ToolSpec` from `decodo_adk` and pass
165
+ `DecodoToolset(specs=[ToolSpec(...)])`.
166
+
167
+ ## Errors
168
+
169
+ A failed tool call does not stop the agent. The tool returns `error`, `code` and `retryable`, and
170
+ the agent decides what to do.
171
+
172
+ | `code` | Meaning |
173
+ |---|---|
174
+ | `authentication_failed` | Decodo rejected the key; check `DECODO_API_KEY` |
175
+ | `rate_limited`, `timeout`, `network_error`, `5xx` | Temporary; `retryable` is true |
176
+ | another HTTP status, such as `403` or `404` | Decodo refused the request; `retryable` is false |
177
+ | `invalid_input` | Decodo refused the input; it must change before a retry |
178
+ | a target status such as `613`, `failed`, `empty_content`, `empty_response` | Decodo answered, but the page or search could not be retrieved |
179
+ | `invalid_request` | The request could not be sent; check `DECODO_API_KEY` for stray characters |
180
+ | `unexpected_error` | Decodo returned something the tool could not read; details are in the log |
181
+
182
+ A crawl start that was sent but not answered is never marked retryable: the crawl may have
183
+ started, and starting it again would bill it twice.
184
+
185
+ ## Development
186
+
187
+ ```bash
188
+ pip install -e ".[dev]"
189
+ ruff check . && ruff format --check . && mypy && pytest
190
+ ```
191
+
192
+ Tests never call Decodo, Gemini or Google Sheets. See [CONTRIBUTING.md](CONTRIBUTING.md).
193
+
194
+ ## License
195
+
196
+ [MIT](LICENSE)
@@ -0,0 +1,164 @@
1
+ # Decodo tools for Google ADK
2
+
3
+ `decodo-adk` gives [Google ADK](https://google.github.io/adk-docs/) agents search, scrape, map and
4
+ crawl on the Decodo Web Data API. This repository also holds `research_agent`, an example agent
5
+ that researches a topic end to end:
6
+
7
+ 1. **Decodo** searches the web and reads the pages (search, scrape, map and crawl on the Web Data API).
8
+ 2. **Gemini** analyses what was found.
9
+ 3. **Google Sheets** keeps a log of the search results and the analysis.
10
+
11
+ The Decodo tools are not written by hand. `decodo_adk` builds them when the agent starts, from what
12
+ Decodo publishes, so a new tool, field or limit reaches the agent without a code change.
13
+
14
+ ## Requirements
15
+
16
+ - Python 3.11 to 3.13
17
+ - A Decodo Web Data API key from the [playground](https://dashboard.decodo.com/web-data/playground)
18
+ - A Gemini API key from [Google AI Studio](https://aistudio.google.com/apikey)
19
+ - A Google Cloud project with the Google Sheets API enabled, a service account in it, and a sheet
20
+ shared with that account
21
+
22
+ ## Setup
23
+
24
+ ```bash
25
+ git clone https://github.com/Decodo/google-adk.git
26
+ cd google-adk
27
+ python -m venv .venv && source .venv/bin/activate
28
+ pip install -e ".[example]"
29
+ cp research_agent/.env.example research_agent/.env
30
+ ```
31
+
32
+ Fill in `research_agent/.env`. Nothing else holds credentials, and the file is git-ignored.
33
+
34
+ | Variable | What it is |
35
+ |---|---|
36
+ | `DECODO_API_KEY` | Decodo Web Data API key |
37
+ | `GOOGLE_API_KEY` | Gemini API key |
38
+ | `GOOGLE_SERVICE_ACCOUNT_FILE` | Path to the service account's JSON key file |
39
+ | `GOOGLE_SHEET_ID` | The id in the sheet's URL: `docs.google.com/spreadsheets/d/<id>/edit` |
40
+ | `GEMINI_MODEL` | Optional. A Gemini model id; defaults to the ADK default model |
41
+
42
+ `adk` reads this file when it starts the agent, and keeps variables already set in your shell over
43
+ the ones in the file. So if `GOOGLE_GENAI_USE_VERTEXAI` is true in your shell, the model goes to
44
+ Vertex AI and `GOOGLE_API_KEY` is ignored; unset it in the shell, not in `.env`.
45
+
46
+ ### Google Sheets access
47
+
48
+ 1. In your Google Cloud project, enable the **Google Sheets API** and create a service account.
49
+ 2. Create a JSON key for it and save the file outside the repository.
50
+ 3. Create a sheet and share it with the service account's email as **Editor**. Share only this
51
+ sheet: the agent asks for the Sheets scope alone and can reach nothing else.
52
+
53
+ An empty sheet is enough. The **Search results** and **Analysis** tabs are created, with their
54
+ headers, the first time the agent writes to each.
55
+
56
+ ### Check the Decodo key
57
+
58
+ ```bash
59
+ export DECODO_API_KEY=...
60
+ python -m decodo_adk.check
61
+ ```
62
+
63
+ ## Run
64
+
65
+ ```bash
66
+ adk run research_agent
67
+ ```
68
+
69
+ Then ask, for example:
70
+
71
+ > Research "best residential proxies 2026" and tell me what the top results have in common.
72
+
73
+ The agent searches, logs the results to the **Search results** tab, reads the top pages, writes an
74
+ analysis, logs it to the **Analysis** tab and shows it to you. `adk web` gives the same agent a
75
+ browser UI.
76
+
77
+ The agent is told that what the tools return is page content, never instructions to it. A scraped
78
+ page is untrusted input: keep that line in any agent you build from this one.
79
+
80
+ ## Tools
81
+
82
+ | Tool | What it does |
83
+ |---|---|
84
+ | `decodo_search` | Web search: ranked results with titles, links and snippets |
85
+ | `decodo_scrape` | Reads one page as markdown |
86
+ | `decodo_map` | Lists the URLs of a site |
87
+ | `decodo_crawl_start` | Starts reading many pages of a site; returns a `crawl_id` |
88
+ | `decodo_crawl_results` | Waits for a crawl and returns its pages as markdown |
89
+ | `decodo_crawl_cancel` | Stops a crawl |
90
+ | `log_search_results`, `log_analysis` | Append rows to the Google Sheet |
91
+
92
+ A crawl is billed per page. `decodo_crawl_start` reads 10 pages unless the agent asks for more, 50 at
93
+ most, and every crawl can be checked or stopped by its `crawl_id`.
94
+
95
+ ### Use the tools in your own agent
96
+
97
+ The toolset needs neither the example nor `gspread`, so install the package on its own, without
98
+ the `example` extra. It is not on PyPI yet, so install it from a clone of this repository:
99
+
100
+ ```bash
101
+ pip install /path/to/google-adk
102
+ ```
103
+
104
+ ```python
105
+ from google.adk.agents import LlmAgent
106
+ from decodo_adk import DecodoToolset
107
+
108
+ agent = LlmAgent(name="my_agent", tools=[DecodoToolset()])
109
+ ```
110
+
111
+ `DecodoToolset()` reads `DECODO_API_KEY`. Pass `api_key=...` to set it in code instead.
112
+
113
+ ### What Decodo controls without a release
114
+
115
+ This repository holds no list of tools, fields or endpoints. When the agent starts, the toolset
116
+ reads these from the schema Decodo publishes:
117
+
118
+ | Published | Controls |
119
+ |---|---|
120
+ | The `google-adk-python` surface | Which tools exist, their names and descriptions, the fields they show, fixed values, defaults and caps |
121
+ | Flows | How each tool runs: one request, a job that is started, waited for and read, or a batch of jobs, and which endpoints that uses |
122
+ | Result rules, in the surface | How each response is read: what counts as a failure inside a successful reply, and which fields the model gets |
123
+ | Limits, in the surface and the flows | How much of a result the model gets, how long a results tool waits for its job, and how often it polls |
124
+ | The API description | Field types, allowed values and limits |
125
+
126
+ So a new field, a new tool for another scrape target, or a tool for another job-style endpoint
127
+ reaches the agent within a day, with no update here. So does a change to how a response is read.
128
+ Code is needed only for a new way of running things. This repository keeps a fallback and a ceiling
129
+ for each limit, so a wrong published value cannot flood the model's context.
130
+
131
+ If the published schema cannot be fetched, or gives no usable tools, the copy bundled with
132
+ `decodo-sdk` is used. To define the tools yourself, import `ToolSpec` from `decodo_adk` and pass
133
+ `DecodoToolset(specs=[ToolSpec(...)])`.
134
+
135
+ ## Errors
136
+
137
+ A failed tool call does not stop the agent. The tool returns `error`, `code` and `retryable`, and
138
+ the agent decides what to do.
139
+
140
+ | `code` | Meaning |
141
+ |---|---|
142
+ | `authentication_failed` | Decodo rejected the key; check `DECODO_API_KEY` |
143
+ | `rate_limited`, `timeout`, `network_error`, `5xx` | Temporary; `retryable` is true |
144
+ | another HTTP status, such as `403` or `404` | Decodo refused the request; `retryable` is false |
145
+ | `invalid_input` | Decodo refused the input; it must change before a retry |
146
+ | a target status such as `613`, `failed`, `empty_content`, `empty_response` | Decodo answered, but the page or search could not be retrieved |
147
+ | `invalid_request` | The request could not be sent; check `DECODO_API_KEY` for stray characters |
148
+ | `unexpected_error` | Decodo returned something the tool could not read; details are in the log |
149
+
150
+ A crawl start that was sent but not answered is never marked retryable: the crawl may have
151
+ started, and starting it again would bill it twice.
152
+
153
+ ## Development
154
+
155
+ ```bash
156
+ pip install -e ".[dev]"
157
+ ruff check . && ruff format --check . && mypy && pytest
158
+ ```
159
+
160
+ Tests never call Decodo, Gemini or Google Sheets. See [CONTRIBUTING.md](CONTRIBUTING.md).
161
+
162
+ ## License
163
+
164
+ [MIT](LICENSE)
@@ -0,0 +1,4 @@
1
+ from .tool_specs import ToolSpec
2
+ from .toolset import DecodoTool, DecodoToolset
3
+
4
+ __all__ = ["DecodoTool", "DecodoToolset", "ToolSpec"]
@@ -0,0 +1,40 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ import httpx
6
+ from decodo import AuthenticationError, RateLimitError, WebScrapingApi
7
+ from decodo.errors import TimeoutError as DecodoTimeoutError
8
+
9
+ from .client import API_KEY_ENV_VAR, build_api, load_schema, resolve_api_key
10
+
11
+
12
+ def api_key_problem(api: WebScrapingApi) -> str | None:
13
+ try:
14
+ api.flows.check_key()
15
+ except AuthenticationError as error:
16
+ return f"Decodo rejected the API key ({error}). Check {API_KEY_ENV_VAR}."
17
+ except RateLimitError:
18
+ return "Decodo rate limit reached, so the key could not be checked. Try again shortly."
19
+ except DecodoTimeoutError:
20
+ return "The request to Decodo timed out, so the key could not be checked."
21
+ except httpx.TransportError as error:
22
+ return f"Could not reach Decodo ({type(error).__name__}), so the key could not be checked."
23
+ except ValueError as error:
24
+ return f"The key could not be checked: {error}"
25
+ return None
26
+
27
+
28
+ def main() -> int:
29
+ try:
30
+ api = build_api(resolve_api_key(), load_schema())
31
+ except ValueError as error:
32
+ print(error)
33
+ return 1
34
+ problem = api_key_problem(api)
35
+ print(problem or f"{API_KEY_ENV_VAR} is accepted.")
36
+ return 1 if problem else 0
37
+
38
+
39
+ if __name__ == "__main__":
40
+ sys.exit(main())
@@ -0,0 +1,46 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+
6
+ from decodo import (
7
+ BundledSchema,
8
+ DecodoClient,
9
+ DecodoConfig,
10
+ DecodoSchema,
11
+ RemoteSchema,
12
+ RemoteSchemaLoadOptions,
13
+ WebScrapingApi,
14
+ WebScrapingApiConfig,
15
+ )
16
+
17
+ API_KEY_ENV_VAR = "DECODO_API_KEY"
18
+ INTEGRATION_HEADER = "google-adk-python"
19
+ SCHEMA_TTL_MS = 24 * 60 * 60 * 1000
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ def resolve_api_key(api_key: str | None = None) -> str:
25
+ key = (api_key or os.environ.get(API_KEY_ENV_VAR) or "").strip()
26
+ if not key:
27
+ raise ValueError(f"Pass api_key or set the {API_KEY_ENV_VAR} environment variable.")
28
+ if not key.isascii() or not key.isprintable():
29
+ raise ValueError(f"{API_KEY_ENV_VAR} contains characters an HTTP header cannot carry.")
30
+ return key
31
+
32
+
33
+ def load_schema() -> DecodoSchema:
34
+ try:
35
+ return RemoteSchema.load(RemoteSchemaLoadOptions(ttl_ms=SCHEMA_TTL_MS))
36
+ except Exception as error:
37
+ logger.warning("Could not load the published Decodo schema (%s); using the bundled one.", error)
38
+ return BundledSchema.shared
39
+
40
+
41
+ def build_api(api_key: str, schema: DecodoSchema) -> WebScrapingApi:
42
+ config = DecodoConfig(
43
+ web_scraping_api=WebScrapingApiConfig(api_key=api_key, integration_header=INTEGRATION_HEADER),
44
+ schema=schema,
45
+ )
46
+ return DecodoClient(config).web_scraping_api
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ import httpx
6
+ from decodo import AuthenticationError, DecodoError, RateLimitError, ValidationError
7
+ from decodo.errors import TimeoutError as DecodoTimeoutError
8
+
9
+ from .client import API_KEY_ENV_VAR
10
+
11
+ MAYBE_SENT_CODES = frozenset({"timeout", "network_error", "unexpected_error"})
12
+
13
+
14
+ def failure(message: str, code: str, *, retryable: bool = False, **details: Any) -> dict[str, Any]:
15
+ return {"error": message, "code": code, "retryable": retryable, **details}
16
+
17
+
18
+ def failure_from(error: BaseException) -> dict[str, Any]:
19
+ if isinstance(error, AuthenticationError):
20
+ return failure(f"Decodo rejected the API key ({error}). Check {API_KEY_ENV_VAR}.", "authentication_failed")
21
+ if isinstance(error, RateLimitError):
22
+ return failure(f"Decodo rate limit reached: {error}", "rate_limited", retryable=True)
23
+ if isinstance(error, ValidationError) or (isinstance(error, DecodoError) and error.status_code == 400):
24
+ return failure(f"Decodo refused the input, change it before retrying: {error}", "invalid_input")
25
+ if isinstance(error, DecodoTimeoutError):
26
+ return failure(f"Decodo request timed out: {error}", "timeout", retryable=True)
27
+ if isinstance(error, DecodoError):
28
+ return failure(f"Decodo request failed: {error}", str(error.status_code), retryable=error.status_code >= 500)
29
+ if isinstance(error, (httpx.LocalProtocolError, UnicodeEncodeError)):
30
+ return failure(
31
+ f"The request to Decodo could not be sent. Check {API_KEY_ENV_VAR} for invalid characters.",
32
+ "invalid_request",
33
+ )
34
+ if isinstance(error, httpx.TransportError):
35
+ return failure(f"Could not reach Decodo: {error}", "network_error", retryable=True)
36
+ return failure(f"Decodo returned something unexpected ({type(error).__name__}).", "unexpected_error")
37
+
38
+
39
+ def maybe_sent(result: dict[str, Any], *, partly: bool = False) -> bool:
40
+ code = str(result.get("code"))
41
+ if partly and code == "invalid_input":
42
+ return True
43
+ return code in MAYBE_SENT_CODES or (code.isdigit() and int(code) >= 500)
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections.abc import Mapping
5
+ from typing import Any, cast
6
+
7
+ from decodo import JobTimeoutError, ResultError, WebScrapingApi, read_result
8
+
9
+ from .errors import failure
10
+ from .tool_specs import Limits, ToolSpec
11
+
12
+ Params = dict[str, Any]
13
+ Result = dict[str, Any]
14
+
15
+
16
+ def _trimmed(value: Any, text_chars: int, list_values: int) -> Any:
17
+ if not isinstance(value, dict):
18
+ return value
19
+ trimmed: Result = {}
20
+ for name, field in value.items():
21
+ if isinstance(field, str) and len(field) > text_chars:
22
+ trimmed[name] = field[:text_chars]
23
+ trimmed["truncated"] = True
24
+ elif isinstance(field, list) and len(field) > list_values:
25
+ trimmed[name] = field[:list_values]
26
+ trimmed[f"{name}_omitted"] = len(field) - list_values
27
+ else:
28
+ trimmed[name] = field
29
+ return trimmed
30
+
31
+
32
+ def _presented(result: Any, limits: Limits) -> Result:
33
+ if isinstance(result, list):
34
+ shown = result[: limits.max_items]
35
+ text_chars = limits.max_text_chars // max(len(shown), 1)
36
+ presented: Result = {"items": [_trimmed(item, text_chars, limits.max_list_values) for item in shown]}
37
+ if len(result) > limits.max_items:
38
+ presented["more_items"] = True
39
+ return presented
40
+ if isinstance(result, dict):
41
+ return cast(Result, _trimmed(result, limits.max_text_chars, limits.max_list_values))
42
+ return {"result": result}
43
+
44
+
45
+ def _bounded(result: Result, limits: Limits) -> Result:
46
+ text = json.dumps(result, ensure_ascii=False, default=str)
47
+ if len(text) <= limits.max_result_chars:
48
+ return result
49
+ return {"result_json": text[: limits.max_result_chars], "truncated": True}
50
+
51
+
52
+ def _read(spec: ToolSpec, response: Any) -> Result:
53
+ try:
54
+ return _presented(read_result(spec.result, response), spec.limits)
55
+ except ResultError as error:
56
+ return failure(str(error), error.code, retryable=error.retryable)
57
+
58
+
59
+ def starts_work(spec: ToolSpec, flow: Mapping[str, Any]) -> bool:
60
+ return flow["pattern"] == "batch" or (flow["pattern"] == "job" and spec.step == "start")
61
+
62
+
63
+ def run(api: WebScrapingApi, spec: ToolSpec, params: Params) -> Result:
64
+ return _bounded(_run(api, spec, params), spec.limits)
65
+
66
+
67
+ def _run(api: WebScrapingApi, spec: ToolSpec, params: Params) -> Result:
68
+ flow = api.flows.describe(spec.flow)
69
+ pattern = flow["pattern"]
70
+
71
+ if pattern == "call":
72
+ return _read(spec, api.flows.call(spec.flow, params))
73
+
74
+ if pattern == "batch":
75
+ job = api.flows.describe(flow["job"])
76
+ jobs = api.flows.start_batch(spec.flow, params)
77
+ return {"jobs": [{key: item.get(key) for key in (job["idField"], job["statusField"])} for item in jobs]}
78
+
79
+ id_field, status_field = flow["idField"], flow["statusField"]
80
+
81
+ if spec.step == "start":
82
+ started = api.flows.start(spec.flow, params)
83
+ return {
84
+ id_field: started[id_field],
85
+ status_field: started.get(status_field),
86
+ "next": f"Fetch the results with this {id_field} right away; the results tool waits for it.",
87
+ }
88
+
89
+ job_id = params[id_field]
90
+
91
+ if spec.step == "cancel":
92
+ cancelled = api.flows.cancel(spec.flow, job_id)
93
+ return {id_field: job_id, status_field: cancelled.get(status_field)}
94
+
95
+ try:
96
+ status = api.flows.wait(spec.flow, job_id, timeout=spec.limits.wait_seconds)
97
+ except JobTimeoutError:
98
+ return {
99
+ id_field: job_id,
100
+ status_field: flow["pendingStatuses"][0],
101
+ "next": f"Still running. Call this tool again right away with the same {id_field}.",
102
+ }
103
+
104
+ result: Result = {id_field: job_id, status_field: status.get(status_field)}
105
+ if status.get("reason"):
106
+ result["reason"] = status["reason"]
107
+ return {**result, **_read(spec, api.flows.results(spec.flow, job_id, max_items=spec.limits.max_items + 1))}