litellm-datacircle 0.1.0__tar.gz

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,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.
@@ -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,147 @@
1
+ # litellm-datacircle
2
+
3
+ Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
4
+
5
+ Our website: https://datacircle.dev
6
+
7
+ 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.
8
+
9
+ | Tool | What the tool gives | Call |
10
+ | --- | --- | --- |
11
+ | `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
12
+ | `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` |
13
+ | `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` |
14
+ | `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install litellm-datacircle
20
+ ```
21
+
22
+ litellm-datacircle works with any version of `litellm`, on Python 3.9 and later. The package does not import `litellm`.
23
+
24
+ ## Use the tools with run_tool_loop
25
+
26
+ LiteLLM 1.106 and later can run the whole tool loop. Pass our `execute_tool` function as the `execute_tool` argument:
27
+
28
+ ```python
29
+ import litellm
30
+ from litellm_datacircle import datacircle_tools, execute_tool
31
+
32
+ answer = litellm.run_tool_loop(
33
+ model="anthropic/claude-haiku-5-5",
34
+ messages=[{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}],
35
+ tools=datacircle_tools(),
36
+ execute_tool=execute_tool,
37
+ )
38
+ print(answer)
39
+ ```
40
+
41
+ With `litellm.arun_tool_loop`, use `aexecute_tool`.
42
+
43
+ ## Use the tools in your own loop
44
+
45
+ Pass the tools to `litellm.completion()`. If the model calls a tool, `call_all()` gives you the tool messages to send back:
46
+
47
+ ```python
48
+ import litellm
49
+ from litellm_datacircle import call_all, datacircle_tools
50
+
51
+ messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
52
+ message = litellm.completion(model="openai/gpt-5-mini", messages=messages, tools=datacircle_tools()).choices[0].message
53
+
54
+ while message.tool_calls:
55
+ messages.append(message)
56
+ messages.extend(call_all(message))
57
+ message = litellm.completion(model="openai/gpt-5-mini", messages=messages, tools=datacircle_tools()).choices[0].message
58
+
59
+ print(message.content)
60
+ ```
61
+
62
+ 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`.
63
+
64
+ 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.
65
+
66
+ ## Use the Datacircle tools beside your own tools
67
+
68
+ You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`.
69
+
70
+ With `run_tool_loop`, `executor()` runs the Datacircle tools and hands every other call to your own function:
71
+
72
+ ```python
73
+ answer = litellm.run_tool_loop(
74
+ model="anthropic/claude-haiku-5-5",
75
+ messages=messages,
76
+ tools=[*datacircle_tools(), my_tool],
77
+ execute_tool=executor(my_execute_tool),
78
+ )
79
+ ```
80
+
81
+ With `arun_tool_loop`, use `aexecutor(my_async_execute_tool)`.
82
+
83
+ In your own loop, `call()` runs one tool call. For your own tools, `call()` returns `None`. Your code then runs the tool itself:
84
+
85
+ ```python
86
+ from litellm_datacircle import call
87
+
88
+ for tool_call in message.tool_calls or []:
89
+ messages.append(call(tool_call) or my_execute_tool(tool_call))
90
+ ```
91
+
92
+ To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
93
+
94
+ ## Use the tools with litellm.responses
95
+
96
+ `responses_tools()` gives our four tools in the Responses API's format. `call_outputs()` gives the `function_call_output` items to send back:
97
+
98
+ ```python
99
+ import litellm
100
+ from litellm_datacircle import call_outputs, responses_tools
101
+
102
+ given = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
103
+ response = litellm.responses(model="anthropic/claude-haiku-5-5", input=given, tools=responses_tools())
104
+
105
+ while any(item.type == "function_call" for item in response.output):
106
+ given += [item.model_dump(exclude_none=True) for item in response.output if item.type == "function_call"]
107
+ given += call_outputs(response)
108
+ response = litellm.responses(model="anthropic/claude-haiku-5-5", input=given, tools=responses_tools())
109
+
110
+ print(response.output[-1].content[0].text)
111
+ ```
112
+
113
+ `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(...)`.
114
+
115
+ ## Call a tool yourself
116
+
117
+ You can call each tool without a model. You get the JSON text of the tool's answer:
118
+
119
+ ```python
120
+ import json
121
+
122
+ from litellm_datacircle import run
123
+
124
+ answer = json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
125
+ print(answer["plans"])
126
+ ```
127
+
128
+ ## What the model reads
129
+
130
+ 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.
131
+
132
+ You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
133
+
134
+ 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.
135
+
136
+ ## Network
137
+
138
+ 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.
139
+
140
+ ## Links
141
+
142
+ - Datacircle: https://datacircle.dev
143
+ - The API: https://datacircle.dev/api
144
+ - The API's spec: https://api.datacircle.dev/v1/openapi.json
145
+ - Every field of a plan: https://datacircle.dev/fields
146
+
147
+ MIT license.
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "litellm-datacircle"
7
+ version = "0.1.0"
8
+ description = "LiteLLM tools for the Datacircle API: find the best GTM APIs"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ # The tools are OpenAI-format definitions and the run of their calls: they never import litellm, so any version takes them.
13
+ dependencies = []
14
+ keywords = ["litellm", "llm", "tools", "function-calling", "tool-calling", "gtm", "api", "api-pricing", "b2b-data", "datacircle"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ "Topic :: Software Development :: Libraries",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://datacircle.dev"
23
+ Documentation = "https://api.datacircle.dev/v1/openapi.json"
24
+ Repository = "https://github.com/waynehamadi/litellm-datacircle"
25
+
26
+ [dependency-groups]
27
+ test = ["pytest>=8"]
28
+
29
+ [tool.hatch.build.targets.wheel]
30
+ packages = ["src/litellm_datacircle"]
31
+
32
+ [tool.hatch.build.targets.sdist]
33
+ include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
@@ -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
@@ -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,207 @@
1
+ """Stand-ins on 127.0.0.1: Datacircle's API, and a model that speaks OpenAI's Chat Completions and Responses, Ollama's
2
+ /api/chat and Anthropic's Messages. The model asks for datacircle_best_plans and the app's own add_two_numbers, then,
3
+ given their results, answers with the text it read."""
4
+
5
+ import json
6
+ import os
7
+ import threading
8
+ import time
9
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
10
+ from urllib.parse import parse_qs, urlparse
11
+
12
+ import pytest
13
+
14
+ os.environ.setdefault("LITELLM_LOCAL_MODEL_COST_MAP", "True")
15
+ os.environ["NO_PROXY"] = os.environ["no_proxy"] = "127.0.0.1,localhost"
16
+
17
+ from litellm_datacircle import _api # noqa: E402
18
+
19
+ PLAN = {"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1, "perThousand": 4.9,
20
+ "page": "https://datacircle.dev/x", "terms": "long", "aggregators": ["a"]}
21
+ OURS = {"name": "datacircle_best_plans", "arguments": {"slug": "email-finder", "limit": 1}}
22
+ OWN = {"name": "add_two_numbers", "arguments": {"a": 1, "b": 2}}
23
+
24
+
25
+ def results(body):
26
+ """The tool results a model request carries, in every protocol's shape."""
27
+ found = []
28
+ for message in body.get("messages") or []:
29
+ if message.get("role") == "tool":
30
+ found.append(message.get("content"))
31
+ content = message.get("content")
32
+ for block in content if isinstance(content, list) else []:
33
+ if isinstance(block, dict) and block.get("type") == "tool_result":
34
+ inner = block.get("content")
35
+ found.append(inner if isinstance(inner, str) else "".join(part.get("text", "") for part in inner or []))
36
+ for item in body.get("input") if isinstance(body.get("input"), list) else []:
37
+ if isinstance(item, dict) and item.get("type") == "function_call_output":
38
+ found.append(item.get("output"))
39
+ return found
40
+
41
+
42
+ class State:
43
+ def __init__(self):
44
+ self.seen, self.busy, self.bodies = [], [], []
45
+
46
+ def results(self):
47
+ """The tool results the last model request carried."""
48
+ return results(self.bodies[-1][1])
49
+
50
+
51
+ def _answered(body):
52
+ return bool(results(body))
53
+
54
+
55
+ def _send(handler, status, body, headers=None):
56
+ data = json.dumps(body).encode()
57
+ handler.send_response(status)
58
+ for key, value in {"Content-Type": "application/json", "Content-Length": str(len(data)), **(headers or {})}.items():
59
+ handler.send_header(key, value)
60
+ handler.end_headers()
61
+ handler.wfile.write(data)
62
+
63
+
64
+ def _final_text(body):
65
+ return "read: " + " | ".join(str(text) for text in results(body))
66
+
67
+
68
+ def _chat(handler, body):
69
+ """OpenAI's /v1/chat/completions, whole or streamed."""
70
+ calls = [] if _answered(body) else [OURS, OWN]
71
+ if body.get("stream"):
72
+ handler.send_response(200)
73
+ handler.send_header("Content-Type", "text/event-stream")
74
+ handler.end_headers()
75
+
76
+ def chunk(delta, finish=None):
77
+ data = {"id": "chatcmpl-1", "object": "chat.completion.chunk", "created": int(time.time()), "model": body["model"],
78
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
79
+ handler.wfile.write(f"data: {json.dumps(data)}\n\n".encode())
80
+ chunk({"role": "assistant", "content": None if calls else ""})
81
+ if calls:
82
+ for index, made in enumerate(calls):
83
+ text = json.dumps(made["arguments"])
84
+ chunk({"tool_calls": [{"index": index, "id": f"call_{index}", "type": "function",
85
+ "function": {"name": made["name"], "arguments": text[:7]}}]})
86
+ chunk({"tool_calls": [{"index": index, "function": {"arguments": text[7:]}}]})
87
+ chunk({}, "tool_calls")
88
+ else:
89
+ chunk({"content": _final_text(body)})
90
+ chunk({}, "stop")
91
+ handler.wfile.write(b"data: [DONE]\n\n")
92
+ return
93
+ message = {"role": "assistant", "content": None if calls else _final_text(body)}
94
+ if calls:
95
+ message["tool_calls"] = [{"id": f"call_{index}", "type": "function",
96
+ "function": {"name": made["name"], "arguments": json.dumps(made["arguments"])}}
97
+ for index, made in enumerate(calls)]
98
+ _send(handler, 200, {"id": "chatcmpl-1", "object": "chat.completion", "created": int(time.time()), "model": body["model"],
99
+ "choices": [{"index": 0, "message": message, "finish_reason": "tool_calls" if calls else "stop"}],
100
+ "usage": {"prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10}})
101
+
102
+
103
+ def _responses(handler, body):
104
+ """OpenAI's /v1/responses, whole."""
105
+ calls = [] if _answered(body) else [OURS, OWN]
106
+ if calls:
107
+ output = [{"type": "function_call", "id": f"fc_{index}", "call_id": f"call_{index}", "name": made["name"],
108
+ "arguments": json.dumps(made["arguments"]), "status": "completed"} for index, made in enumerate(calls)]
109
+ else:
110
+ output = [{"type": "message", "id": "msg_1", "status": "completed", "role": "assistant",
111
+ "content": [{"type": "output_text", "text": _final_text(body), "annotations": []}]}]
112
+ _send(handler, 200, {"id": "resp_1", "object": "response", "created_at": int(time.time()), "status": "completed",
113
+ "model": body["model"], "output": output, "parallel_tool_calls": True, "tool_choice": "auto",
114
+ "tools": [{**tool, "strict": tool.get("strict", True)} for tool in body.get("tools") or []], "text": {"format": {"type": "text"}}, "error": None,
115
+ "incomplete_details": None, "instructions": None, "metadata": {}, "temperature": 1.0,
116
+ "top_p": 1.0, "truncation": "disabled", "max_output_tokens": None,
117
+ "previous_response_id": None, "reasoning": {"effort": None, "summary": None}, "user": None,
118
+ "store": True,
119
+ "usage": {"input_tokens": 5, "output_tokens": 5, "total_tokens": 10,
120
+ "input_tokens_details": {"cached_tokens": 0},
121
+ "output_tokens_details": {"reasoning_tokens": 0}}})
122
+
123
+
124
+ def _ollama(handler, body):
125
+ """Ollama's /api/chat, whole."""
126
+ calls = [] if _answered(body) else [OURS, OWN]
127
+ message = {"role": "assistant", "content": "" if calls else _final_text(body)}
128
+ if calls:
129
+ message["tool_calls"] = [{"function": {"name": made["name"], "arguments": made["arguments"]}} for made in calls]
130
+ _send(handler, 200, {"model": body["model"], "created_at": "2026-11-29T00:00:00Z", "message": message, "done": True,
131
+ "done_reason": "stop", "prompt_eval_count": 5, "eval_count": 5})
132
+
133
+
134
+ def _anthropic(handler, body):
135
+ """Anthropic's /v1/messages, whole."""
136
+ calls = [] if _answered(body) else [OURS, OWN]
137
+ content = ([{"type": "tool_use", "id": f"toolu_{index}", "name": made["name"], "input": made["arguments"]}
138
+ for index, made in enumerate(calls)] if calls else [{"type": "text", "text": _final_text(body)}])
139
+ _send(handler, 200, {"id": "msg_1", "type": "message", "role": "assistant", "model": body["model"], "content": content,
140
+ "stop_reason": "tool_use" if calls else "end_turn", "stop_sequence": None,
141
+ "usage": {"input_tokens": 5, "output_tokens": 5}})
142
+
143
+
144
+ def _handler(state):
145
+ class Handler(BaseHTTPRequestHandler):
146
+ def log_message(self, *args):
147
+ pass
148
+
149
+ def do_POST(self):
150
+ body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
151
+ path = urlparse(self.path).path
152
+ if path.endswith("/api/show"): # a model that takes tools, as Ollama shows one: LiteLLM reads it first
153
+ _send(self, 200, {"template": "{{ if .Tools }}{{ .Tools }}{{ end }}{{ .Prompt }}",
154
+ "capabilities": ["completion", "tools"], "details": {}, "model_info": {}})
155
+ return
156
+ state.bodies.append((path, body))
157
+ if path.endswith("/chat/completions"):
158
+ _chat(self, body)
159
+ elif path.endswith("/responses"):
160
+ _responses(self, body)
161
+ elif path.endswith("/api/chat"):
162
+ _ollama(self, body)
163
+ elif path.endswith("/messages"):
164
+ _anthropic(self, body)
165
+ else:
166
+ _send(self, 404, {"error": f"no {path}"})
167
+
168
+ def do_GET(self):
169
+ url = urlparse(self.path)
170
+ query = {key: values[0] for key, values in parse_qs(url.query).items()}
171
+ state.seen.append((url.path, query, self.headers.get("User-Agent")))
172
+ headers = {}
173
+ if url.path == "/v1/plans" and query.get("query") == "busy" and not state.busy:
174
+ state.busy.append(1)
175
+ status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
176
+ elif url.path == "/v1/plans" and query.get("query") == "always-busy":
177
+ status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
178
+ elif url.path == "/v1/apis":
179
+ status, body = 200, [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3, "extra": 1},
180
+ {"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]
181
+ elif url.path == "/v1/apis/email-finder/best":
182
+ status, body = 200, {"api": "Employee email", "slug": "email-finder", "total": 1, "plans": [PLAN]}
183
+ elif url.path.startswith("/v1/apis/"):
184
+ status, body = 404, {"error": "no API has the slug nope", "slugs": ["email-finder", "linkedin-profile"]}
185
+ elif url.path == "/v1/plans" and query.get("query") == "down":
186
+ status, body = 503, {"error": "down for a minute"}
187
+ elif url.path == "/v1/plans":
188
+ status, body = 200, {"total": 1, "offset": 0, "plans": [PLAN]}
189
+ elif url.path == "/v1/providers/bright-data":
190
+ status, body = 200, {"provider": "Bright Data", "slug": "bright-data",
191
+ "apis": [{"api": "Employee email", "slug": "email-finder", "rank": 7, "bestPage": "b",
192
+ "plans": [{**PLAN, "rank": 9}, {**PLAN, "rank": 7, "plan": "Pro"}]}]}
193
+ else:
194
+ status, body = 404, {"error": "no provider has the slug nope"}
195
+ _send(self, status, body, headers)
196
+ return Handler
197
+
198
+
199
+ @pytest.fixture()
200
+ def stub(monkeypatch):
201
+ state = State()
202
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _handler(state))
203
+ threading.Thread(target=server.serve_forever, daemon=True).start()
204
+ state.url = f"http://127.0.0.1:{server.server_address[1]}"
205
+ monkeypatch.setattr(_api, "BASE_URL", state.url + "/v1")
206
+ yield state
207
+ server.shutdown()
@@ -0,0 +1,174 @@
1
+ """The tools through LiteLLM itself, on the stand-in model (conftest.py): litellm.completion on its openai/, ollama_chat/
2
+ and anthropic/ providers, streamed, async, litellm.run_tool_loop and litellm.responses, each beside an app's own tool."""
3
+
4
+ import asyncio
5
+ import json
6
+
7
+ import pytest
8
+
9
+ litellm = pytest.importorskip("litellm")
10
+
11
+ from litellm_datacircle import ( # noqa: E402
12
+ acall_all,
13
+ acall_outputs,
14
+ aexecutor,
15
+ call,
16
+ call_all,
17
+ call_outputs,
18
+ datacircle_tools,
19
+ execute_tool,
20
+ executor,
21
+ responses_tools,
22
+ )
23
+
24
+ ADD = {"type": "function", "function": {"name": "add_two_numbers", "description": "Adds two numbers.", "parameters": {
25
+ "type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, "required": ["a", "b"]}}}
26
+ QUESTION = [{"role": "user", "content": "Who is best for email finding, and what is 1 + 2?"}]
27
+ MODELS = {"openai/scripted": {"api_key": "test"}, "ollama_chat/scripted": {}, "anthropic/claude-scripted": {"api_key": "test"}}
28
+
29
+
30
+ def _base(stub, model):
31
+ return stub.url + "/v1" if model.startswith("openai/") else stub.url
32
+
33
+
34
+ def _own(tool_call):
35
+ arguments = json.loads(tool_call.function.arguments)
36
+ return {"role": "tool", "tool_call_id": tool_call.id, "content": str(arguments["a"] + arguments["b"])}
37
+
38
+
39
+ async def _aown(tool_call):
40
+ return _own(tool_call)
41
+
42
+
43
+ def _read(stub, answer):
44
+ assert "Hunter" in answer and "| 3" in answer, answer
45
+ results = stub.results()
46
+ assert len(results) == 2 and json.loads(results[0])["plans"][0]["provider"] == "Hunter" and results[1] == "3"
47
+
48
+
49
+ def _sent_tools(stub, model):
50
+ tools = stub.bodies[0][1]["tools"]
51
+ if model.startswith("anthropic/"):
52
+ return {tool["name"]: tool["input_schema"] for tool in tools}
53
+ return {tool["function"]["name"]: tool["function"]["parameters"] for tool in tools}
54
+
55
+
56
+ @pytest.mark.parametrize("model", list(MODELS))
57
+ def test_completion_loop(stub, model, monkeypatch):
58
+ """The app's own loop: litellm.completion, call() on each of ours, its own tool run by itself."""
59
+ monkeypatch.setenv("OLLAMA_API_BASE", stub.url) # where LiteLLM before 1.8x reads a model's tool support from
60
+ messages = list(QUESTION)
61
+ options = {"api_base": _base(stub, model), **MODELS[model]}
62
+ response = litellm.completion(model=model, messages=messages, tools=[*datacircle_tools(), ADD], **options)
63
+ message = response.choices[0].message
64
+ assert [tool_call.function.name for tool_call in message.tool_calls] == ["datacircle_best_plans", "add_two_numbers"]
65
+ sent = _sent_tools(stub, model)
66
+ assert sent["datacircle_best_plans"]["properties"]["slug"]["type"] == "string" and "add_two_numbers" in sent
67
+ messages.append(message)
68
+ for tool_call in message.tool_calls:
69
+ messages.append(call(tool_call) or _own(tool_call))
70
+ answer = litellm.completion(model=model, messages=messages, tools=[*datacircle_tools(), ADD], **options)
71
+ _read(stub, answer.choices[0].message.content)
72
+
73
+
74
+ def test_stream(stub):
75
+ messages = list(QUESTION)
76
+ options = {"api_base": stub.url + "/v1", "api_key": "test"}
77
+ chunks = list(litellm.completion(model="openai/scripted", messages=messages, tools=[*datacircle_tools(), ADD],
78
+ stream=True, **options))
79
+ message = litellm.stream_chunk_builder(chunks, messages=messages).choices[0].message
80
+ ours = call_all(message)
81
+ assert [m["tool_call_id"] for m in ours] == ["call_0"]
82
+ messages += [message, *ours, *[_own(c) for c in message.tool_calls if c.function.name == "add_two_numbers"]]
83
+ chunks = list(litellm.completion(model="openai/scripted", messages=messages, tools=[*datacircle_tools(), ADD],
84
+ stream=True, **options))
85
+ _read(stub, litellm.stream_chunk_builder(chunks, messages=messages).choices[0].message.content)
86
+
87
+
88
+ @pytest.mark.parametrize("model", ["openai/scripted", "anthropic/claude-scripted"])
89
+ def test_acompletion(stub, model):
90
+ async def main():
91
+ messages = list(QUESTION)
92
+ options = {"api_base": _base(stub, model), **MODELS[model]}
93
+ response = await litellm.acompletion(model=model, messages=messages, tools=[*datacircle_tools(), ADD], **options)
94
+ message = response.choices[0].message
95
+ messages += [message, *await acall_all(message)]
96
+ messages += [_own(c) for c in message.tool_calls if c.function.name == "add_two_numbers"]
97
+ answer = await litellm.acompletion(model=model, messages=messages, tools=[*datacircle_tools(), ADD], **options)
98
+ return answer.choices[0].message.content
99
+ _read(stub, asyncio.run(main()))
100
+
101
+
102
+ needs_loop = pytest.mark.skipif(not hasattr(litellm, "run_tool_loop"), reason="litellm.run_tool_loop is litellm 1.106's")
103
+
104
+
105
+ @needs_loop
106
+ @pytest.mark.parametrize("model", list(MODELS))
107
+ def test_run_tool_loop(stub, model):
108
+ options = {"api_base": _base(stub, model), **MODELS[model]}
109
+ answer = litellm.run_tool_loop(model=model, messages=QUESTION, tools=[*datacircle_tools(), ADD],
110
+ execute_tool=executor(_own), **options)
111
+ _read(stub, answer)
112
+
113
+
114
+ @needs_loop
115
+ def test_run_tool_loop_ours_alone(stub):
116
+ answer = litellm.run_tool_loop(model="openai/scripted", messages=QUESTION, tools=datacircle_tools(),
117
+ execute_tool=execute_tool, api_base=stub.url + "/v1", api_key="test")
118
+ assert "Hunter" in answer and "there is no tool 'add_two_numbers'" in answer
119
+
120
+
121
+ @needs_loop
122
+ def test_arun_tool_loop(stub):
123
+ answer = asyncio.run(litellm.arun_tool_loop(model="anthropic/claude-scripted", messages=QUESTION,
124
+ tools=[*datacircle_tools(), ADD], execute_tool=aexecutor(_aown),
125
+ api_base=stub.url, api_key="test"))
126
+ _read(stub, answer)
127
+
128
+
129
+ def _version():
130
+ from importlib.metadata import version
131
+ return tuple(int(part) for part in version("litellm").split(".")[:2])
132
+
133
+
134
+ ADD_RESPONSES = {"type": "function", **ADD["function"]}
135
+
136
+
137
+ def _own_output(item):
138
+ arguments = json.loads(item.arguments)
139
+ return {"type": "function_call_output", "call_id": item.call_id, "output": str(arguments["a"] + arguments["b"])}
140
+
141
+
142
+ def _text(response):
143
+ return "".join(part.text for item in response.output if item.type == "message" for part in item.content)
144
+
145
+
146
+ @pytest.mark.parametrize("model", ["openai/scripted", "anthropic/claude-scripted"])
147
+ def test_responses(stub, model):
148
+ """litellm.responses: OpenAI's own Responses API, and Anthropic's Messages through LiteLLM's bridge."""
149
+ if model.startswith("anthropic/") and _version() < (1, 80):
150
+ pytest.skip("LiteLLM 1.70's bridge from responses to another provider fails on a function_call given back")
151
+ options = {"api_base": _base(stub, model), **MODELS[model]}
152
+ tools = [*responses_tools(), ADD_RESPONSES]
153
+ given = [{"role": "user", "content": QUESTION[0]["content"]}]
154
+ response = litellm.responses(model=model, input=given, tools=tools, **options)
155
+ calls = [item for item in response.output if item.type == "function_call"]
156
+ assert [item.name for item in calls] == ["datacircle_best_plans", "add_two_numbers"]
157
+ ours = call_outputs(response)
158
+ assert [item["call_id"] for item in ours] == [calls[0].call_id]
159
+ given += [item.model_dump(exclude_none=True) for item in calls]
160
+ given += [*ours, _own_output(calls[1])]
161
+ _read(stub, _text(litellm.responses(model=model, input=given, tools=tools, **options)))
162
+
163
+
164
+ def test_aresponses(stub):
165
+ async def main():
166
+ options = {"api_base": stub.url + "/v1", "api_key": "test"}
167
+ tools = [*responses_tools(), ADD_RESPONSES]
168
+ given = [{"role": "user", "content": QUESTION[0]["content"]}]
169
+ response = await litellm.aresponses(model="openai/scripted", input=given, tools=tools, **options)
170
+ calls = [item for item in response.output if item.type == "function_call"]
171
+ given += [item.model_dump(exclude_none=True) for item in calls]
172
+ given += [*await acall_outputs(response), _own_output(calls[1])]
173
+ return _text(await litellm.aresponses(model="openai/scripted", input=given, tools=tools, **options))
174
+ _read(stub, asyncio.run(main()))
@@ -0,0 +1,29 @@
1
+ """Each tool on the live API, https://api.datacircle.dev/v1: run with DATACIRCLE_LIVE=1."""
2
+
3
+ import json
4
+ import os
5
+
6
+ import pytest
7
+
8
+ from litellm_datacircle import _api, call, call_output, run
9
+
10
+ pytestmark = pytest.mark.skipif(os.environ.get("DATACIRCLE_LIVE") != "1", reason="DATACIRCLE_LIVE=1 calls the live API")
11
+
12
+
13
+ def test_live(monkeypatch):
14
+ monkeypatch.setattr(_api, "BASE_URL", "https://api.datacircle.dev/v1")
15
+ apis = json.loads(run("datacircle_list_apis", {"query": "email finder", "limit": 3}))
16
+ assert apis["total"] >= 1 and apis["apis"][0]["slug"] and len(apis["apis"]) <= 3
17
+ best = json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))
18
+ assert 1 <= len(best["plans"]) <= 3 and all(plan["provider"] and plan.get("page") for plan in best["plans"])
19
+ plans = json.loads(run("datacircle_search_plans", {"api": "email-finder", "sort": "price", "limit": 2}))
20
+ assert plans["total"] >= 1 and len(plans["plans"]) <= 2
21
+ slug = _api.slug(best["plans"][0]["provider"])
22
+ provider = json.loads(run("datacircle_provider", {"slug": best["plans"][0]["provider"]}))
23
+ assert provider["slug"] == slug and provider["apis"] and "plans" in provider["apis"][0]
24
+ refused = json.loads(run("datacircle_best_plans", {"slug": "no-such-api"}))
25
+ assert "answered 404" in refused["error"] and "email-finder" in refused["error"]
26
+ message = call({"id": "c", "function": {"name": "datacircle_provider", "arguments": json.dumps({"slug": slug})}})
27
+ assert json.loads(message["content"])["slug"] == slug
28
+ output = call_output({"type": "function_call", "call_id": "c", "name": "datacircle_list_apis", "arguments": "{}"})
29
+ assert json.loads(output["output"])["total"] > 100
@@ -0,0 +1,112 @@
1
+ """Offline tests of the tools alone, on the stand-in API (conftest.py): every call, its cut, every refusal."""
2
+
3
+ import asyncio
4
+ import json
5
+
6
+ import pytest
7
+
8
+ import litellm_datacircle
9
+ from litellm_datacircle import (
10
+ TOOL_NAMES,
11
+ acall_all,
12
+ aexecute_tool,
13
+ call,
14
+ call_all,
15
+ call_output,
16
+ call_outputs,
17
+ datacircle_tools,
18
+ execute_tool,
19
+ executor,
20
+ responses_tools,
21
+ run,
22
+ )
23
+
24
+
25
+ def test_definitions():
26
+ tools = datacircle_tools()
27
+ assert [tool["function"]["name"] for tool in tools] == TOOL_NAMES
28
+ assert all(tool["type"] == "function" and tool["function"]["description"] for tool in tools)
29
+ assert tools[1]["function"]["parameters"]["required"] == ["slug"]
30
+ assert [tool["function"]["name"] for tool in datacircle_tools(["datacircle_provider"])] == ["datacircle_provider"]
31
+ tools[0]["function"]["parameters"]["properties"].clear() # a copy of its own: the next call is whole
32
+ assert datacircle_tools()[0]["function"]["parameters"]["properties"]
33
+ assert responses_tools()[2] == {"type": "function", **datacircle_tools()[2]["function"], "strict": False}
34
+ allowed = {"type", "description", "enum", "minimum", "maximum", "properties", "required"}
35
+ for tool in tools:
36
+ for spec in tool["function"]["parameters"]["properties"].values():
37
+ assert set(spec) <= allowed
38
+ with pytest.raises(ValueError, match="no tool 'nope'"):
39
+ datacircle_tools(["nope"])
40
+ with pytest.raises(TypeError):
41
+ datacircle_tools("datacircle_provider")
42
+ assert litellm_datacircle.__version__ == "0.1.0"
43
+
44
+
45
+ def test_each_tool(stub):
46
+ apis = json.loads(run("datacircle_list_apis", {"query": "email"}))
47
+ assert apis == {"total": 1, "apis": [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3}]}
48
+ assert json.loads(run("datacircle_list_apis", "{}"))["total"] == 2
49
+ best = json.loads(run("datacircle_best_plans", '{"slug": "Email Finder", "limit": "1"}'))
50
+ assert best["plans"] == [{"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1,
51
+ "perThousand": 4.9, "page": "https://datacircle.dev/x"}]
52
+ assert stub.seen[-1][:2] == ("/v1/apis/email-finder/best", {"limit": "1"})
53
+ assert stub.seen[-1][2] == "litellm-datacircle/0.1.0"
54
+ plans = json.loads(run("datacircle_search_plans", {"api": "email-finder", "sort": "Price", "limit": 5, "offset": 0}))
55
+ assert plans["total"] == 1
56
+ assert stub.seen[-1][1] == {"api": "email-finder", "sort": "price", "limit": "5", "offset": "0"}
57
+ provider = json.loads(run("datacircle_provider", {"slug": "Bright Data", "unknown": 1}))
58
+ assert provider["apis"][0]["best"]["plan"] == "Pro" and provider["apis"][0]["plans"] == 2
59
+
60
+
61
+ def test_refusals(stub):
62
+ assert "the slugs: email-finder, linkedin-profile" in json.loads(run("datacircle_best_plans", {"slug": "nope"}))["error"]
63
+ assert "Give an API's slug" in json.loads(run("datacircle_best_plans", {}))["error"]
64
+ assert "limit must be from 1 to 50" in json.loads(run("datacircle_best_plans", {"slug": "x", "limit": 99}))["error"]
65
+ assert "whole number" in json.loads(run("datacircle_search_plans", {"limit": 2.5}))["error"]
66
+ assert "sort must be" in json.loads(run("datacircle_search_plans", {"sort": "cheap"}))["error"]
67
+ assert "answered 503: down for a minute" in json.loads(run("datacircle_search_plans", {"query": "down"}))["error"]
68
+ assert "no JSON object" in json.loads(run("datacircle_provider", "{not json"))["error"]
69
+ assert "no JSON object" in json.loads(run("datacircle_provider", "[1]"))["error"]
70
+ assert "no provider" in json.loads(run("datacircle_provider", {"slug": "nope"}))["error"]
71
+ with pytest.raises(ValueError):
72
+ run("nope", {})
73
+
74
+
75
+ def test_one_wait_on_429(stub):
76
+ assert json.loads(run("datacircle_search_plans", {"query": "busy"}))["total"] == 1
77
+ assert "429 twice" in json.loads(run("datacircle_search_plans", {"query": "always-busy"}))["error"]
78
+
79
+
80
+ def test_out_of_reach(monkeypatch):
81
+ monkeypatch.setattr(litellm_datacircle._api, "BASE_URL", "http://127.0.0.1:9/v1")
82
+ assert "could not be reached" in json.loads(run("datacircle_list_apis"))["error"]
83
+
84
+
85
+ CALLS = [{"id": "call_0", "type": "function", "function": {"name": "datacircle_best_plans",
86
+ "arguments": '{"slug": "email-finder", "limit": 1}'}},
87
+ {"id": "call_1", "type": "function", "function": {"name": "add_two_numbers", "arguments": '{"a": 1}'}}]
88
+
89
+
90
+ def test_call_and_execute(stub):
91
+ message = call(CALLS[0])
92
+ assert message["role"] == "tool" and message["tool_call_id"] == "call_0"
93
+ assert json.loads(message["content"])["plans"][0]["provider"] == "Hunter"
94
+ assert call(CALLS[1]) is None
95
+ assert [m["tool_call_id"] for m in call_all({"role": "assistant", "tool_calls": CALLS})] == ["call_0"]
96
+ assert call_all(CALLS) == call_all({"tool_calls": CALLS}) and call_all(None) == [] and call_all({}) == []
97
+ assert "there is no tool 'add_two_numbers'" in json.loads(execute_tool(CALLS[1])["content"])["error"]
98
+ own = executor(lambda tool_call: {"role": "tool", "tool_call_id": tool_call["id"], "content": "3"})
99
+ assert own(CALLS[1])["content"] == "3" and json.loads(own(CALLS[0])["content"])["plans"]
100
+ assert executor() is execute_tool
101
+ assert [m["tool_call_id"] for m in asyncio.run(acall_all(CALLS))] == ["call_0"]
102
+ assert asyncio.run(aexecute_tool(CALLS[1]))["tool_call_id"] == "call_1"
103
+
104
+
105
+ def test_responses_items(stub):
106
+ items = [{"type": "reasoning", "id": "r"},
107
+ {"type": "function_call", "call_id": "c0", "name": "datacircle_provider", "arguments": '{"slug": "bright-data"}'},
108
+ {"type": "function_call", "call_id": "c1", "name": "add_two_numbers", "arguments": "{}"}]
109
+ outputs = call_outputs({"output": items})
110
+ assert [(o["type"], o["call_id"]) for o in outputs] == [("function_call_output", "c0")]
111
+ assert json.loads(outputs[0]["output"])["slug"] == "bright-data"
112
+ assert call_output(items[2]) is None and call_outputs(items) == outputs