decodo-adk 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.
decodo_adk/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .tool_specs import ToolSpec
2
+ from .toolset import DecodoTool, DecodoToolset
3
+
4
+ __all__ = ["DecodoTool", "DecodoToolset", "ToolSpec"]
decodo_adk/check.py ADDED
@@ -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())
decodo_adk/client.py ADDED
@@ -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
decodo_adk/errors.py ADDED
@@ -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)
decodo_adk/runs.py ADDED
@@ -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))}
@@ -0,0 +1,143 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from collections.abc import Mapping
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, cast
7
+
8
+ from decodo import check_result_rule
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ STEPS = frozenset({"start", "results", "cancel"})
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Limits:
17
+ max_result_chars: int = 60_000
18
+ max_text_chars: int = 40_000
19
+ max_items: int = 50
20
+ max_list_values: int = 500
21
+ wait_seconds: int = 45
22
+
23
+
24
+ CEILINGS = Limits(
25
+ max_result_chars=200_000, max_text_chars=150_000, max_items=200, max_list_values=2_000, wait_seconds=120
26
+ )
27
+
28
+ PUBLISHED_LIMITS = {
29
+ "maxResultChars": "max_result_chars",
30
+ "maxTextChars": "max_text_chars",
31
+ "maxItems": "max_items",
32
+ "maxListValues": "max_list_values",
33
+ "waitSeconds": "wait_seconds",
34
+ }
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class ToolSpec:
39
+ name: str
40
+ description: str
41
+ flow: str
42
+ step: str | None = None
43
+ result: Mapping[str, Any] | None = None
44
+ limits: Limits = Limits()
45
+ target: str | None = None
46
+ fields: tuple[str, ...] = ()
47
+ required: tuple[str, ...] = ()
48
+ fixed: Mapping[str, Any] = field(default_factory=dict)
49
+ defaults: Mapping[str, Any] = field(default_factory=dict)
50
+ maximums: Mapping[str, float] = field(default_factory=dict)
51
+ minimums: Mapping[str, float] = field(default_factory=dict)
52
+ descriptions: Mapping[str, str] = field(default_factory=dict)
53
+
54
+
55
+ def _text(entry: Mapping[str, Any], key: str, *, optional: bool = False) -> Any:
56
+ value = entry.get(key)
57
+ if value is None and optional:
58
+ return None
59
+ if not isinstance(value, str) or not value:
60
+ raise TypeError(f"{key} is not text")
61
+ return value
62
+
63
+
64
+ def _mapping(entry: Mapping[str, Any], key: str) -> Mapping[str, Any]:
65
+ value = entry.get(key) or {}
66
+ if not isinstance(value, Mapping):
67
+ raise TypeError(f"{key} is not an object")
68
+ return value
69
+
70
+
71
+ def _result_rule(entry: Mapping[str, Any]) -> Mapping[str, Any] | None:
72
+ rule = entry.get("result")
73
+ if rule is not None:
74
+ check_result_rule(rule)
75
+ return cast(Mapping[str, Any] | None, rule)
76
+
77
+
78
+ def _limits(entry: Mapping[str, Any]) -> Limits:
79
+ published = entry.get("limits") or {}
80
+ if not isinstance(published, Mapping):
81
+ logger.warning("Ignoring the limits of the published tool %r: not an object.", entry.get("name"))
82
+ return Limits()
83
+ limits: dict[str, int] = {}
84
+ for key, name in PUBLISHED_LIMITS.items():
85
+ value = published.get(key)
86
+ if value is None:
87
+ continue
88
+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:
89
+ logger.warning("Ignoring the limit %s of the published tool %r: %r.", key, entry.get("name"), value)
90
+ continue
91
+ limits[name] = min(value, getattr(CEILINGS, name))
92
+ return Limits(**limits)
93
+
94
+
95
+ def _numbers(entry: Mapping[str, Any], key: str) -> Mapping[str, float]:
96
+ value = _mapping(entry, key)
97
+ if not all(isinstance(number, (int, float)) and not isinstance(number, bool) for number in value.values()):
98
+ raise TypeError(f"{key} holds a value that is not a number")
99
+ return value
100
+
101
+
102
+ def _names(entry: Mapping[str, Any], key: str) -> tuple[str, ...]:
103
+ value = entry.get(key) or ()
104
+ if not isinstance(value, (list, tuple)) or not all(isinstance(name, str) for name in value):
105
+ raise TypeError(f"{key} is not a list of names")
106
+ return tuple(value)
107
+
108
+
109
+ def _spec_from(entry: Any) -> ToolSpec:
110
+ if not isinstance(entry, Mapping):
111
+ raise TypeError("the tool is not an object")
112
+ step = _text(entry, "step", optional=True)
113
+ if step is not None and step not in STEPS:
114
+ raise TypeError(f"step {step!r} is not one this client knows")
115
+ maximums, minimums = _numbers(entry, "maximums"), _numbers(entry, "minimums")
116
+ return ToolSpec(
117
+ name=_text(entry, "name"),
118
+ description=_text(entry, "description"),
119
+ flow=_text(entry, "flow"),
120
+ step=step,
121
+ result=_result_rule(entry),
122
+ limits=_limits(entry),
123
+ target=_text(entry, "target", optional=True),
124
+ fields=_names(entry, "fields"),
125
+ required=_names(entry, "required"),
126
+ fixed=_mapping(entry, "fixed"),
127
+ defaults=_mapping(entry, "defaults"),
128
+ maximums=maximums,
129
+ minimums=minimums,
130
+ descriptions=_mapping(entry, "descriptions"),
131
+ )
132
+
133
+
134
+ def specs_from_surface(surface: Any) -> tuple[ToolSpec, ...]:
135
+ entries = surface.get("tools") if isinstance(surface, Mapping) else None
136
+ specs: list[ToolSpec] = []
137
+ for entry in entries if isinstance(entries, list) else []:
138
+ try:
139
+ specs.append(_spec_from(entry))
140
+ except TypeError as error:
141
+ name = entry.get("name") if isinstance(entry, Mapping) else None
142
+ logger.warning("Leaving out the published tool %r: %s.", name, error)
143
+ return tuple(specs)
decodo_adk/toolset.py ADDED
@@ -0,0 +1,180 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import logging
5
+ import traceback
6
+ from collections.abc import Mapping, Sequence
7
+ from typing import Any
8
+
9
+ from decodo import BundledSchema, DecodoSchema, FlowSchema, WebScrapingApi
10
+ from google.adk.agents.readonly_context import ReadonlyContext
11
+ from google.adk.tools.base_tool import BaseTool
12
+ from google.adk.tools.base_toolset import BaseToolset
13
+ from google.adk.tools.tool_context import ToolContext
14
+ from google.genai import types
15
+
16
+ from . import runs
17
+ from .client import INTEGRATION_HEADER, build_api, load_schema, resolve_api_key
18
+ from .errors import failure, failure_from, maybe_sent
19
+ from .tool_specs import ToolSpec, specs_from_surface
20
+
21
+ JsonSchema = dict[str, Any]
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+
26
+ def _api_schema(spec: ToolSpec, flow: Mapping[str, Any], schema: FlowSchema) -> JsonSchema:
27
+ if spec.target:
28
+ found = schema.get_target_parameter_schema(spec.target) # type: ignore[attr-defined]
29
+ source = f"target {spec.target!r}"
30
+ else:
31
+ name = flow["run"] if flow["pattern"] == "call" else flow["start"]
32
+ found = (schema.get_operation(name) or {}).get("requestSchema")
33
+ source = f"operation {name!r}"
34
+ if not found or "properties" not in found:
35
+ raise ValueError(f"the Decodo schema lists no fields for {source}")
36
+ return dict(found)
37
+
38
+
39
+ def build_parameters(spec: ToolSpec, flow: Mapping[str, Any], schema: FlowSchema) -> JsonSchema:
40
+ if flow["pattern"] == "job" and spec.step in ("results", "cancel"):
41
+ id_field = flow["idField"]
42
+ text = spec.descriptions.get(id_field, f"The {id_field} returned when the {spec.flow} was started.")
43
+ return {
44
+ "type": "object",
45
+ "properties": {id_field: {"type": "string", "description": text}},
46
+ "required": [id_field],
47
+ }
48
+ if (flow["pattern"] == "job") != (spec.step == "start"):
49
+ raise ValueError(f"step {spec.step!r} does not fit a {flow['pattern']} flow")
50
+
51
+ api = _api_schema(spec, flow, schema)
52
+ api_properties: dict[str, JsonSchema] = api["properties"]
53
+ api_required: list[str] = api.get("required") or []
54
+
55
+ uncovered = [name for name in api_required if name not in spec.fields and name not in spec.fixed]
56
+ if uncovered:
57
+ raise ValueError(f"the required API fields {uncovered} are neither shown nor fixed")
58
+
59
+ properties: dict[str, JsonSchema] = {}
60
+ for name in spec.fields:
61
+ if name not in api_properties:
62
+ logger.warning("%s: the Decodo schema has no field %r; leaving it out.", spec.name, name)
63
+ continue
64
+ shown = dict(api_properties[name])
65
+ if name in spec.descriptions:
66
+ shown["description"] = spec.descriptions[name]
67
+ if name in spec.defaults:
68
+ shown["default"] = spec.defaults[name]
69
+ if name in spec.maximums:
70
+ shown["maximum"] = min(spec.maximums[name], shown.get("maximum", spec.maximums[name]))
71
+ if name in spec.minimums:
72
+ shown["minimum"] = max(spec.minimums[name], shown.get("minimum", spec.minimums[name]))
73
+ properties[name] = shown
74
+
75
+ required = [name for name in properties if name in api_required or name in spec.required]
76
+ return {"type": "object", "properties": properties, "required": required}
77
+
78
+
79
+ class DecodoTool(BaseTool):
80
+ def __init__(self, spec: ToolSpec, parameters: JsonSchema, api: WebScrapingApi, *, starts_work: bool) -> None:
81
+ super().__init__(name=spec.name, description=spec.description)
82
+ self._spec = spec
83
+ self._parameters = parameters
84
+ self._api = api
85
+ self._starts_work = starts_work
86
+
87
+ def _get_declaration(self) -> types.FunctionDeclaration:
88
+ return types.FunctionDeclaration(
89
+ name=self.name,
90
+ description=self.description,
91
+ parameters_json_schema=self._parameters,
92
+ )
93
+
94
+ def request_params(self, args: dict[str, Any]) -> dict[str, Any]:
95
+ properties: dict[str, JsonSchema] = self._parameters["properties"]
96
+ params = {name: value for name, value in self._spec.defaults.items() if name in properties}
97
+ params.update({name: value for name, value in args.items() if name in properties and value is not None})
98
+ for name, value in params.items():
99
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
100
+ value = min(value, self._spec.maximums.get(name, value))
101
+ params[name] = max(value, self._spec.minimums.get(name, value))
102
+ return {**params, **self._spec.fixed}
103
+
104
+ async def run_async(self, *, args: dict[str, Any], tool_context: ToolContext) -> Any:
105
+ try:
106
+ params = self.request_params(args)
107
+ missing = [name for name in self._parameters["required"] if name not in params]
108
+ if missing:
109
+ return failure(f"{self.name} needs {', '.join(missing)}.", "invalid_input")
110
+ return await asyncio.to_thread(runs.run, self._api, self._spec, params)
111
+ except Exception as error:
112
+ result = failure_from(error)
113
+ if result["code"] == "unexpected_error":
114
+ frames = "".join(traceback.format_tb(error.__traceback__))
115
+ logger.error("%s failed unexpectedly with %s\n%s", self.name, type(error).__name__, frames)
116
+ if self._starts_work and maybe_sent(result, partly=self._spec.step is None):
117
+ result["retryable"] = False
118
+ result["error"] += " The request may have been accepted, so do not send it again unchanged."
119
+ return result
120
+
121
+
122
+ def build_tools(specs: Sequence[ToolSpec], schema: DecodoSchema, api: WebScrapingApi) -> list[BaseTool]:
123
+ if not isinstance(schema, FlowSchema):
124
+ return []
125
+ tools: list[BaseTool] = []
126
+ for spec in specs:
127
+ try:
128
+ flow = api.flows.describe(spec.flow)
129
+ parameters = build_parameters(spec, flow, schema)
130
+ tools.append(DecodoTool(spec, parameters, api, starts_work=runs.starts_work(spec, flow)))
131
+ except Exception as error:
132
+ logger.warning("Leaving out the tool %r: %s.", spec.name, error)
133
+ return tools
134
+
135
+
136
+ class DecodoToolset(BaseToolset):
137
+ def __init__(
138
+ self,
139
+ *,
140
+ api_key: str | None = None,
141
+ specs: Sequence[ToolSpec] | None = None,
142
+ schema: DecodoSchema | None = None,
143
+ ) -> None:
144
+ super().__init__()
145
+ self._api_key = resolve_api_key(api_key)
146
+ self._specs = specs
147
+ self._schema = schema
148
+ self._tools: list[BaseTool] | None = None
149
+
150
+ def _tools_from(self, schema: DecodoSchema) -> list[BaseTool]:
151
+ try:
152
+ specs = self._specs
153
+ if specs is None:
154
+ get_surface = getattr(schema, "get_surface", None)
155
+ specs = specs_from_surface(get_surface(INTEGRATION_HEADER) if callable(get_surface) else None)
156
+ return build_tools(specs, schema, build_api(self._api_key, schema))
157
+ except Exception as error:
158
+ logger.warning("Could not build tools from the Decodo schema: %s: %s.", type(error).__name__, error)
159
+ return []
160
+
161
+ def _build_tools(self) -> list[BaseTool]:
162
+ if self._schema is not None:
163
+ return self._tools_from(self._schema)
164
+ tools = self._tools_from(load_schema())
165
+ if self._specs is not None and not self._specs:
166
+ return tools
167
+ if not tools:
168
+ logger.warning("The published Decodo schema gave no usable tools; using the one bundled with decodo-sdk.")
169
+ tools = self._tools_from(BundledSchema.shared)
170
+ if not tools:
171
+ raise RuntimeError(
172
+ "No Decodo tools could be built. The Decodo schema must describe flows and a "
173
+ f"{INTEGRATION_HEADER} surface, which needs decodo-sdk 3.1.0 or newer."
174
+ )
175
+ return tools
176
+
177
+ async def get_tools(self, readonly_context: ReadonlyContext | None = None) -> list[BaseTool]:
178
+ if self._tools is None:
179
+ self._tools = await asyncio.to_thread(self._build_tools)
180
+ return self._tools
@@ -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,12 @@
1
+ decodo_adk/__init__.py,sha256=dOJyL4oNM8TZEnZmD28jG_8xoIsmtBU-1nADH-nFrhU,135
2
+ decodo_adk/check.py,sha256=ZIqS3lz2lwZ7qwDJtuYT7pysW_37EZ5B9bRXhqq_igQ,1304
3
+ decodo_adk/client.py,sha256=erXBDAmJrBUrQdigslLEinKnXe4Hm5veH5bAr2-s1VE,1377
4
+ decodo_adk/errors.py,sha256=QSbxkUGX5rmSMCAF0Vco8gGN-9mdaAZ_OpFoZpuZeUc,2120
5
+ decodo_adk/runs.py,sha256=-rnTlb_berzzcMvbc4DfZvH1zfdtebndHbQff9RpxUs,3925
6
+ decodo_adk/tool_specs.py,sha256=PepQooEA97E7l4FjWyGE_M2Z-u80e1JAICm2uRGGTz4,4887
7
+ decodo_adk/toolset.py,sha256=YKRiTpw_yOp9oTZcBDz8_c9e4MJ2_jooJvtLUM8MUmk,8088
8
+ decodo_adk-1.0.0.dist-info/licenses/LICENSE,sha256=G9zLhirS-KF64j5DxLUkpuRebaE_VlIgLv0yqc4JMl0,1063
9
+ decodo_adk-1.0.0.dist-info/METADATA,sha256=BewbJGxC3mbqAZcqhbOEglRfUGwiysIhKh9-nOPSKGQ,8250
10
+ decodo_adk-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ decodo_adk-1.0.0.dist-info/top_level.txt,sha256=9dykcxsPVah05IF1tnoofwZrW7zLH6qBbm79wtnaqMY,11
12
+ decodo_adk-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ decodo_adk