huggingface-hub-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.
- huggingface_hub_datacircle-0.1.0/.gitignore +4 -0
- huggingface_hub_datacircle-0.1.0/LICENSE +9 -0
- huggingface_hub_datacircle-0.1.0/PKG-INFO +145 -0
- huggingface_hub_datacircle-0.1.0/README.md +128 -0
- huggingface_hub_datacircle-0.1.0/pyproject.toml +32 -0
- huggingface_hub_datacircle-0.1.0/src/huggingface_hub_datacircle/__init__.py +17 -0
- huggingface_hub_datacircle-0.1.0/src/huggingface_hub_datacircle/_api.py +114 -0
- huggingface_hub_datacircle-0.1.0/src/huggingface_hub_datacircle/py.typed +0 -0
- huggingface_hub_datacircle-0.1.0/src/huggingface_hub_datacircle/tools.py +259 -0
- huggingface_hub_datacircle-0.1.0/tests/stand_in.py +161 -0
- huggingface_hub_datacircle-0.1.0/tests/test_tools.py +268 -0
|
@@ -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,145 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: huggingface-hub-datacircle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Hugging Face InferenceClient 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/huggingface-hub-datacircle
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: api,api-pricing,b2b-data,datacircle,function-calling,gtm,huggingface,huggingface-hub,inference,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
|
+
Requires-Dist: huggingface-hub>=0.24.6
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# huggingface-hub-datacircle
|
|
19
|
+
|
|
20
|
+
Find the best GTM APIs. We benchmark all the GTM APIs and we put the results on our website.
|
|
21
|
+
|
|
22
|
+
Our website: https://datacircle.dev
|
|
23
|
+
|
|
24
|
+
This package gives the `InferenceClient` of [huggingface_hub](https://github.com/huggingface/huggingface_hub) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You pass the tools to `client.chat_completion()`. The package then runs each tool call from the model. You can run the tools on Inference Providers or on your own server. You need no key and no account for Datacircle.
|
|
25
|
+
|
|
26
|
+
| Tool | What the tool gives | Call |
|
|
27
|
+
| --- | --- | --- |
|
|
28
|
+
| `datacircle_list_apis` | Every GTM API on Datacircle, with the API's slug, number of plans, number of providers and best plan | `GET /apis` |
|
|
29
|
+
| `datacircle_best_plans` | One API's plans, sorted by score out of 100, best first. Each plan comes with a rank and a price per 1,000 calls | `GET /apis/{slug}/best` |
|
|
30
|
+
| `datacircle_search_plans` | Plans that match a provider or plan name, on all APIs or on one API. You can sort them by score, provider or price | `GET /plans` |
|
|
31
|
+
| `datacircle_provider` | The APIs a provider sells, and the provider's rank on each API | `GET /providers/{slug}` |
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install huggingface-hub-datacircle
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
huggingface-hub-datacircle works with `huggingface_hub` 0.24.6 and later, on Python 3.9 and later.
|
|
40
|
+
|
|
41
|
+
## Use the tools
|
|
42
|
+
|
|
43
|
+
Send the tools with `client.chat_completion()`. If the model calls a tool, `call_all()` gives you the tool messages to send back:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from huggingface_hub import InferenceClient
|
|
47
|
+
from huggingface_hub_datacircle import call_all, datacircle_tools
|
|
48
|
+
|
|
49
|
+
client = InferenceClient()
|
|
50
|
+
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
|
51
|
+
messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
52
|
+
response = client.chat_completion(messages, model=model, tools=datacircle_tools())
|
|
53
|
+
|
|
54
|
+
while response.choices[0].message.tool_calls:
|
|
55
|
+
messages.append(response.choices[0].message)
|
|
56
|
+
messages.extend(call_all(response.choices[0].message))
|
|
57
|
+
response = client.chat_completion(messages, model=model, tools=datacircle_tools())
|
|
58
|
+
|
|
59
|
+
print(response.choices[0].message.content)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`InferenceClient()` reads your Hugging Face token from `HF_TOKEN` or from `hf auth login`. For your own server, use `InferenceClient(base_url="http://localhost:8080/v1")`. `client.chat.completions.create()` takes the same arguments as `client.chat_completion()`.
|
|
63
|
+
|
|
64
|
+
Each tool message has `role: "tool"` and the call's id in `tool_call_id`. The tool's name sits in `name`. The answer sits in `content` as JSON text.
|
|
65
|
+
|
|
66
|
+
## Stream
|
|
67
|
+
|
|
68
|
+
With `stream=True`, some chunks hold pieces of tool calls. Pass each chunk's `delta.tool_calls` to `collect_tool_calls()`. `collect_tool_calls()` puts the pieces of each call together in one list. Then run the list with `call_all()`:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from huggingface_hub import InferenceClient
|
|
72
|
+
from huggingface_hub_datacircle import call_all, collect_tool_calls, datacircle_tools
|
|
73
|
+
|
|
74
|
+
client = InferenceClient()
|
|
75
|
+
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
|
76
|
+
messages = [{"role": "user", "content": "Which APIs does the provider Bright Data sell?"}]
|
|
77
|
+
|
|
78
|
+
for turn in range(5):
|
|
79
|
+
content, calls = "", []
|
|
80
|
+
for chunk in client.chat_completion(messages, model=model, tools=datacircle_tools(), stream=True):
|
|
81
|
+
delta = chunk.choices[0].delta
|
|
82
|
+
content += delta.content or ""
|
|
83
|
+
collect_tool_calls(calls, delta.tool_calls)
|
|
84
|
+
if not calls:
|
|
85
|
+
print(content)
|
|
86
|
+
break
|
|
87
|
+
messages.append({"role": "assistant", "content": content, "tool_calls": calls})
|
|
88
|
+
messages.extend(call_all(calls))
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
With `AsyncInferenceClient`, use `await acall_all(...)`. `acall_all()` runs the calls at the same time. Your event loop keeps running.
|
|
92
|
+
|
|
93
|
+
## Use the Datacircle tools beside your own tools
|
|
94
|
+
|
|
95
|
+
You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`. `call()` runs one tool call. For your own tools, `call()` returns `None`. Your code then runs the tool itself:
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
import json
|
|
99
|
+
|
|
100
|
+
from huggingface_hub_datacircle import call
|
|
101
|
+
|
|
102
|
+
for tool_call in response.choices[0].message.tool_calls or []:
|
|
103
|
+
message = call(tool_call)
|
|
104
|
+
if message is None:
|
|
105
|
+
arguments = tool_call.function.arguments
|
|
106
|
+
if isinstance(arguments, str):
|
|
107
|
+
arguments = json.loads(arguments)
|
|
108
|
+
output = my_tools[tool_call.function.name](**arguments)
|
|
109
|
+
message = {"role": "tool", "tool_call_id": tool_call.id, "name": tool_call.function.name, "content": str(output)}
|
|
110
|
+
messages.append(message)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
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 huggingface_hub_datacircle import run
|
|
123
|
+
|
|
124
|
+
print(json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))["plans"])
|
|
125
|
+
print(run("datacircle_provider", {"slug": "Bright Data"}))
|
|
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
|
+
For an unknown slug, the tool returns `{"error": "..."}` with the API's message. The error for an unknown API slug lists every valid slug. The tool checks each number from the model before any API call. 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 tool never raises an error. 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's spec: https://api.datacircle.dev/v1/openapi.json
|
|
144
|
+
|
|
145
|
+
MIT license.
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# huggingface-hub-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 the `InferenceClient` of [huggingface_hub](https://github.com/huggingface/huggingface_hub) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. You pass the tools to `client.chat_completion()`. The package then runs each tool call from the model. You can run the tools on Inference Providers or on your own server. You need no key and no account for Datacircle.
|
|
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 huggingface-hub-datacircle
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
huggingface-hub-datacircle works with `huggingface_hub` 0.24.6 and later, on Python 3.9 and later.
|
|
23
|
+
|
|
24
|
+
## Use the tools
|
|
25
|
+
|
|
26
|
+
Send the tools with `client.chat_completion()`. If the model calls a tool, `call_all()` gives you the tool messages to send back:
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from huggingface_hub import InferenceClient
|
|
30
|
+
from huggingface_hub_datacircle import call_all, datacircle_tools
|
|
31
|
+
|
|
32
|
+
client = InferenceClient()
|
|
33
|
+
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
|
34
|
+
messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
35
|
+
response = client.chat_completion(messages, model=model, tools=datacircle_tools())
|
|
36
|
+
|
|
37
|
+
while response.choices[0].message.tool_calls:
|
|
38
|
+
messages.append(response.choices[0].message)
|
|
39
|
+
messages.extend(call_all(response.choices[0].message))
|
|
40
|
+
response = client.chat_completion(messages, model=model, tools=datacircle_tools())
|
|
41
|
+
|
|
42
|
+
print(response.choices[0].message.content)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`InferenceClient()` reads your Hugging Face token from `HF_TOKEN` or from `hf auth login`. For your own server, use `InferenceClient(base_url="http://localhost:8080/v1")`. `client.chat.completions.create()` takes the same arguments as `client.chat_completion()`.
|
|
46
|
+
|
|
47
|
+
Each tool message has `role: "tool"` and the call's id in `tool_call_id`. The tool's name sits in `name`. The answer sits in `content` as JSON text.
|
|
48
|
+
|
|
49
|
+
## Stream
|
|
50
|
+
|
|
51
|
+
With `stream=True`, some chunks hold pieces of tool calls. Pass each chunk's `delta.tool_calls` to `collect_tool_calls()`. `collect_tool_calls()` puts the pieces of each call together in one list. Then run the list with `call_all()`:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from huggingface_hub import InferenceClient
|
|
55
|
+
from huggingface_hub_datacircle import call_all, collect_tool_calls, datacircle_tools
|
|
56
|
+
|
|
57
|
+
client = InferenceClient()
|
|
58
|
+
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
|
59
|
+
messages = [{"role": "user", "content": "Which APIs does the provider Bright Data sell?"}]
|
|
60
|
+
|
|
61
|
+
for turn in range(5):
|
|
62
|
+
content, calls = "", []
|
|
63
|
+
for chunk in client.chat_completion(messages, model=model, tools=datacircle_tools(), stream=True):
|
|
64
|
+
delta = chunk.choices[0].delta
|
|
65
|
+
content += delta.content or ""
|
|
66
|
+
collect_tool_calls(calls, delta.tool_calls)
|
|
67
|
+
if not calls:
|
|
68
|
+
print(content)
|
|
69
|
+
break
|
|
70
|
+
messages.append({"role": "assistant", "content": content, "tool_calls": calls})
|
|
71
|
+
messages.extend(call_all(calls))
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
With `AsyncInferenceClient`, use `await acall_all(...)`. `acall_all()` runs the calls at the same time. Your event loop keeps running.
|
|
75
|
+
|
|
76
|
+
## Use the Datacircle tools beside your own tools
|
|
77
|
+
|
|
78
|
+
You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`. `call()` runs one tool call. For your own tools, `call()` returns `None`. Your code then runs the tool itself:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
import json
|
|
82
|
+
|
|
83
|
+
from huggingface_hub_datacircle import call
|
|
84
|
+
|
|
85
|
+
for tool_call in response.choices[0].message.tool_calls or []:
|
|
86
|
+
message = call(tool_call)
|
|
87
|
+
if message is None:
|
|
88
|
+
arguments = tool_call.function.arguments
|
|
89
|
+
if isinstance(arguments, str):
|
|
90
|
+
arguments = json.loads(arguments)
|
|
91
|
+
output = my_tools[tool_call.function.name](**arguments)
|
|
92
|
+
message = {"role": "tool", "tool_call_id": tool_call.id, "name": tool_call.function.name, "content": str(output)}
|
|
93
|
+
messages.append(message)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
97
|
+
|
|
98
|
+
## Call a tool yourself
|
|
99
|
+
|
|
100
|
+
You can call each tool without a model. You get the JSON text of the tool's answer:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
import json
|
|
104
|
+
|
|
105
|
+
from huggingface_hub_datacircle import run
|
|
106
|
+
|
|
107
|
+
print(json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 3}))["plans"])
|
|
108
|
+
print(run("datacircle_provider", {"slug": "Bright Data"}))
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## What the model reads
|
|
112
|
+
|
|
113
|
+
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.
|
|
114
|
+
|
|
115
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
116
|
+
|
|
117
|
+
For an unknown slug, the tool returns `{"error": "..."}` with the API's message. The error for an unknown API slug lists every valid slug. The tool checks each number from the model before any API call. 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 tool never raises an error. The model can then call the tool again.
|
|
118
|
+
|
|
119
|
+
## Network
|
|
120
|
+
|
|
121
|
+
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.
|
|
122
|
+
|
|
123
|
+
## Links
|
|
124
|
+
|
|
125
|
+
- Datacircle: https://datacircle.dev
|
|
126
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
127
|
+
|
|
128
|
+
MIT license.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "huggingface-hub-datacircle"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Hugging Face InferenceClient tools for the Datacircle API: find the best GTM APIs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = ["huggingface_hub>=0.24.6"]
|
|
13
|
+
keywords = ["huggingface", "huggingface-hub", "inference", "tools", "function-calling", "tool-calling", "gtm", "api", "api-pricing", "b2b-data", "datacircle"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Topic :: Software Development :: Libraries",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://datacircle.dev"
|
|
22
|
+
Documentation = "https://api.datacircle.dev/v1/openapi.json"
|
|
23
|
+
Repository = "https://github.com/waynehamadi/huggingface-hub-datacircle"
|
|
24
|
+
|
|
25
|
+
[dependency-groups]
|
|
26
|
+
test = ["pytest>=8"]
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/huggingface_hub_datacircle"]
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.sdist]
|
|
32
|
+
include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Tools for huggingface_hub's InferenceClient on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
|
|
2
|
+
|
|
3
|
+
from huggingface_hub_datacircle._api import BASE_URL, DatacircleError
|
|
4
|
+
from huggingface_hub_datacircle.tools import (
|
|
5
|
+
TOOL_NAMES,
|
|
6
|
+
acall,
|
|
7
|
+
acall_all,
|
|
8
|
+
call,
|
|
9
|
+
call_all,
|
|
10
|
+
collect_tool_calls,
|
|
11
|
+
datacircle_tools,
|
|
12
|
+
run,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__version__ = "0.1.0"
|
|
16
|
+
__all__ = ["BASE_URL", "DatacircleError", "TOOL_NAMES", "acall", "acall_all", "call", "call_all", "collect_tool_calls",
|
|
17
|
+
"datacircle_tools", "run"]
|
|
@@ -0,0 +1,114 @@
|
|
|
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 gzip
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
import unicodedata
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.parse
|
|
11
|
+
import urllib.request
|
|
12
|
+
import zlib
|
|
13
|
+
from typing import Any, Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
BASE_URL = "https://api.datacircle.dev/v1"
|
|
16
|
+
TIMEOUT = 30.0
|
|
17
|
+
USER_AGENT = "huggingface-hub-datacircle/0.1.0"
|
|
18
|
+
|
|
19
|
+
# 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.
|
|
20
|
+
PLAN_KEYS = ["api", "rank", "provider", "plan", "score", "perThousand", "notFoundPerThousand", "billing", "pay",
|
|
21
|
+
"currency", "units", "unit", "strengths", "latencyMs", "page", "pricingPage", "docs"]
|
|
22
|
+
API_KEYS = ["api", "slug", "plans", "providers", "best", "bestPage", "sheetPage"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class DatacircleError(Exception):
|
|
26
|
+
"""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
|
|
27
|
+
model its words as its JSON text, {"error": ...}. status is the API's HTTP status, None when it gave none;
|
|
28
|
+
retryable, whether the same call may be answered later (the API out of reach, busy or failing)."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, message: str, status: Optional[int] = None, retryable: bool = False):
|
|
31
|
+
super().__init__(message)
|
|
32
|
+
self.status = status
|
|
33
|
+
self.retryable = retryable
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def brief(item: Dict[str, Any], keys: List[str] = PLAN_KEYS) -> Dict[str, Any]:
|
|
37
|
+
return {key: item[key] for key in keys if item.get(key) is not None}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def slug(value: Any) -> str:
|
|
41
|
+
"""The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen."""
|
|
42
|
+
plain = unicodedata.normalize("NFKD", str(value or "").strip().lower())
|
|
43
|
+
plain = "".join(char for char in plain if not unicodedata.combining(char))
|
|
44
|
+
return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def whole(name: str, value: Any, low: int, high: Optional[int] = None) -> Optional[int]:
|
|
48
|
+
"""A whole number from low to high, or None when left out: a plain call may send one as text."""
|
|
49
|
+
if value is None or value == "":
|
|
50
|
+
return None
|
|
51
|
+
try:
|
|
52
|
+
number = float(value)
|
|
53
|
+
except (TypeError, ValueError):
|
|
54
|
+
number = float("nan")
|
|
55
|
+
if isinstance(value, bool) or not math.isfinite(number) or number != int(number):
|
|
56
|
+
raise DatacircleError(f"{name} must be a whole number, not {value!r}")
|
|
57
|
+
if number < low or (high is not None and number > high):
|
|
58
|
+
raise DatacircleError(f"{name} must be from {low} to {high}, not {int(number)}" if high is not None
|
|
59
|
+
else f"{name} must be {low} or more, not {int(number)}")
|
|
60
|
+
return int(number)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _words(body: bytes) -> str:
|
|
64
|
+
"""A refusal's words: the API's error, with every slug when the slug was unknown."""
|
|
65
|
+
text = body.decode("utf-8", "replace")
|
|
66
|
+
try:
|
|
67
|
+
parsed = json.loads(text)
|
|
68
|
+
if parsed.get("slugs"):
|
|
69
|
+
return f"{parsed['error']}; the slugs: {', '.join(parsed['slugs'])}"
|
|
70
|
+
return str(parsed.get("error", text))
|
|
71
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
72
|
+
return text
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _unpacked(body: bytes, headers: Any) -> bytes:
|
|
76
|
+
"""The answer's bytes as sent before it was squeezed: urllib unpacks nothing by itself, and an answer may pass 10 MB."""
|
|
77
|
+
if str((headers or {}).get("Content-Encoding") or "").strip().lower() != "gzip":
|
|
78
|
+
return body
|
|
79
|
+
try:
|
|
80
|
+
return gzip.decompress(body)
|
|
81
|
+
except (OSError, EOFError, zlib.error) as error:
|
|
82
|
+
raise DatacircleError(f"Datacircle's API gave a broken gzip answer: {error}", retryable=True) from None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def get(path: str, params: Optional[Dict[str, Any]] = None) -> Any:
|
|
86
|
+
"""The API's JSON answer, or a DatacircleError with its words: waits once when it answers 429."""
|
|
87
|
+
query = urllib.parse.urlencode({key: value for key, value in (params or {}).items() if value not in (None, "")})
|
|
88
|
+
url = f"{BASE_URL.rstrip('/')}{path}" + (f"?{query}" if query else "")
|
|
89
|
+
request = urllib.request.Request(url, headers={"Accept": "application/json", "Accept-Encoding": "gzip",
|
|
90
|
+
"User-Agent": USER_AGENT})
|
|
91
|
+
for attempt in range(2):
|
|
92
|
+
try:
|
|
93
|
+
with urllib.request.urlopen(request, timeout=TIMEOUT) as answer:
|
|
94
|
+
body = _unpacked(answer.read(), answer.headers)
|
|
95
|
+
except urllib.error.HTTPError as error:
|
|
96
|
+
body = _unpacked(error.read(), error.headers)
|
|
97
|
+
if error.code == 429 and not attempt:
|
|
98
|
+
try:
|
|
99
|
+
wait = int(error.headers.get("Retry-After") or 30)
|
|
100
|
+
except ValueError:
|
|
101
|
+
wait = 30
|
|
102
|
+
time.sleep(min(max(wait, 1), 60))
|
|
103
|
+
continue
|
|
104
|
+
if error.code == 429:
|
|
105
|
+
raise DatacircleError("Datacircle's API answered 429 twice: wait a minute and call again", 429, True) from None
|
|
106
|
+
raise DatacircleError(f"Datacircle's API answered {error.code}: {_words(body)[:3000]}", error.code,
|
|
107
|
+
error.code >= 500) from None
|
|
108
|
+
except (urllib.error.URLError, OSError) as error:
|
|
109
|
+
raise DatacircleError(f"Datacircle's API could not be reached: {getattr(error, 'reason', error)}",
|
|
110
|
+
retryable=True) from None
|
|
111
|
+
try:
|
|
112
|
+
return json.loads(body)
|
|
113
|
+
except ValueError as error:
|
|
114
|
+
raise DatacircleError(f"Datacircle's API gave no JSON: {error}") from None
|
|
File without changes
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""Tools for huggingface_hub's InferenceClient on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
|
|
2
|
+
|
|
3
|
+
datacircle_tools() gives the four as tool definitions for client.chat_completion(tools=...), its stream=True and its
|
|
4
|
+
alias client.chat.completions.create, and AsyncInferenceClient's, beside an app's own; call() and call_all() run the
|
|
5
|
+
tool calls the model returns into the tool messages to send back, acall() and acall_all() in a thread for an event
|
|
6
|
+
loop, and collect_tool_calls() gathers a stream's calls. A tool makes one HTTPS GET and gives the model the API's answer
|
|
7
|
+
as JSON text. A refusal (an unknown slug, an argument out of range, the API out of reach) is the JSON text
|
|
8
|
+
{"error": the API's words}, so the model can call again and the chat goes on. Not every model keeps to a tool's
|
|
9
|
+
schema, so each tool checks its arguments before any call.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import copy
|
|
14
|
+
import json
|
|
15
|
+
import urllib.parse
|
|
16
|
+
from typing import Any, Dict, List, Mapping, Optional, Sequence
|
|
17
|
+
|
|
18
|
+
from huggingface_hub_datacircle import _api
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _text(answer: Any) -> str:
|
|
22
|
+
return json.dumps(answer, ensure_ascii=False)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _best(plans: Any) -> Optional[Dict[str, Any]]:
|
|
26
|
+
"""A provider's best plan on an API: its lowest rank, a plan with no score having none."""
|
|
27
|
+
ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
|
|
28
|
+
return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _list_apis(query: Any = None, limit: Any = None) -> Dict[str, Any]:
|
|
32
|
+
count = _api.whole("limit", limit, 1, 200) or 20
|
|
33
|
+
apis = _api.get("/apis")
|
|
34
|
+
words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
|
|
35
|
+
held = []
|
|
36
|
+
for index, api in enumerate(apis):
|
|
37
|
+
name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
|
|
38
|
+
matched = sum(word in name for word in words)
|
|
39
|
+
if matched or not words:
|
|
40
|
+
held.append((-matched, index, api))
|
|
41
|
+
found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
|
|
42
|
+
return {"total": len(found), "apis": found[:count]}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _best_plans(slug: Any = None, limit: Any = None) -> Dict[str, Any]:
|
|
46
|
+
made = _api.slug(slug)
|
|
47
|
+
if not made:
|
|
48
|
+
raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
|
|
49
|
+
answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
|
|
50
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _search_plans(api: Any = None, query: Any = None, sort: Any = None, limit: Any = None, offset: Any = None) -> Dict[str, Any]:
|
|
54
|
+
order = str(sort).strip().lower() if sort not in (None, "") else None
|
|
55
|
+
if order is not None and order not in ("score", "provider", "price"):
|
|
56
|
+
raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
|
|
57
|
+
params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
|
|
58
|
+
"offset": _api.whole("offset", offset, 0)}
|
|
59
|
+
answer = _api.get("/plans", params)
|
|
60
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _provider(slug: Any = None) -> Dict[str, Any]:
|
|
64
|
+
made = _api.slug(slug)
|
|
65
|
+
if not made:
|
|
66
|
+
raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
|
|
67
|
+
answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
|
|
68
|
+
apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
|
|
69
|
+
"best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
|
|
70
|
+
return {**answer, "apis": apis}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
_PRICE = "perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency."
|
|
74
|
+
_LIMIT = {"type": "integer", "minimum": 1, "maximum": 50, "description": "How many plans to give, 1 to 50. 10 when left out."}
|
|
75
|
+
|
|
76
|
+
# Each tool: what the model reads of it, and the function that answers it. The schemas use only what every server behind
|
|
77
|
+
# chat_completion takes (Inference Providers, TGI, vLLM, llama.cpp, an OpenAI-compatible base_url): type, description,
|
|
78
|
+
# enum, minimum, maximum, required.
|
|
79
|
+
_TOOLS: Dict[str, Dict[str, Any]] = {
|
|
80
|
+
"datacircle_list_apis": {
|
|
81
|
+
"run": _list_apis,
|
|
82
|
+
"description": "Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how many plans "
|
|
83
|
+
"and providers it has and its best plan. Call it to find an API's slug when you don't know it. Gives "
|
|
84
|
+
"total, the APIs found, and apis, up to limit of them.",
|
|
85
|
+
"parameters": {"type": "object", "properties": {
|
|
86
|
+
"query": {"type": "string", "description": "Words of the API's name or slug, like 'email' or 'linkedin profile'. "
|
|
87
|
+
"The APIs that hold the most of them come first, in the sheet's order "
|
|
88
|
+
"when left out."},
|
|
89
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 200,
|
|
90
|
+
"description": "How many APIs to give, 1 to 200. 20 when left out, of about 170."}}},
|
|
91
|
+
},
|
|
92
|
+
"datacircle_best_plans": {
|
|
93
|
+
"run": _best_plans,
|
|
94
|
+
"description": "Gives an API's plans best first by their score out of 100 on Datacircle's benchmark "
|
|
95
|
+
"(https://datacircle.dev), each with its rank, provider, plan, $ per 1,000 calls and its page: the "
|
|
96
|
+
"best providers of an API. " + _PRICE,
|
|
97
|
+
"parameters": {"type": "object", "properties": {
|
|
98
|
+
"slug": {"type": "string", "description": "The API's slug, like 'email-finder' or 'linkedin-profile', as "
|
|
99
|
+
"datacircle_list_apis gives it."},
|
|
100
|
+
"limit": _LIMIT}, "required": ["slug"]},
|
|
101
|
+
},
|
|
102
|
+
"datacircle_search_plans": {
|
|
103
|
+
"run": _search_plans,
|
|
104
|
+
"description": "Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan "
|
|
105
|
+
"name, sorted by score, provider or price. Gives total, offset and up to limit plans. " + _PRICE,
|
|
106
|
+
"parameters": {"type": "object", "properties": {
|
|
107
|
+
"api": {"type": "string", "description": "Only this API's plans, by its name or slug, like 'email-finder'. A "
|
|
108
|
+
"provider's name goes in query, never here. Every API when left out."},
|
|
109
|
+
"query": {"type": "string", "description": "Words that must all appear in the provider's or plan's name, like "
|
|
110
|
+
"'bright data'."},
|
|
111
|
+
"sort": {"type": "string", "enum": ["score", "provider", "price"],
|
|
112
|
+
"description": "score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first)."},
|
|
113
|
+
"limit": _LIMIT,
|
|
114
|
+
"offset": {"type": "integer", "minimum": 0, "description": "How many found plans to skip first. 0 when left out."}}},
|
|
115
|
+
},
|
|
116
|
+
"datacircle_provider": {
|
|
117
|
+
"run": _provider,
|
|
118
|
+
"description": "Gives each API one provider sells and its rank on each on Datacircle's benchmark "
|
|
119
|
+
"(https://datacircle.dev), with its best plan there.",
|
|
120
|
+
"parameters": {"type": "object", "properties": {
|
|
121
|
+
"slug": {"type": "string", "description": "The provider's slug, like 'bright-data', or its name, like 'Bright "
|
|
122
|
+
"Data', which is made a slug."}}, "required": ["slug"]},
|
|
123
|
+
},
|
|
124
|
+
}
|
|
125
|
+
TOOL_NAMES = list(_TOOLS)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _names(tool_names: Optional[Sequence[str]]) -> List[str]:
|
|
129
|
+
if isinstance(tool_names, str):
|
|
130
|
+
raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
|
|
131
|
+
for name in tool_names or []:
|
|
132
|
+
if name not in _TOOLS:
|
|
133
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
134
|
+
return TOOL_NAMES if tool_names is None else list(tool_names)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def datacircle_tools(tool_names: Optional[Sequence[str]] = None) -> List[Dict[str, Any]]:
|
|
138
|
+
"""The tools for client.chat_completion(messages, model=..., tools=datacircle_tools()), its stream=True, its alias
|
|
139
|
+
client.chat.completions.create and AsyncInferenceClient's, or beside one's own: tools=[*datacircle_tools(), my_tool].
|
|
140
|
+
tool_names keeps some of them only, in their order here; all four when left out. Each is a new dict, so an app may
|
|
141
|
+
change its copy."""
|
|
142
|
+
return [{"type": "function", "function": {"name": name, "description": _TOOLS[name]["description"],
|
|
143
|
+
"parameters": copy.deepcopy(_TOOLS[name]["parameters"])}}
|
|
144
|
+
for name in _names(tool_names)]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def run(name: str, arguments: Any = None) -> str:
|
|
148
|
+
"""What a tool gives the model for these arguments, as JSON text: the API's answer, or {"error": its words}.
|
|
149
|
+
arguments is a mapping or its JSON text (huggingface_hub before 0.25 and some servers give a mapping); the ones the
|
|
150
|
+
tool doesn't take are left out, and null ones too."""
|
|
151
|
+
if name not in _TOOLS:
|
|
152
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
153
|
+
if isinstance(arguments, bytes):
|
|
154
|
+
arguments = arguments.decode("utf-8", "replace")
|
|
155
|
+
if isinstance(arguments, str):
|
|
156
|
+
try:
|
|
157
|
+
arguments = json.loads(arguments) if arguments.strip() else {}
|
|
158
|
+
except ValueError:
|
|
159
|
+
return _text({"error": f"the arguments are no JSON object: {arguments[:200]!r}"})
|
|
160
|
+
if arguments is not None and not isinstance(arguments, Mapping):
|
|
161
|
+
return _text({"error": f"the arguments are no JSON object: {str(arguments)[:200]!r}"})
|
|
162
|
+
given = dict(arguments or {})
|
|
163
|
+
taken = _TOOLS[name]["parameters"]["properties"]
|
|
164
|
+
try:
|
|
165
|
+
return _text(_TOOLS[name]["run"](**{key: given.get(key) for key in taken}))
|
|
166
|
+
except _api.DatacircleError as error:
|
|
167
|
+
return _text({"error": str(error)})
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _field(item: Any, key: str) -> Any:
|
|
171
|
+
"""A field of a dict, or of huggingface_hub's types (dicts too, read by attribute: 0.24 warns on a dict's read)."""
|
|
172
|
+
if type(item) is dict or not hasattr(item, key):
|
|
173
|
+
return item.get(key) if isinstance(item, Mapping) else None
|
|
174
|
+
return getattr(item, key)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _named(tool_call: Any) -> Optional[str]:
|
|
178
|
+
"""The tool's name in a tool call (huggingface_hub's ChatCompletionOutputToolCall, or a dict of its shape): when it
|
|
179
|
+
is one of ours."""
|
|
180
|
+
name = _field(_field(tool_call, "function"), "name")
|
|
181
|
+
return name if name in _TOOLS else None
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def call(tool_call: Any) -> Optional[Dict[str, str]]:
|
|
185
|
+
"""The tool message for one tool call the model returned (one of response.choices[0].message.tool_calls, or a dict
|
|
186
|
+
of its shape), to append to the messages: {"role": "tool", "tool_call_id": its id, "name": the tool's name,
|
|
187
|
+
"content": the JSON text}, as huggingface_hub's own MCP agent sends one. None when the call is for a tool that is
|
|
188
|
+
not one of these four, so the app runs its own."""
|
|
189
|
+
name = _named(tool_call)
|
|
190
|
+
if name is None:
|
|
191
|
+
return None
|
|
192
|
+
return {"role": "tool", "tool_call_id": _field(tool_call, "id"), "name": name,
|
|
193
|
+
"content": run(name, _field(_field(tool_call, "function"), "arguments"))}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _calls(message_or_calls: Any) -> Sequence[Any]:
|
|
197
|
+
"""A reply's tool calls, from its message (or a dict of its shape) or from the list itself."""
|
|
198
|
+
if message_or_calls is None:
|
|
199
|
+
return []
|
|
200
|
+
if isinstance(message_or_calls, (list, tuple)):
|
|
201
|
+
return message_or_calls
|
|
202
|
+
return _field(message_or_calls, "tool_calls") or []
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def call_all(message_or_calls: Any) -> List[Dict[str, str]]:
|
|
206
|
+
"""The tool messages for the calls of these four tools in a reply (its message, or its tool_calls), in their order.
|
|
207
|
+
Calls of other tools are left out, for the app to run."""
|
|
208
|
+
return [message for message in (call(tool_call) for tool_call in _calls(message_or_calls)) if message is not None]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
async def acall(tool_call: Any) -> Optional[Dict[str, str]]:
|
|
212
|
+
"""call() for AsyncInferenceClient: its HTTPS GET runs in a thread, so the event loop goes on."""
|
|
213
|
+
if _named(tool_call) is None:
|
|
214
|
+
return None
|
|
215
|
+
return await asyncio.to_thread(call, tool_call)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
async def acall_all(message_or_calls: Any) -> List[Dict[str, str]]:
|
|
219
|
+
"""call_all() for AsyncInferenceClient: the calls run at once, their messages in the calls' order."""
|
|
220
|
+
messages = await asyncio.gather(*(acall(tool_call) for tool_call in _calls(message_or_calls)))
|
|
221
|
+
return [message for message in messages if message is not None]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class _Gathered(dict):
|
|
225
|
+
"""A tool call gathered from a stream: a plain dict to the JSON that is sent, its index in the stream kept aside, as a
|
|
226
|
+
server that takes OpenAI's shape refuses an index in an assistant message's tool_calls."""
|
|
227
|
+
|
|
228
|
+
index: Any = None
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def collect_tool_calls(calls: List[Dict[str, Any]], delta_tool_calls: Any) -> List[Dict[str, Any]]:
|
|
232
|
+
"""Adds a stream chunk's tool calls (chunk.choices[0].delta.tool_calls) to calls and gives calls back. A server sends
|
|
233
|
+
a call in pieces, its id and name on the first and the call's index on each, and the pieces of an index make one call;
|
|
234
|
+
huggingface_hub before 0.25 gives one piece where later ones give a list. Each call is a dict {"id", "type":
|
|
235
|
+
"function", "function": {"name", "arguments"}}, for the assistant message's tool_calls and for call_all()."""
|
|
236
|
+
if delta_tool_calls is None:
|
|
237
|
+
return calls
|
|
238
|
+
pieces = [delta_tool_calls] if isinstance(delta_tool_calls, Mapping) or not isinstance(delta_tool_calls, (list, tuple)) \
|
|
239
|
+
else delta_tool_calls
|
|
240
|
+
for delta in pieces:
|
|
241
|
+
index, given = _field(delta, "index"), _field(delta, "id")
|
|
242
|
+
given = given if isinstance(given, str) and given not in ("", "null") else None
|
|
243
|
+
function = _field(delta, "function")
|
|
244
|
+
name, arguments = _field(function, "name"), _field(function, "arguments")
|
|
245
|
+
if isinstance(arguments, Mapping):
|
|
246
|
+
arguments = json.dumps(arguments, ensure_ascii=False)
|
|
247
|
+
held = next((made for made in reversed(calls) if index is not None and getattr(made, "index", None) == index), None)
|
|
248
|
+
if held is None or (given and held["id"] and given != held["id"]):
|
|
249
|
+
held = _Gathered(id=given, type="function", function={"name": "", "arguments": ""})
|
|
250
|
+
held.index = index if index is not None else len(calls)
|
|
251
|
+
calls.append(held)
|
|
252
|
+
held["id"] = held["id"] or given
|
|
253
|
+
held["function"]["name"] = held["function"]["name"] or name or ""
|
|
254
|
+
if isinstance(arguments, str):
|
|
255
|
+
held["function"]["arguments"] += arguments
|
|
256
|
+
return calls
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
__all__: List[str] = ["TOOL_NAMES", "acall", "acall_all", "call", "call_all", "collect_tool_calls", "datacircle_tools", "run"]
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""A stand-in on 127.0.0.1 for a chat server as huggingface_hub's InferenceClient calls one through base_url (an
|
|
2
|
+
OpenAI-compatible POST .../chat/completions: TGI, vLLM, llama.cpp, Inference Providers' router), and for Datacircle's
|
|
3
|
+
API when asked.
|
|
4
|
+
|
|
5
|
+
The chat runs a script: the first user text holds one or more lines `CALL <tool> <json arguments>`, and the model asks
|
|
6
|
+
for those tools at once; once every call has its result, it answers `DONE <each result's first 300 characters>`. As
|
|
7
|
+
OpenAI's API does, a request is refused with a 400 when a tool message's tool_call_id is no call of the assistant
|
|
8
|
+
message before it, when a reply's calls are not each answered, or when a message holds a key OpenAI's shape has not
|
|
9
|
+
(an index in a tool call). A stream gives each call in pieces: its id and name first, then its arguments in two, the
|
|
10
|
+
call's index on each. Every request is kept in REQUESTS: its path, its body and what was refused in it (None when
|
|
11
|
+
nothing). Datacircle's answers are sent gzipped when the request asks for it.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import gzip
|
|
15
|
+
import json
|
|
16
|
+
import re
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
import uuid
|
|
20
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
21
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
22
|
+
|
|
23
|
+
REQUESTS: List[Dict[str, Any]] = []
|
|
24
|
+
KEYS = {"system": {"role", "content", "name"}, "user": {"role", "content", "name"},
|
|
25
|
+
"assistant": {"role", "content", "name", "tool_calls", "refusal", "reasoning", "tool_call_id"},
|
|
26
|
+
"tool": {"role", "content", "tool_call_id", "name"}}
|
|
27
|
+
CALL_KEYS = {"id", "type", "function"}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def text_of(content: Any) -> str:
|
|
31
|
+
if isinstance(content, str):
|
|
32
|
+
return content
|
|
33
|
+
if isinstance(content, list):
|
|
34
|
+
return " ".join(part.get("text", "") for part in content if isinstance(part, dict))
|
|
35
|
+
return ""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def script(texts: List[str]) -> List[Tuple[str, Dict[str, Any]]]:
|
|
39
|
+
for text in texts:
|
|
40
|
+
found = re.findall(r"CALL (\w+) (\{.*?\})\s*$", text, re.M)
|
|
41
|
+
if found:
|
|
42
|
+
return [(name, json.loads(arguments)) for name, arguments in found]
|
|
43
|
+
return []
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def done(results: List[str]) -> str:
|
|
47
|
+
return "DONE " + " | ".join(result[:300] for result in results)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def chat_view(body: Dict[str, Any]) -> Tuple[List[str], List[Dict[str, Any]], Optional[str]]:
|
|
51
|
+
"""The user's texts, the tool messages, and what an OpenAI-compatible server would refuse in the messages."""
|
|
52
|
+
users, results, ids, answered, wrong = [], [], [], [], None
|
|
53
|
+
for number, message in enumerate(body.get("messages", [])):
|
|
54
|
+
role = message.get("role")
|
|
55
|
+
extra = set(message) - KEYS.get(role, set())
|
|
56
|
+
if wrong is None and (role not in KEYS or extra):
|
|
57
|
+
wrong = f"messages[{number}]: role {role!r}, keys not allowed: {sorted(extra)}"
|
|
58
|
+
if role != "tool" and ids and len(answered) != len(ids) and wrong is None:
|
|
59
|
+
wrong = f"messages[{number}]: {len(ids)} tool calls, {len(answered)} tool messages"
|
|
60
|
+
if role == "assistant":
|
|
61
|
+
calls = message.get("tool_calls") or []
|
|
62
|
+
for tool_call in calls:
|
|
63
|
+
extra = set(tool_call) - CALL_KEYS
|
|
64
|
+
if wrong is None and extra:
|
|
65
|
+
wrong = f"messages[{number}].tool_calls: keys not allowed: {sorted(extra)}"
|
|
66
|
+
arguments = (tool_call.get("function") or {}).get("arguments")
|
|
67
|
+
if wrong is None and not isinstance(arguments, str):
|
|
68
|
+
wrong = f"messages[{number}].tool_calls: arguments must be a string, not {arguments!r}"
|
|
69
|
+
ids, answered = [tool_call.get("id") for tool_call in calls], []
|
|
70
|
+
elif role == "tool":
|
|
71
|
+
given = message.get("tool_call_id")
|
|
72
|
+
results.append({"tool_call_id": given, "name": message.get("name"), "content": text_of(message.get("content"))})
|
|
73
|
+
answered.append(given)
|
|
74
|
+
if wrong is None and given not in ids:
|
|
75
|
+
wrong = f"messages[{number}]: tool_call_id {given} is no call of the assistant message before it"
|
|
76
|
+
elif role == "user":
|
|
77
|
+
users.append(text_of(message.get("content")))
|
|
78
|
+
if ids and len(answered) != len(ids) and wrong is None:
|
|
79
|
+
wrong = f"{len(ids)} tool calls, {len(answered)} tool messages"
|
|
80
|
+
return users, results, wrong
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Handler(BaseHTTPRequestHandler):
|
|
84
|
+
api: Optional[Callable[[str, Dict[str, str], Dict[str, str]], Tuple[int, Any, Dict[str, str]]]] = None
|
|
85
|
+
|
|
86
|
+
def log_message(self, *args: Any) -> None:
|
|
87
|
+
pass
|
|
88
|
+
|
|
89
|
+
def send(self, status: int, body: Any, content_type: str = "application/json", headers: Optional[Dict[str, str]] = None,
|
|
90
|
+
squeeze: bool = False) -> None:
|
|
91
|
+
data = body.encode() if isinstance(body, str) else json.dumps(body).encode()
|
|
92
|
+
headers = dict(headers or {})
|
|
93
|
+
if squeeze:
|
|
94
|
+
data, headers["Content-Encoding"] = gzip.compress(data), "gzip"
|
|
95
|
+
self.send_response(status)
|
|
96
|
+
for key, value in {"Content-Type": content_type, "Content-Length": str(len(data)), **headers}.items():
|
|
97
|
+
self.send_header(key, value)
|
|
98
|
+
self.end_headers()
|
|
99
|
+
self.wfile.write(data)
|
|
100
|
+
|
|
101
|
+
def do_GET(self) -> None:
|
|
102
|
+
from urllib.parse import parse_qs, urlparse
|
|
103
|
+
url = urlparse(self.path)
|
|
104
|
+
if type(self).api is None or not url.path.startswith("/v1/"):
|
|
105
|
+
return self.send(404, {"error": "no such path"})
|
|
106
|
+
query = {key: values[0] for key, values in parse_qs(url.query).items()}
|
|
107
|
+
status, body, headers = type(self).api(url.path, query, dict(self.headers))
|
|
108
|
+
self.send(status, body, headers=headers, squeeze="gzip" in (self.headers.get("Accept-Encoding") or ""))
|
|
109
|
+
|
|
110
|
+
def do_POST(self) -> None:
|
|
111
|
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
|
|
112
|
+
seen = {"path": self.path, "body": body, "wrong": None, "authorization": self.headers.get("Authorization")}
|
|
113
|
+
REQUESTS.append(seen)
|
|
114
|
+
if self.path.endswith("/chat/completions"):
|
|
115
|
+
return self.chat(body, seen)
|
|
116
|
+
self.send(404, {"error": {"message": f"unknown path {self.path}"}})
|
|
117
|
+
|
|
118
|
+
def chat(self, body: Dict[str, Any], seen: Dict[str, Any]) -> None:
|
|
119
|
+
users, results, wrong = chat_view(body)
|
|
120
|
+
if wrong is not None:
|
|
121
|
+
seen["wrong"] = wrong
|
|
122
|
+
return self.send(400, {"error": {"message": wrong, "type": "invalid_request_error"}})
|
|
123
|
+
calls = script(users)
|
|
124
|
+
answer = done([result["content"] for result in results]) if len(results) >= len(calls) else None
|
|
125
|
+
rid, now = "chatcmpl-" + uuid.uuid4().hex, int(time.time())
|
|
126
|
+
usage = {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
|
|
127
|
+
tool_calls = [{"id": "call_" + uuid.uuid4().hex[:24], "type": "function",
|
|
128
|
+
"function": {"name": name, "arguments": json.dumps(arguments)}} for name, arguments in calls]
|
|
129
|
+
if not body.get("stream"):
|
|
130
|
+
message = {"role": "assistant", "content": answer, **({} if answer else {"tool_calls": tool_calls})}
|
|
131
|
+
return self.send(200, {"id": rid, "object": "chat.completion", "model": body.get("model"), "usage": usage,
|
|
132
|
+
"created": now, "system_fingerprint": "stand-in",
|
|
133
|
+
"choices": [{"index": 0, "message": message, "logprobs": None,
|
|
134
|
+
"finish_reason": "stop" if answer else "tool_calls"}]})
|
|
135
|
+
|
|
136
|
+
def chunk(delta: Dict[str, Any], finish: Optional[str]) -> str:
|
|
137
|
+
return "data: " + json.dumps({"id": rid, "object": "chat.completion.chunk", "created": now, "model": body.get("model"),
|
|
138
|
+
"system_fingerprint": "stand-in",
|
|
139
|
+
"choices": [{"index": 0, "delta": delta, "logprobs": None, "finish_reason": finish}]}) + "\n\n"
|
|
140
|
+
events = [chunk({"role": "assistant", "content": ""}, None)]
|
|
141
|
+
if answer:
|
|
142
|
+
events += [chunk({"role": "assistant", "content": answer[:20]}, None),
|
|
143
|
+
chunk({"role": "assistant", "content": answer[20:]}, "stop")]
|
|
144
|
+
else:
|
|
145
|
+
for index, tool_call in enumerate(tool_calls):
|
|
146
|
+
arguments = tool_call["function"]["arguments"]
|
|
147
|
+
half = len(arguments) // 2
|
|
148
|
+
events.append(chunk({"role": "assistant", "tool_calls": [{"index": index, "id": tool_call["id"], "type": "function",
|
|
149
|
+
"function": {"name": tool_call["function"]["name"], "arguments": ""}}]}, None))
|
|
150
|
+
events.append(chunk({"role": "assistant", "tool_calls": [{"index": index, "function": {"arguments": arguments[:half]}}]}, None))
|
|
151
|
+
events.append(chunk({"role": "assistant", "tool_calls": [{"index": index, "function": {"arguments": arguments[half:]}}]}, None))
|
|
152
|
+
events.append(chunk({"role": "assistant"}, "tool_calls"))
|
|
153
|
+
self.send(200, "".join(events) + "data: [DONE]\n\n", "text/event-stream")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def start(api: Optional[Callable[..., Tuple[int, Any, Dict[str, str]]]] = None) -> ThreadingHTTPServer:
|
|
157
|
+
"""The stand-in, serving on a free port of 127.0.0.1 in a thread; api answers GET /v1/... when given."""
|
|
158
|
+
handler = type("StandIn", (Handler,), {"api": staticmethod(api) if api else None})
|
|
159
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
|
160
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
161
|
+
return server
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Offline tests: the tools against a stand-in for Datacircle's API on 127.0.0.1, by run(), call() and call_all() on
|
|
2
|
+
huggingface_hub's own tool calls, sent by InferenceClient's chat_completion (plain and streamed), its alias
|
|
3
|
+
chat.completions.create and AsyncInferenceClient's chat_completion to a stand-in chat server through base_url."""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
sys.path.insert(0, os.path.dirname(__file__))
|
|
14
|
+
import stand_in # noqa: E402
|
|
15
|
+
|
|
16
|
+
from huggingface_hub import AsyncInferenceClient, InferenceClient # noqa: E402
|
|
17
|
+
|
|
18
|
+
from huggingface_hub_datacircle import ( # noqa: E402
|
|
19
|
+
TOOL_NAMES,
|
|
20
|
+
acall,
|
|
21
|
+
acall_all,
|
|
22
|
+
call,
|
|
23
|
+
call_all,
|
|
24
|
+
collect_tool_calls,
|
|
25
|
+
datacircle_tools,
|
|
26
|
+
run,
|
|
27
|
+
)
|
|
28
|
+
from huggingface_hub_datacircle import _api # noqa: E402
|
|
29
|
+
|
|
30
|
+
PLAN = {"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1, "perThousand": 4.9,
|
|
31
|
+
"page": "https://datacircle.dev/x", "terms": "long", "aggregators": ["a"]}
|
|
32
|
+
SEEN = []
|
|
33
|
+
BUSY = []
|
|
34
|
+
MODEL = "meta-llama/Llama-3.3-70B-Instruct"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def api(path, query, headers):
|
|
38
|
+
SEEN.append((path, query, headers.get("User-Agent"), headers.get("Accept-Encoding")))
|
|
39
|
+
if path == "/v1/plans" and query.get("query") == "busy" and not BUSY:
|
|
40
|
+
BUSY.append(1)
|
|
41
|
+
return 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
42
|
+
if path == "/v1/apis":
|
|
43
|
+
return 200, [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3, "extra": 1},
|
|
44
|
+
{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}], {}
|
|
45
|
+
if path == "/v1/apis/email-finder/best":
|
|
46
|
+
return 200, {"api": "Employee email", "slug": "email-finder", "total": 1, "plans": [PLAN]}, {}
|
|
47
|
+
if path.startswith("/v1/apis/"):
|
|
48
|
+
return 404, {"error": "no API has the slug nope", "slugs": ["email-finder", "linkedin-profile"]}, {}
|
|
49
|
+
if path == "/v1/plans" and query.get("query") == "down":
|
|
50
|
+
return 503, {"error": "down for a minute"}, {}
|
|
51
|
+
if path == "/v1/plans":
|
|
52
|
+
return 200, {"total": 1, "offset": 0, "plans": [PLAN]}, {}
|
|
53
|
+
if path == "/v1/providers/bright-data":
|
|
54
|
+
return 200, {"provider": "Bright Data", "slug": "bright-data", "website": "https://brightdata.com",
|
|
55
|
+
"apis": [{"api": "Employee email", "slug": "email-finder", "rank": 7, "sheetPage": "s",
|
|
56
|
+
"plans": [dict(PLAN, rank=9, plan="B"), dict(PLAN, rank=7, plan="A")]}]}, {}
|
|
57
|
+
return 404, {"error": "no provider has this slug"}, {}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@pytest.fixture(scope="module", autouse=True)
|
|
61
|
+
def server():
|
|
62
|
+
made = stand_in.start(api)
|
|
63
|
+
before = _api.BASE_URL
|
|
64
|
+
_api.BASE_URL = f"http://127.0.0.1:{made.server_address[1]}/v1"
|
|
65
|
+
yield f"http://127.0.0.1:{made.server_address[1]}"
|
|
66
|
+
_api.BASE_URL = before
|
|
67
|
+
made.shutdown()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@pytest.fixture
|
|
71
|
+
def client(server):
|
|
72
|
+
return InferenceClient(base_url=server, api_key="test")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def calls_made(name, arguments):
|
|
76
|
+
SEEN.clear()
|
|
77
|
+
return json.loads(run(name, arguments)), list(SEEN)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def field(item, key):
|
|
81
|
+
"""A field of a dict or of huggingface_hub's types, by attribute: 0.24 warns on a dict's read of its types."""
|
|
82
|
+
return getattr(item, key) if hasattr(item, key) else item[key]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def add_two_numbers(a, b):
|
|
86
|
+
return int(a) + int(b)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
ADD = {"type": "function", "function": {"name": "add_two_numbers", "description": "Adds two numbers.", "parameters": {
|
|
90
|
+
"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, "required": ["a", "b"]}}}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_definitions():
|
|
94
|
+
tools = datacircle_tools()
|
|
95
|
+
assert [tool["function"]["name"] for tool in tools] == TOOL_NAMES == [
|
|
96
|
+
"datacircle_list_apis", "datacircle_best_plans", "datacircle_search_plans", "datacircle_provider"]
|
|
97
|
+
for tool in tools:
|
|
98
|
+
assert tool["type"] == "function" and "https://datacircle.dev" in tool["function"]["description"]
|
|
99
|
+
assert tool["function"]["parameters"]["type"] == "object"
|
|
100
|
+
search = tools[2]["function"]["parameters"]["properties"]
|
|
101
|
+
assert search["sort"]["enum"] == ["score", "provider", "price"] and search["limit"]["maximum"] == 50
|
|
102
|
+
assert tools[1]["function"]["parameters"]["required"] == ["slug"]
|
|
103
|
+
assert [tool["function"]["name"] for tool in datacircle_tools(["datacircle_provider"])] == ["datacircle_provider"]
|
|
104
|
+
tools[0]["function"]["description"] = "changed"
|
|
105
|
+
assert datacircle_tools()[0]["function"]["description"] != "changed"
|
|
106
|
+
with pytest.raises(ValueError):
|
|
107
|
+
datacircle_tools(["nope"])
|
|
108
|
+
with pytest.raises(TypeError):
|
|
109
|
+
datacircle_tools("datacircle_provider")
|
|
110
|
+
from huggingface_hub import ChatCompletionInputTool
|
|
111
|
+
for tool in tools:
|
|
112
|
+
assert ChatCompletionInputTool.parse_obj_as_instance(tool).function.name == tool["function"]["name"]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_each_tool_calls_the_api_gzipped():
|
|
116
|
+
answer, seen = calls_made("datacircle_list_apis", {"query": "profile", "limit": 1})
|
|
117
|
+
assert answer == {"total": 1, "apis": [{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]}
|
|
118
|
+
assert seen == [("/v1/apis", {}, "huggingface-hub-datacircle/0.1.0", "gzip")]
|
|
119
|
+
answer, seen = calls_made("datacircle_best_plans", '{"slug": "Email Finder", "limit": 3}')
|
|
120
|
+
assert seen[0][:2] == ("/v1/apis/email-finder/best", {"limit": "3"})
|
|
121
|
+
assert answer["plans"] == [{key: PLAN[key] for key in ("api", "rank", "provider", "plan", "score", "perThousand", "page")}]
|
|
122
|
+
answer, seen = calls_made("datacircle_search_plans", {"api": "email-finder", "query": "hunter", "sort": "price",
|
|
123
|
+
"limit": "2", "offset": 1, "unknown": 1})
|
|
124
|
+
assert seen[0][:2] == ("/v1/plans", {"api": "email-finder", "query": "hunter", "sort": "price", "limit": "2", "offset": "1"})
|
|
125
|
+
answer, seen = calls_made("datacircle_provider", {"slug": "Bright Data"})
|
|
126
|
+
assert seen[0][0] == "/v1/providers/bright-data"
|
|
127
|
+
assert answer["apis"] == [{"api": "Employee email", "slug": "email-finder", "rank": 7, "plans": 2,
|
|
128
|
+
"best": {"plan": "A", "score": 80.1, "perThousand": 4.9, "page": "https://datacircle.dev/x"}}]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def test_refusals_in_the_apis_words():
|
|
132
|
+
answer, _ = calls_made("datacircle_best_plans", {"slug": "nope"})
|
|
133
|
+
assert "404" in answer["error"] and "email-finder, linkedin-profile" in answer["error"]
|
|
134
|
+
answer, _ = calls_made("datacircle_search_plans", {"query": "down"})
|
|
135
|
+
assert "503" in answer["error"] and "down for a minute" in answer["error"]
|
|
136
|
+
answer, seen = calls_made("datacircle_best_plans", {"slug": "email-finder", "limit": 51})
|
|
137
|
+
assert answer == {"error": "limit must be from 1 to 50, not 51"} and seen == []
|
|
138
|
+
answer, seen = calls_made("datacircle_search_plans", '{"sort": "cheapest"}')
|
|
139
|
+
assert "sort must be score, provider or price" in answer["error"] and seen == []
|
|
140
|
+
assert "no JSON object" in json.loads(run("datacircle_provider", "{oops"))["error"]
|
|
141
|
+
assert "Give a provider's slug" in json.loads(run("datacircle_provider", None))["error"]
|
|
142
|
+
with pytest.raises(ValueError):
|
|
143
|
+
run("nope", {})
|
|
144
|
+
started = time.monotonic()
|
|
145
|
+
answer, seen = calls_made("datacircle_search_plans", {"query": "busy"})
|
|
146
|
+
assert answer["total"] == 1 and len(seen) == 2 and time.monotonic() - started >= 1
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def test_call_on_huggingface_hubs_tool_calls():
|
|
150
|
+
from huggingface_hub import ChatCompletionOutputMessage
|
|
151
|
+
message = ChatCompletionOutputMessage.parse_obj_as_instance({"role": "assistant", "content": None, "tool_calls": [
|
|
152
|
+
{"id": "call_1", "type": "function", "function": {"name": "datacircle_best_plans", "arguments": '{"slug": "email-finder"}'}},
|
|
153
|
+
{"id": "call_2", "type": "function", "function": {"name": "add_two_numbers", "arguments": '{"a": 1, "b": 2}'}},
|
|
154
|
+
# huggingface_hub before 0.25 and some servers give the arguments as an object
|
|
155
|
+
{"id": "call_3", "type": "function", "function": {"name": "datacircle_provider", "arguments": {"slug": "bright-data"}}}]})
|
|
156
|
+
first = call(message.tool_calls[0])
|
|
157
|
+
assert first["role"] == "tool" and first["tool_call_id"] == "call_1" and first["name"] == "datacircle_best_plans"
|
|
158
|
+
assert json.loads(first["content"])["plans"][0]["provider"] == "Hunter"
|
|
159
|
+
assert call(message.tool_calls[1]) is None
|
|
160
|
+
messages = call_all(message)
|
|
161
|
+
assert [m["tool_call_id"] for m in messages] == ["call_1", "call_3"]
|
|
162
|
+
assert json.loads(messages[1]["content"])["slug"] == "bright-data"
|
|
163
|
+
assert call_all(message.tool_calls[2:])[0]["name"] == "datacircle_provider" and call_all(None) == []
|
|
164
|
+
assert asyncio.run(acall(message.tool_calls[1])) is None
|
|
165
|
+
assert [m["tool_call_id"] for m in asyncio.run(acall_all(message))] == ["call_1", "call_3"]
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def stream_turn(chunks):
|
|
169
|
+
content, calls = "", []
|
|
170
|
+
for chunk in chunks:
|
|
171
|
+
delta = chunk.choices[0].delta
|
|
172
|
+
content += delta.content or ""
|
|
173
|
+
collect_tool_calls(calls, delta.tool_calls)
|
|
174
|
+
return content, calls
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def chat_loop(client, question, tools, stream=False, alias=False):
|
|
178
|
+
"""The README's loop: ask, run each call (ours with call(), the app's own itself), ask again, till an answer."""
|
|
179
|
+
messages = [{"role": "user", "content": question}]
|
|
180
|
+
ask = client.chat.completions.create if alias else client.chat_completion
|
|
181
|
+
for _ in range(4):
|
|
182
|
+
if stream:
|
|
183
|
+
content, calls = stream_turn(ask(model=MODEL, messages=messages, tools=tools, stream=True))
|
|
184
|
+
message = {"role": "assistant", "content": content, "tool_calls": calls}
|
|
185
|
+
else:
|
|
186
|
+
message = ask(model=MODEL, messages=messages, tools=tools).choices[0].message
|
|
187
|
+
content, calls = message.content, message.tool_calls or []
|
|
188
|
+
if not calls:
|
|
189
|
+
return content
|
|
190
|
+
messages.append(message)
|
|
191
|
+
for tool_call in calls:
|
|
192
|
+
result = call(tool_call)
|
|
193
|
+
if result is None:
|
|
194
|
+
function = field(tool_call, "function")
|
|
195
|
+
result = {"role": "tool", "tool_call_id": field(tool_call, "id"), "name": field(function, "name"),
|
|
196
|
+
"content": str(add_two_numbers(**json.loads(field(function, "arguments"))))}
|
|
197
|
+
messages.append(result)
|
|
198
|
+
raise AssertionError("no answer after 4 turns")
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
QUESTION = ('CALL datacircle_best_plans {"slug": "email-finder", "limit": 1}\nCALL add_two_numbers {"a": 1, "b": 2}\n'
|
|
202
|
+
'CALL datacircle_list_apis {"query": "profile"}')
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
@pytest.mark.parametrize("stream,alias", [(False, False), (True, False), (False, True), (True, True)])
|
|
206
|
+
def test_chat_beside_an_apps_own_tool(client, stream, alias):
|
|
207
|
+
stand_in.REQUESTS.clear()
|
|
208
|
+
answer = chat_loop(client, QUESTION, [*datacircle_tools(), ADD], stream, alias)
|
|
209
|
+
assert answer.startswith("DONE ") and '"Hunter"' in answer and "| 3 |" in answer and "linkedin-profile" in answer
|
|
210
|
+
sent = stand_in.REQUESTS
|
|
211
|
+
assert [r["wrong"] for r in sent] == [None, None] and all(bool(r["body"].get("stream")) == stream for r in sent)
|
|
212
|
+
assert all(r["path"] == "/v1/chat/completions" and r["authorization"] == "Bearer test" for r in sent)
|
|
213
|
+
assert [tool["function"]["name"] for tool in sent[0]["body"]["tools"]] == TOOL_NAMES + ["add_two_numbers"]
|
|
214
|
+
assert sent[0]["body"]["tools"][2]["function"]["parameters"] == datacircle_tools()[2]["function"]["parameters"]
|
|
215
|
+
tool_messages = [m for m in sent[1]["body"]["messages"] if m["role"] == "tool"]
|
|
216
|
+
assert [m["name"] for m in tool_messages] == ["datacircle_best_plans", "add_two_numbers", "datacircle_list_apis"]
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def test_a_refusal_goes_back_to_the_model(client):
|
|
220
|
+
stand_in.REQUESTS.clear()
|
|
221
|
+
answer = chat_loop(client, 'CALL datacircle_best_plans {"slug": "nope"}', datacircle_tools())
|
|
222
|
+
assert "no API has the slug nope" in answer and "email-finder, linkedin-profile" in answer
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@pytest.mark.parametrize("stream", [False, True])
|
|
226
|
+
def test_async_client_runs_the_calls_at_once(server, stream):
|
|
227
|
+
stand_in.REQUESTS.clear()
|
|
228
|
+
client = AsyncInferenceClient(base_url=server, api_key="test")
|
|
229
|
+
|
|
230
|
+
async def turn(messages):
|
|
231
|
+
if not stream:
|
|
232
|
+
return (await client.chat_completion(messages, model=MODEL, tools=datacircle_tools())).choices[0].message
|
|
233
|
+
content, calls = "", []
|
|
234
|
+
async for chunk in await client.chat_completion(messages, model=MODEL, tools=datacircle_tools(), stream=True):
|
|
235
|
+
content += chunk.choices[0].delta.content or ""
|
|
236
|
+
collect_tool_calls(calls, chunk.choices[0].delta.tool_calls)
|
|
237
|
+
return {"role": "assistant", "content": content, "tool_calls": calls}
|
|
238
|
+
|
|
239
|
+
async def main():
|
|
240
|
+
messages = [{"role": "user", "content": 'CALL datacircle_best_plans {"slug": "email-finder"}\n'
|
|
241
|
+
'CALL datacircle_provider {"slug": "Bright Data"}'}]
|
|
242
|
+
message = await turn(messages)
|
|
243
|
+
messages.append(message)
|
|
244
|
+
messages.extend(await acall_all(message))
|
|
245
|
+
answer = await turn(messages)
|
|
246
|
+
if hasattr(client, "close"):
|
|
247
|
+
await client.close()
|
|
248
|
+
return field(answer, "content")
|
|
249
|
+
answer = asyncio.run(main())
|
|
250
|
+
assert answer.startswith("DONE ") and "Hunter" in answer and "bright-data" in answer
|
|
251
|
+
assert [r["wrong"] for r in stand_in.REQUESTS] == [None, None]
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def test_collect_tool_calls_from_pieces():
|
|
255
|
+
calls = []
|
|
256
|
+
collect_tool_calls(calls, [{"index": 0, "id": "call_1", "function": {"name": "datacircle_provider", "arguments": '{"sl'}}])
|
|
257
|
+
collect_tool_calls(calls, [{"index": 0, "function": {"arguments": 'ug": "bright-data"}'}},
|
|
258
|
+
{"index": 1, "id": "call_2", "function": {"name": "add_two_numbers", "arguments": {"a": 1}}}])
|
|
259
|
+
collect_tool_calls(calls, None)
|
|
260
|
+
collect_tool_calls(calls, {"index": 1, "id": None, "function": {"name": None, "arguments": ""}}) # one piece, as 0.24 gives
|
|
261
|
+
assert json.loads(json.dumps(calls)) == calls == [
|
|
262
|
+
{"id": "call_1", "type": "function", "function": {"name": "datacircle_provider", "arguments": '{"slug": "bright-data"}'}},
|
|
263
|
+
{"id": "call_2", "type": "function", "function": {"name": "add_two_numbers", "arguments": '{"a": 1}'}}]
|
|
264
|
+
assert [json.loads(m["content"])["slug"] for m in call_all(calls)] == ["bright-data"]
|
|
265
|
+
whole = []
|
|
266
|
+
collect_tool_calls(whole, [{"index": 0, "id": "call_a", "function": {"name": "datacircle_provider", "arguments": "{}"}}])
|
|
267
|
+
collect_tool_calls(whole, [{"index": 0, "id": "call_b", "function": {"name": "datacircle_list_apis", "arguments": "{}"}}])
|
|
268
|
+
assert [made["id"] for made in whole] == ["call_a", "call_b"]
|