litellm-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.
- litellm_datacircle/__init__.py +25 -0
- litellm_datacircle/_api.py +101 -0
- litellm_datacircle/py.typed +0 -0
- litellm_datacircle/tools.py +286 -0
- litellm_datacircle-0.1.0.dist-info/METADATA +163 -0
- litellm_datacircle-0.1.0.dist-info/RECORD +8 -0
- litellm_datacircle-0.1.0.dist-info/WHEEL +4 -0
- litellm_datacircle-0.1.0.dist-info/licenses/LICENSE +9 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Tools for LiteLLM on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
|
|
2
|
+
|
|
3
|
+
from litellm_datacircle._api import BASE_URL, DatacircleError
|
|
4
|
+
from litellm_datacircle.tools import (
|
|
5
|
+
TOOL_NAMES,
|
|
6
|
+
acall,
|
|
7
|
+
acall_all,
|
|
8
|
+
acall_outputs,
|
|
9
|
+
aexecute_tool,
|
|
10
|
+
aexecutor,
|
|
11
|
+
call,
|
|
12
|
+
call_all,
|
|
13
|
+
call_output,
|
|
14
|
+
call_outputs,
|
|
15
|
+
datacircle_tools,
|
|
16
|
+
execute_tool,
|
|
17
|
+
executor,
|
|
18
|
+
responses_tools,
|
|
19
|
+
run,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
__all__ = ["BASE_URL", "DatacircleError", "TOOL_NAMES", "acall", "acall_all", "acall_outputs", "aexecute_tool",
|
|
24
|
+
"aexecutor", "call", "call_all", "call_output", "call_outputs", "datacircle_tools", "execute_tool", "executor",
|
|
25
|
+
"responses_tools", "run"]
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""One HTTPS GET to Datacircle's open API (https://api.datacircle.dev/v1), no key, and what its answers are cut to for a model."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import re
|
|
6
|
+
import time
|
|
7
|
+
import unicodedata
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.parse
|
|
10
|
+
import urllib.request
|
|
11
|
+
from typing import Any, Dict, List, Optional
|
|
12
|
+
|
|
13
|
+
BASE_URL = "https://api.datacircle.dev/v1"
|
|
14
|
+
TIMEOUT = 30.0
|
|
15
|
+
USER_AGENT = "litellm-datacircle/0.1.0"
|
|
16
|
+
|
|
17
|
+
# A plan holds about 90 keys (its terms of use, its aggregators...): the tools keep the ones that choose a plan, the rest is on its page.
|
|
18
|
+
PLAN_KEYS = ["api", "rank", "provider", "plan", "score", "perThousand", "notFoundPerThousand", "billing", "pay",
|
|
19
|
+
"currency", "units", "unit", "strengths", "latencyMs", "page", "pricingPage", "docs"]
|
|
20
|
+
API_KEYS = ["api", "slug", "plans", "providers", "best", "bestPage", "sheetPage"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class DatacircleError(Exception):
|
|
24
|
+
"""The API's refusal in its own words, why it could not be reached, or an argument it can't take: a tool gives the
|
|
25
|
+
model its words as its JSON text, {"error": ...}. status is the API's HTTP status, None when it gave none;
|
|
26
|
+
retryable, whether the same call may be answered later (the API out of reach, busy or failing)."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, message: str, status: Optional[int] = None, retryable: bool = False):
|
|
29
|
+
super().__init__(message)
|
|
30
|
+
self.status = status
|
|
31
|
+
self.retryable = retryable
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def brief(item: Dict[str, Any], keys: List[str] = PLAN_KEYS) -> Dict[str, Any]:
|
|
35
|
+
return {key: item[key] for key in keys if item.get(key) is not None}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def slug(value: Any) -> str:
|
|
39
|
+
"""The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen."""
|
|
40
|
+
plain = unicodedata.normalize("NFKD", str(value or "").strip().lower())
|
|
41
|
+
plain = "".join(char for char in plain if not unicodedata.combining(char))
|
|
42
|
+
return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def whole(name: str, value: Any, low: int, high: Optional[int] = None) -> Optional[int]:
|
|
46
|
+
"""A whole number from low to high, or None when left out: a plain call may send one as text."""
|
|
47
|
+
if value is None or value == "":
|
|
48
|
+
return None
|
|
49
|
+
try:
|
|
50
|
+
number = float(value)
|
|
51
|
+
except (TypeError, ValueError):
|
|
52
|
+
number = float("nan")
|
|
53
|
+
if isinstance(value, bool) or not math.isfinite(number) or number != int(number):
|
|
54
|
+
raise DatacircleError(f"{name} must be a whole number, not {value!r}")
|
|
55
|
+
if number < low or (high is not None and number > high):
|
|
56
|
+
raise DatacircleError(f"{name} must be from {low} to {high}, not {int(number)}" if high is not None
|
|
57
|
+
else f"{name} must be {low} or more, not {int(number)}")
|
|
58
|
+
return int(number)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _words(body: bytes) -> str:
|
|
62
|
+
"""A refusal's words: the API's error, with every slug when the slug was unknown."""
|
|
63
|
+
text = body.decode("utf-8", "replace")
|
|
64
|
+
try:
|
|
65
|
+
parsed = json.loads(text)
|
|
66
|
+
if parsed.get("slugs"):
|
|
67
|
+
return f"{parsed['error']}; the slugs: {', '.join(parsed['slugs'])}"
|
|
68
|
+
return str(parsed.get("error", text))
|
|
69
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
70
|
+
return text
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def get(path: str, params: Optional[Dict[str, Any]] = None) -> Any:
|
|
74
|
+
"""The API's JSON answer, or a DatacircleError with its words: waits once when it answers 429."""
|
|
75
|
+
query = urllib.parse.urlencode({key: value for key, value in (params or {}).items() if value not in (None, "")})
|
|
76
|
+
url = f"{BASE_URL.rstrip('/')}{path}" + (f"?{query}" if query else "")
|
|
77
|
+
request = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": USER_AGENT})
|
|
78
|
+
for attempt in range(2):
|
|
79
|
+
try:
|
|
80
|
+
with urllib.request.urlopen(request, timeout=TIMEOUT) as answer:
|
|
81
|
+
body = answer.read()
|
|
82
|
+
except urllib.error.HTTPError as error:
|
|
83
|
+
body = error.read()
|
|
84
|
+
if error.code == 429 and not attempt:
|
|
85
|
+
try:
|
|
86
|
+
wait = int(error.headers.get("Retry-After") or 30)
|
|
87
|
+
except ValueError:
|
|
88
|
+
wait = 30
|
|
89
|
+
time.sleep(min(max(wait, 1), 60))
|
|
90
|
+
continue
|
|
91
|
+
if error.code == 429:
|
|
92
|
+
raise DatacircleError("Datacircle's API answered 429 twice: wait a minute and call again", 429, True) from None
|
|
93
|
+
raise DatacircleError(f"Datacircle's API answered {error.code}: {_words(body)[:3000]}", error.code,
|
|
94
|
+
error.code >= 500) from None
|
|
95
|
+
except (urllib.error.URLError, OSError) as error:
|
|
96
|
+
raise DatacircleError(f"Datacircle's API could not be reached: {getattr(error, 'reason', error)}",
|
|
97
|
+
retryable=True) from None
|
|
98
|
+
try:
|
|
99
|
+
return json.loads(body)
|
|
100
|
+
except ValueError as error:
|
|
101
|
+
raise DatacircleError(f"Datacircle's API gave no JSON: {error}") from None
|
|
File without changes
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""Tools for LiteLLM on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
|
|
2
|
+
|
|
3
|
+
The tools are OpenAI-format definitions, which litellm.completion turns into each provider's own. The app runs the calls
|
|
4
|
+
the model returns: call() and call_all() for its own loop, execute_tool for litellm.run_tool_loop, call_output() for
|
|
5
|
+
litellm.responses. A tool makes one HTTPS GET and gives the model the API's answer as JSON text. A refusal (an unknown
|
|
6
|
+
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
|
|
7
|
+
again and the chat goes on. Few providers hold a model to a tool's schema, so each tool checks its arguments before any
|
|
8
|
+
call.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import copy
|
|
13
|
+
import json
|
|
14
|
+
import urllib.parse
|
|
15
|
+
from typing import Any, Awaitable, Callable, Dict, List, Mapping, Optional, Sequence
|
|
16
|
+
|
|
17
|
+
from litellm_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
|
+
answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
|
|
67
|
+
apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
|
|
68
|
+
"best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
|
|
69
|
+
return {**answer, "apis": apis}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
_PRICE = "perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
|
|
73
|
+
_LIMIT = {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give, 1 to 50. 10 when left out."}
|
|
74
|
+
|
|
75
|
+
# Each tool: what the model reads of it, and the function that answers it. The schemas use only what every provider
|
|
76
|
+
# LiteLLM turns them for takes (Gemini's and Bedrock's included): type, description, enum, minimum, maximum, required.
|
|
77
|
+
_TOOLS: Dict[str, Dict[str, Any]] = {
|
|
78
|
+
"datacircle_list_apis": {
|
|
79
|
+
"run": _list_apis,
|
|
80
|
+
"description": "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how many plans "
|
|
81
|
+
"and providers it has and its best plan. Call it to find an API's slug when you don't know it. Gives "
|
|
82
|
+
"total, the APIs found, and apis, up to limit of them.",
|
|
83
|
+
"parameters": {"type": "object", "properties": {
|
|
84
|
+
"query": {"type": "string", "description": "Words of the API's name or slug, like 'email' or 'linkedin profile'. "
|
|
85
|
+
"The APIs that hold the most of them come first, in the sheet's order "
|
|
86
|
+
"when left out."},
|
|
87
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 200,
|
|
88
|
+
"description": "How many APIs to give, 1 to 200. 20 when left out, of about 170."}}},
|
|
89
|
+
},
|
|
90
|
+
"datacircle_best_plans": {
|
|
91
|
+
"run": _best_plans,
|
|
92
|
+
"description": "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark "
|
|
93
|
+
"(https://datacircle.dev), each with its rank, provider, plan, $ per 1,000 calls and its page: the "
|
|
94
|
+
"best providers of an API. " + _PRICE,
|
|
95
|
+
"parameters": {"type": "object", "properties": {
|
|
96
|
+
"slug": {"type": "string", "description": "The API's slug, like 'email-finder' or 'linkedin-profile', as "
|
|
97
|
+
"datacircle_list_apis gives it."},
|
|
98
|
+
"limit": _LIMIT}, "required": ["slug"]},
|
|
99
|
+
},
|
|
100
|
+
"datacircle_search_plans": {
|
|
101
|
+
"run": _search_plans,
|
|
102
|
+
"description": "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan "
|
|
103
|
+
"name, sorted by score, provider or price. Gives total, offset and up to limit plans. " + _PRICE,
|
|
104
|
+
"parameters": {"type": "object", "properties": {
|
|
105
|
+
"api": {"type": "string", "description": "Only this API's plans, by its name or slug, like 'email-finder'. A "
|
|
106
|
+
"provider's name goes in query, never here. Every API when left out."},
|
|
107
|
+
"query": {"type": "string", "description": "Words that must all appear in the provider's or plan's name, like "
|
|
108
|
+
"'bright data'."},
|
|
109
|
+
"sort": {"type": "string", "enum": ["score", "provider", "price"],
|
|
110
|
+
"description": "score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first)."},
|
|
111
|
+
"limit": _LIMIT,
|
|
112
|
+
"offset": {"type": "integer", "minimum": 0, "description": "How many found plans to skip first. 0 when left out."}}},
|
|
113
|
+
},
|
|
114
|
+
"datacircle_provider": {
|
|
115
|
+
"run": _provider,
|
|
116
|
+
"description": "Gives each API one provider sells and its rank on each on Datacircle's benchmark "
|
|
117
|
+
"(https://datacircle.dev), with its best plan there.",
|
|
118
|
+
"parameters": {"type": "object", "properties": {
|
|
119
|
+
"slug": {"type": "string", "description": "The provider's slug, like 'bright-data', or its name, like 'Bright "
|
|
120
|
+
"Data', which is made a slug."}}, "required": ["slug"]},
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
TOOL_NAMES = list(_TOOLS)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _names(tool_names: Optional[Sequence[str]]) -> List[str]:
|
|
127
|
+
if isinstance(tool_names, str):
|
|
128
|
+
raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
|
|
129
|
+
for name in tool_names or []:
|
|
130
|
+
if name not in _TOOLS:
|
|
131
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
132
|
+
return TOOL_NAMES if tool_names is None else list(tool_names)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def datacircle_tools(tool_names: Optional[Sequence[str]] = None) -> List[Dict[str, Any]]:
|
|
136
|
+
"""The tools, for litellm.completion(model, messages, tools=datacircle_tools()) or beside one's own:
|
|
137
|
+
tools=[*datacircle_tools(), my_tool]. tool_names keeps some of them only, in their order here; all four when left out.
|
|
138
|
+
Each is a new dict, so an app may change its copy."""
|
|
139
|
+
return [{"type": "function", "function": {"name": name, "description": _TOOLS[name]["description"],
|
|
140
|
+
"parameters": copy.deepcopy(_TOOLS[name]["parameters"])}}
|
|
141
|
+
for name in _names(tool_names)]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def responses_tools(tool_names: Optional[Sequence[str]] = None) -> List[Dict[str, Any]]:
|
|
145
|
+
"""The tools in the Responses API's shape, for litellm.responses(model, input, tools=responses_tools()). strict is
|
|
146
|
+
False, as OpenAI's Responses API holds a tool to strict mode when it is left out, which needs every argument."""
|
|
147
|
+
return [{"type": "function", **tool["function"], "strict": False} for tool in datacircle_tools(tool_names)]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def run(name: str, arguments: Any = None) -> str:
|
|
151
|
+
"""What a tool gives the model for these arguments, as JSON text: the API's answer, or {"error": its words}.
|
|
152
|
+
arguments is a mapping or its JSON text; the ones the tool doesn't take are left out."""
|
|
153
|
+
if name not in _TOOLS:
|
|
154
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
155
|
+
if isinstance(arguments, bytes):
|
|
156
|
+
arguments = arguments.decode("utf-8", "replace")
|
|
157
|
+
if isinstance(arguments, str):
|
|
158
|
+
try:
|
|
159
|
+
arguments = json.loads(arguments) if arguments.strip() else {}
|
|
160
|
+
except ValueError:
|
|
161
|
+
return _text({"error": f"the arguments are no JSON object: {arguments[:200]!r}"})
|
|
162
|
+
if arguments is not None and not isinstance(arguments, Mapping):
|
|
163
|
+
return _text({"error": f"the arguments are no JSON object: {str(arguments)[:200]!r}"})
|
|
164
|
+
given = dict(arguments or {})
|
|
165
|
+
taken = _TOOLS[name]["parameters"]["properties"]
|
|
166
|
+
try:
|
|
167
|
+
return _text(_TOOLS[name]["run"](**{key: given.get(key) for key in taken}))
|
|
168
|
+
except _api.DatacircleError as error:
|
|
169
|
+
return _text({"error": str(error)})
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _field(item: Any, key: str) -> Any:
|
|
173
|
+
return item.get(key) if isinstance(item, Mapping) else getattr(item, key, None)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _named(tool_call: Any) -> Optional[str]:
|
|
177
|
+
"""The tool's name in a tool call (LiteLLM's ChatCompletionMessageToolCall, or a dict of its shape): one of ours."""
|
|
178
|
+
name = _field(_field(tool_call, "function"), "name")
|
|
179
|
+
return name if name in _TOOLS else None
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def call(tool_call: Any) -> Optional[Dict[str, str]]:
|
|
183
|
+
"""The tool message for one tool call the model returned (a ChatCompletionMessageToolCall of
|
|
184
|
+
response.choices[0].message.tool_calls, or a dict of its shape), to append to the messages:
|
|
185
|
+
{"role": "tool", "tool_call_id": its id, "content": the JSON text}. None when the call is for a tool that is not one
|
|
186
|
+
of these four, so the app runs its own."""
|
|
187
|
+
name = _named(tool_call)
|
|
188
|
+
if name is None:
|
|
189
|
+
return None
|
|
190
|
+
return {"role": "tool", "tool_call_id": _field(tool_call, "id"),
|
|
191
|
+
"content": run(name, _field(_field(tool_call, "function"), "arguments"))}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _calls(message_or_calls: Any) -> Sequence[Any]:
|
|
195
|
+
"""A reply's tool calls, from its message (or a dict of its shape) or from the list itself."""
|
|
196
|
+
if message_or_calls is None:
|
|
197
|
+
return []
|
|
198
|
+
if isinstance(message_or_calls, (list, tuple)):
|
|
199
|
+
return message_or_calls
|
|
200
|
+
return _field(message_or_calls, "tool_calls") or []
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def call_all(message_or_calls: Any) -> List[Dict[str, str]]:
|
|
204
|
+
"""The tool messages for the calls of these four tools in a reply (its message, or its tool_calls), in their order.
|
|
205
|
+
Calls of other tools are left out, for the app to run."""
|
|
206
|
+
return [message for message in (call(tool_call) for tool_call in _calls(message_or_calls)) if message is not None]
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
async def acall(tool_call: Any) -> Optional[Dict[str, str]]:
|
|
210
|
+
"""call() for litellm.acompletion: its HTTPS GET runs in a thread, so the event loop goes on."""
|
|
211
|
+
if _named(tool_call) is None:
|
|
212
|
+
return None
|
|
213
|
+
return await asyncio.to_thread(call, tool_call)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
async def acall_all(message_or_calls: Any) -> List[Dict[str, str]]:
|
|
217
|
+
"""call_all() for litellm.acompletion: the calls run at once, their messages in the calls' order."""
|
|
218
|
+
messages = await asyncio.gather(*(acall(tool_call) for tool_call in _calls(message_or_calls)))
|
|
219
|
+
return [message for message in messages if message is not None]
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _unknown(tool_call: Any) -> Dict[str, str]:
|
|
223
|
+
name = _field(_field(tool_call, "function"), "name")
|
|
224
|
+
return {"role": "tool", "tool_call_id": _field(tool_call, "id"),
|
|
225
|
+
"content": _text({"error": f"there is no tool {name!r}: the tools are {', '.join(TOOL_NAMES)}"})}
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def execute_tool(tool_call: Any) -> Dict[str, str]:
|
|
229
|
+
"""litellm.run_tool_loop's execute_tool for these four tools alone: the tool message of each call, a call of
|
|
230
|
+
another tool answered {"error": ...} so the loop goes on."""
|
|
231
|
+
return call(tool_call) or _unknown(tool_call)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
async def aexecute_tool(tool_call: Any) -> Dict[str, str]:
|
|
235
|
+
"""execute_tool for litellm.arun_tool_loop."""
|
|
236
|
+
return await acall(tool_call) or _unknown(tool_call)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def executor(own: Optional[Callable[[Any], Any]] = None) -> Callable[[Any], Any]:
|
|
240
|
+
"""An execute_tool for litellm.run_tool_loop that runs these four tools and hands every other call to own, the
|
|
241
|
+
app's own execute_tool: run_tool_loop(..., tools=[*datacircle_tools(), my_tool], execute_tool=executor(my_execute))."""
|
|
242
|
+
if own is None:
|
|
243
|
+
return execute_tool
|
|
244
|
+
|
|
245
|
+
def execute(tool_call: Any) -> Any:
|
|
246
|
+
return call(tool_call) or own(tool_call)
|
|
247
|
+
return execute
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def aexecutor(own: Optional[Callable[[Any], Awaitable[Any]]] = None) -> Callable[[Any], Awaitable[Any]]:
|
|
251
|
+
"""executor() for litellm.arun_tool_loop: own is the app's own async execute_tool."""
|
|
252
|
+
if own is None:
|
|
253
|
+
return aexecute_tool
|
|
254
|
+
|
|
255
|
+
async def execute(tool_call: Any) -> Any:
|
|
256
|
+
return await acall(tool_call) or await own(tool_call)
|
|
257
|
+
return execute
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def call_output(item: Any) -> Optional[Dict[str, str]]:
|
|
261
|
+
"""For litellm.responses: the function_call_output input item for one function_call item of response.output (or a
|
|
262
|
+
dict of its shape), {"type": "function_call_output", "call_id": its call_id, "output": the JSON text}. None for any
|
|
263
|
+
other item, or a call of a tool that is not one of these four."""
|
|
264
|
+
name = _field(item, "name")
|
|
265
|
+
if _field(item, "type") != "function_call" or name not in _TOOLS:
|
|
266
|
+
return None
|
|
267
|
+
return {"type": "function_call_output", "call_id": _field(item, "call_id"), "output": run(name, _field(item, "arguments"))}
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def call_outputs(response_or_output: Any) -> List[Dict[str, str]]:
|
|
271
|
+
"""The function_call_output items for the calls of these four tools in a response of litellm.responses (or its
|
|
272
|
+
output list), in their order. Other items and calls of other tools are left out, for the app to run."""
|
|
273
|
+
items = response_or_output if isinstance(response_or_output, (list, tuple)) else _field(response_or_output, "output")
|
|
274
|
+
return [output for output in (call_output(item) for item in items or []) if output is not None]
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
async def acall_outputs(response_or_output: Any) -> List[Dict[str, str]]:
|
|
278
|
+
"""call_outputs() for litellm.aresponses: the calls run at once, in threads, their items in the calls' order."""
|
|
279
|
+
items = response_or_output if isinstance(response_or_output, (list, tuple)) else _field(response_or_output, "output")
|
|
280
|
+
outputs = await asyncio.gather(*(asyncio.to_thread(call_output, item) for item in items or []))
|
|
281
|
+
return [output for output in outputs if output is not None]
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
__all__: List[str] = ["TOOL_NAMES", "acall", "acall_all", "acall_outputs", "aexecute_tool", "aexecutor", "call",
|
|
285
|
+
"call_all", "call_output", "call_outputs", "datacircle_tools", "execute_tool", "executor",
|
|
286
|
+
"responses_tools", "run"]
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: litellm-datacircle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LiteLLM 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/litellm-datacircle
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: api,api-pricing,b2b-data,datacircle,function-calling,gtm,litellm,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
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# litellm-datacircle
|
|
18
|
+
|
|
19
|
+
Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
|
|
20
|
+
|
|
21
|
+
Our website: https://datacircle.dev
|
|
22
|
+
|
|
23
|
+
This package gives [LiteLLM](https://github.com/BerriAI/litellm) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You pass the four tools to `litellm.completion()`, on any provider LiteLLM supports. The package then runs each tool call the model returns. You need no key and no account.
|
|
24
|
+
|
|
25
|
+
| Tool | What the tool gives | Call |
|
|
26
|
+
| --- | --- | --- |
|
|
27
|
+
| `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
|
|
28
|
+
| `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` |
|
|
29
|
+
| `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` |
|
|
30
|
+
| `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install litellm-datacircle
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
litellm-datacircle works with any version of `litellm`, on Python 3.9 and later. The package does not import `litellm`.
|
|
39
|
+
|
|
40
|
+
## Use the tools with run_tool_loop
|
|
41
|
+
|
|
42
|
+
LiteLLM 1.106 and later can run the whole tool loop. Pass our `execute_tool` function as the `execute_tool` argument:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import litellm
|
|
46
|
+
from litellm_datacircle import datacircle_tools, execute_tool
|
|
47
|
+
|
|
48
|
+
answer = litellm.run_tool_loop(
|
|
49
|
+
model="anthropic/claude-haiku-5-5",
|
|
50
|
+
messages=[{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}],
|
|
51
|
+
tools=datacircle_tools(),
|
|
52
|
+
execute_tool=execute_tool,
|
|
53
|
+
)
|
|
54
|
+
print(answer)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
With `litellm.arun_tool_loop`, use `aexecute_tool`.
|
|
58
|
+
|
|
59
|
+
## Use the tools in your own loop
|
|
60
|
+
|
|
61
|
+
Pass the tools to `litellm.completion()`. If the model calls a tool, `call_all()` gives you the tool messages to send back:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import litellm
|
|
65
|
+
from litellm_datacircle import call_all, datacircle_tools
|
|
66
|
+
|
|
67
|
+
messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
68
|
+
message = litellm.completion(model="openai/gpt-5-mini", messages=messages, tools=datacircle_tools()).choices[0].message
|
|
69
|
+
|
|
70
|
+
while message.tool_calls:
|
|
71
|
+
messages.append(message)
|
|
72
|
+
messages.extend(call_all(message))
|
|
73
|
+
message = litellm.completion(model="openai/gpt-5-mini", messages=messages, tools=datacircle_tools()).choices[0].message
|
|
74
|
+
|
|
75
|
+
print(message.content)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Each tool is an OpenAI-format tool definition. LiteLLM turns each tool into the provider's own format. Each tool message has `role: "tool"`, the call's id in `tool_call_id`, and the answer as JSON text in `content`.
|
|
79
|
+
|
|
80
|
+
With `stream=True`, build the reply with `litellm.stream_chunk_builder(chunks, messages=messages)`. Then pass the reply's message to `call_all()`. With `litellm.acompletion()`, use `await acall_all(...)`. `acall_all()` runs the calls at the same time. Your event loop keeps running.
|
|
81
|
+
|
|
82
|
+
## Use the Datacircle tools beside your own tools
|
|
83
|
+
|
|
84
|
+
You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`.
|
|
85
|
+
|
|
86
|
+
With `run_tool_loop`, `executor()` runs the Datacircle tools and hands every other call to your own function:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
answer = litellm.run_tool_loop(
|
|
90
|
+
model="anthropic/claude-haiku-5-5",
|
|
91
|
+
messages=messages,
|
|
92
|
+
tools=[*datacircle_tools(), my_tool],
|
|
93
|
+
execute_tool=executor(my_execute_tool),
|
|
94
|
+
)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
With `arun_tool_loop`, use `aexecutor(my_async_execute_tool)`.
|
|
98
|
+
|
|
99
|
+
In your own loop, `call()` runs one tool call. For your own tools, `call()` returns `None`. Your code then runs the tool itself:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from litellm_datacircle import call
|
|
103
|
+
|
|
104
|
+
for tool_call in message.tool_calls or []:
|
|
105
|
+
messages.append(call(tool_call) or my_execute_tool(tool_call))
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
109
|
+
|
|
110
|
+
## Use the tools with litellm.responses
|
|
111
|
+
|
|
112
|
+
`responses_tools()` gives our four tools in the Responses API's format. `call_outputs()` gives the `function_call_output` items to send back:
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
import litellm
|
|
116
|
+
from litellm_datacircle import call_outputs, responses_tools
|
|
117
|
+
|
|
118
|
+
given = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
119
|
+
response = litellm.responses(model="anthropic/claude-haiku-5-5", input=given, tools=responses_tools())
|
|
120
|
+
|
|
121
|
+
while any(item.type == "function_call" for item in response.output):
|
|
122
|
+
given += [item.model_dump(exclude_none=True) for item in response.output if item.type == "function_call"]
|
|
123
|
+
given += call_outputs(response)
|
|
124
|
+
response = litellm.responses(model="anthropic/claude-haiku-5-5", input=given, tools=responses_tools())
|
|
125
|
+
|
|
126
|
+
print(response.output[-1].content[0].text)
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
`call_output()` takes one item. `call_output()` returns `None` for a call to one of your own tools. With `litellm.aresponses()`, use `await acall_outputs(...)`.
|
|
130
|
+
|
|
131
|
+
## Call a tool yourself
|
|
132
|
+
|
|
133
|
+
You can call each tool without a model. You get the JSON text of the tool's answer:
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
import json
|
|
137
|
+
|
|
138
|
+
from litellm_datacircle import run
|
|
139
|
+
|
|
140
|
+
answer = json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
|
|
141
|
+
print(answer["plans"])
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
## What the model reads
|
|
145
|
+
|
|
146
|
+
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.
|
|
147
|
+
|
|
148
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
149
|
+
|
|
150
|
+
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.
|
|
151
|
+
|
|
152
|
+
## Network
|
|
153
|
+
|
|
154
|
+
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.
|
|
155
|
+
|
|
156
|
+
## Links
|
|
157
|
+
|
|
158
|
+
- Datacircle: https://datacircle.dev
|
|
159
|
+
- The API: https://datacircle.dev/api
|
|
160
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
161
|
+
- Every field of a plan: https://datacircle.dev/fields
|
|
162
|
+
|
|
163
|
+
MIT license.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
litellm_datacircle/__init__.py,sha256=75yEuWouVfocytLoQ3AlNCCOwykFiqgBuWe1hYaEziA,751
|
|
2
|
+
litellm_datacircle/_api.py,sha256=BC_3rAuDtF3ujAdySJ5HeEZukNBe8aWnekHec5YLgSQ,4868
|
|
3
|
+
litellm_datacircle/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
litellm_datacircle/tools.py,sha256=bASl4f-vX7SzJgcJvdmJJhWwgadbWesUT39GjDfe_QE,16012
|
|
5
|
+
litellm_datacircle-0.1.0.dist-info/METADATA,sha256=FpyLhpTxcsl-odh7iTSzWdG6nfiRDsSvg2oEI5GcVcs,7347
|
|
6
|
+
litellm_datacircle-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
litellm_datacircle-0.1.0.dist-info/licenses/LICENSE,sha256=dpgF7zGxeOd9IpQ9yUGa4a-cTj8fI6ulHnuilZEonCo,1067
|
|
8
|
+
litellm_datacircle-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Datacircle
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|