agentscope-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,22 @@
1
+ """AgentScope tools for Datacircle's open API, https://api.datacircle.dev/v1: every GTM API, who is best for each, every
2
+ plan and a provider's ranks. No key, no account. https://datacircle.dev
3
+
4
+ On AgentScope 2: Toolkit(tools=agentscope_datacircle.tools()). On AgentScope 1: agentscope_datacircle.register(toolkit).
5
+ list_apis, best_plans, search_plans and provider give each tool's answer as a dict, on either."""
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ from agentscope_datacircle._api import DatacircleError
10
+ from agentscope_datacircle._plain import NAMES, best_plans, list_apis, provider, search_plans
11
+
12
+ import importlib.metadata as _metadata
13
+
14
+ # The installed AgentScope's major version, which tools() and register() are made for.
15
+ AGENTSCOPE = int(_metadata.version("agentscope").split(".")[0])
16
+
17
+ if AGENTSCOPE >= 2:
18
+ from agentscope_datacircle._v2 import (DatacircleBestPlans, DatacircleListApis, DatacircleProvider,
19
+ DatacircleSearchPlans, DatacircleTool, register, tools)
20
+ else:
21
+ from agentscope_datacircle._v1 import (datacircle_best_plans, datacircle_list_apis, datacircle_provider,
22
+ datacircle_search_plans, json_schema, register, tools)
@@ -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 = "agentscope-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: each tool gives
25
+ the model its words as the call's result, {"error": ...}. status is the API's HTTP status, None when
26
+ it gave none; 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
@@ -0,0 +1,137 @@
1
+ """The four calls of Datacircle's open API as plain functions giving dicts, and what a model reads of each tool: its
2
+ name, its description and its parameters as a JSON schema. Both AgentScope 1 and 2 tools are made from these."""
3
+
4
+ import json
5
+ import urllib.parse
6
+ from typing import Any, Dict, Optional
7
+
8
+ from agentscope_datacircle import _api
9
+
10
+ NAMES = ["datacircle_list_apis", "datacircle_best_plans", "datacircle_search_plans", "datacircle_provider"]
11
+
12
+
13
+ def _best(plans: Any) -> Optional[Dict[str, Any]]:
14
+ """A provider's best plan on an API: its lowest rank, a plan with no score having none."""
15
+ ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
16
+ return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
17
+
18
+
19
+ def _text(value: Any) -> Optional[str]:
20
+ """A text argument as the API takes it: a number made text, null left out."""
21
+ return None if value is None else str(value)
22
+
23
+
24
+ def list_apis(query: Optional[str] = None, limit: Optional[int] = None) -> Dict[str, Any]:
25
+ """Every API on the sheet, those whose name or slug holds the most words of query first: {"total", "apis"}."""
26
+ count = _api.whole("limit", limit, 1, 200) or 20
27
+ apis = _api.get("/apis")
28
+ words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
29
+ held = []
30
+ for index, api in enumerate(apis):
31
+ name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
32
+ matched = sum(word in name for word in words)
33
+ if matched or not words:
34
+ held.append((-matched, index, api))
35
+ found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
36
+ return {"total": len(found), "apis": found[:count]}
37
+
38
+
39
+ def best_plans(slug: Optional[str] = None, limit: Optional[int] = None) -> Dict[str, Any]:
40
+ """One API's plans best first by score, each with its rank."""
41
+ made = _api.slug(slug)
42
+ if not made:
43
+ raise _api.DatacircleError("Give an API's slug, like 'email-finder'. The list of APIs gives every slug.")
44
+ answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
45
+ return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
46
+
47
+
48
+ def search_plans(api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
49
+ limit: Optional[int] = None, offset: Optional[int] = None) -> Dict[str, Any]:
50
+ """Every plan, or one API's, or those whose provider or plan name holds every word of query: {"total", "offset", "plans"}."""
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": _text(api), "query": _text(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: Optional[str] = None) -> Dict[str, Any]:
61
+ """One provider's APIs, its rank on each and its best plan there. A name is made a slug."""
62
+ made = _api.slug(slug)
63
+ if not made:
64
+ raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
65
+ answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
66
+ apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
67
+ "best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
68
+ return {**answer, "apis": apis}
69
+
70
+
71
+ def _schema(properties: Dict[str, Any], required: Optional[list] = None) -> Dict[str, Any]:
72
+ return {"type": "object", "properties": properties, "required": required or []}
73
+
74
+
75
+ _PRICE = " perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
76
+ _LIMIT = {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give, 1 to 50. 10 when left out."}
77
+
78
+ # Each tool: (its description, its parameters, the plain function it calls with them).
79
+ TOOLS = {
80
+ "datacircle_list_apis": (
81
+ "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how many plans and "
82
+ "providers it has and its best plan. Use it first to find an API's slug. Gives total, the APIs found, and apis, "
83
+ "up to limit of them.",
84
+ _schema({
85
+ "query": {"type": "string", "description": "Words of the API's name or slug, like 'email' or 'linkedin "
86
+ "profile': the APIs that hold the most of them come first. The sheet's order when left out."},
87
+ "limit": {"type": "integer", "minimum": 1, "maximum": 200, "description": "How many APIs to give, 1 to "
88
+ "200. 20 when left out."},
89
+ }),
90
+ lambda args: list_apis(_text(args.get("query")), args.get("limit")),
91
+ ),
92
+ "datacircle_best_plans": (
93
+ "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark (https://datacircle.dev), "
94
+ "each with its rank, provider, plan, $ per 1,000 calls and its page: the best providers of an API." + _PRICE,
95
+ _schema({
96
+ "slug": {"type": "string", "description": "The API's slug, like 'email-finder' or 'linkedin-profile'. The "
97
+ "list of APIs gives every slug."},
98
+ "limit": _LIMIT,
99
+ }, ["slug"]),
100
+ lambda args: best_plans(_text(args.get("slug")), args.get("limit")),
101
+ ),
102
+ "datacircle_search_plans": (
103
+ "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan name, "
104
+ "sorted by score, provider or price. Gives total, offset and up to limit plans." + _PRICE,
105
+ _schema({
106
+ "api": {"type": "string", "description": "Only this API's plans: 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, "
109
+ "like 'bright data'."},
110
+ "sort": {"type": "string", "enum": ["score", "provider", "price"], "description": "score (best first, the "
111
+ "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 "
114
+ "left out."},
115
+ }),
116
+ lambda args: search_plans(args.get("api"), args.get("query"), args.get("sort"), args.get("limit"),
117
+ args.get("offset")),
118
+ ),
119
+ "datacircle_provider": (
120
+ "Gives each API one provider sells and its rank on each on Datacircle's benchmark (https://datacircle.dev), "
121
+ "with its best plan there.",
122
+ _schema({
123
+ "slug": {"type": "string", "description": "The provider's slug, like 'bright-data', or its name, like "
124
+ "'Bright Data': the name is made a slug."},
125
+ }, ["slug"]),
126
+ lambda args: provider(_text(args.get("slug"))),
127
+ ),
128
+ }
129
+
130
+
131
+ def answer(name: str, args: Dict[str, Any]) -> "tuple[str, bool]":
132
+ """A tool's call with the model's arguments: the answer as JSON text and True, or {"error": ...} and False when the
133
+ API or the tool refused it, in their words, so the model can call again."""
134
+ try:
135
+ return json.dumps(TOOLS[name][2](args), ensure_ascii=False), True
136
+ except _api.DatacircleError as error:
137
+ return json.dumps({"error": str(error)}, ensure_ascii=False), False
@@ -0,0 +1,68 @@
1
+ """The four tools for AgentScope 1: async tool functions giving a ToolResponse, which register(toolkit) adds to a
2
+ Toolkit by its register_tool_function, with their JSON schemas, beside an app's own, for a ReActAgent.
3
+
4
+ A function's docstring is the schema AgentScope 1 reads when the function is registered alone. A call runs the API's
5
+ one HTTPS GET in a thread and gives the model the answer as JSON text; a refusal (an unknown slug, a number out of
6
+ range, the API out of reach) is {"error": ...}, so the model can call again."""
7
+
8
+ import asyncio
9
+ import copy
10
+ from typing import Any, Callable, Dict, List, Optional
11
+
12
+ from agentscope.message import TextBlock
13
+ from agentscope.tool import ToolResponse
14
+
15
+ from agentscope_datacircle import _plain
16
+
17
+
18
+ async def _respond(name: str, args: Dict[str, Any]) -> ToolResponse:
19
+ text, _ = await asyncio.to_thread(_plain.answer, name, args)
20
+ return ToolResponse(content=[TextBlock(type="text", text=text)])
21
+
22
+
23
+ async def datacircle_list_apis(query: Optional[str] = None, limit: Optional[int] = None) -> ToolResponse:
24
+ return await _respond("datacircle_list_apis", {"query": query, "limit": limit})
25
+
26
+
27
+ async def datacircle_best_plans(slug: str, limit: Optional[int] = None) -> ToolResponse:
28
+ return await _respond("datacircle_best_plans", {"slug": slug, "limit": limit})
29
+
30
+
31
+ async def datacircle_search_plans(api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
32
+ limit: Optional[int] = None, offset: Optional[int] = None) -> ToolResponse:
33
+ return await _respond("datacircle_search_plans", {"api": api, "query": query, "sort": sort, "limit": limit,
34
+ "offset": offset})
35
+
36
+
37
+ async def datacircle_provider(slug: str) -> ToolResponse:
38
+ return await _respond("datacircle_provider", {"slug": slug})
39
+
40
+
41
+ FUNCTIONS: List[Callable[..., Any]] = [datacircle_list_apis, datacircle_best_plans, datacircle_search_plans,
42
+ datacircle_provider]
43
+ _TYPES = {"string": "str", "integer": "int"}
44
+
45
+ for _function in FUNCTIONS:
46
+ _description, _schema, _ = _plain.TOOLS[_function.__name__]
47
+ _function.__doc__ = _description + "\n\nArgs:\n" + "".join(
48
+ f" {key} (`{_TYPES[spec['type']]}`{'' if key in _schema['required'] else ', optional'}):\n"
49
+ f" {spec['description']}\n" for key, spec in _schema["properties"].items())
50
+
51
+
52
+ def json_schema(name: str) -> Dict[str, Any]:
53
+ """A tool's schema as AgentScope 1's register_tool_function takes it."""
54
+ description, schema, _ = _plain.TOOLS[name]
55
+ return {"type": "function", "function": {"name": name, "description": description,
56
+ "parameters": copy.deepcopy(schema)}}
57
+
58
+
59
+ def tools() -> List[Callable[..., Any]]:
60
+ """The four tool functions."""
61
+ return list(FUNCTIONS)
62
+
63
+
64
+ def register(toolkit: Any, group_name: str = "basic") -> None:
65
+ """Adds the four tools to an AgentScope 1 Toolkit, in its basic group (always active) or in group_name, a group
66
+ made with toolkit.create_tool_group first."""
67
+ for function in FUNCTIONS:
68
+ toolkit.register_tool_function(function, group_name=group_name, json_schema=json_schema(function.__name__))
@@ -0,0 +1,66 @@
1
+ """The four tools for AgentScope 2: ToolBase objects for a Toolkit's tools (Toolkit(tools=tools()), or
2
+ await toolkit.add_tool(tools()) on a toolkit that exists), beside an app's own tools, for an Agent's ReAct loop.
3
+
4
+ Each is read-only, so the permission engine allows it in every mode, explore mode too, and its check_permissions allows
5
+ it too, so no user is asked to confirm a call. A call runs the API's one HTTPS GET in a thread and gives the model the
6
+ answer as JSON text in a ToolChunk; a refusal (an unknown slug, a number out of range, the API out of reach) is
7
+ {"error": ...} in a ToolChunk whose state is error, so the model can call again."""
8
+
9
+ import asyncio
10
+ import copy
11
+ from typing import Any, List
12
+
13
+ from agentscope.message import TextBlock, ToolResultState
14
+ from agentscope.permission import PermissionBehavior, PermissionDecision
15
+ from agentscope.tool import ToolBase, ToolChunk
16
+
17
+ from agentscope_datacircle import _plain
18
+
19
+
20
+ class DatacircleTool(ToolBase):
21
+ """One call of Datacircle's open API: its name, description and input_schema are the model's, its call the API's."""
22
+
23
+ is_concurrency_safe = True
24
+ is_read_only = True
25
+
26
+ def __init__(self, **kwargs: Any) -> None:
27
+ super().__init__(**kwargs)
28
+ self.input_schema = copy.deepcopy(type(self).input_schema)
29
+
30
+ async def check_permissions(self, *args: Any, **kwargs: Any) -> PermissionDecision:
31
+ return PermissionDecision(behavior=PermissionBehavior.ALLOW,
32
+ message=f"{self.name} only reads Datacircle's open API.")
33
+
34
+ async def call(self, **kwargs: Any) -> ToolChunk:
35
+ kwargs.pop("_agent_state", None)
36
+ text, ok = await asyncio.to_thread(_plain.answer, self.name, kwargs)
37
+ if ok:
38
+ return ToolChunk(content=[TextBlock(text=text)])
39
+ return ToolChunk(content=[TextBlock(text=text)], state=ToolResultState.ERROR)
40
+
41
+ if not hasattr(ToolBase, "call"): # AgentScope 2.0.0 calls a tool's __call__, later ones its call
42
+ async def __call__(self, **kwargs: Any) -> ToolChunk:
43
+ return await self.call(**kwargs)
44
+
45
+
46
+ def _tool(name: str, class_name: str) -> type:
47
+ description, schema, _ = _plain.TOOLS[name]
48
+ return type(class_name, (DatacircleTool,), {"name": name, "description": description, "input_schema": schema,
49
+ "__doc__": description, "__module__": __name__})
50
+
51
+
52
+ DatacircleListApis = _tool("datacircle_list_apis", "DatacircleListApis")
53
+ DatacircleBestPlans = _tool("datacircle_best_plans", "DatacircleBestPlans")
54
+ DatacircleSearchPlans = _tool("datacircle_search_plans", "DatacircleSearchPlans")
55
+ DatacircleProvider = _tool("datacircle_provider", "DatacircleProvider")
56
+ CLASSES = [DatacircleListApis, DatacircleBestPlans, DatacircleSearchPlans, DatacircleProvider]
57
+
58
+
59
+ def tools() -> List[DatacircleTool]:
60
+ """The four tools, new objects each time, for Toolkit(tools=[...]) or toolkit.add_tool(...)."""
61
+ return [cls() for cls in CLASSES]
62
+
63
+
64
+ def register(toolkit: Any, group_name: str = "basic") -> None:
65
+ raise TypeError("AgentScope 2 takes tools in Toolkit(tools=...) or await toolkit.add_tool(...): "
66
+ "give it agentscope_datacircle.tools()")
File without changes
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentscope-datacircle
3
+ Version: 0.1.0
4
+ Summary: AgentScope 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/agentscope-datacircle
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: agents,agentscope,api,api-pricing,b2b-data,datacircle,function-calling,gtm,react,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: agentscope>=1.0.0
16
+ Description-Content-Type: text/markdown
17
+
18
+ # agentscope-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 [AgentScope](https://github.com/agentscope-ai/agentscope) four tools that call Datacircle's public API, https://api.datacircle.dev/v1. You need no key and no account.
25
+
26
+ | 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 agentscope-datacircle
37
+ ```
38
+
39
+ The package works with AgentScope 2 on Python 3.11 or later, and with AgentScope 1.0 on Python 3.10 or later.
40
+
41
+ ## Give the tools to an agent
42
+
43
+ On AgentScope 2, put the tools in the agent's `Toolkit`:
44
+
45
+ ```python
46
+ import asyncio
47
+ import os
48
+
49
+ import agentscope_datacircle
50
+ from agentscope.agent import Agent
51
+ from agentscope.credential import OpenAICredential
52
+ from agentscope.message import UserMsg
53
+ from agentscope.model import OpenAIChatModel
54
+ from agentscope.tool import Toolkit
55
+
56
+
57
+ async def main():
58
+ agent = Agent(
59
+ name="Friday",
60
+ system_prompt="You help people choose an API.",
61
+ model=OpenAIChatModel(
62
+ credential=OpenAICredential(api_key=os.environ["OPENAI_API_KEY"]),
63
+ model="gpt-4.1",
64
+ ),
65
+ toolkit=Toolkit(tools=agentscope_datacircle.tools()),
66
+ )
67
+ reply = await agent.reply(UserMsg(name="user", content="Which email finder API is best for under $5 per 1,000?"))
68
+ print(reply.get_text_content())
69
+
70
+
71
+ asyncio.run(main())
72
+ ```
73
+
74
+ The model picks a tool. The agent runs the tool and gives the model the result. Each tool only reads data, so AgentScope runs it without asking you first, in every permission mode. That includes explore mode.
75
+
76
+ To add the Datacircle tools to your own tools, list them together: `Toolkit(tools=[Bash(), Read(), *agentscope_datacircle.tools()])`. On AgentScope 2.0.5 or later, you can add them to a toolkit you already have: `await toolkit.add_tool(agentscope_datacircle.tools())`. To give an agent only a few Datacircle tools, list only those: `Toolkit(tools=[agentscope_datacircle.DatacircleBestPlans()])`.
77
+
78
+ ## AgentScope 1.0
79
+
80
+ On AgentScope 1.0, `register` adds the four tools to a `Toolkit` with `register_tool_function`. A new install of AgentScope 1.0 also needs older mcp and openai packages, and two packages it leaves out, greenlet and tqdm:
81
+
82
+ ```bash
83
+ pip install agentscope-datacircle "agentscope<2" "mcp<2" "openai<3.25" greenlet tqdm
84
+ ```
85
+
86
+ Then:
87
+
88
+ ```python
89
+ import os
90
+
91
+ import agentscope_datacircle
92
+ from agentscope.agent import ReActAgent
93
+ from agentscope.formatter import OpenAIChatFormatter
94
+ from agentscope.model import OpenAIChatModel
95
+ from agentscope.tool import Toolkit
96
+
97
+ toolkit = Toolkit()
98
+ agentscope_datacircle.register(toolkit)
99
+
100
+ agent = ReActAgent(
101
+ name="Friday",
102
+ sys_prompt="You help people choose an API.",
103
+ model=OpenAIChatModel(model_name="gpt-4.1", api_key=os.environ["OPENAI_API_KEY"]),
104
+ formatter=OpenAIChatFormatter(),
105
+ toolkit=toolkit,
106
+ )
107
+ ```
108
+
109
+ To put the tools in a tool group of your own, create the group first and give its name: `agentscope_datacircle.register(toolkit, group_name="datacircle")`. Each tool is also an async function that returns a `ToolResponse`, like `agentscope_datacircle.datacircle_best_plans`.
110
+
111
+ ## Call a tool yourself
112
+
113
+ The functions `list_apis`, `best_plans`, `search_plans` and `provider` return each tool's output as Python dicts:
114
+
115
+ ```python
116
+ import agentscope_datacircle
117
+
118
+ result = agentscope_datacircle.best_plans("email-finder", limit=3)
119
+ print(result["plans"][0])
120
+ ```
121
+
122
+ ## Tool output for the model
123
+
124
+ Each result is our API's answer as JSON 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.
125
+
126
+ You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
127
+
128
+ For an unknown slug, the model gets `{"error": ...}` with a list of every valid slug. The model can then pick a valid slug and call the tool again. The tool checks each value from the model before the API call. For a number out of range, the tool makes no API call. The model gets `{"error": ...}` instead. On AgentScope 2, the tool result's state is then `error`.
129
+
130
+ ## Network
131
+
132
+ Each tool call makes one HTTPS GET request to https://api.datacircle.dev/v1 and no other network calls. The request holds only the tool's input. The API takes up to 60 calls a minute from one IP address. If the API says to wait, the tool waits up to a minute. The tool waits at most once per call. All plans are in one file at https://datacircle.dev/datacircle.json.
133
+
134
+ ## Links
135
+
136
+ - Datacircle: https://datacircle.dev
137
+ - The API: https://datacircle.dev/api
138
+ - The API's spec: https://api.datacircle.dev/v1/openapi.json
139
+ - The meaning of each key: https://datacircle.dev/fields
140
+
141
+ MIT license.
@@ -0,0 +1,10 @@
1
+ agentscope_datacircle/__init__.py,sha256=QUwfbV2rXPPxe_kWqFXNN-Wtk6IueBRWoUzh0IY7sLc,1215
2
+ agentscope_datacircle/_api.py,sha256=kqdDmGNVJgso4EoV1SUwvmV0UD-3P-5VUeIADf-EZpQ,4878
3
+ agentscope_datacircle/_plain.py,sha256=2bfq1U_cNJ8JC8svfnbF80PNTqUglzgeGLfT6IiHpo4,7897
4
+ agentscope_datacircle/_v1.py,sha256=w74pNPXepRqRg74GazM1Pq2owl4dpN3-yt-kM_7k-Co,3242
5
+ agentscope_datacircle/_v2.py,sha256=o0nqfYpo9Tg0SJKMM7CAyMsU-IM4_6ItGXs8UC52TSA,3201
6
+ agentscope_datacircle/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ agentscope_datacircle-0.1.0.dist-info/METADATA,sha256=nwPr3lp6JqKMosqak4uXVCTKMPbNu3-8VrM53Ecuodc,6080
8
+ agentscope_datacircle-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ agentscope_datacircle-0.1.0.dist-info/licenses/LICENSE,sha256=dpgF7zGxeOd9IpQ9yUGa4a-cTj8fI6ulHnuilZEonCo,1067
10
+ agentscope_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.