aisuite-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.
- aisuite_datacircle-0.1.0/.gitignore +4 -0
- aisuite_datacircle-0.1.0/LICENSE +9 -0
- aisuite_datacircle-0.1.0/PKG-INFO +141 -0
- aisuite_datacircle-0.1.0/README.md +125 -0
- aisuite_datacircle-0.1.0/pyproject.toml +32 -0
- aisuite_datacircle-0.1.0/src/aisuite_datacircle/__init__.py +17 -0
- aisuite_datacircle-0.1.0/src/aisuite_datacircle/_api.py +101 -0
- aisuite_datacircle-0.1.0/src/aisuite_datacircle/py.typed +0 -0
- aisuite_datacircle-0.1.0/src/aisuite_datacircle/tools.py +180 -0
- aisuite_datacircle-0.1.0/tests/conftest.py +175 -0
- aisuite_datacircle-0.1.0/tests/test_aisuite.py +121 -0
- aisuite_datacircle-0.1.0/tests/test_live.py +28 -0
- aisuite_datacircle-0.1.0/tests/test_tools.py +72 -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,141 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: aisuite-datacircle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: aisuite 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/aisuite-datacircle
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agents,aisuite,api,api-pricing,b2b-data,datacircle,function-calling,gtm,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.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# aisuite-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 [aisuite](https://github.com/andrewyng/aisuite) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. Each tool is a plain Python function with type hints and a docstring. aisuite reads each tool's schema from the type hints and the docstring. aisuite runs each tool call from the model, on any aisuite provider. 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 aisuite-datacircle
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
aisuite-datacircle works with aisuite 0.1.13 and later, on Python 3.10 and later. The package does not import `aisuite`.
|
|
39
|
+
|
|
40
|
+
## Use the tools with max_turns
|
|
41
|
+
|
|
42
|
+
Pass the tools to `client.chat.completions.create()` with `max_turns`. aisuite runs each tool call and sends each tool result back to the model:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import aisuite as ai
|
|
46
|
+
from aisuite_datacircle import datacircle_tools
|
|
47
|
+
|
|
48
|
+
client = ai.Client()
|
|
49
|
+
response = client.chat.completions.create(
|
|
50
|
+
model="anthropic:claude-haiku-5-5",
|
|
51
|
+
messages=[{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}],
|
|
52
|
+
tools=datacircle_tools(),
|
|
53
|
+
max_turns=5,
|
|
54
|
+
)
|
|
55
|
+
print(response.choices[0].message.content)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
With aisuite 0.2.0 and later, `await client.chat.completions.acreate(...)` takes the same arguments as `client.chat.completions.create()`. aisuite runs each tool in a thread. Your event loop keeps running.
|
|
59
|
+
|
|
60
|
+
## Use the tools in an agent
|
|
61
|
+
|
|
62
|
+
With aisuite 0.2.0 and later, give the tools to an `Agent`:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from aisuite.agents import Agent, Runner
|
|
66
|
+
from aisuite_datacircle import datacircle_tools
|
|
67
|
+
|
|
68
|
+
agent = Agent(
|
|
69
|
+
name="gtm",
|
|
70
|
+
model="anthropic:claude-haiku-5-5",
|
|
71
|
+
instructions="Answer from the tools.",
|
|
72
|
+
tools=datacircle_tools(),
|
|
73
|
+
)
|
|
74
|
+
result = Runner.run_sync(agent, "Who are the 3 best providers for the email-finder API?")
|
|
75
|
+
print(result.final_output)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
To limit the agent, name the allowed tools in a tool policy. This call lets the agent run only `datacircle_best_plans`: `Runner.run_sync(agent, question, tool_policy=AllowToolsPolicy(["datacircle_best_plans"]))`
|
|
79
|
+
|
|
80
|
+
## Use the Datacircle tools beside your own tools
|
|
81
|
+
|
|
82
|
+
You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`.
|
|
83
|
+
|
|
84
|
+
To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
85
|
+
|
|
86
|
+
## Use the tools in your own loop
|
|
87
|
+
|
|
88
|
+
With aisuite 0.2.0 and later, you can leave out `max_turns`. Then run the tool calls yourself with aisuite's `Tools`:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
import aisuite as ai
|
|
92
|
+
from aisuite.utils.tools import Tools
|
|
93
|
+
from aisuite_datacircle import datacircle_tools
|
|
94
|
+
|
|
95
|
+
client, tools = ai.Client(), datacircle_tools()
|
|
96
|
+
messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
97
|
+
message = client.chat.completions.create(model="anthropic:claude-haiku-5-5", messages=messages, tools=tools).choices[0].message
|
|
98
|
+
|
|
99
|
+
while message.tool_calls:
|
|
100
|
+
_, tool_messages = Tools(tools).execute_tool(message.tool_calls)
|
|
101
|
+
messages += [message, *tool_messages]
|
|
102
|
+
message = client.chat.completions.create(model="anthropic:claude-haiku-5-5", messages=messages, tools=tools).choices[0].message
|
|
103
|
+
|
|
104
|
+
print(message.content)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Pass the list from `datacircle_tools()` as `tools`. aisuite turns the functions into each provider's format. On aisuite 0.2.0, a schema dict in `tools` with no `max_turns` needs one more install: `pip install 'aisuite[mcp]'`.
|
|
108
|
+
|
|
109
|
+
With `stream=True`, put the `delta.tool_calls` parts together into tool calls. Then give the tool calls to `Tools(tools).execute_tool()`.
|
|
110
|
+
|
|
111
|
+
## Call a tool yourself
|
|
112
|
+
|
|
113
|
+
You can call each tool without a model. You get the tool's answer as a dict:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from aisuite_datacircle import datacircle_best_plans, run
|
|
117
|
+
|
|
118
|
+
print(datacircle_best_plans("email-finder", limit=3)["plans"])
|
|
119
|
+
print(run("datacircle_provider", {"slug": "Bright Data"}))
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## What the model reads
|
|
123
|
+
|
|
124
|
+
Each tool returns a dict. aisuite gives the model the dict as JSON text. Each plan comes with a rank, provider, plan, score, price per 1,000 (`perThousand`, in dollars) and a page on datacircle.dev. That page lists every field.
|
|
125
|
+
|
|
126
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
127
|
+
|
|
128
|
+
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 tool never raises an error. aisuite's loop keeps running, and the model can call the tool again.
|
|
129
|
+
|
|
130
|
+
## Network
|
|
131
|
+
|
|
132
|
+
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.
|
|
133
|
+
|
|
134
|
+
## Links
|
|
135
|
+
|
|
136
|
+
- Datacircle: https://datacircle.dev
|
|
137
|
+
- The API: https://datacircle.dev/api
|
|
138
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
139
|
+
- Every field of a plan: https://datacircle.dev/fields
|
|
140
|
+
|
|
141
|
+
MIT license.
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# aisuite-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 [aisuite](https://github.com/andrewyng/aisuite) four tools that call Datacircle's open API, https://api.datacircle.dev/v1. Each tool is a plain Python function with type hints and a docstring. aisuite reads each tool's schema from the type hints and the docstring. aisuite runs each tool call from the model, on any aisuite provider. 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 aisuite-datacircle
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
aisuite-datacircle works with aisuite 0.1.13 and later, on Python 3.10 and later. The package does not import `aisuite`.
|
|
23
|
+
|
|
24
|
+
## Use the tools with max_turns
|
|
25
|
+
|
|
26
|
+
Pass the tools to `client.chat.completions.create()` with `max_turns`. aisuite runs each tool call and sends each tool result back to the model:
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
import aisuite as ai
|
|
30
|
+
from aisuite_datacircle import datacircle_tools
|
|
31
|
+
|
|
32
|
+
client = ai.Client()
|
|
33
|
+
response = client.chat.completions.create(
|
|
34
|
+
model="anthropic:claude-haiku-5-5",
|
|
35
|
+
messages=[{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}],
|
|
36
|
+
tools=datacircle_tools(),
|
|
37
|
+
max_turns=5,
|
|
38
|
+
)
|
|
39
|
+
print(response.choices[0].message.content)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
With aisuite 0.2.0 and later, `await client.chat.completions.acreate(...)` takes the same arguments as `client.chat.completions.create()`. aisuite runs each tool in a thread. Your event loop keeps running.
|
|
43
|
+
|
|
44
|
+
## Use the tools in an agent
|
|
45
|
+
|
|
46
|
+
With aisuite 0.2.0 and later, give the tools to an `Agent`:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from aisuite.agents import Agent, Runner
|
|
50
|
+
from aisuite_datacircle import datacircle_tools
|
|
51
|
+
|
|
52
|
+
agent = Agent(
|
|
53
|
+
name="gtm",
|
|
54
|
+
model="anthropic:claude-haiku-5-5",
|
|
55
|
+
instructions="Answer from the tools.",
|
|
56
|
+
tools=datacircle_tools(),
|
|
57
|
+
)
|
|
58
|
+
result = Runner.run_sync(agent, "Who are the 3 best providers for the email-finder API?")
|
|
59
|
+
print(result.final_output)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
To limit the agent, name the allowed tools in a tool policy. This call lets the agent run only `datacircle_best_plans`: `Runner.run_sync(agent, question, tool_policy=AllowToolsPolicy(["datacircle_best_plans"]))`
|
|
63
|
+
|
|
64
|
+
## Use the Datacircle tools beside your own tools
|
|
65
|
+
|
|
66
|
+
You can put the Datacircle tools in the same list as yours: `tools=[*datacircle_tools(), my_tool]`.
|
|
67
|
+
|
|
68
|
+
To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
69
|
+
|
|
70
|
+
## Use the tools in your own loop
|
|
71
|
+
|
|
72
|
+
With aisuite 0.2.0 and later, you can leave out `max_turns`. Then run the tool calls yourself with aisuite's `Tools`:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
import aisuite as ai
|
|
76
|
+
from aisuite.utils.tools import Tools
|
|
77
|
+
from aisuite_datacircle import datacircle_tools
|
|
78
|
+
|
|
79
|
+
client, tools = ai.Client(), datacircle_tools()
|
|
80
|
+
messages = [{"role": "user", "content": "Who are the 3 best providers for the email-finder API?"}]
|
|
81
|
+
message = client.chat.completions.create(model="anthropic:claude-haiku-5-5", messages=messages, tools=tools).choices[0].message
|
|
82
|
+
|
|
83
|
+
while message.tool_calls:
|
|
84
|
+
_, tool_messages = Tools(tools).execute_tool(message.tool_calls)
|
|
85
|
+
messages += [message, *tool_messages]
|
|
86
|
+
message = client.chat.completions.create(model="anthropic:claude-haiku-5-5", messages=messages, tools=tools).choices[0].message
|
|
87
|
+
|
|
88
|
+
print(message.content)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Pass the list from `datacircle_tools()` as `tools`. aisuite turns the functions into each provider's format. On aisuite 0.2.0, a schema dict in `tools` with no `max_turns` needs one more install: `pip install 'aisuite[mcp]'`.
|
|
92
|
+
|
|
93
|
+
With `stream=True`, put the `delta.tool_calls` parts together into tool calls. Then give the tool calls to `Tools(tools).execute_tool()`.
|
|
94
|
+
|
|
95
|
+
## Call a tool yourself
|
|
96
|
+
|
|
97
|
+
You can call each tool without a model. You get the tool's answer as a dict:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from aisuite_datacircle import datacircle_best_plans, run
|
|
101
|
+
|
|
102
|
+
print(datacircle_best_plans("email-finder", limit=3)["plans"])
|
|
103
|
+
print(run("datacircle_provider", {"slug": "Bright Data"}))
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## What the model reads
|
|
107
|
+
|
|
108
|
+
Each tool returns a dict. aisuite gives the model the dict as JSON text. Each plan comes with a rank, provider, plan, score, price per 1,000 (`perThousand`, in dollars) and a page on datacircle.dev. That page lists every field.
|
|
109
|
+
|
|
110
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
111
|
+
|
|
112
|
+
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 tool never raises an error. aisuite's loop keeps running, and the model can call the tool again.
|
|
113
|
+
|
|
114
|
+
## Network
|
|
115
|
+
|
|
116
|
+
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.
|
|
117
|
+
|
|
118
|
+
## Links
|
|
119
|
+
|
|
120
|
+
- Datacircle: https://datacircle.dev
|
|
121
|
+
- The API: https://datacircle.dev/api
|
|
122
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
123
|
+
- Every field of a plan: https://datacircle.dev/fields
|
|
124
|
+
|
|
125
|
+
MIT license.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "aisuite-datacircle"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "aisuite tools for the Datacircle API: find the best GTM APIs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = ["aisuite", "tools", "function-calling", "tool-calling", "agents", "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/aisuite-datacircle"
|
|
24
|
+
|
|
25
|
+
[dependency-groups]
|
|
26
|
+
test = ["pytest>=8", "aisuite[openai,anthropic]>=0.1.13"]
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/aisuite_datacircle"]
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.sdist]
|
|
32
|
+
include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Tools for aisuite on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
|
|
2
|
+
|
|
3
|
+
from aisuite_datacircle._api import BASE_URL, DatacircleError
|
|
4
|
+
from aisuite_datacircle.tools import (
|
|
5
|
+
FUNCTIONS,
|
|
6
|
+
TOOL_NAMES,
|
|
7
|
+
datacircle_best_plans,
|
|
8
|
+
datacircle_list_apis,
|
|
9
|
+
datacircle_provider,
|
|
10
|
+
datacircle_search_plans,
|
|
11
|
+
datacircle_tools,
|
|
12
|
+
run,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__version__ = "0.1.0"
|
|
16
|
+
__all__ = ["BASE_URL", "DatacircleError", "FUNCTIONS", "TOOL_NAMES", "datacircle_best_plans", "datacircle_list_apis",
|
|
17
|
+
"datacircle_provider", "datacircle_search_plans", "datacircle_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 = "aisuite-datacircle/0.1.0"
|
|
16
|
+
|
|
17
|
+
# A plan holds about 90 keys (its terms of use, its aggregators...): the tools keep the ones that choose a plan, the rest is on its page.
|
|
18
|
+
PLAN_KEYS = ["api", "rank", "provider", "plan", "score", "perThousand", "notFoundPerThousand", "billing", "pay",
|
|
19
|
+
"currency", "units", "unit", "strengths", "latencyMs", "page", "pricingPage", "docs"]
|
|
20
|
+
API_KEYS = ["api", "slug", "plans", "providers", "best", "bestPage", "sheetPage"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class DatacircleError(Exception):
|
|
24
|
+
"""The API's refusal in its own words, why it could not be reached, or an argument it can't take: a tool gives the
|
|
25
|
+
model its words as its JSON text, {"error": ...}. status is the API's HTTP status, None when it gave none;
|
|
26
|
+
retryable, whether the same call may be answered later (the API out of reach, busy or failing)."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, message: str, status: Optional[int] = None, retryable: bool = False):
|
|
29
|
+
super().__init__(message)
|
|
30
|
+
self.status = status
|
|
31
|
+
self.retryable = retryable
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def brief(item: Dict[str, Any], keys: List[str] = PLAN_KEYS) -> Dict[str, Any]:
|
|
35
|
+
return {key: item[key] for key in keys if item.get(key) is not None}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def slug(value: Any) -> str:
|
|
39
|
+
"""The API's rule for a slug: the name in lowercase letters and digits, the rest a hyphen."""
|
|
40
|
+
plain = unicodedata.normalize("NFKD", str(value or "").strip().lower())
|
|
41
|
+
plain = "".join(char for char in plain if not unicodedata.combining(char))
|
|
42
|
+
return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def whole(name: str, value: Any, low: int, high: Optional[int] = None) -> Optional[int]:
|
|
46
|
+
"""A whole number from low to high, or None when left out: a plain call may send one as text."""
|
|
47
|
+
if value is None or value == "":
|
|
48
|
+
return None
|
|
49
|
+
try:
|
|
50
|
+
number = float(value)
|
|
51
|
+
except (TypeError, ValueError):
|
|
52
|
+
number = float("nan")
|
|
53
|
+
if isinstance(value, bool) or not math.isfinite(number) or number != int(number):
|
|
54
|
+
raise DatacircleError(f"{name} must be a whole number, not {value!r}")
|
|
55
|
+
if number < low or (high is not None and number > high):
|
|
56
|
+
raise DatacircleError(f"{name} must be from {low} to {high}, not {int(number)}" if high is not None
|
|
57
|
+
else f"{name} must be {low} or more, not {int(number)}")
|
|
58
|
+
return int(number)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _words(body: bytes) -> str:
|
|
62
|
+
"""A refusal's words: the API's error, with every slug when the slug was unknown."""
|
|
63
|
+
text = body.decode("utf-8", "replace")
|
|
64
|
+
try:
|
|
65
|
+
parsed = json.loads(text)
|
|
66
|
+
if parsed.get("slugs"):
|
|
67
|
+
return f"{parsed['error']}; the slugs: {', '.join(parsed['slugs'])}"
|
|
68
|
+
return str(parsed.get("error", text))
|
|
69
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
70
|
+
return text
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def get(path: str, params: Optional[Dict[str, Any]] = None) -> Any:
|
|
74
|
+
"""The API's JSON answer, or a DatacircleError with its words: waits once when it answers 429."""
|
|
75
|
+
query = urllib.parse.urlencode({key: value for key, value in (params or {}).items() if value not in (None, "")})
|
|
76
|
+
url = f"{BASE_URL.rstrip('/')}{path}" + (f"?{query}" if query else "")
|
|
77
|
+
request = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": USER_AGENT})
|
|
78
|
+
for attempt in range(2):
|
|
79
|
+
try:
|
|
80
|
+
with urllib.request.urlopen(request, timeout=TIMEOUT) as answer:
|
|
81
|
+
body = answer.read()
|
|
82
|
+
except urllib.error.HTTPError as error:
|
|
83
|
+
body = error.read()
|
|
84
|
+
if error.code == 429 and not attempt:
|
|
85
|
+
try:
|
|
86
|
+
wait = int(error.headers.get("Retry-After") or 30)
|
|
87
|
+
except ValueError:
|
|
88
|
+
wait = 30
|
|
89
|
+
time.sleep(min(max(wait, 1), 60))
|
|
90
|
+
continue
|
|
91
|
+
if error.code == 429:
|
|
92
|
+
raise DatacircleError("Datacircle's API answered 429 twice: wait a minute and call again", 429, True) from None
|
|
93
|
+
raise DatacircleError(f"Datacircle's API answered {error.code}: {_words(body)[:3000]}", error.code,
|
|
94
|
+
error.code >= 500) from None
|
|
95
|
+
except (urllib.error.URLError, OSError) as error:
|
|
96
|
+
raise DatacircleError(f"Datacircle's API could not be reached: {getattr(error, 'reason', error)}",
|
|
97
|
+
retryable=True) from None
|
|
98
|
+
try:
|
|
99
|
+
return json.loads(body)
|
|
100
|
+
except ValueError as error:
|
|
101
|
+
raise DatacircleError(f"Datacircle's API gave no JSON: {error}") from None
|
|
File without changes
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Tools for aisuite on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
|
|
2
|
+
|
|
3
|
+
Each tool is a plain typed function with a docstring. aisuite reads its schema from them (the types from the
|
|
4
|
+
signature, the description and each argument's from the Google-style docstring), checks the model's arguments with
|
|
5
|
+
pydantic and runs it: in chat.completions.create(tools=[...], max_turns=...), its async acreate, an Agent's Runner, or
|
|
6
|
+
an app's own loop through aisuite.utils.tools.Tools. A tool makes one HTTPS GET and returns the API's answer as a dict,
|
|
7
|
+
which aisuite gives the model as JSON text. A refusal (an unknown slug, an argument out of range, the API out of reach)
|
|
8
|
+
is the dict {"error": the API's words}, never an exception, which would end aisuite's loop: the model can call again
|
|
9
|
+
and the chat goes on.
|
|
10
|
+
|
|
11
|
+
No `from __future__ import annotations` here: aisuite builds each tool's pydantic model from its signature's types.
|
|
12
|
+
Each optional argument is Optional[...] = None, so a model's null for it passes pydantic; aisuite writes it as its type
|
|
13
|
+
from 0.1.13 (0.1.12 and before give it the type "typing.Optional[int]", which providers refuse).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import urllib.parse
|
|
18
|
+
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence
|
|
19
|
+
|
|
20
|
+
from aisuite_datacircle import _api
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _answer(function: Callable[..., Any], *args: Any) -> Dict[str, Any]:
|
|
24
|
+
"""What a tool gives the model: its answer, or {"error": ...} when the API or its checks refused."""
|
|
25
|
+
try:
|
|
26
|
+
return function(*args)
|
|
27
|
+
except _api.DatacircleError as error:
|
|
28
|
+
return {"error": str(error)}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _best(plans: Any) -> Optional[Dict[str, Any]]:
|
|
32
|
+
"""A provider's best plan on an API: its lowest rank, a plan with no score having none."""
|
|
33
|
+
ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
|
|
34
|
+
return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _list_apis(query: Any, limit: Any) -> Dict[str, Any]:
|
|
38
|
+
count = _api.whole("limit", limit, 1, 200) or 20
|
|
39
|
+
apis = _api.get("/apis")
|
|
40
|
+
words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
|
|
41
|
+
held = []
|
|
42
|
+
for index, api in enumerate(apis):
|
|
43
|
+
name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
|
|
44
|
+
matched = sum(word in name for word in words)
|
|
45
|
+
if matched or not words:
|
|
46
|
+
held.append((-matched, index, api))
|
|
47
|
+
found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
|
|
48
|
+
return {"total": len(found), "apis": found[:count]}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _best_plans(slug: Any, limit: Any) -> Dict[str, Any]:
|
|
52
|
+
made = _api.slug(slug)
|
|
53
|
+
if not made:
|
|
54
|
+
raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
|
|
55
|
+
answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
|
|
56
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _search_plans(api: Any, query: Any, sort: Any, limit: Any, offset: Any) -> Dict[str, Any]:
|
|
60
|
+
order = str(sort).strip().lower() if sort not in (None, "") else None
|
|
61
|
+
if order is not None and order not in ("score", "provider", "price"):
|
|
62
|
+
raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
|
|
63
|
+
params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
|
|
64
|
+
"offset": _api.whole("offset", offset, 0)}
|
|
65
|
+
answer = _api.get("/plans", params)
|
|
66
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _provider(slug: Any) -> Dict[str, Any]:
|
|
70
|
+
made = _api.slug(slug)
|
|
71
|
+
if not made:
|
|
72
|
+
raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
|
|
73
|
+
answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
|
|
74
|
+
apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
|
|
75
|
+
"best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
|
|
76
|
+
return {**answer, "apis": apis}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# The tools. aisuite's parser of a docstring (docstring_parser) takes its first line as the short description and the
|
|
80
|
+
# rest before "Args:" as the long one, and joins them with a blank line: so each description is one line, then what
|
|
81
|
+
# it gives after a blank line. sort is a str, not a Literal: a value pydantic refuses ends aisuite's loop with an
|
|
82
|
+
# exception, while the tool's own check gives the model its words.
|
|
83
|
+
|
|
84
|
+
def datacircle_list_apis(query: Optional[str] = None, limit: Optional[int] = None) -> Dict[str, Any]:
|
|
85
|
+
"""Lists the GTM APIs on Datacircle's sheet (https://datacircle.dev), with each API's slug, how many plans and providers it has and its best plan. Call it to find an API's slug when you don't know it.
|
|
86
|
+
|
|
87
|
+
Gives total, the APIs found, and apis, up to limit of them.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
query: Words of the API's name or slug, like 'email' or 'linkedin profile'. The APIs that hold the most of them come first, in the sheet's order when left out.
|
|
91
|
+
limit: How many APIs to give, 1 to 200. 20 when left out, of about 160.
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
The API's answer, or {"error": ...} in its words.
|
|
95
|
+
"""
|
|
96
|
+
return _answer(_list_apis, query, limit)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def datacircle_best_plans(slug: str, limit: Optional[int] = None) -> Dict[str, Any]:
|
|
100
|
+
"""Gives an API's plans best first by their score out of 100 on Datacircle's benchmark (https://datacircle.dev), each with its rank, provider, plan, $ per 1,000 calls and its page: the best providers of an API.
|
|
101
|
+
|
|
102
|
+
perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
slug: The API's slug, like 'email-finder' or 'linkedin-profile', as datacircle_list_apis gives it.
|
|
106
|
+
limit: How many plans to give, 1 to 50. 10 when left out.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
The API's answer, or {"error": ...} in its words.
|
|
110
|
+
"""
|
|
111
|
+
return _answer(_best_plans, slug, limit)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def datacircle_search_plans(api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
|
|
115
|
+
limit: Optional[int] = None, offset: Optional[int] = None) -> Dict[str, Any]:
|
|
116
|
+
"""Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan name, sorted by score, provider or price.
|
|
117
|
+
|
|
118
|
+
Gives total, offset and up to limit plans. perThousand is a plan's price of 1,000 items in dollars, pay the plan's whole price in its currency.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
api: Only this API's plans, by its name or slug, like 'email-finder'. A provider's name goes in query, never here. Every API when left out.
|
|
122
|
+
query: Words that must all appear in the provider's or plan's name, like 'bright data'.
|
|
123
|
+
sort: score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first).
|
|
124
|
+
limit: How many plans to give, 1 to 50. 10 when left out.
|
|
125
|
+
offset: How many found plans to skip first. 0 when left out.
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
The API's answer, or {"error": ...} in its words.
|
|
129
|
+
"""
|
|
130
|
+
return _answer(_search_plans, api, query, sort, limit, offset)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def datacircle_provider(slug: str) -> Dict[str, Any]:
|
|
134
|
+
"""Gives each API one provider sells and its rank on each on Datacircle's benchmark (https://datacircle.dev), with its best plan there.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
slug: The provider's slug, like 'bright-data', or its name, like 'Bright Data', which is made a slug.
|
|
138
|
+
|
|
139
|
+
Returns:
|
|
140
|
+
The API's answer, or {"error": ...} in its words.
|
|
141
|
+
"""
|
|
142
|
+
return _answer(_provider, slug)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
FUNCTIONS: Dict[str, Callable[..., Dict[str, Any]]] = {function.__name__: function for function in (
|
|
146
|
+
datacircle_list_apis, datacircle_best_plans, datacircle_search_plans, datacircle_provider)}
|
|
147
|
+
TOOL_NAMES = list(FUNCTIONS)
|
|
148
|
+
_ARGUMENTS = {"datacircle_list_apis": ("query", "limit"), "datacircle_best_plans": ("slug", "limit"),
|
|
149
|
+
"datacircle_search_plans": ("api", "query", "sort", "limit", "offset"),
|
|
150
|
+
"datacircle_provider": ("slug",)}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def datacircle_tools(tool_names: Optional[Sequence[str]] = None) -> List[Callable[..., Dict[str, Any]]]:
|
|
154
|
+
"""The tools, for client.chat.completions.create(model, messages, tools=datacircle_tools(), max_turns=5), an
|
|
155
|
+
Agent's tools, or beside one's own: tools=[*datacircle_tools(), my_tool]. tool_names keeps some of them only, in
|
|
156
|
+
their order here; all four when left out."""
|
|
157
|
+
if isinstance(tool_names, str):
|
|
158
|
+
raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
|
|
159
|
+
for name in tool_names or []:
|
|
160
|
+
if name not in FUNCTIONS:
|
|
161
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
162
|
+
return [FUNCTIONS[name] for name in (TOOL_NAMES if tool_names is None else tool_names)]
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def run(name: str, arguments: Any = None) -> Dict[str, Any]:
|
|
166
|
+
"""What a tool gives the model for these arguments: the API's answer, or {"error": its words}. arguments is a
|
|
167
|
+
mapping or its JSON text; the ones the tool doesn't take are left out."""
|
|
168
|
+
if name not in FUNCTIONS:
|
|
169
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
170
|
+
if isinstance(arguments, (str, bytes)):
|
|
171
|
+
try:
|
|
172
|
+
arguments = json.loads(arguments or "{}")
|
|
173
|
+
except ValueError:
|
|
174
|
+
return {"error": f"the arguments are no JSON object: {arguments[:200]!r}"}
|
|
175
|
+
given = arguments if isinstance(arguments, Mapping) else {}
|
|
176
|
+
return FUNCTIONS[name](**{key: given.get(key) for key in _ARGUMENTS[name]})
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
__all__: List[str] = ["FUNCTIONS", "TOOL_NAMES", "datacircle_best_plans", "datacircle_list_apis", "datacircle_provider",
|
|
180
|
+
"datacircle_search_plans", "datacircle_tools", "run"]
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Stand-ins on 127.0.0.1: Datacircle's API, and a model that speaks OpenAI's Chat Completions (whole and streamed,
|
|
2
|
+
which aisuite's openai and ollama providers call) and Anthropic's Messages. The model asks, in one turn, for each of
|
|
3
|
+
the four tools and the app's own add_two_numbers (or what a test sets in state.calls; on Anthropic's, one a turn), then,
|
|
4
|
+
given their results, answers with the text it read."""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import threading
|
|
9
|
+
import time
|
|
10
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
11
|
+
from urllib.parse import parse_qs, urlparse
|
|
12
|
+
|
|
13
|
+
import pytest
|
|
14
|
+
|
|
15
|
+
os.environ["NO_PROXY"] = os.environ["no_proxy"] = "127.0.0.1,localhost"
|
|
16
|
+
|
|
17
|
+
from aisuite_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
|
+
CALLS = [{"name": "datacircle_list_apis", "arguments": {"query": "email"}},
|
|
22
|
+
{"name": "datacircle_best_plans", "arguments": {"slug": "email-finder", "limit": 1}},
|
|
23
|
+
{"name": "datacircle_search_plans", "arguments": {"api": "email-finder", "sort": "price", "limit": 2}},
|
|
24
|
+
{"name": "datacircle_provider", "arguments": {"slug": "Bright Data"}},
|
|
25
|
+
{"name": "add_two_numbers", "arguments": {"a": 1, "b": 2}}]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def add_two_numbers(a: int, b: int) -> int:
|
|
29
|
+
"""Adds two numbers: the app's own tool, beside Datacircle's.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
a: The first number.
|
|
33
|
+
b: The second number.
|
|
34
|
+
"""
|
|
35
|
+
return a + b
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def results(body):
|
|
39
|
+
"""The tool results a model request carries, in both protocols' shapes."""
|
|
40
|
+
found = []
|
|
41
|
+
for message in body.get("messages") or []:
|
|
42
|
+
if message.get("role") == "tool":
|
|
43
|
+
found.append(message.get("content"))
|
|
44
|
+
content = message.get("content")
|
|
45
|
+
for block in content if isinstance(content, list) else []:
|
|
46
|
+
if isinstance(block, dict) and block.get("type") == "tool_result":
|
|
47
|
+
inner = block.get("content")
|
|
48
|
+
found.append(inner if isinstance(inner, str) else "".join(part.get("text", "") for part in inner or []))
|
|
49
|
+
return found
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class State:
|
|
53
|
+
def __init__(self):
|
|
54
|
+
self.seen, self.busy, self.bodies, self.calls = [], [], [], CALLS
|
|
55
|
+
|
|
56
|
+
def results(self):
|
|
57
|
+
"""The tool results the last model request carried, each read from its JSON text."""
|
|
58
|
+
return [json.loads(text) for text in results(self.bodies[-1][1])]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _send(handler, status, body, headers=None):
|
|
62
|
+
data = json.dumps(body).encode()
|
|
63
|
+
handler.send_response(status)
|
|
64
|
+
for key, value in {"Content-Type": "application/json", "Content-Length": str(len(data)), **(headers or {})}.items():
|
|
65
|
+
handler.send_header(key, value)
|
|
66
|
+
handler.end_headers()
|
|
67
|
+
handler.wfile.write(data)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _final_text(body):
|
|
71
|
+
return "read: " + " | ".join(str(text) for text in results(body))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _chat(handler, body, state):
|
|
75
|
+
"""OpenAI's /v1/chat/completions, whole or streamed."""
|
|
76
|
+
calls = [] if results(body) else state.calls
|
|
77
|
+
if body.get("stream"):
|
|
78
|
+
handler.send_response(200)
|
|
79
|
+
handler.send_header("Content-Type", "text/event-stream")
|
|
80
|
+
handler.end_headers()
|
|
81
|
+
|
|
82
|
+
def chunk(delta, finish=None):
|
|
83
|
+
data = {"id": "chatcmpl-1", "object": "chat.completion.chunk", "created": int(time.time()), "model": body["model"],
|
|
84
|
+
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
|
|
85
|
+
handler.wfile.write(f"data: {json.dumps(data)}\n\n".encode())
|
|
86
|
+
chunk({"role": "assistant", "content": None if calls else ""})
|
|
87
|
+
if calls:
|
|
88
|
+
for index, made in enumerate(calls):
|
|
89
|
+
text = json.dumps(made["arguments"])
|
|
90
|
+
chunk({"tool_calls": [{"index": index, "id": f"call_{index}", "type": "function",
|
|
91
|
+
"function": {"name": made["name"], "arguments": text[:7]}}]})
|
|
92
|
+
chunk({"tool_calls": [{"index": index, "function": {"arguments": text[7:]}}]})
|
|
93
|
+
chunk({}, "tool_calls")
|
|
94
|
+
else:
|
|
95
|
+
chunk({"content": _final_text(body)})
|
|
96
|
+
chunk({}, "stop")
|
|
97
|
+
handler.wfile.write(b"data: [DONE]\n\n")
|
|
98
|
+
return
|
|
99
|
+
message = {"role": "assistant", "content": None if calls else _final_text(body)}
|
|
100
|
+
if calls:
|
|
101
|
+
message["tool_calls"] = [{"id": f"call_{index}", "type": "function",
|
|
102
|
+
"function": {"name": made["name"], "arguments": json.dumps(made["arguments"])}}
|
|
103
|
+
for index, made in enumerate(calls)]
|
|
104
|
+
_send(handler, 200, {"id": "chatcmpl-1", "object": "chat.completion", "created": int(time.time()), "model": body["model"],
|
|
105
|
+
"choices": [{"index": 0, "message": message, "finish_reason": "tool_calls" if calls else "stop"}],
|
|
106
|
+
"usage": {"prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10}})
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _anthropic(handler, body, state):
|
|
110
|
+
"""Anthropic's /v1/messages, whole: one tool call a turn, as aisuite's anthropic provider keeps only a reply's first."""
|
|
111
|
+
answered = len(results(body))
|
|
112
|
+
calls = state.calls[answered:answered + 1]
|
|
113
|
+
content = ([{"type": "tool_use", "id": f"toolu_{index}", "name": made["name"], "input": made["arguments"]}
|
|
114
|
+
for index, made in enumerate(calls)] if calls else [{"type": "text", "text": _final_text(body)}])
|
|
115
|
+
_send(handler, 200, {"id": "msg_1", "type": "message", "role": "assistant", "model": body["model"], "content": content,
|
|
116
|
+
"stop_reason": "tool_use" if calls else "end_turn", "stop_sequence": None,
|
|
117
|
+
"usage": {"input_tokens": 5, "output_tokens": 5}})
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _handler(state):
|
|
121
|
+
class Handler(BaseHTTPRequestHandler):
|
|
122
|
+
def log_message(self, *args):
|
|
123
|
+
pass
|
|
124
|
+
|
|
125
|
+
def do_POST(self):
|
|
126
|
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
|
|
127
|
+
path = urlparse(self.path).path
|
|
128
|
+
state.bodies.append((path, body))
|
|
129
|
+
if path.endswith("/chat/completions"):
|
|
130
|
+
_chat(self, body, state)
|
|
131
|
+
elif path.endswith("/messages"):
|
|
132
|
+
_anthropic(self, body, state)
|
|
133
|
+
else:
|
|
134
|
+
_send(self, 404, {"error": f"no {path}"})
|
|
135
|
+
|
|
136
|
+
def do_GET(self):
|
|
137
|
+
url = urlparse(self.path)
|
|
138
|
+
query = {key: values[0] for key, values in parse_qs(url.query).items()}
|
|
139
|
+
state.seen.append((url.path, query, self.headers.get("User-Agent")))
|
|
140
|
+
headers = {}
|
|
141
|
+
if url.path == "/v1/plans" and query.get("query") == "busy" and not state.busy:
|
|
142
|
+
state.busy.append(1)
|
|
143
|
+
status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
144
|
+
elif url.path == "/v1/plans" and query.get("query") == "always-busy":
|
|
145
|
+
status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
146
|
+
elif url.path == "/v1/apis":
|
|
147
|
+
status, body = 200, [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3, "extra": 1},
|
|
148
|
+
{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]
|
|
149
|
+
elif url.path == "/v1/apis/email-finder/best":
|
|
150
|
+
status, body = 200, {"api": "Employee email", "slug": "email-finder", "total": 1, "plans": [PLAN]}
|
|
151
|
+
elif url.path.startswith("/v1/apis/"):
|
|
152
|
+
status, body = 404, {"error": "no API has the slug nope", "slugs": ["email-finder", "linkedin-profile"]}
|
|
153
|
+
elif url.path == "/v1/plans" and query.get("query") == "down":
|
|
154
|
+
status, body = 503, {"error": "down for a minute"}
|
|
155
|
+
elif url.path == "/v1/plans":
|
|
156
|
+
status, body = 200, {"total": 1, "offset": 0, "plans": [PLAN]}
|
|
157
|
+
elif url.path == "/v1/providers/bright-data":
|
|
158
|
+
status, body = 200, {"provider": "Bright Data", "slug": "bright-data",
|
|
159
|
+
"apis": [{"api": "Employee email", "slug": "email-finder", "rank": 7, "bestPage": "b",
|
|
160
|
+
"plans": [{**PLAN, "rank": 9}, {**PLAN, "rank": 7, "plan": "Pro"}]}]}
|
|
161
|
+
else:
|
|
162
|
+
status, body = 404, {"error": "no provider has the slug nope"}
|
|
163
|
+
_send(self, status, body, headers)
|
|
164
|
+
return Handler
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@pytest.fixture()
|
|
168
|
+
def stub(monkeypatch):
|
|
169
|
+
state = State()
|
|
170
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), _handler(state))
|
|
171
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
172
|
+
state.url = f"http://127.0.0.1:{server.server_address[1]}"
|
|
173
|
+
monkeypatch.setattr(_api, "BASE_URL", state.url + "/v1")
|
|
174
|
+
yield state
|
|
175
|
+
server.shutdown()
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""The tools through aisuite itself, offline: the stand-in model (conftest.py) calls the four tools and the app's own
|
|
2
|
+
add_two_numbers in one turn, aisuite runs them, and the model's next request carries their results. Each path aisuite
|
|
3
|
+
calls a tool by: create(max_turns=...) on its openai, anthropic and ollama providers, an app's own loop through
|
|
4
|
+
aisuite's Tools, a streamed turn, acreate, an Agent's Runner (sync and async), with a tool policy."""
|
|
5
|
+
|
|
6
|
+
import asyncio
|
|
7
|
+
from importlib.metadata import version
|
|
8
|
+
|
|
9
|
+
import aisuite as ai
|
|
10
|
+
import pytest
|
|
11
|
+
from aisuite.utils.tools import Tools
|
|
12
|
+
|
|
13
|
+
from aisuite_datacircle import TOOL_NAMES, datacircle_tools
|
|
14
|
+
from conftest import add_two_numbers
|
|
15
|
+
|
|
16
|
+
AISUITE = tuple(int(part) for part in version("aisuite").split(".")[:3])
|
|
17
|
+
since_0_2 = pytest.mark.skipif(AISUITE < (0, 2), reason="aisuite 0.2.0 or later")
|
|
18
|
+
# 0.1.14's anthropic provider reads usage.cache_read_input_tokens, which the anthropic<0.31 it pins lacks: every call fails
|
|
19
|
+
anthropic_works = pytest.mark.skipif((0, 1, 13) <= AISUITE < (0, 2), reason="aisuite 0.1.14 fails on every Anthropic call")
|
|
20
|
+
QUESTION = [{"role": "user", "content": "Who is best for email-finder?"}]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def client(stub):
|
|
24
|
+
return ai.Client(provider_configs={"openai": {"base_url": stub.url + "/v1", "api_key": "test"},
|
|
25
|
+
"anthropic": {"base_url": stub.url, "api_key": "test"},
|
|
26
|
+
"ollama": {"api_url": stub.url}})
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def check(stub, text):
|
|
30
|
+
"""The model's last request carried each tool's answer, and its reply is the text it read."""
|
|
31
|
+
got = stub.results()
|
|
32
|
+
assert got[0]["apis"][0]["slug"] == "email-finder"
|
|
33
|
+
assert got[1]["plans"][0]["provider"] == "Hunter" and "terms" not in got[1]["plans"][0]
|
|
34
|
+
assert got[2]["total"] == 1 and stub.seen[2][1] == {"api": "email-finder", "sort": "price", "limit": "2"}
|
|
35
|
+
assert got[3]["apis"][0]["best"]["plan"] == "Pro"
|
|
36
|
+
assert got[4] == 3
|
|
37
|
+
assert text.startswith("read: ") and "Hunter" in text
|
|
38
|
+
assert [path for path, _, _ in stub.seen] == ["/v1/apis", "/v1/apis/email-finder/best", "/v1/plans",
|
|
39
|
+
"/v1/providers/bright-data"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@pytest.mark.parametrize("model", ["openai:stand-in", pytest.param("anthropic:stand-in", marks=anthropic_works),
|
|
43
|
+
pytest.param("ollama:stand-in", marks=since_0_2)])
|
|
44
|
+
def test_max_turns(stub, model):
|
|
45
|
+
response = client(stub).chat.completions.create(model=model, messages=list(QUESTION), max_turns=6,
|
|
46
|
+
tools=[*datacircle_tools(), add_two_numbers],
|
|
47
|
+
**({"max_tokens": 500} if model.startswith("anthropic") else {}))
|
|
48
|
+
check(stub, response.choices[0].message.content)
|
|
49
|
+
tools = stub.bodies[0][1]["tools"]
|
|
50
|
+
names = [tool.get("name") or tool["function"]["name"] for tool in tools]
|
|
51
|
+
assert names == [*TOOL_NAMES, "add_two_numbers"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_refusal_goes_on(stub):
|
|
55
|
+
stub.calls = [{"name": "datacircle_best_plans", "arguments": {"slug": "nope"}}]
|
|
56
|
+
response = client(stub).chat.completions.create(model="openai:stand-in", messages=list(QUESTION), max_turns=3,
|
|
57
|
+
tools=datacircle_tools())
|
|
58
|
+
assert "the slugs: email-finder" in stub.results()[0]["error"]
|
|
59
|
+
assert "the slugs: email-finder" in response.choices[0].message.content
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@since_0_2 # 0.1.12 to 0.1.14 drop the tools of a call without max_turns (aisuite's #266)
|
|
63
|
+
def test_own_loop_through_tools(stub):
|
|
64
|
+
# the functions themselves: a schema dict without max_turns needs aisuite's mcp extra (its NameError)
|
|
65
|
+
own, messages, model = [*datacircle_tools(), add_two_numbers], list(QUESTION), client(stub)
|
|
66
|
+
message = model.chat.completions.create(model="openai:stand-in", messages=messages, tools=own).choices[0].message
|
|
67
|
+
_, tool_messages = Tools(own).execute_tool(message.tool_calls)
|
|
68
|
+
messages += [message, *tool_messages]
|
|
69
|
+
answer = model.chat.completions.create(model="openai:stand-in", messages=messages, tools=own)
|
|
70
|
+
check(stub, answer.choices[0].message.content)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@since_0_2
|
|
74
|
+
def test_streamed_turn(stub):
|
|
75
|
+
model, messages, own = client(stub), list(QUESTION), [*datacircle_tools(), add_two_numbers]
|
|
76
|
+
calls = {}
|
|
77
|
+
for chunk in model.chat.completions.create(model="openai:stand-in", messages=messages, tools=own, stream=True):
|
|
78
|
+
for delta in chunk.choices[0].delta.tool_calls or [] if chunk.choices else []:
|
|
79
|
+
made = calls.setdefault(delta.index, {"id": None, "type": "function", "function": {"name": "", "arguments": ""}})
|
|
80
|
+
made["id"] = delta.id or made["id"]
|
|
81
|
+
made["function"]["name"] += delta.function.name or ""
|
|
82
|
+
made["function"]["arguments"] += delta.function.arguments or ""
|
|
83
|
+
tool_calls = [calls[index] for index in sorted(calls)]
|
|
84
|
+
_, tool_messages = Tools(own).execute_tool(tool_calls)
|
|
85
|
+
messages += [{"role": "assistant", "content": None, "tool_calls": tool_calls}, *tool_messages]
|
|
86
|
+
text = "".join(chunk.choices[0].delta.content or "" for chunk in
|
|
87
|
+
model.chat.completions.create(model="openai:stand-in", messages=messages, tools=own, stream=True)
|
|
88
|
+
if chunk.choices)
|
|
89
|
+
check(stub, text)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@since_0_2
|
|
93
|
+
def test_acreate(stub):
|
|
94
|
+
response = asyncio.run(client(stub).chat.completions.acreate(
|
|
95
|
+
model="openai:stand-in", messages=list(QUESTION), tools=[*datacircle_tools(), add_two_numbers], max_turns=3))
|
|
96
|
+
check(stub, response.choices[0].message.content)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@since_0_2
|
|
100
|
+
@pytest.mark.parametrize("mode", ["sync", "async"])
|
|
101
|
+
def test_agent_runner(stub, mode):
|
|
102
|
+
from aisuite.agents import Agent, Runner
|
|
103
|
+
|
|
104
|
+
agent = Agent(name="gtm", model="openai:stand-in", instructions="Answer from the tools.",
|
|
105
|
+
tools=[*datacircle_tools(), add_two_numbers])
|
|
106
|
+
if mode == "sync":
|
|
107
|
+
result = Runner.run_sync(agent, "Who is best for email-finder?", client=client(stub))
|
|
108
|
+
else:
|
|
109
|
+
result = asyncio.run(Runner.run(agent, "Who is best for email-finder?", client=client(stub)))
|
|
110
|
+
check(stub, result.final_output)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@since_0_2
|
|
114
|
+
def test_tool_policy(stub):
|
|
115
|
+
from aisuite.agents import Agent, AllowToolsPolicy, Runner
|
|
116
|
+
|
|
117
|
+
agent = Agent(name="gtm", model="openai:stand-in", tools=[*datacircle_tools(), add_two_numbers])
|
|
118
|
+
result = Runner.run_sync(agent, "Who is best?", client=client(stub), tool_policy=AllowToolsPolicy(TOOL_NAMES))
|
|
119
|
+
assert stub.results()[1]["plans"][0]["provider"] == "Hunter"
|
|
120
|
+
assert stub.results()[4]["error"] == "Tool call denied by policy"
|
|
121
|
+
assert result.final_output.startswith("read: ")
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Each tool on the live API, https://api.datacircle.dev/v1: run with DATACIRCLE_LIVE=1."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from aisuite.utils.tools import Tools
|
|
7
|
+
|
|
8
|
+
from aisuite_datacircle import _api, datacircle_tools, 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 = 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 = 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 = 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 = run("datacircle_provider", {"slug": best["plans"][0]["provider"]})
|
|
23
|
+
assert provider["slug"] == slug and provider["apis"] and "plans" in provider["apis"][0]
|
|
24
|
+
refused = run("datacircle_best_plans", {"slug": "no-such-api"})
|
|
25
|
+
assert "answered 404" in refused["error"] and "email-finder" in refused["error"]
|
|
26
|
+
_, messages = Tools(datacircle_tools()).execute_tool(
|
|
27
|
+
[{"id": "c", "function": {"name": "datacircle_list_apis", "arguments": "{}"}}])
|
|
28
|
+
assert messages[0]["tool_call_id"] == "c" and '"total": ' in messages[0]["content"]
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Offline tests of the tools alone, on the stand-in API (conftest.py): the schema aisuite reads from them, every call,
|
|
2
|
+
its cut, every refusal."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from aisuite.utils.tools import Tools
|
|
8
|
+
|
|
9
|
+
import aisuite_datacircle
|
|
10
|
+
from aisuite_datacircle import TOOL_NAMES, datacircle_tools, run
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_schema_as_aisuite_reads_it():
|
|
14
|
+
specs = Tools(datacircle_tools()).tools()
|
|
15
|
+
assert [spec["function"]["name"] for spec in specs] == TOOL_NAMES
|
|
16
|
+
for spec in specs:
|
|
17
|
+
function = spec["function"]
|
|
18
|
+
assert spec["type"] == "function" and "https://datacircle.dev" in function["description"]
|
|
19
|
+
assert "Args:" not in function["description"] and "Returns:" not in function["description"]
|
|
20
|
+
assert all(prop["description"] for prop in function["parameters"]["properties"].values())
|
|
21
|
+
for prop in function["parameters"]["properties"].values(): # a provider refuses any other (0.1.12's "typing.Optional[str]")
|
|
22
|
+
assert {part["type"] for part in prop.get("anyOf", [prop])} <= {"string", "integer", "null"}, prop
|
|
23
|
+
best = specs[1]["function"]["parameters"]
|
|
24
|
+
assert best["required"] == ["slug"] and list(best["properties"]) == ["slug", "limit"]
|
|
25
|
+
assert list(specs[2]["function"]["parameters"]["properties"]) == ["api", "query", "sort", "limit", "offset"]
|
|
26
|
+
assert not specs[2]["function"]["parameters"].get("required")
|
|
27
|
+
assert [f.__name__ for f in datacircle_tools(["datacircle_provider"])] == ["datacircle_provider"]
|
|
28
|
+
with pytest.raises(ValueError, match="no tool 'nope'"):
|
|
29
|
+
datacircle_tools(["nope"])
|
|
30
|
+
with pytest.raises(TypeError):
|
|
31
|
+
datacircle_tools("datacircle_provider")
|
|
32
|
+
assert aisuite_datacircle.__version__ == "0.1.0"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_each_tool(stub):
|
|
36
|
+
apis = run("datacircle_list_apis", {"query": "email"})
|
|
37
|
+
assert apis == {"total": 1, "apis": [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3}]}
|
|
38
|
+
assert run("datacircle_list_apis", "{}")["total"] == 2
|
|
39
|
+
best = run("datacircle_best_plans", '{"slug": "Email Finder", "limit": "1"}')
|
|
40
|
+
assert best["plans"] == [{"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1,
|
|
41
|
+
"perThousand": 4.9, "page": "https://datacircle.dev/x"}]
|
|
42
|
+
assert stub.seen[-1] == ("/v1/apis/email-finder/best", {"limit": "1"}, "aisuite-datacircle/0.1.0")
|
|
43
|
+
plans = run("datacircle_search_plans", {"api": "email-finder", "sort": "Price", "limit": 5, "offset": 0})
|
|
44
|
+
assert plans["total"] == 1
|
|
45
|
+
assert stub.seen[-1][1] == {"api": "email-finder", "sort": "price", "limit": "5", "offset": "0"}
|
|
46
|
+
provider = run("datacircle_provider", {"slug": "Bright Data", "unknown": 1})
|
|
47
|
+
assert provider["apis"][0]["best"]["plan"] == "Pro" and provider["apis"][0]["plans"] == 2
|
|
48
|
+
json.dumps(provider) # what aisuite does with it
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_refusals(stub):
|
|
52
|
+
assert "the slugs: email-finder, linkedin-profile" in run("datacircle_best_plans", {"slug": "nope"})["error"]
|
|
53
|
+
assert "Give an API's slug" in run("datacircle_best_plans", {})["error"]
|
|
54
|
+
assert "limit must be from 1 to 50" in run("datacircle_best_plans", {"slug": "x", "limit": 99})["error"]
|
|
55
|
+
assert "whole number" in run("datacircle_search_plans", {"limit": 2.5})["error"]
|
|
56
|
+
assert "sort must be" in run("datacircle_search_plans", {"sort": "cheap"})["error"]
|
|
57
|
+
assert "answered 503: down for a minute" in run("datacircle_search_plans", {"query": "down"})["error"]
|
|
58
|
+
assert "no JSON object" in run("datacircle_provider", "{not json")["error"]
|
|
59
|
+
assert "Give a provider's slug" in run("datacircle_provider", "[1]")["error"]
|
|
60
|
+
assert "no provider" in run("datacircle_provider", {"slug": "nope"})["error"]
|
|
61
|
+
with pytest.raises(ValueError):
|
|
62
|
+
run("nope", {})
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_one_wait_on_429(stub):
|
|
66
|
+
assert run("datacircle_search_plans", {"query": "busy"})["total"] == 1
|
|
67
|
+
assert "429 twice" in run("datacircle_search_plans", {"query": "always-busy"})["error"]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_out_of_reach(monkeypatch):
|
|
71
|
+
monkeypatch.setattr(aisuite_datacircle._api, "BASE_URL", "http://127.0.0.1:9/v1")
|
|
72
|
+
assert "could not be reached" in run("datacircle_list_apis")["error"]
|