groq-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.
@@ -0,0 +1,8 @@
1
+ """Tools for Groq's Python library on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
2
+
3
+ from groq_datacircle._api import BASE_URL, DatacircleError
4
+ from groq_datacircle.tools import TOOL_NAMES, acall, acall_all, call, call_all, collect_tool_calls, datacircle_tools, run
5
+
6
+ __version__ = "0.1.0"
7
+ __all__ = ["BASE_URL", "DatacircleError", "TOOL_NAMES", "acall", "acall_all", "call", "call_all", "collect_tool_calls",
8
+ "datacircle_tools", "run"]
@@ -0,0 +1,114 @@
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 gzip
4
+ import json
5
+ import math
6
+ import re
7
+ import time
8
+ import unicodedata
9
+ import urllib.error
10
+ import urllib.parse
11
+ import urllib.request
12
+ import zlib
13
+ from typing import Any, Dict, List, Optional
14
+
15
+ BASE_URL = "https://api.datacircle.dev/v1"
16
+ TIMEOUT = 30.0
17
+ USER_AGENT = "groq-datacircle/0.1.0"
18
+
19
+ # 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.
20
+ PLAN_KEYS = ["api", "rank", "provider", "plan", "score", "perThousand", "notFoundPerThousand", "billing", "pay",
21
+ "currency", "units", "unit", "strengths", "latencyMs", "page", "pricingPage", "docs"]
22
+ API_KEYS = ["api", "slug", "plans", "providers", "best", "bestPage", "sheetPage"]
23
+
24
+
25
+ class DatacircleError(Exception):
26
+ """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
27
+ model its words as its JSON text, {"error": ...}. status is the API's HTTP status, None when it gave none;
28
+ retryable, whether the same call may be answered later (the API out of reach, busy or failing)."""
29
+
30
+ def __init__(self, message: str, status: Optional[int] = None, retryable: bool = False):
31
+ super().__init__(message)
32
+ self.status = status
33
+ self.retryable = retryable
34
+
35
+
36
+ def brief(item: Dict[str, Any], keys: List[str] = PLAN_KEYS) -> Dict[str, Any]:
37
+ return {key: item[key] for key in keys if item.get(key) is not None}
38
+
39
+
40
+ def slug(value: Any) -> str:
41
+ """The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen."""
42
+ plain = unicodedata.normalize("NFKD", str(value or "").strip().lower())
43
+ plain = "".join(char for char in plain if not unicodedata.combining(char))
44
+ return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
45
+
46
+
47
+ def whole(name: str, value: Any, low: int, high: Optional[int] = None) -> Optional[int]:
48
+ """A whole number from low to high, or None when left out: a plain call may send one as text."""
49
+ if value is None or value == "":
50
+ return None
51
+ try:
52
+ number = float(value)
53
+ except (TypeError, ValueError):
54
+ number = float("nan")
55
+ if isinstance(value, bool) or not math.isfinite(number) or number != int(number):
56
+ raise DatacircleError(f"{name} must be a whole number, not {value!r}")
57
+ if number < low or (high is not None and number > high):
58
+ raise DatacircleError(f"{name} must be from {low} to {high}, not {int(number)}" if high is not None
59
+ else f"{name} must be {low} or more, not {int(number)}")
60
+ return int(number)
61
+
62
+
63
+ def _words(body: bytes) -> str:
64
+ """A refusal's words: the API's error, with every slug when the slug was unknown."""
65
+ text = body.decode("utf-8", "replace")
66
+ try:
67
+ parsed = json.loads(text)
68
+ if parsed.get("slugs"):
69
+ return f"{parsed['error']}; the slugs: {', '.join(parsed['slugs'])}"
70
+ return str(parsed.get("error", text))
71
+ except (ValueError, KeyError, TypeError, AttributeError):
72
+ return text
73
+
74
+
75
+ def _unpacked(body: bytes, headers: Any) -> bytes:
76
+ """The answer's bytes as sent before it was squeezed: urllib unpacks nothing by itself, and an answer may pass 10 MB."""
77
+ if str((headers or {}).get("Content-Encoding") or "").strip().lower() != "gzip":
78
+ return body
79
+ try:
80
+ return gzip.decompress(body)
81
+ except (OSError, EOFError, zlib.error) as error:
82
+ raise DatacircleError(f"Datacircle's API gave a broken gzip answer: {error}", retryable=True) from None
83
+
84
+
85
+ def get(path: str, params: Optional[Dict[str, Any]] = None) -> Any:
86
+ """The API's JSON answer, or a DatacircleError with its words: waits once when it answers 429."""
87
+ query = urllib.parse.urlencode({key: value for key, value in (params or {}).items() if value not in (None, "")})
88
+ url = f"{BASE_URL.rstrip('/')}{path}" + (f"?{query}" if query else "")
89
+ request = urllib.request.Request(url, headers={"Accept": "application/json", "Accept-Encoding": "gzip",
90
+ "User-Agent": USER_AGENT})
91
+ for attempt in range(2):
92
+ try:
93
+ with urllib.request.urlopen(request, timeout=TIMEOUT) as answer:
94
+ body = _unpacked(answer.read(), answer.headers)
95
+ except urllib.error.HTTPError as error:
96
+ body = _unpacked(error.read(), error.headers)
97
+ if error.code == 429 and not attempt:
98
+ try:
99
+ wait = int(error.headers.get("Retry-After") or 30)
100
+ except ValueError:
101
+ wait = 30
102
+ time.sleep(min(max(wait, 1), 60))
103
+ continue
104
+ if error.code == 429:
105
+ raise DatacircleError("Datacircle's API answered 429 twice: wait a minute and call again", 429, True) from None
106
+ raise DatacircleError(f"Datacircle's API answered {error.code}: {_words(body)[:3000]}", error.code,
107
+ error.code >= 500) from None
108
+ except (urllib.error.URLError, OSError) as error:
109
+ raise DatacircleError(f"Datacircle's API could not be reached: {getattr(error, 'reason', error)}",
110
+ retryable=True) from None
111
+ try:
112
+ return json.loads(body)
113
+ except ValueError as error:
114
+ raise DatacircleError(f"Datacircle's API gave no JSON: {error}") from None
File without changes
@@ -0,0 +1,247 @@
1
+ """Tools for Groq's Python library (groq) on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
2
+
3
+ datacircle_tools() gives the four as tool definitions for client.chat.completions.create(tools=...), Groq's and
4
+ AsyncGroq's, streamed or not, beside an app's own tools; call() and call_all() run the tool calls the model returns into
5
+ the tool messages to send back, acall() and acall_all() in a thread for an event loop, and collect_tool_calls() gathers
6
+ a stream's calls. A tool makes one HTTPS GET and gives the model the API's answer as JSON text. A refusal (an unknown
7
+ slug, an argument out of range, the API out of reach) is the JSON text {"error": the API's words}, so the model can call
8
+ again and the chat goes on. Not every model keeps to a tool's schema, so each tool checks its arguments before any call.
9
+ """
10
+
11
+ import asyncio
12
+ import copy
13
+ import json
14
+ import urllib.parse
15
+ from typing import Any, Dict, List, Mapping, Optional, Sequence
16
+
17
+ from groq_datacircle import _api
18
+
19
+
20
+ def _text(answer: Any) -> str:
21
+ return json.dumps(answer, ensure_ascii=False)
22
+
23
+
24
+ def _best(plans: Any) -> Optional[Dict[str, Any]]:
25
+ """A provider's best plan on an API: its lowest rank, a plan with no score having none."""
26
+ ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
27
+ return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
28
+
29
+
30
+ def _list_apis(query: Any = None, limit: Any = None) -> Dict[str, Any]:
31
+ count = _api.whole("limit", limit, 1, 200) or 20
32
+ apis = _api.get("/apis")
33
+ words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
34
+ held = []
35
+ for index, api in enumerate(apis):
36
+ name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
37
+ matched = sum(word in name for word in words)
38
+ if matched or not words:
39
+ held.append((-matched, index, api))
40
+ found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
41
+ return {"total": len(found), "apis": found[:count]}
42
+
43
+
44
+ def _best_plans(slug: Any = None, limit: Any = None) -> Dict[str, Any]:
45
+ made = _api.slug(slug)
46
+ if not made:
47
+ raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
48
+ answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
49
+ return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
50
+
51
+
52
+ def _search_plans(api: Any = None, query: Any = None, sort: Any = None, limit: Any = None, offset: Any = None) -> Dict[str, Any]:
53
+ order = str(sort).strip().lower() if sort not in (None, "") else None
54
+ if order is not None and order not in ("score", "provider", "price"):
55
+ raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
56
+ params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
57
+ "offset": _api.whole("offset", offset, 0)}
58
+ answer = _api.get("/plans", params)
59
+ return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
60
+
61
+
62
+ def _provider(slug: Any = None) -> Dict[str, Any]:
63
+ made = _api.slug(slug)
64
+ if not made:
65
+ raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
66
+ # plans=best: each API's best plan of the provider alone, its count in planCount (a provider's every plan passes 10 MB)
67
+ answer = _api.get(f"/providers/{urllib.parse.quote(made)}", {"plans": "best"})
68
+ apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]),
69
+ "plans": entry.get("planCount", len(entry.get("plans") or [])), "best": _best(entry.get("plans") or [])}
70
+ for entry in answer.get("apis") or []]
71
+ return {**answer, "apis": apis}
72
+
73
+
74
+ _PRICE = "perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
75
+ _LIMIT = {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give, 1 to 50. 10 when left out."}
76
+
77
+ # Each tool: what the model reads of it, and the function that answers it. The schemas use only the plain words of JSON
78
+ # Schema every model on Groq takes: type, description, enum, minimum, maximum, required.
79
+ _TOOLS: Dict[str, Dict[str, Any]] = {
80
+ "datacircle_list_apis": {
81
+ "run": _list_apis,
82
+ "description": "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how many plans "
83
+ "and providers it has and its best plan. Call it to find an API's slug when you don't know it. Gives "
84
+ "total, the APIs found, and apis, up to limit of them.",
85
+ "parameters": {"type": "object", "properties": {
86
+ "query": {"type": "string", "description": "Words of the API's name or slug, like 'email' or 'linkedin profile'. "
87
+ "The APIs that hold the most of them come first, in the sheet's order "
88
+ "when left out."},
89
+ "limit": {"type": "integer", "minimum": 1, "maximum": 200,
90
+ "description": "How many APIs to give, 1 to 200. 20 when left out, of about 170."}}},
91
+ },
92
+ "datacircle_best_plans": {
93
+ "run": _best_plans,
94
+ "description": "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark "
95
+ "(https://datacircle.dev), each with its rank, provider, plan, $ per 1,000 calls and its page: the "
96
+ "best providers of an API. " + _PRICE,
97
+ "parameters": {"type": "object", "properties": {
98
+ "slug": {"type": "string", "description": "The API's slug, like 'email-finder' or 'linkedin-profile', as "
99
+ "datacircle_list_apis gives it."},
100
+ "limit": _LIMIT}, "required": ["slug"]},
101
+ },
102
+ "datacircle_search_plans": {
103
+ "run": _search_plans,
104
+ "description": "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan "
105
+ "name, sorted by score, provider or price. Gives total, offset and up to limit plans. " + _PRICE,
106
+ "parameters": {"type": "object", "properties": {
107
+ "api": {"type": "string", "description": "Only this API's plans, by its name or slug, like 'email-finder'. A "
108
+ "provider's name goes in query, never here. Every API when left out."},
109
+ "query": {"type": "string", "description": "Words that must all appear in the provider's or plan's name, like "
110
+ "'bright data'."},
111
+ "sort": {"type": "string", "enum": ["score", "provider", "price"],
112
+ "description": "score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first)."},
113
+ "limit": _LIMIT,
114
+ "offset": {"type": "integer", "minimum": 0, "description": "How many found plans to skip first. 0 when left out."}}},
115
+ },
116
+ "datacircle_provider": {
117
+ "run": _provider,
118
+ "description": "Gives each API one provider sells and its rank on each on Datacircle's benchmark "
119
+ "(https://datacircle.dev), with how many plans it has there and its best one.",
120
+ "parameters": {"type": "object", "properties": {
121
+ "slug": {"type": "string", "description": "The provider's slug, like 'bright-data', or its name, like 'Bright "
122
+ "Data', which is made a slug."}}, "required": ["slug"]},
123
+ },
124
+ }
125
+ TOOL_NAMES = list(_TOOLS)
126
+
127
+
128
+ def _names(tool_names: Optional[Sequence[str]]) -> List[str]:
129
+ if isinstance(tool_names, str):
130
+ raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
131
+ for name in tool_names or []:
132
+ if name not in _TOOLS:
133
+ raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
134
+ return TOOL_NAMES if tool_names is None else list(tool_names)
135
+
136
+
137
+ def datacircle_tools(tool_names: Optional[Sequence[str]] = None) -> List[Dict[str, Any]]:
138
+ """The tools for client.chat.completions.create(model=..., messages=..., tools=datacircle_tools()), Groq's and
139
+ AsyncGroq's, or beside one's own: tools=[*datacircle_tools(), my_tool]. tool_names keeps some of them only, in their
140
+ order here; all four when left out. Each is a new dict, so an app may change its copy."""
141
+ return [{"type": "function", "function": {"name": name, "description": _TOOLS[name]["description"],
142
+ "parameters": copy.deepcopy(_TOOLS[name]["parameters"])}}
143
+ for name in _names(tool_names)]
144
+
145
+
146
+ def run(name: str, arguments: Any = None) -> str:
147
+ """What a tool gives the model for these arguments, as JSON text: the API's answer, or {"error": its words}.
148
+ arguments is a mapping or its JSON text; the ones the tool doesn't take are left out, and null ones too."""
149
+ if name not in _TOOLS:
150
+ raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
151
+ if isinstance(arguments, bytes):
152
+ arguments = arguments.decode("utf-8", "replace")
153
+ if isinstance(arguments, str):
154
+ try:
155
+ arguments = json.loads(arguments) if arguments.strip() else {}
156
+ except ValueError:
157
+ return _text({"error": f"the arguments are no JSON object: {arguments[:200]!r}"})
158
+ if arguments is not None and not isinstance(arguments, Mapping):
159
+ return _text({"error": f"the arguments are no JSON object: {str(arguments)[:200]!r}"})
160
+ given = dict(arguments or {})
161
+ taken = _TOOLS[name]["parameters"]["properties"]
162
+ try:
163
+ return _text(_TOOLS[name]["run"](**{key: given.get(key) for key in taken}))
164
+ except _api.DatacircleError as error:
165
+ return _text({"error": str(error)})
166
+
167
+
168
+ def _field(item: Any, key: str) -> Any:
169
+ """A field of a dict, or of groq's types by attribute."""
170
+ return item.get(key) if isinstance(item, Mapping) else getattr(item, key, None)
171
+
172
+
173
+ def _named(tool_call: Any) -> Optional[str]:
174
+ """The tool's name in a tool call (groq's ChatCompletionMessageToolCall, or a dict of its shape): when it is one of
175
+ ours."""
176
+ name = _field(_field(tool_call, "function"), "name")
177
+ return name if name in _TOOLS else None
178
+
179
+
180
+ def call(tool_call: Any) -> Optional[Dict[str, str]]:
181
+ """The tool message for one tool call the model returned (one of completion.choices[0].message.tool_calls, or a
182
+ dict of its shape), to append to the messages: {"role": "tool", "tool_call_id": its id, "content": the JSON text}.
183
+ None when the call is for a tool that is not one of these four, so the app runs its own."""
184
+ name = _named(tool_call)
185
+ if name is None:
186
+ return None
187
+ return {"role": "tool", "tool_call_id": _field(tool_call, "id"),
188
+ "content": run(name, _field(_field(tool_call, "function"), "arguments"))}
189
+
190
+
191
+ def _calls(message_or_calls: Any) -> Sequence[Any]:
192
+ """A reply's tool calls, from its message (or a dict of its shape) or from the list itself."""
193
+ if message_or_calls is None:
194
+ return []
195
+ if isinstance(message_or_calls, (list, tuple)):
196
+ return message_or_calls
197
+ return _field(message_or_calls, "tool_calls") or []
198
+
199
+
200
+ def call_all(message_or_calls: Any) -> List[Dict[str, str]]:
201
+ """The tool messages for the calls of these four tools in a reply (its message, or its tool_calls), in their order.
202
+ Calls of other tools are left out, for the app to run."""
203
+ return [message for message in (call(tool_call) for tool_call in _calls(message_or_calls)) if message is not None]
204
+
205
+
206
+ async def acall(tool_call: Any) -> Optional[Dict[str, str]]:
207
+ """call() for AsyncGroq: its HTTPS GET runs in a thread, so the event loop goes on."""
208
+ if _named(tool_call) is None:
209
+ return None
210
+ return await asyncio.to_thread(call, tool_call)
211
+
212
+
213
+ async def acall_all(message_or_calls: Any) -> List[Dict[str, str]]:
214
+ """call_all() for AsyncGroq: the calls run at once, their messages in the calls' order."""
215
+ messages = await asyncio.gather(*(acall(tool_call) for tool_call in _calls(message_or_calls)))
216
+ return [message for message in messages if message is not None]
217
+
218
+
219
+ class _Gathered(dict):
220
+ """A tool call gathered from a stream: a plain dict to the JSON that is sent, its index in the stream kept aside, as
221
+ Groq's API takes no index in an assistant message's tool_calls."""
222
+
223
+ index: Any = None
224
+
225
+
226
+ def collect_tool_calls(calls: List[Dict[str, Any]], delta_tool_calls: Any) -> List[Dict[str, Any]]:
227
+ """Adds a stream chunk's tool calls (chunk.choices[0].delta.tool_calls) to calls and gives calls back. A call may
228
+ come in pieces, its id and name on the first and the call's index on each, and the pieces of an index make one call.
229
+ Each call is a dict {"id", "type": "function", "function": {"name", "arguments"}}, for the assistant message's
230
+ tool_calls and for call_all()."""
231
+ for delta in delta_tool_calls or []:
232
+ index, given = _field(delta, "index"), _field(delta, "id")
233
+ function = _field(delta, "function")
234
+ name, arguments = _field(function, "name"), _field(function, "arguments")
235
+ held = next((made for made in reversed(calls) if index is not None and getattr(made, "index", None) == index), None)
236
+ if held is None or (given and held["id"] and given != held["id"]):
237
+ held = _Gathered(id=given, type="function", function={"name": "", "arguments": ""})
238
+ held.index = index if index is not None else len(calls)
239
+ calls.append(held)
240
+ held["id"] = held["id"] or given
241
+ held["function"]["name"] = held["function"]["name"] or name or ""
242
+ if isinstance(arguments, str):
243
+ held["function"]["arguments"] += arguments
244
+ return calls
245
+
246
+
247
+ __all__: List[str] = ["TOOL_NAMES", "acall", "acall_all", "call", "call_all", "collect_tool_calls", "datacircle_tools", "run"]
@@ -0,0 +1,160 @@
1
+ Metadata-Version: 2.5
2
+ Name: groq-datacircle
3
+ Version: 0.1.0
4
+ Summary: Tools for Groq's 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/groq-python-datacircle
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: api,api-pricing,b2b-data,datacircle,function-calling,groq,gtm,llm,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: groq>=0.13.0
16
+ Description-Content-Type: text/markdown
17
+
18
+ # groq-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 [Groq's Python library](https://github.com/groq/groq-python) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You pass the four Datacircle tools to `client.chat.completions.create()`. 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, with the provider's rank and best plan on each API | `GET /providers/{slug}` |
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install groq-datacircle
37
+ ```
38
+
39
+ groq-datacircle works with `groq` 0.13.0 and later, on Python 3.9 and later.
40
+
41
+ ## Use the tools
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 groq import Groq
47
+ from groq_datacircle import call_all, datacircle_tools
48
+
49
+ client = Groq()
50
+ messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
51
+ message = client.chat.completions.create(model="openai/gpt-oss-20b", 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="openai/gpt-oss-20b", 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
+ ## Use the tools with a stream
64
+
65
+ With `stream=True`, the model's tool calls come in pieces. `collect_tool_calls()` puts the pieces of each call together:
66
+
67
+ ```python
68
+ from groq import Groq
69
+ from groq_datacircle import call_all, collect_tool_calls, datacircle_tools
70
+
71
+ client = Groq()
72
+ messages = [{"role": "user", "content": "Which provider has the cheapest plan of the email-finder API?"}]
73
+
74
+ while True:
75
+ content, calls = "", []
76
+ for chunk in client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools(), stream=True):
77
+ if chunk.choices:
78
+ content += chunk.choices[0].delta.content or ""
79
+ collect_tool_calls(calls, chunk.choices[0].delta.tool_calls)
80
+ if not calls:
81
+ break
82
+ messages.append({"role": "assistant", "content": content, "tool_calls": calls})
83
+ messages.extend(call_all(calls))
84
+
85
+ print(content)
86
+ ```
87
+
88
+ ## Use the tools with AsyncGroq
89
+
90
+ With `AsyncGroq`, use `await acall_all(message)`. `acall_all()` runs the calls at the same time. Your event loop keeps running.
91
+
92
+ ```python
93
+ import asyncio
94
+
95
+ from groq import AsyncGroq
96
+ from groq_datacircle import acall_all, datacircle_tools
97
+
98
+
99
+ async def main():
100
+ client = AsyncGroq()
101
+ messages = [{"role": "user", "content": "Which APIs does Bright Data sell?"}]
102
+ message = (await client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools())).choices[0].message
103
+ while message.tool_calls:
104
+ messages.append(message)
105
+ messages.extend(await acall_all(message))
106
+ message = (await client.chat.completions.create(model="openai/gpt-oss-20b", messages=messages, tools=datacircle_tools())).choices[0].message
107
+ print(message.content)
108
+
109
+
110
+ asyncio.run(main())
111
+ ```
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 groq_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
+ To give the model fewer Datacircle tools, list the tool names: `datacircle_tools(["datacircle_best_plans"])`.
127
+
128
+ ## Call a tool yourself
129
+
130
+ You can call each tool without a model. You get the JSON text of the tool's answer:
131
+
132
+ ```python
133
+ import json
134
+
135
+ from groq_datacircle import run
136
+
137
+ answer = json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
138
+ print(answer["plans"])
139
+ ```
140
+
141
+ ## What the model reads
142
+
143
+ 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.
144
+
145
+ You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
146
+
147
+ 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.
148
+
149
+ ## Network
150
+
151
+ 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.
152
+
153
+ ## Links
154
+
155
+ - Datacircle: https://datacircle.dev
156
+ - The API: https://datacircle.dev/api
157
+ - The API's spec: https://api.datacircle.dev/v1/openapi.json
158
+ - Every field of a plan: https://datacircle.dev/fields
159
+
160
+ MIT license.
@@ -0,0 +1,8 @@
1
+ groq_datacircle/__init__.py,sha256=Mgjfkk9yf9aM-ZCDTWjijN47KU8urED7qAOweZfJaVs,491
2
+ groq_datacircle/_api.py,sha256=zR27gBkr8Oiyc_abrt8JU15hvmJH0C-F1Z7c8NV7LAA,5513
3
+ groq_datacircle/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ groq_datacircle/tools.py,sha256=9boeXDpe6ZL46xHxWOZd6qEQYRAZJZ5RHItYS4v9KNw,14187
5
+ groq_datacircle-0.1.0.dist-info/METADATA,sha256=PlAPe2GTBsSzlT06CosTIzMgptj2R_OSv1Wwtw7M8kA,6820
6
+ groq_datacircle-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ groq_datacircle-0.1.0.dist-info/licenses/LICENSE,sha256=dpgF7zGxeOd9IpQ9yUGa4a-cTj8fI6ulHnuilZEonCo,1067
8
+ groq_datacircle-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.