openai-datacircle 0.1.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,4 @@
1
+ dist/
2
+ __pycache__/
3
+ *.pyc
4
+ .venv/
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Datacircle
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.5
2
+ Name: openai-datacircle
3
+ Version: 0.1.0
4
+ Summary: Tools for the OpenAI Python library on the Datacircle API: find the best GTM APIs
5
+ Project-URL: Homepage, https://datacircle.dev
6
+ Project-URL: Documentation, https://api.datacircle.dev/v1/openapi.json
7
+ Project-URL: Repository, https://github.com/waynehamadi/openai-python-datacircle
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: api,api-pricing,b2b-data,datacircle,function-calling,gtm,llm,openai,responses,tool-calling,tools
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Software Development :: Libraries
14
+ Requires-Python: >=3.9
15
+ Requires-Dist: openai>=1.66.0
16
+ Description-Content-Type: text/markdown
17
+
18
+ # openai-datacircle
19
+
20
+ Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
21
+
22
+ Our website: https://datacircle.dev
23
+
24
+ This package gives the [OpenAI Python library](https://github.com/openai/openai-python) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You pass the four Datacircle tools to `client.chat.completions` or `client.responses`. The package then runs each tool call the model returns. Our API needs no key and no account.
25
+
26
+ | Tool | What the tool gives | Call |
27
+ | --- | --- | --- |
28
+ | `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
29
+ | `datacircle_best_plans` | One API's plans, sorted by score out of 100, best first. Each plan comes with a rank and a price per 1,000 calls | `GET /apis/{slug}/best` |
30
+ | `datacircle_search_plans` | Plans that match a provider or plan name, on all APIs or on one API. You can sort them by score, provider or price | `GET /plans` |
31
+ | `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install openai-datacircle
37
+ ```
38
+
39
+ openai-datacircle works with `openai` 1.66.0 and later, on Python 3.9 and later.
40
+
41
+ ## Use the tools with Chat Completions
42
+
43
+ Pass the tools to `client.chat.completions.create()`. If the model calls a tool, `call_all()` gives you the tool messages to send back:
44
+
45
+ ```python
46
+ from openai import OpenAI
47
+ from openai_datacircle import call_all, datacircle_tools
48
+
49
+ client = OpenAI()
50
+ messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
51
+ message = client.chat.completions.create(model="gpt-5.4-mini", messages=messages, tools=datacircle_tools()).choices[0].message
52
+
53
+ while message.tool_calls:
54
+ messages.append(message)
55
+ messages.extend(call_all(message))
56
+ message = client.chat.completions.create(model="gpt-5.4-mini", messages=messages, tools=datacircle_tools()).choices[0].message
57
+
58
+ print(message.content)
59
+ ```
60
+
61
+ Each tool message has `role: "tool"`, the call's id in `tool_call_id`, and the answer as JSON text in `content`.
62
+
63
+ `client.chat.completions.parse()` takes only strict tools. Use `datacircle_tools(strict=True)` with `parse()`. In strict mode the model gives every argument. For an optional argument, the model can send `null`. The Datacircle tools treat `null` as a missing argument.
64
+
65
+ With `client.chat.completions.stream()`, pass the message of `stream.get_final_completion()` to `call_all()`. Before `openai` 1.92.0, `parse()` and `stream()` are in `client.beta.chat.completions`.
66
+
67
+ With `AsyncOpenAI`, use `await acall_all(message)`. `acall_all()` runs the calls at the same time. Your event loop keeps running.
68
+
69
+ ## Use the tools with the Responses API
70
+
71
+ `responses_tools()` gives the four Datacircle tools in the Responses API's format. `call_outputs()` gives the `function_call_output` items to send back:
72
+
73
+ ```python
74
+ from openai import OpenAI
75
+ from openai_datacircle import call_outputs, responses_tools
76
+
77
+ client = OpenAI()
78
+ given = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
79
+ response = client.responses.create(model="gpt-5.4-mini", input=given, tools=responses_tools())
80
+
81
+ while any(item.type == "function_call" for item in response.output):
82
+ given += response.output
83
+ given += call_outputs(response)
84
+ response = client.responses.create(model="gpt-5.4-mini", input=given, tools=responses_tools())
85
+
86
+ print(response.output_text)
87
+ ```
88
+
89
+ `call_outputs()` also works with `client.responses.parse()`. `call_outputs()` also works with `client.responses.stream()` and the stream's `get_final_response()`. With `AsyncOpenAI`, use `await acall_outputs(response)`.
90
+
91
+ The Responses API treats a tool with no `strict` field as strict. `responses_tools()` sets `strict` on each tool. By default, `strict` is `False`. `responses_tools(strict=True)` sets `strict` to `True`.
92
+
93
+ ## Use the tools with ResponsesToolRunner
94
+
95
+ `openai` 3.31.0 and later can run the whole tool loop with `ResponsesToolRunner`. `registered_functions()` gives the four Datacircle tools as a list of `RegisteredFunction` objects:
96
+
97
+ ```python
98
+ from openai import OpenAI
99
+ from openai.lib.responses_tool_runner import ResponsesToolRunner
100
+ from openai_datacircle import registered_functions
101
+
102
+ runner = ResponsesToolRunner(functions=registered_functions())
103
+ response = runner.run(
104
+ OpenAI(),
105
+ {"model": "gpt-5.4-mini", "input": "Who are the 3 best providers for the email-finder API?"},
106
+ max_steps=6,
107
+ )
108
+ print(response.output_text)
109
+ ```
110
+
111
+ With `AsyncResponsesToolRunner`, use `async_registered_functions()`. The runner stops at a call to an unknown tool. Give the runner each of your own tools as a `RegisteredFunction` too: `functions=[*registered_functions(), my_function]`.
112
+
113
+ ## Use the Datacircle tools beside your own tools
114
+
115
+ You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`.
116
+
117
+ `call()` runs one tool call. For your own tools, `call()` returns `None`. Your code then runs the tool itself:
118
+
119
+ ```python
120
+ from openai_datacircle import call
121
+
122
+ for tool_call in message.tool_calls or []:
123
+ messages.append(call(tool_call) or my_tool_message(tool_call))
124
+ ```
125
+
126
+ `call_output()` runs one tool call from one item of a Responses API answer. To give the model fewer Datacircle tools, list the tool names: `datacircle_tools(["datacircle_best_plans"])`.
127
+
128
+ ## Use the tools on another server
129
+
130
+ The tools work with any server that offers OpenAI's API. Give the server's address to the client: `OpenAI(base_url="https://.../v1", api_key="...")`.
131
+
132
+ ## Call a tool yourself
133
+
134
+ You can call each tool without a model. You get the JSON text of the tool's answer:
135
+
136
+ ```python
137
+ import json
138
+
139
+ from openai_datacircle import run
140
+
141
+ answer = json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
142
+ print(answer["plans"])
143
+ ```
144
+
145
+ ## What the model reads
146
+
147
+ Each tool gives the model a JSON object as text. Each plan comes with a rank, provider, plan, score, price per 1,000 (`perThousand`, in dollars) and a page on datacircle.dev. That page lists every field.
148
+
149
+ You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
150
+
151
+ The tool returns `{"error": "..."}` with the API's message when the API gives no data, such as for an unknown slug. The error for an unknown API slug lists every valid slug. The tool checks each number from the model first. For a number out of range, the tool returns `{"error": "..."}` and makes no API call. If the network fails, the tool returns `{"error": "..."}` with the network error's message. The model can then call the tool again.
152
+
153
+ ## Network
154
+
155
+ Each tool call makes one HTTPS GET request to https://api.datacircle.dev/v1 and nothing else. The request holds only the tool's own arguments: no key and nothing from your chats. The API takes up to 60 calls a minute from one IP address. The API can ask the tool to wait. The tool then waits once, for a minute at most. Each call uses only Python's standard library. Nothing goes to disk.
156
+
157
+ ## Links
158
+
159
+ - Datacircle: https://datacircle.dev
160
+ - The API: https://datacircle.dev/api
161
+ - The API's spec: https://api.datacircle.dev/v1/openapi.json
162
+ - Every field of a plan: https://datacircle.dev/fields
163
+
164
+ MIT license.
@@ -0,0 +1,147 @@
1
+ # openai-datacircle
2
+
3
+ Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
4
+
5
+ Our website: https://datacircle.dev
6
+
7
+ This package gives the [OpenAI Python library](https://github.com/openai/openai-python) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You pass the four Datacircle tools to `client.chat.completions` or `client.responses`. The package then runs each tool call the model returns. Our API needs no key and no account.
8
+
9
+ | Tool | What the tool gives | Call |
10
+ | --- | --- | --- |
11
+ | `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
12
+ | `datacircle_best_plans` | One API's plans, sorted by score out of 100, best first. Each plan comes with a rank and a price per 1,000 calls | `GET /apis/{slug}/best` |
13
+ | `datacircle_search_plans` | Plans that match a provider or plan name, on all APIs or on one API. You can sort them by score, provider or price | `GET /plans` |
14
+ | `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install openai-datacircle
20
+ ```
21
+
22
+ openai-datacircle works with `openai` 1.66.0 and later, on Python 3.9 and later.
23
+
24
+ ## Use the tools with Chat Completions
25
+
26
+ Pass the tools to `client.chat.completions.create()`. If the model calls a tool, `call_all()` gives you the tool messages to send back:
27
+
28
+ ```python
29
+ from openai import OpenAI
30
+ from openai_datacircle import call_all, datacircle_tools
31
+
32
+ client = OpenAI()
33
+ messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
34
+ message = client.chat.completions.create(model="gpt-5.4-mini", messages=messages, tools=datacircle_tools()).choices[0].message
35
+
36
+ while message.tool_calls:
37
+ messages.append(message)
38
+ messages.extend(call_all(message))
39
+ message = client.chat.completions.create(model="gpt-5.4-mini", messages=messages, tools=datacircle_tools()).choices[0].message
40
+
41
+ print(message.content)
42
+ ```
43
+
44
+ Each tool message has `role: "tool"`, the call's id in `tool_call_id`, and the answer as JSON text in `content`.
45
+
46
+ `client.chat.completions.parse()` takes only strict tools. Use `datacircle_tools(strict=True)` with `parse()`. In strict mode the model gives every argument. For an optional argument, the model can send `null`. The Datacircle tools treat `null` as a missing argument.
47
+
48
+ With `client.chat.completions.stream()`, pass the message of `stream.get_final_completion()` to `call_all()`. Before `openai` 1.92.0, `parse()` and `stream()` are in `client.beta.chat.completions`.
49
+
50
+ With `AsyncOpenAI`, use `await acall_all(message)`. `acall_all()` runs the calls at the same time. Your event loop keeps running.
51
+
52
+ ## Use the tools with the Responses API
53
+
54
+ `responses_tools()` gives the four Datacircle tools in the Responses API's format. `call_outputs()` gives the `function_call_output` items to send back:
55
+
56
+ ```python
57
+ from openai import OpenAI
58
+ from openai_datacircle import call_outputs, responses_tools
59
+
60
+ client = OpenAI()
61
+ given = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
62
+ response = client.responses.create(model="gpt-5.4-mini", input=given, tools=responses_tools())
63
+
64
+ while any(item.type == "function_call" for item in response.output):
65
+ given += response.output
66
+ given += call_outputs(response)
67
+ response = client.responses.create(model="gpt-5.4-mini", input=given, tools=responses_tools())
68
+
69
+ print(response.output_text)
70
+ ```
71
+
72
+ `call_outputs()` also works with `client.responses.parse()`. `call_outputs()` also works with `client.responses.stream()` and the stream's `get_final_response()`. With `AsyncOpenAI`, use `await acall_outputs(response)`.
73
+
74
+ The Responses API treats a tool with no `strict` field as strict. `responses_tools()` sets `strict` on each tool. By default, `strict` is `False`. `responses_tools(strict=True)` sets `strict` to `True`.
75
+
76
+ ## Use the tools with ResponsesToolRunner
77
+
78
+ `openai` 3.31.0 and later can run the whole tool loop with `ResponsesToolRunner`. `registered_functions()` gives the four Datacircle tools as a list of `RegisteredFunction` objects:
79
+
80
+ ```python
81
+ from openai import OpenAI
82
+ from openai.lib.responses_tool_runner import ResponsesToolRunner
83
+ from openai_datacircle import registered_functions
84
+
85
+ runner = ResponsesToolRunner(functions=registered_functions())
86
+ response = runner.run(
87
+ OpenAI(),
88
+ {"model": "gpt-5.4-mini", "input": "Who are the 3 best providers for the email-finder API?"},
89
+ max_steps=6,
90
+ )
91
+ print(response.output_text)
92
+ ```
93
+
94
+ With `AsyncResponsesToolRunner`, use `async_registered_functions()`. The runner stops at a call to an unknown tool. Give the runner each of your own tools as a `RegisteredFunction` too: `functions=[*registered_functions(), my_function]`.
95
+
96
+ ## Use the Datacircle tools beside your own tools
97
+
98
+ You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`.
99
+
100
+ `call()` runs one tool call. For your own tools, `call()` returns `None`. Your code then runs the tool itself:
101
+
102
+ ```python
103
+ from openai_datacircle import call
104
+
105
+ for tool_call in message.tool_calls or []:
106
+ messages.append(call(tool_call) or my_tool_message(tool_call))
107
+ ```
108
+
109
+ `call_output()` runs one tool call from one item of a Responses API answer. To give the model fewer Datacircle tools, list the tool names: `datacircle_tools(["datacircle_best_plans"])`.
110
+
111
+ ## Use the tools on another server
112
+
113
+ The tools work with any server that offers OpenAI's API. Give the server's address to the client: `OpenAI(base_url="https://.../v1", api_key="...")`.
114
+
115
+ ## Call a tool yourself
116
+
117
+ You can call each tool without a model. You get the JSON text of the tool's answer:
118
+
119
+ ```python
120
+ import json
121
+
122
+ from openai_datacircle import run
123
+
124
+ answer = json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
125
+ print(answer["plans"])
126
+ ```
127
+
128
+ ## What the model reads
129
+
130
+ Each tool gives the model a JSON object as text. Each plan comes with a rank, provider, plan, score, price per 1,000 (`perThousand`, in dollars) and a page on datacircle.dev. That page lists every field.
131
+
132
+ You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
133
+
134
+ The tool returns `{"error": "..."}` with the API's message when the API gives no data, such as for an unknown slug. The error for an unknown API slug lists every valid slug. The tool checks each number from the model first. For a number out of range, the tool returns `{"error": "..."}` and makes no API call. If the network fails, the tool returns `{"error": "..."}` with the network error's message. The model can then call the tool again.
135
+
136
+ ## Network
137
+
138
+ Each tool call makes one HTTPS GET request to https://api.datacircle.dev/v1 and nothing else. The request holds only the tool's own arguments: no key and nothing from your chats. The API takes up to 60 calls a minute from one IP address. The API can ask the tool to wait. The tool then waits once, for a minute at most. Each call uses only Python's standard library. Nothing goes to disk.
139
+
140
+ ## Links
141
+
142
+ - Datacircle: https://datacircle.dev
143
+ - The API: https://datacircle.dev/api
144
+ - The API's spec: https://api.datacircle.dev/v1/openapi.json
145
+ - Every field of a plan: https://datacircle.dev/fields
146
+
147
+ MIT license.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "openai-datacircle"
7
+ version = "0.1.0"
8
+ description = "Tools for the OpenAI Python library on the Datacircle API: find the best GTM APIs"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ # 1.66.0 is the first with the Responses API. The tools themselves are plain dicts and the run of their calls.
13
+ dependencies = ["openai>=1.66.0"]
14
+ keywords = ["openai", "llm", "tools", "function-calling", "tool-calling", "responses", "gtm", "api", "api-pricing", "b2b-data",
15
+ "datacircle"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Operating System :: OS Independent",
19
+ "Topic :: Software Development :: Libraries",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://datacircle.dev"
24
+ Documentation = "https://api.datacircle.dev/v1/openapi.json"
25
+ Repository = "https://github.com/waynehamadi/openai-python-datacircle"
26
+
27
+ [dependency-groups]
28
+ test = ["pytest>=8"]
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["src/openai_datacircle"]
32
+
33
+ [tool.hatch.build.targets.sdist]
34
+ include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
@@ -0,0 +1,24 @@
1
+ """Tools for the official OpenAI Python library on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM
2
+ APIs, no key."""
3
+
4
+ from openai_datacircle._api import BASE_URL, DatacircleError
5
+ from openai_datacircle.tools import (
6
+ TOOL_NAMES,
7
+ acall,
8
+ acall_all,
9
+ acall_outputs,
10
+ async_registered_functions,
11
+ call,
12
+ call_all,
13
+ call_output,
14
+ call_outputs,
15
+ datacircle_tools,
16
+ registered_functions,
17
+ responses_tools,
18
+ run,
19
+ )
20
+
21
+ __version__ = "0.1.0"
22
+ __all__ = ["BASE_URL", "DatacircleError", "TOOL_NAMES", "acall", "acall_all", "acall_outputs",
23
+ "async_registered_functions", "call", "call_all", "call_output", "call_outputs", "datacircle_tools",
24
+ "registered_functions", "responses_tools", "run"]
@@ -0,0 +1,101 @@
1
+ """One HTTPS GET to Datacircle's open API (https://api.datacircle.dev/v1), no key, and what its answers are cut to for a model."""
2
+
3
+ import json
4
+ import math
5
+ import re
6
+ import time
7
+ import unicodedata
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from typing import Any, Dict, List, Optional
12
+
13
+ BASE_URL = "https://api.datacircle.dev/v1"
14
+ TIMEOUT = 30.0
15
+ USER_AGENT = "openai-datacircle/0.1.0"
16
+
17
+ # A plan holds about 90 keys (its terms of use, its aggregators...): the tools keep the ones that choose a plan, the rest is on its page.
18
+ PLAN_KEYS = ["api", "rank", "provider", "plan", "score", "perThousand", "notFoundPerThousand", "billing", "pay",
19
+ "currency", "units", "unit", "strengths", "latencyMs", "page", "pricingPage", "docs"]
20
+ API_KEYS = ["api", "slug", "plans", "providers", "best", "bestPage", "sheetPage"]
21
+
22
+
23
+ class DatacircleError(Exception):
24
+ """The API's refusal in its own words, why it could not be reached, or an argument it can't take: a tool gives the
25
+ model its words as its JSON text, {"error": ...}. status is the API's HTTP status, None when it gave none;
26
+ retryable, whether the same call may be answered later (the API out of reach, busy or failing)."""
27
+
28
+ def __init__(self, message: str, status: Optional[int] = None, retryable: bool = False):
29
+ super().__init__(message)
30
+ self.status = status
31
+ self.retryable = retryable
32
+
33
+
34
+ def brief(item: Dict[str, Any], keys: List[str] = PLAN_KEYS) -> Dict[str, Any]:
35
+ return {key: item[key] for key in keys if item.get(key) is not None}
36
+
37
+
38
+ def slug(value: Any) -> str:
39
+ """The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen."""
40
+ plain = unicodedata.normalize("NFKD", str(value or "").strip().lower())
41
+ plain = "".join(char for char in plain if not unicodedata.combining(char))
42
+ return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
43
+
44
+
45
+ def whole(name: str, value: Any, low: int, high: Optional[int] = None) -> Optional[int]:
46
+ """A whole number from low to high, or None when left out: a plain call may send one as text."""
47
+ if value is None or value == "":
48
+ return None
49
+ try:
50
+ number = float(value)
51
+ except (TypeError, ValueError):
52
+ number = float("nan")
53
+ if isinstance(value, bool) or not math.isfinite(number) or number != int(number):
54
+ raise DatacircleError(f"{name} must be a whole number, not {value!r}")
55
+ if number < low or (high is not None and number > high):
56
+ raise DatacircleError(f"{name} must be from {low} to {high}, not {int(number)}" if high is not None
57
+ else f"{name} must be {low} or more, not {int(number)}")
58
+ return int(number)
59
+
60
+
61
+ def _words(body: bytes) -> str:
62
+ """A refusal's words: the API's error, with every slug when the slug was unknown."""
63
+ text = body.decode("utf-8", "replace")
64
+ try:
65
+ parsed = json.loads(text)
66
+ if parsed.get("slugs"):
67
+ return f"{parsed['error']}; the slugs: {', '.join(parsed['slugs'])}"
68
+ return str(parsed.get("error", text))
69
+ except (ValueError, KeyError, TypeError, AttributeError):
70
+ return text
71
+
72
+
73
+ def get(path: str, params: Optional[Dict[str, Any]] = None) -> Any:
74
+ """The API's JSON answer, or a DatacircleError with its words: waits once when it answers 429."""
75
+ query = urllib.parse.urlencode({key: value for key, value in (params or {}).items() if value not in (None, "")})
76
+ url = f"{BASE_URL.rstrip('/')}{path}" + (f"?{query}" if query else "")
77
+ request = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": USER_AGENT})
78
+ for attempt in range(2):
79
+ try:
80
+ with urllib.request.urlopen(request, timeout=TIMEOUT) as answer:
81
+ body = answer.read()
82
+ except urllib.error.HTTPError as error:
83
+ body = error.read()
84
+ if error.code == 429 and not attempt:
85
+ try:
86
+ wait = int(error.headers.get("Retry-After") or 30)
87
+ except ValueError:
88
+ wait = 30
89
+ time.sleep(min(max(wait, 1), 60))
90
+ continue
91
+ if error.code == 429:
92
+ raise DatacircleError("Datacircle's API answered 429 twice: wait a minute and call again", 429, True) from None
93
+ raise DatacircleError(f"Datacircle's API answered {error.code}: {_words(body)[:3000]}", error.code,
94
+ error.code >= 500) from None
95
+ except (urllib.error.URLError, OSError) as error:
96
+ raise DatacircleError(f"Datacircle's API could not be reached: {getattr(error, 'reason', error)}",
97
+ retryable=True) from None
98
+ try:
99
+ return json.loads(body)
100
+ except ValueError as error:
101
+ raise DatacircleError(f"Datacircle's API gave no JSON: {error}") from None
File without changes