anthropic-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,25 @@
1
+ """Tools for the Anthropic Python SDK's tool runner on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
2
+
3
+ from anthropic_datacircle._api import BASE_URL, DatacircleError
4
+ from anthropic_datacircle.tools import (
5
+ ASYNC_TOOLS,
6
+ TOOL_NAMES,
7
+ TOOLS,
8
+ atool_results,
9
+ best_plans,
10
+ datacircle_async_tools,
11
+ datacircle_best_plans,
12
+ datacircle_list_apis,
13
+ datacircle_provider,
14
+ datacircle_search_plans,
15
+ datacircle_tools,
16
+ list_apis,
17
+ provider,
18
+ search_plans,
19
+ tool_results,
20
+ )
21
+
22
+ __version__ = "0.1.0"
23
+ __all__ = ["ASYNC_TOOLS", "BASE_URL", "DatacircleError", "TOOLS", "TOOL_NAMES", "atool_results", "best_plans",
24
+ "datacircle_async_tools", "datacircle_best_plans", "datacircle_list_apis", "datacircle_provider",
25
+ "datacircle_search_plans", "datacircle_tools", "list_apis", "provider", "search_plans", "tool_results"]
@@ -0,0 +1,109 @@
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
+ try: # anthropic 0.84.0 and later: the tool runner sends a ToolError's words as the call's result, with is_error
14
+ from anthropic.lib.tools import ToolError as _Refusal
15
+ except ImportError: # before it, the runner sends repr() of any exception, with is_error
16
+ _Refusal = Exception
17
+
18
+ BASE_URL = "https://api.datacircle.dev/v1"
19
+ TIMEOUT = 30.0
20
+ USER_AGENT = "anthropic-datacircle/0.1.0"
21
+
22
+ # 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.
23
+ PLAN_KEYS = ["api", "rank", "provider", "plan", "score", "perThousand", "notFoundPerThousand", "billing", "pay",
24
+ "currency", "units", "unit", "strengths", "latencyMs", "page", "pricingPage", "docs"]
25
+ API_KEYS = ["api", "slug", "plans", "providers", "best", "bestPage", "sheetPage"]
26
+
27
+
28
+ class DatacircleError(_Refusal): # type: ignore[valid-type, misc]
29
+ """The API's refusal in its own words, why it could not be reached, or an argument it can't take. Raised in a tool,
30
+ the tool runner gives the model its words as the call's result, with is_error. status is the API's HTTP status, None
31
+ when it gave none; retryable, whether the same call may be answered later (the API out of reach, busy or failing)."""
32
+
33
+ def __init__(self, message: str, status: Optional[int] = None, retryable: bool = False):
34
+ super().__init__(message)
35
+ self.status = status
36
+ self.retryable = retryable
37
+
38
+ def __str__(self) -> str:
39
+ return str(self.args[0]) if self.args else ""
40
+
41
+
42
+ def brief(item: Dict[str, Any], keys: List[str] = PLAN_KEYS) -> Dict[str, Any]:
43
+ return {key: item[key] for key in keys if item.get(key) is not None}
44
+
45
+
46
+ def slug(value: Any) -> str:
47
+ """The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen."""
48
+ plain = unicodedata.normalize("NFKD", str(value or "").strip().lower())
49
+ plain = "".join(char for char in plain if not unicodedata.combining(char))
50
+ return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
51
+
52
+
53
+ def whole(name: str, value: Any, low: int, high: Optional[int] = None) -> Optional[int]:
54
+ """A whole number from low to high, or None when left out: a plain call may send one as text."""
55
+ if value is None or value == "":
56
+ return None
57
+ try:
58
+ number = float(value)
59
+ except (TypeError, ValueError):
60
+ number = float("nan")
61
+ if isinstance(value, bool) or not math.isfinite(number) or number != int(number):
62
+ raise DatacircleError(f"{name} must be a whole number, not {value!r}")
63
+ if number < low or (high is not None and number > high):
64
+ raise DatacircleError(f"{name} must be from {low} to {high}, not {int(number)}" if high is not None
65
+ else f"{name} must be {low} or more, not {int(number)}")
66
+ return int(number)
67
+
68
+
69
+ def _words(body: bytes) -> str:
70
+ """A refusal's words: the API's error, with every slug when the slug was unknown."""
71
+ text = body.decode("utf-8", "replace")
72
+ try:
73
+ parsed = json.loads(text)
74
+ if parsed.get("slugs"):
75
+ return f"{parsed['error']}; the slugs: {', '.join(parsed['slugs'])}"
76
+ return str(parsed.get("error", text))
77
+ except (ValueError, KeyError, TypeError, AttributeError):
78
+ return text
79
+
80
+
81
+ def get(path: str, params: Optional[Dict[str, Any]] = None) -> Any:
82
+ """The API's JSON answer, or a DatacircleError with its words: waits once when it answers 429."""
83
+ query = urllib.parse.urlencode({key: value for key, value in (params or {}).items() if value not in (None, "")})
84
+ url = f"{BASE_URL.rstrip('/')}{path}" + (f"?{query}" if query else "")
85
+ request = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": USER_AGENT})
86
+ for attempt in range(2):
87
+ try:
88
+ with urllib.request.urlopen(request, timeout=TIMEOUT) as answer:
89
+ body = answer.read()
90
+ except urllib.error.HTTPError as error:
91
+ body = error.read()
92
+ if error.code == 429 and not attempt:
93
+ try:
94
+ wait = int(error.headers.get("Retry-After") or 30)
95
+ except ValueError:
96
+ wait = 30
97
+ time.sleep(min(max(wait, 1), 60))
98
+ continue
99
+ if error.code == 429:
100
+ raise DatacircleError("Datacircle's API answered 429 twice: wait a minute and call again", 429, True) from None
101
+ raise DatacircleError(f"Datacircle's API answered {error.code}: {_words(body)[:3000]}", error.code,
102
+ error.code >= 500) from None
103
+ except (urllib.error.URLError, OSError) as error:
104
+ raise DatacircleError(f"Datacircle's API could not be reached: {getattr(error, 'reason', error)}",
105
+ retryable=True) from None
106
+ try:
107
+ return json.loads(body)
108
+ except ValueError as error:
109
+ raise DatacircleError(f"Datacircle's API gave no JSON: {error}") from None
File without changes
@@ -0,0 +1,258 @@
1
+ """Tools for the Anthropic Python SDK on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
2
+
3
+ Each tool is a beta_tool, and a beta_async_tool of the same name for an AsyncAnthropic client, with its own JSON schema:
4
+ given to client.beta.messages.tool_runner(), the runner sends its definition and runs the calls the model makes, whole
5
+ or streamed. A tool makes one HTTPS GET and gives the model the API's answer as JSON text. A refusal (an unknown slug,
6
+ an argument out of range, the API out of reach) raises DatacircleError: the runner sends its words as the call's result
7
+ with is_error, so the model can call again and the run goes on. Each tool checks its own arguments before any call, as
8
+ a loop of the app's own may send them unchecked.
9
+ """
10
+
11
+ import json
12
+ import urllib.parse
13
+ from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence
14
+
15
+ import anyio
16
+ import anyio.to_thread
17
+ from anthropic import beta_async_tool, beta_tool
18
+
19
+ from anthropic_datacircle import _api
20
+
21
+
22
+ def _best(plans: Any) -> Optional[Dict[str, Any]]:
23
+ """A provider's best plan on an API: its lowest rank, a plan with no score having none."""
24
+ ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
25
+ return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
26
+
27
+
28
+ def _list_apis(query: Any, limit: Any) -> Dict[str, Any]:
29
+ count = _api.whole("limit", limit, 1, 200) or 20
30
+ apis = _api.get("/apis")
31
+ words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
32
+ held = []
33
+ for index, api in enumerate(apis):
34
+ name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
35
+ matched = sum(word in name for word in words)
36
+ if matched or not words:
37
+ held.append((-matched, index, api))
38
+ found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
39
+ return {"total": len(found), "apis": found[:count]}
40
+
41
+
42
+ def _best_plans(slug: Any, limit: Any) -> Dict[str, Any]:
43
+ made = _api.slug(slug)
44
+ if not made:
45
+ raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
46
+ answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
47
+ return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
48
+
49
+
50
+ def _search_plans(api: Any, query: Any, sort: Any, limit: Any, offset: Any) -> Dict[str, Any]:
51
+ order = str(sort).strip().lower() if sort not in (None, "") else None
52
+ if order is not None and order not in ("score", "provider", "price"):
53
+ raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
54
+ params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
55
+ "offset": _api.whole("offset", offset, 0)}
56
+ answer = _api.get("/plans", params)
57
+ return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
58
+
59
+
60
+ def _provider(slug: Any) -> Dict[str, Any]:
61
+ made = _api.slug(slug)
62
+ if not made:
63
+ raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
64
+ answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
65
+ apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
66
+ "best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
67
+ return {**answer, "apis": apis}
68
+
69
+
70
+ def _text(answer: Dict[str, Any]) -> str:
71
+ return json.dumps(answer, ensure_ascii=False)
72
+
73
+
74
+ # What the model reads of each tool: its description and its input schema, the API's own bounds in it.
75
+
76
+ _SLUG_OF_API = "The API's slug, like 'email-finder' or 'linkedin-profile', as datacircle_list_apis gives it."
77
+ _PRICE = "perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
78
+ DESCRIPTIONS = {
79
+ "datacircle_list_apis": "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how "
80
+ "many plans and providers it has and its best plan. Call it to find an API's slug when you "
81
+ "don't know it. Gives total, the APIs found, and apis, up to limit of them.",
82
+ "datacircle_best_plans": "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark "
83
+ "(https://datacircle.dev), each with its rank, provider, plan, $ per 1,000 calls and its "
84
+ "page: the best providers of an API. " + _PRICE,
85
+ "datacircle_search_plans": "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by "
86
+ "provider or plan name, sorted by score, provider or price. Gives total, offset and up "
87
+ "to limit plans. " + _PRICE,
88
+ "datacircle_provider": "Gives each API one provider sells and its rank on each on Datacircle's benchmark "
89
+ "(https://datacircle.dev), with its best plan there.",
90
+ }
91
+ SCHEMAS: Dict[str, Dict[str, Any]] = {
92
+ "datacircle_list_apis": {"type": "object", "properties": {
93
+ "query": {"type": "string", "description": "Words of the API's name or slug, like 'email' or 'linkedin "
94
+ "profile'. The APIs that hold the most of them come first, in the sheet's order when left out."},
95
+ "limit": {"type": "integer", "minimum": 1, "maximum": 200,
96
+ "description": "How many APIs to give. 20 when left out, of about 160."},
97
+ }, "additionalProperties": False},
98
+ "datacircle_best_plans": {"type": "object", "properties": {
99
+ "slug": {"type": "string", "description": _SLUG_OF_API},
100
+ "limit": {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give. 10 when left out."},
101
+ }, "required": ["slug"], "additionalProperties": False},
102
+ "datacircle_search_plans": {"type": "object", "properties": {
103
+ "api": {"type": "string", "description": "Only this API's plans, by its name or slug, like 'email-finder'. A "
104
+ "provider's name goes in query, never here. Every API when left out."},
105
+ "query": {"type": "string", "description": "Words that must all appear in the provider's or plan's name, like "
106
+ "'bright data'."},
107
+ "sort": {"type": "string", "enum": ["score", "provider", "price"],
108
+ "description": "score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first)."},
109
+ "limit": {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give. 10 when left out."},
110
+ "offset": {"type": "integer", "minimum": 0, "description": "How many found plans to skip first. 0 when left out."},
111
+ }, "additionalProperties": False},
112
+ "datacircle_provider": {"type": "object", "properties": {
113
+ "slug": {"type": "string", "description": "The provider's slug, like 'bright-data', or its name, like 'Bright "
114
+ "Data', which is made a slug."},
115
+ }, "required": ["slug"], "additionalProperties": False},
116
+ }
117
+
118
+
119
+ # The functions. Called alone, each gives the API's answer as JSON text, or raises DatacircleError with its words.
120
+
121
+ def list_apis(query: Optional[str] = None, limit: Optional[int] = None) -> str:
122
+ """The GTM APIs on Datacircle's sheet, those whose name or slug holds the most of query's words first: total and
123
+ up to limit apis (1 to 200, 20 when left out), as JSON text."""
124
+ return _text(_list_apis(query, limit))
125
+
126
+
127
+ def best_plans(slug: str, limit: Optional[int] = None) -> str:
128
+ """An API's plans best first by their score out of 100, up to limit (1 to 50, 10 when left out), as JSON text."""
129
+ return _text(_best_plans(slug, limit))
130
+
131
+
132
+ def search_plans(api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
133
+ limit: Optional[int] = None, offset: Optional[int] = None) -> str:
134
+ """Every plan, or one API's, whose provider or plan name holds query's words, sorted by score, provider or price:
135
+ total, offset and up to limit plans (1 to 50, 10 when left out), as JSON text."""
136
+ return _text(_search_plans(api, query, sort, limit, offset))
137
+
138
+
139
+ def provider(slug: str) -> str:
140
+ """Each API one provider sells, its rank on each and its best plan there, as JSON text. slug may be its name."""
141
+ return _text(_provider(slug))
142
+
143
+
144
+ async def _list_apis_async(query: Optional[str] = None, limit: Optional[int] = None) -> str:
145
+ return await anyio.to_thread.run_sync(list_apis, query, limit)
146
+
147
+
148
+ async def _best_plans_async(slug: str, limit: Optional[int] = None) -> str:
149
+ return await anyio.to_thread.run_sync(best_plans, slug, limit)
150
+
151
+
152
+ async def _search_plans_async(api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
153
+ limit: Optional[int] = None, offset: Optional[int] = None) -> str:
154
+ return await anyio.to_thread.run_sync(search_plans, api, query, sort, limit, offset)
155
+
156
+
157
+ async def _provider_async(slug: str) -> str:
158
+ return await anyio.to_thread.run_sync(provider, slug)
159
+
160
+
161
+ def _made(make: Callable[..., Any], name: str, function: Callable[..., Any]) -> Any:
162
+ return make(function, name=name, description=DESCRIPTIONS[name], input_schema=SCHEMAS[name])
163
+
164
+
165
+ datacircle_list_apis = _made(beta_tool, "datacircle_list_apis", list_apis)
166
+ datacircle_best_plans = _made(beta_tool, "datacircle_best_plans", best_plans)
167
+ datacircle_search_plans = _made(beta_tool, "datacircle_search_plans", search_plans)
168
+ datacircle_provider = _made(beta_tool, "datacircle_provider", provider)
169
+
170
+ TOOLS = {tool.name: tool for tool in (datacircle_list_apis, datacircle_best_plans, datacircle_search_plans,
171
+ datacircle_provider)}
172
+ ASYNC_TOOLS = {name: _made(beta_async_tool, name, function) for name, function in (
173
+ ("datacircle_list_apis", _list_apis_async), ("datacircle_best_plans", _best_plans_async),
174
+ ("datacircle_search_plans", _search_plans_async), ("datacircle_provider", _provider_async))}
175
+ TOOL_NAMES = list(TOOLS)
176
+
177
+
178
+ def _chosen(tools: Mapping[str, Any], tool_names: Optional[Sequence[str]]) -> List[Any]:
179
+ if isinstance(tool_names, str):
180
+ raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
181
+ for name in tool_names or []:
182
+ if name not in tools:
183
+ raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
184
+ return [tools[name] for name in (TOOL_NAMES if tool_names is None else tool_names)]
185
+
186
+
187
+ def datacircle_tools(tool_names: Optional[Sequence[str]] = None) -> List[Any]:
188
+ """The tools, for client.beta.messages.tool_runner(tools=datacircle_tools()) or beside one's own:
189
+ tools=[*datacircle_tools(), my_tool]. tool_names keeps some of them only, in their order here; all four when left out."""
190
+ return _chosen(TOOLS, tool_names)
191
+
192
+
193
+ def datacircle_async_tools(tool_names: Optional[Sequence[str]] = None) -> List[Any]:
194
+ """The same tools for an AsyncAnthropic client's tool runner: each runs its HTTPS GET in a worker thread."""
195
+ return _chosen(ASYNC_TOOLS, tool_names)
196
+
197
+
198
+ def _field(item: Any, key: str) -> Any:
199
+ return item.get(key) if isinstance(item, Mapping) else getattr(item, key, None)
200
+
201
+
202
+ def _calls(source: Any) -> List[Any]:
203
+ """The calls of these tools in a reply: a Message or BetaMessage, its content, or a list of its blocks or their dicts."""
204
+ if source is None:
205
+ return []
206
+ if _field(source, "content") is not None and not isinstance(source, (list, tuple)):
207
+ source = _field(source, "content")
208
+ blocks = source if isinstance(source, Iterable) and not isinstance(source, (str, bytes, Mapping)) else [source]
209
+ return [block for block in blocks if _field(block, "type") == "tool_use" and _field(block, "name") in TOOLS]
210
+
211
+
212
+ def _why(error: Exception) -> str:
213
+ """A failed call's words for the model: the API's or the check's, or which argument the SDK's validation refused."""
214
+ cause = error.__cause__
215
+ if cause is not None and hasattr(cause, "errors"):
216
+ try:
217
+ return f"{error}: " + "; ".join(f"{'.'.join(map(str, item['loc'])) or 'input'}: {item['msg']}"
218
+ for item in cause.errors())
219
+ except Exception: # noqa: BLE001 - its plain words then
220
+ pass
221
+ return str(error) if isinstance(error, _api.DatacircleError) else f"{type(error).__name__}: {error}"
222
+
223
+
224
+ def _result(block: Any) -> Dict[str, Any]:
225
+ result: Dict[str, Any] = {"type": "tool_result", "tool_use_id": _field(block, "id")}
226
+ try:
227
+ result["content"] = TOOLS[_field(block, "name")].call(_field(block, "input"))
228
+ except Exception as error: # noqa: BLE001 - every failure is the call's result, as the tool runner gives it
229
+ result.update(content=_why(error), is_error=True)
230
+ return result
231
+
232
+
233
+ def tool_results(message: Any) -> List[Dict[str, Any]]:
234
+ """For a loop of the app's own on client.messages.create(): the tool_result block of each call of these tools in
235
+ a reply (a Message, its content, or a list of its blocks or their dicts), in their order, with its call's id. A
236
+ refused call's block holds the refusal's words and is_error. Calls of other tools are left out, for the app to run."""
237
+ return [_result(block) for block in _calls(message)]
238
+
239
+
240
+ async def atool_results(message: Any) -> List[Dict[str, Any]]:
241
+ """tool_results() for an AsyncAnthropic client: the calls run at once, each in a worker thread, their blocks in the
242
+ calls' order."""
243
+ calls = _calls(message)
244
+ results: List[Dict[str, Any]] = [{} for _ in calls]
245
+
246
+ async def one(index: int, block: Any) -> None:
247
+ results[index] = await anyio.to_thread.run_sync(_result, block)
248
+
249
+ async with anyio.create_task_group() as group:
250
+ for index, block in enumerate(calls):
251
+ group.start_soon(one, index, block)
252
+ return results
253
+
254
+
255
+ __all__: List[str] = ["ASYNC_TOOLS", "DESCRIPTIONS", "SCHEMAS", "TOOLS", "TOOL_NAMES", "atool_results", "best_plans",
256
+ "datacircle_async_tools", "datacircle_best_plans", "datacircle_list_apis", "datacircle_provider",
257
+ "datacircle_search_plans", "datacircle_tools", "list_apis", "provider", "search_plans",
258
+ "tool_results"]
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.5
2
+ Name: anthropic-datacircle
3
+ Version: 0.1.0
4
+ Summary: Anthropic Python SDK tools for 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/anthropic-datacircle-py
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: anthropic,api,api-pricing,b2b-data,claude,datacircle,gtm,tool-runner,tool-use,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: anthropic>=0.68.0
16
+ Requires-Dist: anyio>=3.5.0
17
+ Description-Content-Type: text/markdown
18
+
19
+ # anthropic-datacircle
20
+
21
+ Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
22
+
23
+ Our website: https://datacircle.dev
24
+
25
+ This package gives the [Anthropic Python SDK](https://github.com/anthropics/anthropic-sdk-python) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You give them to the SDK's tool runner, which runs each call Claude makes. You need no key and no account for Datacircle.
26
+
27
+ | Tool | What the tool gives | Call |
28
+ | --- | --- | --- |
29
+ | `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
30
+ | `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` |
31
+ | `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` |
32
+ | `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install anthropic-datacircle
38
+ ```
39
+
40
+ anthropic-datacircle works with `anthropic` 0.68.0 and later, on Python 3.9 and later.
41
+
42
+ ## Use the tools
43
+
44
+ Give the tools to the tool runner. The runner runs each call and sends the answer back to Claude:
45
+
46
+ ```python
47
+ import anthropic
48
+ from anthropic_datacircle import datacircle_tools
49
+
50
+ client = anthropic.Anthropic()
51
+ runner = client.beta.messages.tool_runner(
52
+ model="claude-opus-5-5",
53
+ max_tokens=16000,
54
+ tools=datacircle_tools(),
55
+ messages=[{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}],
56
+ )
57
+ message = runner.until_done()
58
+ print(next(block.text for block in message.content if block.type == "text"))
59
+ ```
60
+
61
+ You can also loop over the runner (`for message in runner:`) to see each message. With `stream=True`, the runner gives you a stream for each message.
62
+
63
+ With `AsyncAnthropic`, use `datacircle_async_tools()`. Each async tool runs its HTTPS request in a worker thread, so your event loop keeps running:
64
+
65
+ ```python
66
+ import anthropic
67
+ from anthropic_datacircle import datacircle_async_tools
68
+
69
+ client = anthropic.AsyncAnthropic()
70
+ runner = client.beta.messages.tool_runner(
71
+ model="claude-opus-5-5",
72
+ max_tokens=16000,
73
+ tools=datacircle_async_tools(),
74
+ messages=[{"role": "user", "content": "What does Bright Data sell?"}],
75
+ )
76
+ message = await runner.until_done()
77
+ ```
78
+
79
+ ## Use them beside your own tools
80
+
81
+ You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), get_weather]`. To give Claude only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
82
+
83
+ ## Run the calls yourself
84
+
85
+ In a loop of your own on `client.messages.create()`, send each tool's definition with `tool.to_dict()`. Then `tool_results()` runs the Datacircle calls in a reply. It gives you one `tool_result` block for each call, with the call's id. Calls of your own tools are left out, for your code to run:
86
+
87
+ ```python
88
+ import anthropic
89
+ from anthropic_datacircle import datacircle_tools, tool_results
90
+
91
+ client = anthropic.Anthropic()
92
+ tools = [tool.to_dict() for tool in datacircle_tools()]
93
+ messages = [{"role": "user", "content": "What does Bright Data sell?"}]
94
+ reply = client.messages.create(model="claude-opus-5-5", max_tokens=16000, tools=tools, messages=messages)
95
+
96
+ while reply.stop_reason == "tool_use":
97
+ messages.append({"role": "assistant", "content": reply.content})
98
+ messages.append({"role": "user", "content": tool_results(reply)})
99
+ reply = client.messages.create(model="claude-opus-5-5", max_tokens=16000, tools=tools, messages=messages)
100
+
101
+ print(next(block.text for block in reply.content if block.type == "text"))
102
+ ```
103
+
104
+ With `AsyncAnthropic`, use `await atool_results(reply)`. It runs the calls at the same time.
105
+
106
+ ## Call a tool yourself
107
+
108
+ You can call each tool without Claude. You get the tool's answer as JSON text:
109
+
110
+ ```python
111
+ import json
112
+ from anthropic_datacircle import best_plans
113
+
114
+ answer = json.loads(best_plans("email-finder", limit=3))
115
+ print(answer["plans"])
116
+ ```
117
+
118
+ The other functions are `list_apis()`, `search_plans()` and `provider()`.
119
+
120
+ ## What Claude reads
121
+
122
+ Each tool gives Claude 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.
123
+
124
+ You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
125
+
126
+ When the API gives no data, such as for an unknown slug, the tool raises `DatacircleError` with the API's message. The runner sends that message to Claude as the call's result, with `is_error`. The error for an unknown API slug lists every valid slug. The tool checks each number first. For a number out of range, the tool raises the error and makes no API call. If the network fails, the error holds the network error's message. Claude can then call the tool again.
127
+
128
+ ## Network
129
+
130
+ 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 tool waits once, for a minute at most, when the API asks the tool to wait. Each call uses only Python's standard library. Nothing goes to disk.
131
+
132
+ ## Links
133
+
134
+ - Datacircle: https://datacircle.dev
135
+ - The API: https://datacircle.dev/api
136
+ - The API's spec: https://api.datacircle.dev/v1/openapi.json
137
+ - What each key means: https://datacircle.dev/fields
138
+
139
+ MIT license.
@@ -0,0 +1,8 @@
1
+ anthropic_datacircle/__init__.py,sha256=Q41hvgi14w-31VQ2v7y3wB2qQN_6ckGId5NWY8kin7M,912
2
+ anthropic_datacircle/_api.py,sha256=S8sSPItG_qmRTO4STVQoMzdUfKCf4nQ2swgL_AcHWc0,5306
3
+ anthropic_datacircle/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ anthropic_datacircle/tools.py,sha256=EUkAJAdZwhPqI2pCVmVjwz7zSXbojB32JGRa8HW8ERg,14447
5
+ anthropic_datacircle-0.1.0.dist-info/METADATA,sha256=Qcai_BL-J3oJE802t9bVSiIJNhGX1DMu13Yk5HIkn0c,6368
6
+ anthropic_datacircle-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ anthropic_datacircle-0.1.0.dist-info/licenses/LICENSE,sha256=dpgF7zGxeOd9IpQ9yUGa4a-cTj8fI6ulHnuilZEonCo,1067
8
+ anthropic_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.