magentic-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.
- magentic_datacircle-0.1.0/.gitignore +4 -0
- magentic_datacircle-0.1.0/LICENSE +9 -0
- magentic_datacircle-0.1.0/PKG-INFO +150 -0
- magentic_datacircle-0.1.0/README.md +133 -0
- magentic_datacircle-0.1.0/pyproject.toml +32 -0
- magentic_datacircle-0.1.0/src/magentic_datacircle/__init__.py +21 -0
- magentic_datacircle-0.1.0/src/magentic_datacircle/_api.py +101 -0
- magentic_datacircle-0.1.0/src/magentic_datacircle/py.typed +0 -0
- magentic_datacircle-0.1.0/src/magentic_datacircle/tools.py +185 -0
- magentic_datacircle-0.1.0/tests/test_functions.py +326 -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,150 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: magentic-datacircle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: magentic functions 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/magentic-datacircle
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: api,api-pricing,b2b-data,datacircle,function-calling,gtm,llm,magentic,prompt-chain,tools
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Requires-Dist: pydantic>=2.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# magentic-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 [magentic](https://github.com/jackmpcollins/magentic) four functions that call Datacircle's open API, https://api.datacircle.dev/v1. You need no key and no account. Each function has type hints and a docstring. Each argument has a description. magentic reads the name, docstring and arguments of each function. magentic sends the name, docstring and arguments to the model.
|
|
25
|
+
|
|
26
|
+
| Function | What the function 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 magentic-datacircle magentic
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
magentic-datacircle works with magentic 0.40 and later, on Python 3.10 and later. magentic-datacircle does not import `magentic`.
|
|
40
|
+
|
|
41
|
+
magentic uses OpenAI's `gpt-4o` by default. To use another model for each prompt, set `MAGENTIC_OPENAI_MODEL`. To use another model for one prompt, pass `model=` to that prompt. The Datacircle functions work with each of magentic's chat models: `OpenaiChatModel`, `AnthropicChatModel` and `LitellmChatModel`.
|
|
42
|
+
|
|
43
|
+
## Use the functions in a prompt chain
|
|
44
|
+
|
|
45
|
+
With `@prompt_chain`, magentic runs each function call from the model. magentic then gives each function result back to the model. magentic repeats these steps until the model has the final answer:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from magentic import prompt_chain
|
|
49
|
+
from magentic_datacircle import datacircle_functions
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@prompt_chain("Who are the 3 best providers for the {api} API? Name each with its score.", functions=datacircle_functions())
|
|
53
|
+
def best_providers(api: str) -> str: ...
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
print(best_providers("email-finder"))
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Call the function yourself
|
|
60
|
+
|
|
61
|
+
With `@prompt`, the model returns a `FunctionCall`. You choose when to call the `FunctionCall`:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from magentic import FunctionCall, prompt
|
|
65
|
+
from magentic_datacircle import datacircle_functions
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@prompt("Find the best plans for the {api} API.", functions=datacircle_functions())
|
|
69
|
+
def plan(api: str) -> FunctionCall[str]: ...
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
call = plan("email-finder")
|
|
73
|
+
print(call())
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
To get many calls at once, set the return type to `ParallelFunctionCall[str]`.
|
|
77
|
+
|
|
78
|
+
## Use the Datacircle functions in a chat prompt
|
|
79
|
+
|
|
80
|
+
`@chatprompt` takes `functions=datacircle_functions()`:
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from magentic import FunctionCall, SystemMessage, UserMessage, chatprompt
|
|
84
|
+
from magentic_datacircle import datacircle_functions
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@chatprompt(
|
|
88
|
+
SystemMessage("Use the Datacircle functions for questions on GTM APIs."),
|
|
89
|
+
UserMessage("On which APIs does {provider} rank?"),
|
|
90
|
+
functions=datacircle_functions(),
|
|
91
|
+
)
|
|
92
|
+
def ranks(provider: str) -> FunctionCall[str]: ...
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
print(ranks("Hunter")())
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Use the functions in async code
|
|
99
|
+
|
|
100
|
+
For a prompt on an `async def`, use `datacircle_async_functions()`. The async functions have the same names and arguments as the sync functions. Each async function runs the API call in a thread. Several calls then run at the same time:
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
import asyncio
|
|
104
|
+
|
|
105
|
+
from magentic import prompt_chain
|
|
106
|
+
from magentic_datacircle import datacircle_async_functions
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@prompt_chain("Who is the best provider for the {api} API?", functions=datacircle_async_functions())
|
|
110
|
+
async def best_provider(api: str) -> str: ...
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
print(asyncio.run(best_provider("email-finder")))
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Use the Datacircle functions beside your own functions
|
|
117
|
+
|
|
118
|
+
Put the Datacircle functions in one list with your own functions: `functions=[*datacircle_functions(), my_function]`.
|
|
119
|
+
|
|
120
|
+
To give the model only some Datacircle functions, list the names of those functions: `datacircle_functions(["datacircle_best_plans"])`.
|
|
121
|
+
|
|
122
|
+
## Call a function without a model
|
|
123
|
+
|
|
124
|
+
Each function runs without a model. You get the Datacircle API's answer as JSON text:
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
import json
|
|
128
|
+
|
|
129
|
+
from magentic_datacircle import datacircle_best_plans, run
|
|
130
|
+
|
|
131
|
+
print(json.loads(datacircle_best_plans("email-finder", limit=3))["plans"])
|
|
132
|
+
print(run("datacircle_provider", {"slug": "Bright Data"}))
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## What the model reads
|
|
136
|
+
|
|
137
|
+
Each function returns the API's answer as JSON text. magentic gives the model this text with every backend. 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.
|
|
138
|
+
|
|
139
|
+
You can give a provider's name in place of a slug. The function turns `Bright Data` into `bright-data`.
|
|
140
|
+
|
|
141
|
+
An unknown slug gets no data from the API. With no data, the function returns `{"error": "..."}` and the API's message. The error for an unknown API slug lists every valid slug. The function checks each number from the model before any API call. For a number out of range, the function returns `{"error": "..."}` and makes no API call. If the network fails, the function returns `{"error": "..."}` with the network error's message. The function never raises an error. Your prompt chain keeps running. The model can call the function again.
|
|
142
|
+
|
|
143
|
+
## Network
|
|
144
|
+
|
|
145
|
+
Each function call makes one HTTPS GET request to https://api.datacircle.dev/v1 and nothing else. The request holds only the function's own arguments: no key and nothing from your prompts. The API takes up to 60 calls a minute from one IP address. The API can ask the function to wait. The function then waits once, for a minute at most. Each call uses only Python's standard library. Nothing goes to disk.
|
|
146
|
+
|
|
147
|
+
## Links
|
|
148
|
+
|
|
149
|
+
- Datacircle: https://datacircle.dev
|
|
150
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# magentic-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 [magentic](https://github.com/jackmpcollins/magentic) four functions that call Datacircle's open API, https://api.datacircle.dev/v1. You need no key and no account. Each function has type hints and a docstring. Each argument has a description. magentic reads the name, docstring and arguments of each function. magentic sends the name, docstring and arguments to the model.
|
|
8
|
+
|
|
9
|
+
| Function | What the function 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 magentic-datacircle magentic
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
magentic-datacircle works with magentic 0.40 and later, on Python 3.10 and later. magentic-datacircle does not import `magentic`.
|
|
23
|
+
|
|
24
|
+
magentic uses OpenAI's `gpt-4o` by default. To use another model for each prompt, set `MAGENTIC_OPENAI_MODEL`. To use another model for one prompt, pass `model=` to that prompt. The Datacircle functions work with each of magentic's chat models: `OpenaiChatModel`, `AnthropicChatModel` and `LitellmChatModel`.
|
|
25
|
+
|
|
26
|
+
## Use the functions in a prompt chain
|
|
27
|
+
|
|
28
|
+
With `@prompt_chain`, magentic runs each function call from the model. magentic then gives each function result back to the model. magentic repeats these steps until the model has the final answer:
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from magentic import prompt_chain
|
|
32
|
+
from magentic_datacircle import datacircle_functions
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@prompt_chain("Who are the 3 best providers for the {api} API? Name each with its score.", functions=datacircle_functions())
|
|
36
|
+
def best_providers(api: str) -> str: ...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
print(best_providers("email-finder"))
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Call the function yourself
|
|
43
|
+
|
|
44
|
+
With `@prompt`, the model returns a `FunctionCall`. You choose when to call the `FunctionCall`:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from magentic import FunctionCall, prompt
|
|
48
|
+
from magentic_datacircle import datacircle_functions
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@prompt("Find the best plans for the {api} API.", functions=datacircle_functions())
|
|
52
|
+
def plan(api: str) -> FunctionCall[str]: ...
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
call = plan("email-finder")
|
|
56
|
+
print(call())
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
To get many calls at once, set the return type to `ParallelFunctionCall[str]`.
|
|
60
|
+
|
|
61
|
+
## Use the Datacircle functions in a chat prompt
|
|
62
|
+
|
|
63
|
+
`@chatprompt` takes `functions=datacircle_functions()`:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from magentic import FunctionCall, SystemMessage, UserMessage, chatprompt
|
|
67
|
+
from magentic_datacircle import datacircle_functions
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@chatprompt(
|
|
71
|
+
SystemMessage("Use the Datacircle functions for questions on GTM APIs."),
|
|
72
|
+
UserMessage("On which APIs does {provider} rank?"),
|
|
73
|
+
functions=datacircle_functions(),
|
|
74
|
+
)
|
|
75
|
+
def ranks(provider: str) -> FunctionCall[str]: ...
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
print(ranks("Hunter")())
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Use the functions in async code
|
|
82
|
+
|
|
83
|
+
For a prompt on an `async def`, use `datacircle_async_functions()`. The async functions have the same names and arguments as the sync functions. Each async function runs the API call in a thread. Several calls then run at the same time:
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
import asyncio
|
|
87
|
+
|
|
88
|
+
from magentic import prompt_chain
|
|
89
|
+
from magentic_datacircle import datacircle_async_functions
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@prompt_chain("Who is the best provider for the {api} API?", functions=datacircle_async_functions())
|
|
93
|
+
async def best_provider(api: str) -> str: ...
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
print(asyncio.run(best_provider("email-finder")))
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Use the Datacircle functions beside your own functions
|
|
100
|
+
|
|
101
|
+
Put the Datacircle functions in one list with your own functions: `functions=[*datacircle_functions(), my_function]`.
|
|
102
|
+
|
|
103
|
+
To give the model only some Datacircle functions, list the names of those functions: `datacircle_functions(["datacircle_best_plans"])`.
|
|
104
|
+
|
|
105
|
+
## Call a function without a model
|
|
106
|
+
|
|
107
|
+
Each function runs without a model. You get the Datacircle API's answer as JSON text:
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
import json
|
|
111
|
+
|
|
112
|
+
from magentic_datacircle import datacircle_best_plans, run
|
|
113
|
+
|
|
114
|
+
print(json.loads(datacircle_best_plans("email-finder", limit=3))["plans"])
|
|
115
|
+
print(run("datacircle_provider", {"slug": "Bright Data"}))
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## What the model reads
|
|
119
|
+
|
|
120
|
+
Each function returns the API's answer as JSON text. magentic gives the model this text with every backend. 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.
|
|
121
|
+
|
|
122
|
+
You can give a provider's name in place of a slug. The function turns `Bright Data` into `bright-data`.
|
|
123
|
+
|
|
124
|
+
An unknown slug gets no data from the API. With no data, the function returns `{"error": "..."}` and the API's message. The error for an unknown API slug lists every valid slug. The function checks each number from the model before any API call. For a number out of range, the function returns `{"error": "..."}` and makes no API call. If the network fails, the function returns `{"error": "..."}` with the network error's message. The function never raises an error. Your prompt chain keeps running. The model can call the function again.
|
|
125
|
+
|
|
126
|
+
## Network
|
|
127
|
+
|
|
128
|
+
Each function call makes one HTTPS GET request to https://api.datacircle.dev/v1 and nothing else. The request holds only the function's own arguments: no key and nothing from your prompts. The API takes up to 60 calls a minute from one IP address. The API can ask the function to wait. The function then waits once, for a minute at most. Each call uses only Python's standard library. Nothing goes to disk.
|
|
129
|
+
|
|
130
|
+
## Links
|
|
131
|
+
|
|
132
|
+
- Datacircle: https://datacircle.dev
|
|
133
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "magentic-datacircle"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "magentic functions for the Datacircle API: find the best GTM APIs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = ["pydantic>=2.10"]
|
|
13
|
+
keywords = ["magentic", "llm", "function-calling", "tools", "prompt-chain", "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/magentic-datacircle"
|
|
24
|
+
|
|
25
|
+
[dependency-groups]
|
|
26
|
+
test = ["pytest>=8", "magentic[anthropic,litellm]>=0.40"]
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/magentic_datacircle"]
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.sdist]
|
|
32
|
+
include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Functions for magentic on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
|
|
2
|
+
|
|
3
|
+
from magentic_datacircle._api import BASE_URL, DatacircleError
|
|
4
|
+
from magentic_datacircle.tools import (
|
|
5
|
+
ASYNC_FUNCTIONS,
|
|
6
|
+
FUNCTIONS,
|
|
7
|
+
TOOL_NAMES,
|
|
8
|
+
arun,
|
|
9
|
+
datacircle_async_functions,
|
|
10
|
+
datacircle_best_plans,
|
|
11
|
+
datacircle_functions,
|
|
12
|
+
datacircle_list_apis,
|
|
13
|
+
datacircle_provider,
|
|
14
|
+
datacircle_search_plans,
|
|
15
|
+
run,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
19
|
+
__all__ = ["ASYNC_FUNCTIONS", "BASE_URL", "DatacircleError", "FUNCTIONS", "TOOL_NAMES", "arun", "datacircle_async_functions",
|
|
20
|
+
"datacircle_best_plans", "datacircle_functions", "datacircle_list_apis", "datacircle_provider",
|
|
21
|
+
"datacircle_search_plans", "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 = "magentic-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,185 @@
|
|
|
1
|
+
"""Functions for magentic on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
|
|
2
|
+
|
|
3
|
+
magentic makes a function's schema from the function itself: its name, its docstring as the description, and each
|
|
4
|
+
argument's type and description from its Annotated Field. Each function goes in @prompt(functions=[...]),
|
|
5
|
+
@prompt_chain(functions=[...]) and @chatprompt(functions=[...]) beside an app's own, on each of magentic's chat models.
|
|
6
|
+
A function makes one HTTPS GET and returns the API's answer as JSON text, which magentic gives the model as it is on
|
|
7
|
+
every backend: a dict would go to Anthropic as an object, where a tool result takes text or blocks. A refusal (an
|
|
8
|
+
unknown slug, an argument out of range, the API out of reach) is the JSON text {"error": the API's words}, never an
|
|
9
|
+
exception: magentic raises a function's exception out of the prompt, which ends the chain.
|
|
10
|
+
|
|
11
|
+
The async functions have the same names, docstrings and arguments, and run the GET in a thread, so an async prompt's
|
|
12
|
+
parallel calls run at once and its event loop is never held.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import asyncio
|
|
16
|
+
import functools
|
|
17
|
+
import json
|
|
18
|
+
import urllib.parse
|
|
19
|
+
from typing import Annotated, Any, Awaitable, Callable, Dict, List, Mapping, Optional, Sequence
|
|
20
|
+
|
|
21
|
+
from pydantic import Field
|
|
22
|
+
|
|
23
|
+
from magentic_datacircle import _api
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _text(function: Callable[..., Dict[str, Any]], *args: Any) -> str:
|
|
27
|
+
"""What a function gives the model: its answer as JSON text, or {"error": ...} when the API or its checks refused."""
|
|
28
|
+
try:
|
|
29
|
+
answer = function(*args)
|
|
30
|
+
except _api.DatacircleError as error:
|
|
31
|
+
answer = {"error": str(error)}
|
|
32
|
+
return json.dumps(answer, ensure_ascii=False)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _best(plans: Any) -> Optional[Dict[str, Any]]:
|
|
36
|
+
"""A provider's best plan on an API: its lowest rank, a plan with no score having none."""
|
|
37
|
+
ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
|
|
38
|
+
return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _list_apis(query: Any, limit: Any) -> Dict[str, Any]:
|
|
42
|
+
count = _api.whole("limit", limit, 1, 200) or 20
|
|
43
|
+
apis = _api.get("/apis")
|
|
44
|
+
words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
|
|
45
|
+
held = []
|
|
46
|
+
for index, api in enumerate(apis):
|
|
47
|
+
name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
|
|
48
|
+
matched = sum(word in name for word in words)
|
|
49
|
+
if matched or not words:
|
|
50
|
+
held.append((-matched, index, api))
|
|
51
|
+
found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
|
|
52
|
+
return {"total": len(found), "apis": found[:count]}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _best_plans(slug: Any, limit: Any) -> Dict[str, Any]:
|
|
56
|
+
made = _api.slug(slug)
|
|
57
|
+
if not made:
|
|
58
|
+
raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
|
|
59
|
+
answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
|
|
60
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _search_plans(api: Any, query: Any, sort: Any, limit: Any, offset: Any) -> Dict[str, Any]:
|
|
64
|
+
order = str(sort).strip().lower() if sort not in (None, "") else None
|
|
65
|
+
if order is not None and order not in ("score", "provider", "price"):
|
|
66
|
+
raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
|
|
67
|
+
params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
|
|
68
|
+
"offset": _api.whole("offset", offset, 0)}
|
|
69
|
+
answer = _api.get("/plans", params)
|
|
70
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _provider(slug: Any) -> Dict[str, Any]:
|
|
74
|
+
made = _api.slug(slug)
|
|
75
|
+
if not made:
|
|
76
|
+
raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
|
|
77
|
+
answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
|
|
78
|
+
apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
|
|
79
|
+
"best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
|
|
80
|
+
return {**answer, "apis": apis}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# The functions. A number has no bounds in its schema and sort is a str, not a Literal: magentic raises a schema's
|
|
84
|
+
# refusal out of the prompt, where the function's own check gives the model its words and the chain goes on.
|
|
85
|
+
|
|
86
|
+
def datacircle_list_apis(
|
|
87
|
+
query: Annotated[Optional[str], Field(description="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.")] = None,
|
|
88
|
+
limit: Annotated[Optional[int], Field(description="How many APIs to give, 1 to 200. 20 when left out, of about 170.")] = None,
|
|
89
|
+
) -> str:
|
|
90
|
+
"""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. Gives JSON: total, the APIs found, and apis, each with api, slug, plans, providers and best. Or {"error": ...} in the API's words."""
|
|
91
|
+
return _text(_list_apis, query, limit)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def datacircle_best_plans(
|
|
95
|
+
slug: Annotated[str, Field(description="The API's slug, like 'email-finder' or 'linkedin-profile', as datacircle_list_apis gives it.")],
|
|
96
|
+
limit: Annotated[Optional[int], Field(description="How many plans to give, 1 to 50. 10 when left out.")] = None,
|
|
97
|
+
) -> str:
|
|
98
|
+
"""Gives an API's plans best first by their score out of 100 on Datacircle's benchmark (https://datacircle.dev): the best providers of an API. Gives JSON: api, slug, total and plans, each with rank, provider, plan, score, perThousand (a plan's price of 1,000 items in dollars), pay (the plan's whole price in its currency) and page. Or {"error": ...} in the API's words."""
|
|
99
|
+
return _text(_best_plans, slug, limit)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def datacircle_search_plans(
|
|
103
|
+
api: Annotated[Optional[str], Field(description="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.")] = None,
|
|
104
|
+
query: Annotated[Optional[str], Field(description="Words that must all appear in the provider's or plan's name, like 'bright data'.")] = None,
|
|
105
|
+
sort: Annotated[Optional[str], Field(description="score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first).")] = None,
|
|
106
|
+
limit: Annotated[Optional[int], Field(description="How many plans to give, 1 to 50. 10 when left out.")] = None,
|
|
107
|
+
offset: Annotated[Optional[int], Field(description="How many found plans to skip first. 0 when left out.")] = None,
|
|
108
|
+
) -> str:
|
|
109
|
+
"""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. Gives JSON: total, the plans found, offset and plans, each with api, rank, provider, plan, score, perThousand (a plan's price of 1,000 items in dollars), pay and page. Or {"error": ...} in the API's words."""
|
|
110
|
+
return _text(_search_plans, api, query, sort, limit, offset)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def datacircle_provider(
|
|
114
|
+
slug: Annotated[str, Field(description="The provider's slug, like 'bright-data', or its name, like 'Bright Data', which is made a slug.")],
|
|
115
|
+
) -> str:
|
|
116
|
+
"""Gives each API one provider sells and its rank on each on Datacircle's benchmark (https://datacircle.dev), with its best plan there. Gives JSON: provider, slug, website and apis, each with api, slug, rank, plans (how many it has there) and best, its best plan there. Or {"error": ...} in the API's words."""
|
|
117
|
+
return _text(_provider, slug)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _in_thread(function: Callable[..., str]) -> Callable[..., Awaitable[str]]:
|
|
121
|
+
"""The async function of a function: the same name, docstring and signature (inspect follows __wrapped__), its GET in a thread."""
|
|
122
|
+
@functools.wraps(function)
|
|
123
|
+
async def run_in_thread(*args: Any, **kwargs: Any) -> str:
|
|
124
|
+
return await asyncio.to_thread(function, *args, **kwargs)
|
|
125
|
+
return run_in_thread
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
FUNCTIONS: Dict[str, Callable[..., str]] = {function.__name__: function for function in (
|
|
129
|
+
datacircle_list_apis, datacircle_best_plans, datacircle_search_plans, datacircle_provider)}
|
|
130
|
+
ASYNC_FUNCTIONS: Dict[str, Callable[..., Awaitable[str]]] = {name: _in_thread(function) for name, function in FUNCTIONS.items()}
|
|
131
|
+
TOOL_NAMES = list(FUNCTIONS)
|
|
132
|
+
_ARGUMENTS = {"datacircle_list_apis": ("query", "limit"), "datacircle_best_plans": ("slug", "limit"),
|
|
133
|
+
"datacircle_search_plans": ("api", "query", "sort", "limit", "offset"),
|
|
134
|
+
"datacircle_provider": ("slug",)}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _names(tool_names: Optional[Sequence[str]]) -> List[str]:
|
|
138
|
+
if isinstance(tool_names, str):
|
|
139
|
+
raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
|
|
140
|
+
for name in tool_names or []:
|
|
141
|
+
if name not in FUNCTIONS:
|
|
142
|
+
raise ValueError(f"Datacircle has no function {name!r}: its functions are {', '.join(TOOL_NAMES)}")
|
|
143
|
+
return list(TOOL_NAMES if tool_names is None else tool_names)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def datacircle_functions(tool_names: Optional[Sequence[str]] = None) -> List[Callable[..., str]]:
|
|
147
|
+
"""The functions, for @prompt(..., functions=datacircle_functions()), @prompt_chain or @chatprompt, or beside one's
|
|
148
|
+
own: functions=[*datacircle_functions(), my_function]. tool_names keeps some of them only, in their order here;
|
|
149
|
+
all four when left out."""
|
|
150
|
+
return [FUNCTIONS[name] for name in _names(tool_names)]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def datacircle_async_functions(tool_names: Optional[Sequence[str]] = None) -> List[Callable[..., Awaitable[str]]]:
|
|
154
|
+
"""The async functions, for a prompt on an async def: the same names and arguments as datacircle_functions()."""
|
|
155
|
+
return [ASYNC_FUNCTIONS[name] for name in _names(tool_names)]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _given(name: str, arguments: Any) -> Dict[str, Any]:
|
|
159
|
+
_names([name])
|
|
160
|
+
if isinstance(arguments, (str, bytes)):
|
|
161
|
+
arguments = json.loads(arguments or "{}")
|
|
162
|
+
given = arguments if isinstance(arguments, Mapping) else {}
|
|
163
|
+
return {key: given.get(key) for key in _ARGUMENTS[name]}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def run(name: str, arguments: Any = None) -> str:
|
|
167
|
+
"""What a function gives the model for these arguments, as JSON text: the API's answer, or {"error": its words}.
|
|
168
|
+
arguments is a mapping or its JSON text; the ones the function doesn't take are left out."""
|
|
169
|
+
try:
|
|
170
|
+
given = _given(name, arguments)
|
|
171
|
+
except ValueError as error:
|
|
172
|
+
if name not in FUNCTIONS:
|
|
173
|
+
raise
|
|
174
|
+
return json.dumps({"error": f"the arguments are no JSON object: {error}"})
|
|
175
|
+
return FUNCTIONS[name](**given)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
async def arun(name: str, arguments: Any = None) -> str:
|
|
179
|
+
"""run() in a thread, for async code."""
|
|
180
|
+
return await asyncio.to_thread(run, name, arguments)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
__all__: List[str] = ["ASYNC_FUNCTIONS", "FUNCTIONS", "TOOL_NAMES", "arun", "datacircle_async_functions",
|
|
184
|
+
"datacircle_best_plans", "datacircle_functions", "datacircle_list_apis", "datacircle_provider",
|
|
185
|
+
"datacircle_search_plans", "run"]
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
"""Offline tests: the functions against a local stand-in for the API on 127.0.0.1, by their own call and run(), and by
|
|
2
|
+
magentic's @prompt, @prompt_chain and @chatprompt on OpenaiChatModel and LitellmChatModel, sync and async, each sent
|
|
3
|
+
to a scripted OpenAI-compatible chat server on 127.0.0.1 that streams the tool calls it is told to."""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
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
|
+
os.environ.setdefault("LITELLM_LOCAL_MODEL_COST_MAP", "True")
|
|
14
|
+
os.environ.setdefault("OPENAI_API_KEY", "stand-in")
|
|
15
|
+
|
|
16
|
+
import pytest # noqa: E402
|
|
17
|
+
from magentic import ( # noqa: E402
|
|
18
|
+
AsyncParallelFunctionCall,
|
|
19
|
+
FunctionCall,
|
|
20
|
+
OpenaiChatModel,
|
|
21
|
+
ParallelFunctionCall,
|
|
22
|
+
SystemMessage,
|
|
23
|
+
UserMessage,
|
|
24
|
+
chatprompt,
|
|
25
|
+
prompt,
|
|
26
|
+
prompt_chain,
|
|
27
|
+
)
|
|
28
|
+
from magentic.chat_model.function_schema import FunctionCallFunctionSchema # noqa: E402
|
|
29
|
+
|
|
30
|
+
from magentic_datacircle import ( # noqa: E402
|
|
31
|
+
ASYNC_FUNCTIONS,
|
|
32
|
+
FUNCTIONS,
|
|
33
|
+
TOOL_NAMES,
|
|
34
|
+
arun,
|
|
35
|
+
datacircle_async_functions,
|
|
36
|
+
datacircle_best_plans,
|
|
37
|
+
datacircle_functions,
|
|
38
|
+
datacircle_list_apis,
|
|
39
|
+
datacircle_provider,
|
|
40
|
+
datacircle_search_plans,
|
|
41
|
+
run,
|
|
42
|
+
)
|
|
43
|
+
from magentic_datacircle import _api # noqa: E402
|
|
44
|
+
|
|
45
|
+
PLAN = {"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1, "perThousand": 4.9,
|
|
46
|
+
"page": "https://datacircle.dev/x", "terms": "long", "aggregators": ["a"]}
|
|
47
|
+
SEEN = []
|
|
48
|
+
BUSY = []
|
|
49
|
+
CHATS = []
|
|
50
|
+
SCRIPT = [] # the scripted model's next answers: a list of (name, arguments) tool calls, or a text
|
|
51
|
+
SLOW = []
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Handler(BaseHTTPRequestHandler):
|
|
55
|
+
protocol_version = "HTTP/1.1"
|
|
56
|
+
|
|
57
|
+
def log_message(self, *args):
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
def send(self, status, body, headers=None):
|
|
61
|
+
data = json.dumps(body).encode()
|
|
62
|
+
self.send_response(status)
|
|
63
|
+
for key, value in {"Content-Type": "application/json", "Content-Length": str(len(data)), **(headers or {})}.items():
|
|
64
|
+
self.send_header(key, value)
|
|
65
|
+
self.end_headers()
|
|
66
|
+
self.wfile.write(data)
|
|
67
|
+
|
|
68
|
+
def do_POST(self): # an OpenAI-compatible /v1/chat/completions that streams SCRIPT's next answer
|
|
69
|
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
|
|
70
|
+
CHATS.append(body)
|
|
71
|
+
answer = SCRIPT.pop(0) if SCRIPT else "done"
|
|
72
|
+
base = {"id": "chatcmpl-1", "object": "chat.completion.chunk", "created": 0, "model": body["model"]}
|
|
73
|
+
if isinstance(answer, str):
|
|
74
|
+
deltas = [({"role": "assistant", "content": answer}, None), ({}, "stop")]
|
|
75
|
+
else:
|
|
76
|
+
calls = [{"index": index, "id": f"call_{len(CHATS)}_{index}", "type": "function",
|
|
77
|
+
"function": {"name": name, "arguments": json.dumps(arguments)}}
|
|
78
|
+
for index, (name, arguments) in enumerate(answer)]
|
|
79
|
+
deltas = [({"role": "assistant", "content": None, "tool_calls": calls}, None), ({}, "tool_calls")]
|
|
80
|
+
events = [{**base, "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]} for delta, finish in deltas]
|
|
81
|
+
events.append({**base, "choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}})
|
|
82
|
+
data = "".join(f"data: {json.dumps(event)}\n\n" for event in events) + "data: [DONE]\n\n"
|
|
83
|
+
self.send_response(200)
|
|
84
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
85
|
+
self.send_header("Content-Length", str(len(data.encode())))
|
|
86
|
+
self.end_headers()
|
|
87
|
+
self.wfile.write(data.encode())
|
|
88
|
+
|
|
89
|
+
def do_GET(self):
|
|
90
|
+
url = urlparse(self.path)
|
|
91
|
+
query = {key: values[0] for key, values in parse_qs(url.query).items()}
|
|
92
|
+
SEEN.append((url.path, query, self.headers.get("User-Agent")))
|
|
93
|
+
if SLOW:
|
|
94
|
+
time.sleep(SLOW[0])
|
|
95
|
+
headers = {}
|
|
96
|
+
if url.path == "/v1/plans" and query.get("query") == "busy" and not BUSY:
|
|
97
|
+
BUSY.append(1)
|
|
98
|
+
status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
99
|
+
elif url.path == "/v1/apis":
|
|
100
|
+
status, body = 200, [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3, "extra": 1},
|
|
101
|
+
{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]
|
|
102
|
+
elif url.path == "/v1/apis/email-finder/best":
|
|
103
|
+
status, body = 200, {"api": "Employee email", "slug": "email-finder", "total": 1, "plans": [PLAN]}
|
|
104
|
+
elif url.path.startswith("/v1/apis/"):
|
|
105
|
+
status, body = 404, {"error": "no API has the slug nope", "slugs": ["email-finder", "linkedin-profile"]}
|
|
106
|
+
elif url.path == "/v1/plans" and query.get("query") == "down":
|
|
107
|
+
status, body = 503, {"error": "down for a minute"}
|
|
108
|
+
elif url.path == "/v1/plans":
|
|
109
|
+
status, body = 200, {"total": 1, "offset": 0, "plans": [PLAN]}
|
|
110
|
+
elif url.path == "/v1/providers/bright-data":
|
|
111
|
+
status, body = 200, {"provider": "Bright Data", "slug": "bright-data", "website": "https://brightdata.com",
|
|
112
|
+
"apis": [{"api": "Employee email", "slug": "email-finder", "rank": 7, "sheetPage": "s",
|
|
113
|
+
"plans": [dict(PLAN, rank=9, plan="B"), dict(PLAN, rank=7, plan="A")]}]}
|
|
114
|
+
else:
|
|
115
|
+
status, body = 404, {"error": "no provider has this slug"}
|
|
116
|
+
self.send(status, body, headers)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@pytest.fixture(scope="module", autouse=True)
|
|
120
|
+
def stand_in():
|
|
121
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
122
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
123
|
+
before = _api.BASE_URL
|
|
124
|
+
_api.BASE_URL = f"http://127.0.0.1:{server.server_address[1]}/v1"
|
|
125
|
+
yield f"http://127.0.0.1:{server.server_address[1]}/v1"
|
|
126
|
+
_api.BASE_URL = before
|
|
127
|
+
server.shutdown()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@pytest.fixture(autouse=True)
|
|
131
|
+
def fresh():
|
|
132
|
+
SEEN.clear()
|
|
133
|
+
CHATS.clear()
|
|
134
|
+
SCRIPT.clear()
|
|
135
|
+
SLOW.clear()
|
|
136
|
+
yield
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@pytest.fixture()
|
|
140
|
+
def model(stand_in):
|
|
141
|
+
return OpenaiChatModel("stand-in", base_url=stand_in, api_key="stand-in")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def add_two_numbers(a: int, b: int) -> int:
|
|
145
|
+
"""Adds two numbers: the app's own function, beside Datacircle's."""
|
|
146
|
+
return a + b
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def tool_messages(chat):
|
|
150
|
+
return [message for message in chat["messages"] if message["role"] == "tool"]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def test_schemas_as_magentic_sends_them(model):
|
|
154
|
+
SCRIPT.append("done")
|
|
155
|
+
|
|
156
|
+
@prompt("Say done.", functions=[*datacircle_functions(), add_two_numbers], model=model)
|
|
157
|
+
def ask() -> str: ...
|
|
158
|
+
|
|
159
|
+
assert ask() == "done"
|
|
160
|
+
tools = {tool["function"]["name"]: tool["function"] for tool in CHATS[0]["tools"]}
|
|
161
|
+
assert list(tools) == [*TOOL_NAMES, "add_two_numbers"]
|
|
162
|
+
assert TOOL_NAMES == ["datacircle_list_apis", "datacircle_best_plans", "datacircle_search_plans", "datacircle_provider"]
|
|
163
|
+
wanted = {"datacircle_list_apis": ({"query", "limit"}, []),
|
|
164
|
+
"datacircle_best_plans": ({"slug", "limit"}, ["slug"]),
|
|
165
|
+
"datacircle_search_plans": ({"api", "query", "sort", "limit", "offset"}, []),
|
|
166
|
+
"datacircle_provider": ({"slug"}, ["slug"])}
|
|
167
|
+
for name, (keys, required) in wanted.items():
|
|
168
|
+
function = tools[name]
|
|
169
|
+
assert "datacircle.dev" in function["description"] and "{\"error\": ...}" in function["description"]
|
|
170
|
+
properties = function["parameters"]["properties"]
|
|
171
|
+
assert set(properties) == keys and function["parameters"].get("required", []) == required, name
|
|
172
|
+
assert all(len(value["description"]) > 20 for value in properties.values()), name
|
|
173
|
+
assert all("maximum" not in value and "enum" not in value for value in properties.values()), name
|
|
174
|
+
assert "price ($ per 1,000, lowest first)" in tools["datacircle_search_plans"]["parameters"]["properties"]["sort"]["description"]
|
|
175
|
+
for name, function in ASYNC_FUNCTIONS.items():
|
|
176
|
+
assert asyncio.iscoroutinefunction(function)
|
|
177
|
+
assert FunctionCallFunctionSchema(function).parameters == FunctionCallFunctionSchema(FUNCTIONS[name]).parameters
|
|
178
|
+
assert FunctionCallFunctionSchema(function).description == FunctionCallFunctionSchema(FUNCTIONS[name]).description
|
|
179
|
+
assert not SEEN
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def test_some_functions_by_name():
|
|
183
|
+
assert datacircle_functions(["datacircle_provider", "datacircle_best_plans"]) == [datacircle_provider, datacircle_best_plans]
|
|
184
|
+
assert datacircle_functions() == list(FUNCTIONS.values())
|
|
185
|
+
assert [f.__name__ for f in datacircle_async_functions(["datacircle_provider"])] == ["datacircle_provider"]
|
|
186
|
+
with pytest.raises(ValueError):
|
|
187
|
+
datacircle_functions(["nope"])
|
|
188
|
+
with pytest.raises(TypeError):
|
|
189
|
+
datacircle_functions("datacircle_provider")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def test_each_function_by_its_own_call(stand_in):
|
|
193
|
+
apis = json.loads(datacircle_list_apis("profile", 1))
|
|
194
|
+
assert apis == {"total": 1, "apis": [{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]}
|
|
195
|
+
best = json.loads(datacircle_best_plans("Email Finder", "1"))
|
|
196
|
+
assert best["plans"][0]["provider"] == "Hunter" and "terms" not in best["plans"][0]
|
|
197
|
+
plans = json.loads(datacircle_search_plans(api="email-finder", query="hunter", sort="Price", limit=5, offset=0))
|
|
198
|
+
assert plans["plans"][0]["plan"] == "Starter"
|
|
199
|
+
provider = json.loads(datacircle_provider("Bright Data"))
|
|
200
|
+
assert provider["apis"][0]["best"]["plan"] == "A" and provider["apis"][0]["plans"] == 2
|
|
201
|
+
assert [path for path, _, _ in SEEN] == ["/v1/apis", "/v1/apis/email-finder/best", "/v1/plans", "/v1/providers/bright-data"]
|
|
202
|
+
assert SEEN[1][1] == {"limit": "1"} and SEEN[2][1] == {"api": "email-finder", "query": "hunter", "sort": "price",
|
|
203
|
+
"limit": "5", "offset": "0"}
|
|
204
|
+
assert {agent for _, _, agent in SEEN} == {"magentic-datacircle/0.1.0"}
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def test_refusals_are_json_text_never_raised():
|
|
208
|
+
unknown = json.loads(datacircle_best_plans("nope"))
|
|
209
|
+
assert "404" in unknown["error"] and "email-finder, linkedin-profile" in unknown["error"]
|
|
210
|
+
SEEN.clear()
|
|
211
|
+
assert "1 to 50" in json.loads(datacircle_best_plans("email-finder", 500))["error"]
|
|
212
|
+
assert "whole number" in json.loads(datacircle_search_plans(limit="ten"))["error"]
|
|
213
|
+
assert "score, provider or price" in json.loads(datacircle_search_plans(sort="cheapest"))["error"]
|
|
214
|
+
assert "slug" in json.loads(datacircle_provider(" "))["error"]
|
|
215
|
+
assert not SEEN
|
|
216
|
+
down = json.loads(datacircle_search_plans(query="down"))
|
|
217
|
+
assert "503" in down["error"] and "down for a minute" in down["error"]
|
|
218
|
+
started = time.monotonic()
|
|
219
|
+
assert json.loads(datacircle_search_plans(query="busy"))["total"] == 1 and time.monotonic() - started >= 1
|
|
220
|
+
before = _api.BASE_URL
|
|
221
|
+
_api.BASE_URL = "http://127.0.0.1:9/v1"
|
|
222
|
+
try:
|
|
223
|
+
assert "could not be reached" in json.loads(datacircle_list_apis())["error"]
|
|
224
|
+
finally:
|
|
225
|
+
_api.BASE_URL = before
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def test_run_and_arun():
|
|
229
|
+
assert json.loads(run("datacircle_provider", '{"slug": "bright-data", "other": 1}'))["slug"] == "bright-data"
|
|
230
|
+
assert json.loads(run("datacircle_best_plans", {"slug": "email-finder", "limit": 1}))["total"] == 1
|
|
231
|
+
assert "no JSON object" in json.loads(run("datacircle_best_plans", "{not json"))["error"]
|
|
232
|
+
assert json.loads(asyncio.run(arun("datacircle_list_apis", None)))["total"] == 2
|
|
233
|
+
with pytest.raises(ValueError):
|
|
234
|
+
run("nope", {})
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def test_prompt_chain_runs_each_call_beside_the_apps_own(model):
|
|
238
|
+
SCRIPT.extend([[("datacircle_best_plans", {"slug": "email-finder", "limit": 1})],
|
|
239
|
+
[("add_two_numbers", {"a": 1, "b": 2})],
|
|
240
|
+
[("datacircle_best_plans", {"slug": "nope"})],
|
|
241
|
+
"Hunter is first"])
|
|
242
|
+
|
|
243
|
+
@prompt_chain("Who is best for {api}?", functions=[*datacircle_functions(), add_two_numbers], model=model)
|
|
244
|
+
def best(api: str) -> str: ...
|
|
245
|
+
|
|
246
|
+
assert best("email-finder") == "Hunter is first"
|
|
247
|
+
results = [message["content"] for message in tool_messages(CHATS[-1])]
|
|
248
|
+
assert json.loads(results[0])["plans"][0]["provider"] == "Hunter"
|
|
249
|
+
assert json.loads(results[1]) == {"value": 3} # magentic's own text of an int
|
|
250
|
+
assert "email-finder, linkedin-profile" in json.loads(results[2])["error"]
|
|
251
|
+
assert CHATS[0]["messages"][0]["content"] == "Who is best for email-finder?"
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def test_prompt_gives_a_function_call_of_each(model):
|
|
255
|
+
@prompt("Use a function for {question}.", functions=datacircle_functions(), model=model)
|
|
256
|
+
def ask(question: str) -> FunctionCall[str]: ...
|
|
257
|
+
|
|
258
|
+
for name, arguments, key in [("datacircle_list_apis", {"query": "email"}, "apis"),
|
|
259
|
+
("datacircle_best_plans", {"slug": "email-finder"}, "plans"),
|
|
260
|
+
("datacircle_search_plans", {"api": "email-finder", "sort": "price"}, "plans"),
|
|
261
|
+
("datacircle_provider", {"slug": "Bright Data"}, "apis")]:
|
|
262
|
+
SCRIPT.append([(name, arguments)])
|
|
263
|
+
call = ask(name)
|
|
264
|
+
assert isinstance(call, FunctionCall) and call.function is FUNCTIONS[name]
|
|
265
|
+
assert json.loads(call())[key]
|
|
266
|
+
assert [path for path, _, _ in SEEN] == ["/v1/apis", "/v1/apis/email-finder/best", "/v1/plans", "/v1/providers/bright-data"]
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def test_parallel_function_call(model):
|
|
270
|
+
SCRIPT.append([("datacircle_best_plans", {"slug": "email-finder"}), ("datacircle_provider", {"slug": "bright-data"}),
|
|
271
|
+
("add_two_numbers", {"a": 2, "b": 2})])
|
|
272
|
+
|
|
273
|
+
@prompt("Look it all up.", functions=[*datacircle_functions(), add_two_numbers], model=model)
|
|
274
|
+
def ask() -> ParallelFunctionCall[str]: ...
|
|
275
|
+
|
|
276
|
+
best, provider, four = ask()()
|
|
277
|
+
assert json.loads(best)["total"] == 1 and json.loads(provider)["slug"] == "bright-data" and four == 4
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def test_chatprompt(model):
|
|
281
|
+
SCRIPT.append([("datacircle_provider", {"slug": "Bright Data"})])
|
|
282
|
+
|
|
283
|
+
@chatprompt(SystemMessage("Use the Datacircle functions."), UserMessage("On which APIs does {provider} rank?"),
|
|
284
|
+
functions=datacircle_functions(), model=model)
|
|
285
|
+
def ranks(provider: str) -> FunctionCall[str]: ...
|
|
286
|
+
|
|
287
|
+
assert json.loads(ranks("Bright Data")())["apis"][0]["rank"] == 7
|
|
288
|
+
assert [message["role"] for message in CHATS[0]["messages"]] == ["system", "user"]
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def test_async_chain_and_parallel_calls_at_once(model):
|
|
292
|
+
@prompt_chain("How many APIs?", functions=datacircle_async_functions(), model=model)
|
|
293
|
+
async def count() -> str: ...
|
|
294
|
+
|
|
295
|
+
@prompt("Look it up three times.", functions=datacircle_async_functions(), model=model)
|
|
296
|
+
async def thrice() -> AsyncParallelFunctionCall[str]: ...
|
|
297
|
+
|
|
298
|
+
async def both(): # one event loop: the model's async client is bound to the first
|
|
299
|
+
SCRIPT.extend([[("datacircle_list_apis", {})], "two APIs"])
|
|
300
|
+
counted = await count()
|
|
301
|
+
SCRIPT.append([("datacircle_best_plans", {"slug": "email-finder"})] * 3)
|
|
302
|
+
call = await thrice()
|
|
303
|
+
SLOW.append(0.5)
|
|
304
|
+
started = time.monotonic()
|
|
305
|
+
results = await call()
|
|
306
|
+
return counted, results, time.monotonic() - started
|
|
307
|
+
|
|
308
|
+
counted, results, took = asyncio.run(both())
|
|
309
|
+
assert counted == "two APIs"
|
|
310
|
+
assert json.loads(tool_messages(CHATS[1])[0]["content"])["total"] == 2
|
|
311
|
+
assert [json.loads(result)["total"] for result in results] == [1, 1, 1]
|
|
312
|
+
assert took < 1.2 # the three GETs ran at once, not 1.5 s one after another
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def test_litellm_chat_model(stand_in):
|
|
316
|
+
from magentic.chat_model.litellm_chat_model import LitellmChatModel
|
|
317
|
+
|
|
318
|
+
SCRIPT.extend([[("datacircle_search_plans", {"query": "hunter", "sort": "score"})], "Starter"])
|
|
319
|
+
|
|
320
|
+
@prompt_chain("Hunter's best plan?", functions=datacircle_functions(),
|
|
321
|
+
model=LitellmChatModel("openai/stand-in", api_base=stand_in))
|
|
322
|
+
def plan() -> str: ...
|
|
323
|
+
|
|
324
|
+
assert plan() == "Starter"
|
|
325
|
+
assert json.loads(tool_messages(CHATS[-1])[0]["content"])["plans"][0]["plan"] == "Starter"
|
|
326
|
+
assert {tool["function"]["name"] for tool in CHATS[0]["tools"]} == set(TOOL_NAMES)
|