langchain-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,20 @@
1
+ """LangChain tools for Datacircle's open API: find the best GTM APIs. https://datacircle.dev"""
2
+
3
+ from langchain_datacircle.toolkit import DatacircleToolkit
4
+ from langchain_datacircle.tools import (
5
+ DatacircleBestPlansTool,
6
+ DatacircleListApisTool,
7
+ DatacircleProviderTool,
8
+ DatacircleSearchPlansTool,
9
+ )
10
+
11
+ __version__ = "0.1.0"
12
+
13
+ __all__ = [
14
+ "DatacircleBestPlansTool",
15
+ "DatacircleListApisTool",
16
+ "DatacircleProviderTool",
17
+ "DatacircleSearchPlansTool",
18
+ "DatacircleToolkit",
19
+ "__version__",
20
+ ]
@@ -0,0 +1,61 @@
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 re
5
+ import time
6
+ import unicodedata
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ from typing import Any, Dict, List, Optional
11
+
12
+ from langchain_core.tools import ToolException
13
+
14
+ BASE_URL = "https://api.datacircle.dev/v1"
15
+ USER_AGENT = "langchain-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
+ def brief(item: Dict[str, Any], keys: List[str] = PLAN_KEYS) -> Dict[str, Any]:
24
+ return {key: item[key] for key in keys if item.get(key) is not None}
25
+
26
+
27
+ def slug(value: Any) -> str:
28
+ """The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen."""
29
+ plain = unicodedata.normalize("NFKD", str(value or "").strip().lower())
30
+ plain = "".join(char for char in plain if not unicodedata.combining(char))
31
+ return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
32
+
33
+
34
+ def get(path: str, params: Optional[Dict[str, Any]] = None, base_url: str = BASE_URL, timeout: float = 30) -> Any:
35
+ """The API's JSON answer, or a ToolException with its words: an unknown slug's answer lists every slug."""
36
+ query = urllib.parse.urlencode({key: value for key, value in (params or {}).items() if value not in (None, "")})
37
+ url = f"{base_url.rstrip('/')}{path}{'?' + query if query else ''}"
38
+ request = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": USER_AGENT})
39
+ for attempt in range(2):
40
+ try:
41
+ with urllib.request.urlopen(request, timeout=timeout) as answer:
42
+ return json.loads(answer.read().decode("utf-8"))
43
+ except urllib.error.HTTPError as error:
44
+ body = error.read().decode("utf-8", "replace")
45
+ if error.code == 429 and attempt == 0:
46
+ try:
47
+ wait = int(error.headers.get("Retry-After") or 30)
48
+ except ValueError:
49
+ wait = 30
50
+ time.sleep(min(max(wait, 1), 60))
51
+ continue
52
+ words = body
53
+ try:
54
+ parsed = json.loads(body)
55
+ words = f"{parsed['error']}; the slugs: {', '.join(parsed['slugs'])}" if parsed.get("slugs") else parsed.get("error", body)
56
+ except (ValueError, KeyError, TypeError, AttributeError):
57
+ pass
58
+ raise ToolException(f"Datacircle's API answered {error.code}: {str(words)[:3000]}") from None
59
+ except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error:
60
+ raise ToolException(f"Datacircle's API could not be reached: {error}") from None
61
+ raise ToolException("Datacircle's API answered 429 twice: wait a minute and call again")
@@ -0,0 +1,23 @@
1
+ """The four Datacircle tools as one toolkit."""
2
+
3
+ from typing import List
4
+
5
+ from langchain_core.tools import BaseTool, BaseToolkit
6
+
7
+ from langchain_datacircle import _api
8
+ from langchain_datacircle.tools import (
9
+ DatacircleBestPlansTool,
10
+ DatacircleListApisTool,
11
+ DatacircleProviderTool,
12
+ DatacircleSearchPlansTool,
13
+ )
14
+
15
+
16
+ class DatacircleToolkit(BaseToolkit):
17
+ """Datacircle's four tools: every GTM API, who is best for each, plan search and a provider. No key."""
18
+
19
+ base_url: str = _api.BASE_URL
20
+
21
+ def get_tools(self) -> List[BaseTool]:
22
+ return [tool(base_url=self.base_url) for tool in
23
+ (DatacircleListApisTool, DatacircleBestPlansTool, DatacircleSearchPlansTool, DatacircleProviderTool)]
@@ -0,0 +1,146 @@
1
+ """Four LangChain tools on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account."""
2
+
3
+ import urllib.parse
4
+ from typing import Any, Dict, Literal, Optional, Type
5
+
6
+ from langchain_core.callbacks import CallbackManagerForToolRun
7
+ from langchain_core.tools import BaseTool, ToolException
8
+ from pydantic import BaseModel, Field, ValidationError
9
+
10
+ from langchain_datacircle import _api
11
+
12
+ PRICE = "perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
13
+
14
+
15
+ def _invalid(error: ValidationError) -> str:
16
+ return "Invalid arguments: " + "; ".join(f"{'.'.join(map(str, e['loc']))}: {e['msg']}" for e in error.errors())
17
+
18
+
19
+ class _DatacircleTool(BaseTool):
20
+ """What the four tools share: the API's address, and its errors and a model's wrong arguments given as the tool's answer."""
21
+
22
+ base_url: str = _api.BASE_URL
23
+ handle_tool_error: bool = True
24
+ handle_validation_error: Any = _invalid
25
+
26
+ def _get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
27
+ return _api.get(path, params, base_url=self.base_url)
28
+
29
+
30
+ class ListApisInput(BaseModel):
31
+ query: Optional[str] = Field(
32
+ default=None,
33
+ description="Words of the API's name or slug, like 'email' or 'linkedin profile': the APIs that hold the most "
34
+ "of them come first. The sheet's order when left out.",
35
+ )
36
+ limit: Optional[int] = Field(default=None, ge=1, le=200,
37
+ description="How many APIs to give, 1 to 200. 20 when left out: the sheet has about 150.")
38
+
39
+
40
+ class DatacircleListApisTool(_DatacircleTool):
41
+ """Every GTM API on Datacircle's sheet: `GET /apis`."""
42
+
43
+ name: str = "datacircle_list_apis"
44
+ description: str = (
45
+ "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how many plans and "
46
+ "providers it has and its best plan. Call it first to find an API's slug."
47
+ )
48
+ args_schema: Type[BaseModel] = ListApisInput
49
+
50
+ def _run(self, query: Optional[str] = None, limit: Optional[int] = None,
51
+ run_manager: Optional[CallbackManagerForToolRun] = None) -> Dict[str, Any]:
52
+ apis = self._get("/apis")
53
+ words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
54
+ held = []
55
+ for index, api in enumerate(apis):
56
+ name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
57
+ matched = sum(word in name for word in words)
58
+ if matched or not words:
59
+ held.append((-matched, index, api))
60
+ found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
61
+ return {"total": len(found), "apis": found[:limit or 20]}
62
+
63
+
64
+ class BestPlansInput(BaseModel):
65
+ slug: str = Field(description="The API's slug, like 'email-finder' or 'linkedin-profile', as datacircle_list_apis gives it.")
66
+ limit: Optional[int] = Field(default=None, ge=1, le=50, description="How many plans to give, 1 to 50. 10 when left out.")
67
+
68
+
69
+ class DatacircleBestPlansTool(_DatacircleTool):
70
+ """One API's plans, best first by score: `GET /apis/{slug}/best`."""
71
+
72
+ name: str = "datacircle_best_plans"
73
+ description: str = (
74
+ "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark (https://datacircle.dev), "
75
+ "each with its rank, provider, plan, $ per 1,000 calls and its page. " + PRICE
76
+ )
77
+ args_schema: Type[BaseModel] = BestPlansInput
78
+
79
+ def _run(self, slug: str, limit: Optional[int] = None,
80
+ run_manager: Optional[CallbackManagerForToolRun] = None) -> Dict[str, Any]:
81
+ made = _api.slug(slug)
82
+ if not made:
83
+ raise ToolException("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
84
+ answer = self._get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": limit})
85
+ return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
86
+
87
+
88
+ class SearchPlansInput(BaseModel):
89
+ api: Optional[str] = Field(
90
+ default=None,
91
+ description="Only this API's plans: its name or slug, like 'email-finder'. A provider's name goes in query, never "
92
+ "here. Every API when left out.",
93
+ )
94
+ query: Optional[str] = Field(default=None,
95
+ description="Words that must all appear in the provider's or plan's name, like 'bright data'.")
96
+ sort: Optional[Literal["score", "provider", "price"]] = Field(
97
+ default=None, description="score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first).")
98
+ limit: Optional[int] = Field(default=None, ge=1, le=50, description="How many plans to give, 1 to 50. 10 when left out.")
99
+ offset: Optional[int] = Field(default=None, ge=0, description="How many found plans to skip first. 0 when left out.")
100
+
101
+
102
+ class DatacircleSearchPlansTool(_DatacircleTool):
103
+ """Every plan, or an API's, by provider or plan name: `GET /plans`."""
104
+
105
+ name: str = "datacircle_search_plans"
106
+ description: str = (
107
+ "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan name, "
108
+ "sorted by score, provider or price. Gives how many were found and up to limit of them. " + PRICE
109
+ )
110
+ args_schema: Type[BaseModel] = SearchPlansInput
111
+
112
+ def _run(self, api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
113
+ limit: Optional[int] = None, offset: Optional[int] = None,
114
+ run_manager: Optional[CallbackManagerForToolRun] = None) -> Dict[str, Any]:
115
+ answer = self._get("/plans", {"api": api, "query": query, "sort": sort, "limit": limit, "offset": offset})
116
+ return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
117
+
118
+
119
+ class ProviderInput(BaseModel):
120
+ slug: str = Field(description="The provider's slug, like 'bright-data', or its name, like 'Bright Data': the name is made a slug.")
121
+
122
+
123
+ def _best(plans: Any) -> Optional[Dict[str, Any]]:
124
+ """A provider's best plan on an API: its lowest rank, a plan with no score having none."""
125
+ ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
126
+ return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
127
+
128
+
129
+ class DatacircleProviderTool(_DatacircleTool):
130
+ """One provider on every API it sells: `GET /providers/{slug}`."""
131
+
132
+ name: str = "datacircle_provider"
133
+ description: str = (
134
+ "Gives each API one provider sells and its rank on each on Datacircle's benchmark (https://datacircle.dev), "
135
+ "with its best plan there."
136
+ )
137
+ args_schema: Type[BaseModel] = ProviderInput
138
+
139
+ def _run(self, slug: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> Dict[str, Any]:
140
+ made = _api.slug(slug)
141
+ if not made:
142
+ raise ToolException("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
143
+ answer = self._get(f"/providers/{urllib.parse.quote(made)}")
144
+ apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
145
+ "best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
146
+ return {**answer, "apis": apis}
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-datacircle
3
+ Version: 0.1.0
4
+ Summary: LangChain 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/langchain-datacircle
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: api,api-pricing,b2b-data,datacircle,gtm,langchain,langchain-tools
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Software Development :: Libraries
14
+ Requires-Python: >=3.10
15
+ Requires-Dist: langchain-core<2.0.0,>=0.3.15
16
+ Description-Content-Type: text/markdown
17
+
18
+ # langchain-datacircle
19
+
20
+ Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website: https://datacircle.dev
21
+
22
+ This package gives LangChain four tools on Datacircle's open API, https://api.datacircle.dev/v1. You need no key and no account.
23
+
24
+ ```bash
25
+ pip install langchain-datacircle
26
+ ```
27
+
28
+ | Tool | What it gives | Call |
29
+ | --- | --- | --- |
30
+ | `DatacircleListApisTool` (`datacircle_list_apis`) | Every GTM API on Datacircle, with its slug, number of plans and providers, and its best plan | `GET /apis` |
31
+ | `DatacircleBestPlansTool` (`datacircle_best_plans`) | One API's plans, best first by score out of 100, each with its rank and price per 1,000 calls | `GET /apis/{slug}/best` |
32
+ | `DatacircleSearchPlansTool` (`datacircle_search_plans`) | Plans by provider or plan name, on every API or one, sorted by score, provider or price | `GET /plans` |
33
+ | `DatacircleProviderTool` (`datacircle_provider`) | The APIs a provider sells and its rank on each | `GET /providers/{slug}` |
34
+
35
+ ## Use
36
+
37
+ ```python
38
+ from langchain_datacircle import DatacircleBestPlansTool, DatacircleToolkit
39
+
40
+ DatacircleBestPlansTool().invoke({"slug": "email-finder", "limit": 3})
41
+
42
+ tools = DatacircleToolkit().get_tools() # the four, for an agent
43
+ ```
44
+
45
+ With an agent (any chat model that calls tools):
46
+
47
+ ```python
48
+ from langchain.agents import create_agent
49
+ from langchain_ollama import ChatOllama
50
+
51
+ agent = create_agent(ChatOllama(model="gpt-oss:20b"), tools=DatacircleToolkit().get_tools())
52
+ agent.invoke({"messages": [("user", "Which email finder API is best for under $5 per 1,000?")]})
53
+ ```
54
+
55
+ Each tool gives a dict; an agent reads it as JSON. An unknown slug or a value out of range comes back as the tool's answer, with the API's words (an unknown API's answer lists every slug).
56
+
57
+ ## Network
58
+
59
+ Each call makes one HTTPS GET to https://api.datacircle.dev/v1 with the tool's arguments and nothing else. The API takes up to 60 calls a minute from one address; the tools wait once, a minute at most, when it asks them to. Every plan is also one file at https://datacircle.dev/datacircle.json.
60
+
61
+ ## Links
62
+
63
+ - Datacircle: https://datacircle.dev
64
+ - The API: https://datacircle.dev/api
65
+ - Its spec: https://api.datacircle.dev/v1/openapi.json
66
+ - What each key means: https://datacircle.dev/fields
67
+
68
+ MIT license.
@@ -0,0 +1,8 @@
1
+ langchain_datacircle/__init__.py,sha256=IaPVvyNQuaoDiRhpeXFB36TEA7dX7IoN8QDI-Cvtql4,521
2
+ langchain_datacircle/_api.py,sha256=gPeaVIp9ziAo12BUruFqsC0qDXIBrZkpLj1OlDaMaZU,3144
3
+ langchain_datacircle/toolkit.py,sha256=Sjma77X0R1z_PIsOYC-BdrCfzLsYDwvVJabP77N0o8w,729
4
+ langchain_datacircle/tools.py,sha256=eepOpWtUbJLEoL0N9v_FNvORBqcAmGbJgR0MEhgA2Uw,7359
5
+ langchain_datacircle-0.1.0.dist-info/METADATA,sha256=lLJLxDs7PonW_6IYp9qszedgigE-Jyxjq7xU4LSqcwQ,2997
6
+ langchain_datacircle-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ langchain_datacircle-0.1.0.dist-info/licenses/LICENSE,sha256=dpgF7zGxeOd9IpQ9yUGa4a-cTj8fI6ulHnuilZEonCo,1067
8
+ langchain_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.