openai-datacircle 0.1.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.
- openai_datacircle/__init__.py +24 -0
- openai_datacircle/_api.py +101 -0
- openai_datacircle/py.typed +0 -0
- openai_datacircle/tools.py +299 -0
- openai_datacircle-0.1.0.dist-info/METADATA +164 -0
- openai_datacircle-0.1.0.dist-info/RECORD +8 -0
- openai_datacircle-0.1.0.dist-info/WHEEL +4 -0
- openai_datacircle-0.1.0.dist-info/licenses/LICENSE +9 -0
|
@@ -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
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
"""Tools for the official OpenAI Python library on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
|
|
2
|
+
|
|
3
|
+
The tools are function tools for client.chat.completions (create, parse, stream) and client.responses (create, parse,
|
|
4
|
+
stream), on OpenAI or any server that speaks its API. The app runs the calls the model returns: call() and call_all()
|
|
5
|
+
give the tool messages of Chat Completions, call_output() and call_outputs() the function_call_output items of Responses,
|
|
6
|
+
and registered_functions() hands the four to the library's own ResponsesToolRunner. A tool makes one HTTPS GET and gives
|
|
7
|
+
the model the API's answer as JSON text. A refusal (an unknown slug, an argument out of range, the API out of reach) is
|
|
8
|
+
the JSON text {"error": the API's words}, so the model can call again and the chat goes on. Not every server holds a
|
|
9
|
+
model to a tool's schema, so each tool checks its arguments before any call.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import copy
|
|
14
|
+
import json
|
|
15
|
+
import urllib.parse
|
|
16
|
+
from typing import Any, Dict, List, Mapping, Optional, Sequence
|
|
17
|
+
|
|
18
|
+
from openai_datacircle import _api
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _text(answer: Any) -> str:
|
|
22
|
+
return json.dumps(answer, ensure_ascii=False)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _best(plans: Any) -> Optional[Dict[str, Any]]:
|
|
26
|
+
"""A provider's best plan on an API: its lowest rank, a plan with no score having none."""
|
|
27
|
+
ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
|
|
28
|
+
return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _list_apis(query: Any = None, limit: Any = None) -> Dict[str, Any]:
|
|
32
|
+
count = _api.whole("limit", limit, 1, 200) or 20
|
|
33
|
+
apis = _api.get("/apis")
|
|
34
|
+
words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
|
|
35
|
+
held = []
|
|
36
|
+
for index, api in enumerate(apis):
|
|
37
|
+
name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
|
|
38
|
+
matched = sum(word in name for word in words)
|
|
39
|
+
if matched or not words:
|
|
40
|
+
held.append((-matched, index, api))
|
|
41
|
+
found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
|
|
42
|
+
return {"total": len(found), "apis": found[:count]}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _best_plans(slug: Any = None, limit: Any = None) -> Dict[str, Any]:
|
|
46
|
+
made = _api.slug(slug)
|
|
47
|
+
if not made:
|
|
48
|
+
raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
|
|
49
|
+
answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
|
|
50
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _search_plans(api: Any = None, query: Any = None, sort: Any = None, limit: Any = None, offset: Any = None) -> Dict[str, Any]:
|
|
54
|
+
order = str(sort).strip().lower() if sort not in (None, "") else None
|
|
55
|
+
if order is not None and order not in ("score", "provider", "price"):
|
|
56
|
+
raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
|
|
57
|
+
params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
|
|
58
|
+
"offset": _api.whole("offset", offset, 0)}
|
|
59
|
+
answer = _api.get("/plans", params)
|
|
60
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _provider(slug: Any = None) -> Dict[str, Any]:
|
|
64
|
+
made = _api.slug(slug)
|
|
65
|
+
if not made:
|
|
66
|
+
raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
|
|
67
|
+
answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
|
|
68
|
+
apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
|
|
69
|
+
"best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
|
|
70
|
+
return {**answer, "apis": apis}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
_PRICE = "perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
|
|
74
|
+
_LIMIT = {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give, 1 to 50. 10 when left out."}
|
|
75
|
+
|
|
76
|
+
# Each tool: what the model reads of it, and the function that answers it. The schemas use only what OpenAI's strict mode
|
|
77
|
+
# and the servers that copy its API take: type, description, enum, minimum, maximum, required.
|
|
78
|
+
_TOOLS: Dict[str, Dict[str, Any]] = {
|
|
79
|
+
"datacircle_list_apis": {
|
|
80
|
+
"run": _list_apis,
|
|
81
|
+
"description": "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how many plans "
|
|
82
|
+
"and providers it has and its best plan. Call it to find an API's slug when you don't know it. Gives "
|
|
83
|
+
"total, the APIs found, and apis, up to limit of them.",
|
|
84
|
+
"parameters": {"type": "object", "properties": {
|
|
85
|
+
"query": {"type": "string", "description": "Words of the API's name or slug, like 'email' or 'linkedin profile'. "
|
|
86
|
+
"The APIs that hold the most of them come first, in the sheet's order "
|
|
87
|
+
"when left out."},
|
|
88
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 200,
|
|
89
|
+
"description": "How many APIs to give, 1 to 200. 20 when left out, of about 170."}}},
|
|
90
|
+
},
|
|
91
|
+
"datacircle_best_plans": {
|
|
92
|
+
"run": _best_plans,
|
|
93
|
+
"description": "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark "
|
|
94
|
+
"(https://datacircle.dev), each with its rank, provider, plan, $ per 1,000 calls and its page: the "
|
|
95
|
+
"best providers of an API. " + _PRICE,
|
|
96
|
+
"parameters": {"type": "object", "properties": {
|
|
97
|
+
"slug": {"type": "string", "description": "The API's slug, like 'email-finder' or 'linkedin-profile', as "
|
|
98
|
+
"datacircle_list_apis gives it."},
|
|
99
|
+
"limit": _LIMIT}, "required": ["slug"]},
|
|
100
|
+
},
|
|
101
|
+
"datacircle_search_plans": {
|
|
102
|
+
"run": _search_plans,
|
|
103
|
+
"description": "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan "
|
|
104
|
+
"name, sorted by score, provider or price. Gives total, offset and up to limit plans. " + _PRICE,
|
|
105
|
+
"parameters": {"type": "object", "properties": {
|
|
106
|
+
"api": {"type": "string", "description": "Only this API's plans, by its name or slug, like 'email-finder'. A "
|
|
107
|
+
"provider's name goes in query, never here. Every API when left out."},
|
|
108
|
+
"query": {"type": "string", "description": "Words that must all appear in the provider's or plan's name, like "
|
|
109
|
+
"'bright data'."},
|
|
110
|
+
"sort": {"type": "string", "enum": ["score", "provider", "price"],
|
|
111
|
+
"description": "score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first)."},
|
|
112
|
+
"limit": _LIMIT,
|
|
113
|
+
"offset": {"type": "integer", "minimum": 0, "description": "How many found plans to skip first. 0 when left out."}}},
|
|
114
|
+
},
|
|
115
|
+
"datacircle_provider": {
|
|
116
|
+
"run": _provider,
|
|
117
|
+
"description": "Gives each API one provider sells and its rank on each on Datacircle's benchmark "
|
|
118
|
+
"(https://datacircle.dev), with its best plan there.",
|
|
119
|
+
"parameters": {"type": "object", "properties": {
|
|
120
|
+
"slug": {"type": "string", "description": "The provider's slug, like 'bright-data', or its name, like 'Bright "
|
|
121
|
+
"Data', which is made a slug."}}, "required": ["slug"]},
|
|
122
|
+
},
|
|
123
|
+
}
|
|
124
|
+
TOOL_NAMES = list(_TOOLS)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _names(tool_names: Optional[Sequence[str]]) -> List[str]:
|
|
128
|
+
if isinstance(tool_names, str):
|
|
129
|
+
raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
|
|
130
|
+
for name in tool_names or []:
|
|
131
|
+
if name not in _TOOLS:
|
|
132
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
133
|
+
return TOOL_NAMES if tool_names is None else list(tool_names)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _parameters(name: str, strict: bool) -> Dict[str, Any]:
|
|
137
|
+
"""A tool's JSON schema. Strict mode wants every argument in required and no other: one the model may leave out
|
|
138
|
+
takes null as well, which the tool reads as left out."""
|
|
139
|
+
parameters = copy.deepcopy(_TOOLS[name]["parameters"])
|
|
140
|
+
if not strict:
|
|
141
|
+
return parameters
|
|
142
|
+
properties = {}
|
|
143
|
+
for key, spec in parameters["properties"].items():
|
|
144
|
+
if key in parameters.get("required", []):
|
|
145
|
+
properties[key] = spec
|
|
146
|
+
else:
|
|
147
|
+
kept = {field: value for field, value in spec.items() if field != "description"}
|
|
148
|
+
properties[key] = {"anyOf": [kept, {"type": "null"}], "description": spec["description"]}
|
|
149
|
+
return {"type": "object", "properties": properties, "required": list(properties), "additionalProperties": False}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def datacircle_tools(tool_names: Optional[Sequence[str]] = None, *, strict: bool = False) -> List[Dict[str, Any]]:
|
|
153
|
+
"""The tools for Chat Completions: client.chat.completions.create(model=..., messages=..., tools=datacircle_tools()),
|
|
154
|
+
or beside one's own: tools=[*datacircle_tools(), my_tool]. strict=True gives them in strict mode, which
|
|
155
|
+
client.chat.completions.parse() needs. tool_names keeps some of them only, in their order here; all four when left
|
|
156
|
+
out. Each is a new dict, so an app may change its copy."""
|
|
157
|
+
tools = []
|
|
158
|
+
for name in _names(tool_names):
|
|
159
|
+
function = {"name": name, "description": _TOOLS[name]["description"], "parameters": _parameters(name, strict)}
|
|
160
|
+
tools.append({"type": "function", "function": {**function, "strict": True} if strict else function})
|
|
161
|
+
return tools
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def responses_tools(tool_names: Optional[Sequence[str]] = None, *, strict: bool = False) -> List[Dict[str, Any]]:
|
|
165
|
+
"""The tools for the Responses API: client.responses.create(model=..., input=..., tools=responses_tools()). strict
|
|
166
|
+
is always given, as the Responses API holds a tool to strict mode when it is left out."""
|
|
167
|
+
return [{"type": "function", **tool["function"], "strict": strict}
|
|
168
|
+
for tool in datacircle_tools(tool_names, strict=strict)]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def run(name: str, arguments: Any = None) -> str:
|
|
172
|
+
"""What a tool gives the model for these arguments, as JSON text: the API's answer, or {"error": its words}.
|
|
173
|
+
arguments is a mapping or its JSON text; the ones the tool doesn't take are left out, and null ones too."""
|
|
174
|
+
if name not in _TOOLS:
|
|
175
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
176
|
+
if isinstance(arguments, bytes):
|
|
177
|
+
arguments = arguments.decode("utf-8", "replace")
|
|
178
|
+
if isinstance(arguments, str):
|
|
179
|
+
try:
|
|
180
|
+
arguments = json.loads(arguments) if arguments.strip() else {}
|
|
181
|
+
except ValueError:
|
|
182
|
+
return _text({"error": f"the arguments are no JSON object: {arguments[:200]!r}"})
|
|
183
|
+
if arguments is not None and not isinstance(arguments, Mapping):
|
|
184
|
+
return _text({"error": f"the arguments are no JSON object: {str(arguments)[:200]!r}"})
|
|
185
|
+
given = dict(arguments or {})
|
|
186
|
+
taken = _TOOLS[name]["parameters"]["properties"]
|
|
187
|
+
try:
|
|
188
|
+
return _text(_TOOLS[name]["run"](**{key: given.get(key) for key in taken}))
|
|
189
|
+
except _api.DatacircleError as error:
|
|
190
|
+
return _text({"error": str(error)})
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _field(item: Any, key: str) -> Any:
|
|
194
|
+
return item.get(key) if isinstance(item, Mapping) else getattr(item, key, None)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _named(tool_call: Any) -> Optional[str]:
|
|
198
|
+
"""The tool's name in a tool call (the library's ChatCompletionMessageToolCall, or a dict of its shape): one of ours."""
|
|
199
|
+
name = _field(_field(tool_call, "function"), "name")
|
|
200
|
+
return name if name in _TOOLS else None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def call(tool_call: Any) -> Optional[Dict[str, str]]:
|
|
204
|
+
"""The tool message for one tool call the model returned (one of completion.choices[0].message.tool_calls, or a
|
|
205
|
+
dict of its shape), to append to the messages: {"role": "tool", "tool_call_id": its id, "content": the JSON text}.
|
|
206
|
+
None when the call is for a tool that is not one of these four, so the app runs its own."""
|
|
207
|
+
name = _named(tool_call)
|
|
208
|
+
if name is None:
|
|
209
|
+
return None
|
|
210
|
+
return {"role": "tool", "tool_call_id": _field(tool_call, "id"),
|
|
211
|
+
"content": run(name, _field(_field(tool_call, "function"), "arguments"))}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _calls(message_or_calls: Any) -> Sequence[Any]:
|
|
215
|
+
"""A reply's tool calls, from its message (or a dict of its shape) or from the list itself."""
|
|
216
|
+
if message_or_calls is None:
|
|
217
|
+
return []
|
|
218
|
+
if isinstance(message_or_calls, (list, tuple)):
|
|
219
|
+
return message_or_calls
|
|
220
|
+
return _field(message_or_calls, "tool_calls") or []
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def call_all(message_or_calls: Any) -> List[Dict[str, str]]:
|
|
224
|
+
"""The tool messages for the calls of these four tools in a reply (its message, or its tool_calls), in their order.
|
|
225
|
+
Calls of other tools are left out, for the app to run."""
|
|
226
|
+
return [message for message in (call(tool_call) for tool_call in _calls(message_or_calls)) if message is not None]
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
async def acall(tool_call: Any) -> Optional[Dict[str, str]]:
|
|
230
|
+
"""call() for AsyncOpenAI: its HTTPS GET runs in a thread, so the event loop goes on."""
|
|
231
|
+
if _named(tool_call) is None:
|
|
232
|
+
return None
|
|
233
|
+
return await asyncio.to_thread(call, tool_call)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
async def acall_all(message_or_calls: Any) -> List[Dict[str, str]]:
|
|
237
|
+
"""call_all() for AsyncOpenAI: the calls run at once, their messages in the calls' order."""
|
|
238
|
+
messages = await asyncio.gather(*(acall(tool_call) for tool_call in _calls(message_or_calls)))
|
|
239
|
+
return [message for message in messages if message is not None]
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def call_output(item: Any) -> Optional[Dict[str, str]]:
|
|
243
|
+
"""For the Responses API: the function_call_output input item for one function_call item of response.output (or a
|
|
244
|
+
dict of its shape), {"type": "function_call_output", "call_id": its call_id, "output": the JSON text}. None for any
|
|
245
|
+
other item, or a call of a tool that is not one of these four."""
|
|
246
|
+
name = _field(item, "name")
|
|
247
|
+
if _field(item, "type") != "function_call" or name not in _TOOLS:
|
|
248
|
+
return None
|
|
249
|
+
return {"type": "function_call_output", "call_id": _field(item, "call_id"), "output": run(name, _field(item, "arguments"))}
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _items(response_or_output: Any) -> Sequence[Any]:
|
|
253
|
+
return response_or_output if isinstance(response_or_output, (list, tuple)) else _field(response_or_output, "output") or []
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def call_outputs(response_or_output: Any) -> List[Dict[str, str]]:
|
|
257
|
+
"""The function_call_output items for the calls of these four tools in a response (or its output list), in their
|
|
258
|
+
order. Other items and calls of other tools are left out, for the app to run."""
|
|
259
|
+
return [output for output in (call_output(item) for item in _items(response_or_output)) if output is not None]
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
async def acall_outputs(response_or_output: Any) -> List[Dict[str, str]]:
|
|
263
|
+
"""call_outputs() for AsyncOpenAI: the calls run at once, in threads, their items in the calls' order."""
|
|
264
|
+
outputs = await asyncio.gather(*(asyncio.to_thread(call_output, item) for item in _items(response_or_output)))
|
|
265
|
+
return [output for output in outputs if output is not None]
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _runner() -> Any:
|
|
269
|
+
try:
|
|
270
|
+
from openai.lib import responses_tool_runner
|
|
271
|
+
except ImportError:
|
|
272
|
+
raise ImportError("ResponsesToolRunner is in openai 3.31.0 and later: pip install -U openai") from None
|
|
273
|
+
return responses_tool_runner
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def registered_functions(tool_names: Optional[Sequence[str]] = None, *, strict: bool = False) -> List[Any]:
|
|
277
|
+
"""The tools as the library's RegisteredFunction, for its own tool loop:
|
|
278
|
+
ResponsesToolRunner(functions=[*registered_functions(), my_function]).run(client, {"model": ..., "input": ...}).
|
|
279
|
+
Each runs its call and gives the model its JSON text; none shares state with another, so each is independent."""
|
|
280
|
+
made = _runner().RegisteredFunction
|
|
281
|
+
return [made(tool=tool, execute=lambda arguments, name=tool["name"]: run(name, arguments), independent=True)
|
|
282
|
+
for tool in responses_tools(tool_names, strict=strict)]
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def async_registered_functions(tool_names: Optional[Sequence[str]] = None, *, strict: bool = False) -> List[Any]:
|
|
286
|
+
"""registered_functions() for AsyncResponsesToolRunner: each call's HTTPS GET runs in a thread."""
|
|
287
|
+
made = _runner().AsyncRegisteredFunction
|
|
288
|
+
|
|
289
|
+
def execute(name: str) -> Any:
|
|
290
|
+
async def execute_one(arguments: Any) -> str:
|
|
291
|
+
return await asyncio.to_thread(run, name, arguments)
|
|
292
|
+
return execute_one
|
|
293
|
+
return [made(tool=tool, execute=execute(tool["name"]), independent=True)
|
|
294
|
+
for tool in responses_tools(tool_names, strict=strict)]
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
__all__: List[str] = ["TOOL_NAMES", "acall", "acall_all", "acall_outputs", "async_registered_functions", "call",
|
|
298
|
+
"call_all", "call_output", "call_outputs", "datacircle_tools", "registered_functions",
|
|
299
|
+
"responses_tools", "run"]
|
|
@@ -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,8 @@
|
|
|
1
|
+
openai_datacircle/__init__.py,sha256=JJZ5bN-WDtOfHcuE-al2EfFhv_iatT_-Tp60nAvoWuA,764
|
|
2
|
+
openai_datacircle/_api.py,sha256=TGuRK4-zykmU8fo8G44WIBgke0w9zygM23X1YLMyPp0,4867
|
|
3
|
+
openai_datacircle/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
openai_datacircle/tools.py,sha256=Ki_bgVLZ5Xf6jE6TnNQ9fbPa-54gU8byAPuFZqffLj8,17053
|
|
5
|
+
openai_datacircle-0.1.0.dist-info/METADATA,sha256=HkXZaANJwwHp2U8o9SAH_2V25Es4MQmh8I97lsFU23c,8050
|
|
6
|
+
openai_datacircle-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
openai_datacircle-0.1.0.dist-info/licenses/LICENSE,sha256=dpgF7zGxeOd9IpQ9yUGa4a-cTj8fI6ulHnuilZEonCo,1067
|
|
8
|
+
openai_datacircle-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|