marvin-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.
- marvin_datacircle-0.1.0/.gitignore +4 -0
- marvin_datacircle-0.1.0/LICENSE +9 -0
- marvin_datacircle-0.1.0/PKG-INFO +111 -0
- marvin_datacircle-0.1.0/README.md +95 -0
- marvin_datacircle-0.1.0/pyproject.toml +32 -0
- marvin_datacircle-0.1.0/src/marvin_datacircle/__init__.py +17 -0
- marvin_datacircle-0.1.0/src/marvin_datacircle/_api.py +101 -0
- marvin_datacircle-0.1.0/src/marvin_datacircle/py.typed +0 -0
- marvin_datacircle-0.1.0/src/marvin_datacircle/tools.py +169 -0
- marvin_datacircle-0.1.0/tests/conftest.py +170 -0
- marvin_datacircle-0.1.0/tests/test_live.py +40 -0
- marvin_datacircle-0.1.0/tests/test_marvin.py +86 -0
- marvin_datacircle-0.1.0/tests/test_tools.py +81 -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,111 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: marvin-datacircle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Marvin 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/marvin-datacircle
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agents,api,api-pricing,b2b-data,datacircle,gtm,marvin,pydantic-ai,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.11
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# marvin-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 [Marvin](https://github.com/PrefectHQ/marvin) 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. Marvin reads each tool's name, description and arguments from the type hints and the docstring. 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 marvin-datacircle marvin
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
marvin-datacircle works with Marvin 3.2.8 and later, on Python 3.11 and later. marvin-datacircle does not import `marvin`.
|
|
39
|
+
|
|
40
|
+
Marvin uses OpenAI's `gpt-4o` by default. To use another model, set `MARVIN_AGENT_MODEL=anthropic:claude-haiku-5-5`. You can also give one agent a model: `marvin.Agent(model="anthropic:claude-haiku-5-5")`.
|
|
41
|
+
|
|
42
|
+
## Use the tools in a run
|
|
43
|
+
|
|
44
|
+
Give the Datacircle tools to `marvin.run`:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import marvin
|
|
48
|
+
from marvin_datacircle import datacircle_tools
|
|
49
|
+
|
|
50
|
+
print(marvin.run("Who are the 3 best providers for the email-finder API?", tools=datacircle_tools()))
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`marvin.run_async` and `marvin.run_stream` take the same `tools`.
|
|
54
|
+
|
|
55
|
+
## Use the tools in an agent
|
|
56
|
+
|
|
57
|
+
Give the Datacircle tools to an `Agent`. The agent can use the tools on every task:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import marvin
|
|
61
|
+
from marvin_datacircle import datacircle_tools
|
|
62
|
+
|
|
63
|
+
agent = marvin.Agent(name="GTM", tools=datacircle_tools(), instructions="Use the Datacircle tools for questions on GTM APIs.")
|
|
64
|
+
print(agent.run("Which provider is first for the email-finder API, and on which other APIs does it rank?"))
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Use the tools in a task
|
|
68
|
+
|
|
69
|
+
Give the Datacircle tools to a `Task`. Set `result_type` to choose the type of the task's result:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import marvin
|
|
73
|
+
from marvin_datacircle import datacircle_tools
|
|
74
|
+
|
|
75
|
+
task = marvin.Task("Name the 3 best providers for the email-finder API.", result_type=list[str], tools=datacircle_tools())
|
|
76
|
+
print(task.run())
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Use the Datacircle tools beside your own tools
|
|
80
|
+
|
|
81
|
+
Put the Datacircle tools in one list with your own tools: `tools=[*datacircle_tools(), my_tool]`.
|
|
82
|
+
|
|
83
|
+
To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
84
|
+
|
|
85
|
+
## Call a tool yourself
|
|
86
|
+
|
|
87
|
+
You can call each tool without a model. You get the tool's answer as a dict:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
from marvin_datacircle import datacircle_best_plans, run
|
|
91
|
+
|
|
92
|
+
print(datacircle_best_plans("email-finder", limit=3)["plans"])
|
|
93
|
+
print(run("datacircle_provider", {"slug": "Bright Data"}))
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## What the model reads
|
|
97
|
+
|
|
98
|
+
Each tool returns a dict. The model reads the dict as JSON. 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.
|
|
99
|
+
|
|
100
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
101
|
+
|
|
102
|
+
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, so your program keeps running. The model can call the tool again.
|
|
103
|
+
|
|
104
|
+
## Network
|
|
105
|
+
|
|
106
|
+
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.
|
|
107
|
+
|
|
108
|
+
## Links
|
|
109
|
+
|
|
110
|
+
- Datacircle: https://datacircle.dev
|
|
111
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# marvin-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 [Marvin](https://github.com/PrefectHQ/marvin) 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. Marvin reads each tool's name, description and arguments from the type hints and the docstring. 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 marvin-datacircle marvin
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
marvin-datacircle works with Marvin 3.2.8 and later, on Python 3.11 and later. marvin-datacircle does not import `marvin`.
|
|
23
|
+
|
|
24
|
+
Marvin uses OpenAI's `gpt-4o` by default. To use another model, set `MARVIN_AGENT_MODEL=anthropic:claude-haiku-5-5`. You can also give one agent a model: `marvin.Agent(model="anthropic:claude-haiku-5-5")`.
|
|
25
|
+
|
|
26
|
+
## Use the tools in a run
|
|
27
|
+
|
|
28
|
+
Give the Datacircle tools to `marvin.run`:
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
import marvin
|
|
32
|
+
from marvin_datacircle import datacircle_tools
|
|
33
|
+
|
|
34
|
+
print(marvin.run("Who are the 3 best providers for the email-finder API?", tools=datacircle_tools()))
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`marvin.run_async` and `marvin.run_stream` take the same `tools`.
|
|
38
|
+
|
|
39
|
+
## Use the tools in an agent
|
|
40
|
+
|
|
41
|
+
Give the Datacircle tools to an `Agent`. The agent can use the tools on every task:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import marvin
|
|
45
|
+
from marvin_datacircle import datacircle_tools
|
|
46
|
+
|
|
47
|
+
agent = marvin.Agent(name="GTM", tools=datacircle_tools(), instructions="Use the Datacircle tools for questions on GTM APIs.")
|
|
48
|
+
print(agent.run("Which provider is first for the email-finder API, and on which other APIs does it rank?"))
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Use the tools in a task
|
|
52
|
+
|
|
53
|
+
Give the Datacircle tools to a `Task`. Set `result_type` to choose the type of the task's result:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import marvin
|
|
57
|
+
from marvin_datacircle import datacircle_tools
|
|
58
|
+
|
|
59
|
+
task = marvin.Task("Name the 3 best providers for the email-finder API.", result_type=list[str], tools=datacircle_tools())
|
|
60
|
+
print(task.run())
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Use the Datacircle tools beside your own tools
|
|
64
|
+
|
|
65
|
+
Put the Datacircle tools in one list with your own tools: `tools=[*datacircle_tools(), my_tool]`.
|
|
66
|
+
|
|
67
|
+
To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
68
|
+
|
|
69
|
+
## Call a tool yourself
|
|
70
|
+
|
|
71
|
+
You can call each tool without a model. You get the tool's answer as a dict:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
from marvin_datacircle import datacircle_best_plans, run
|
|
75
|
+
|
|
76
|
+
print(datacircle_best_plans("email-finder", limit=3)["plans"])
|
|
77
|
+
print(run("datacircle_provider", {"slug": "Bright Data"}))
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## What the model reads
|
|
81
|
+
|
|
82
|
+
Each tool returns a dict. The model reads the dict as JSON. 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.
|
|
83
|
+
|
|
84
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
85
|
+
|
|
86
|
+
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, so your program keeps running. The model can call the tool again.
|
|
87
|
+
|
|
88
|
+
## Network
|
|
89
|
+
|
|
90
|
+
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.
|
|
91
|
+
|
|
92
|
+
## Links
|
|
93
|
+
|
|
94
|
+
- Datacircle: https://datacircle.dev
|
|
95
|
+
- 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 = "marvin-datacircle"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Marvin tools for the Datacircle API: find the best GTM APIs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = ["marvin", "pydantic-ai", "agents", "tools", "tool-calling", "gtm", "api", "api-pricing", "b2b-data", "datacircle"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Topic :: Software Development :: Libraries",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://datacircle.dev"
|
|
22
|
+
Documentation = "https://api.datacircle.dev/v1/openapi.json"
|
|
23
|
+
Repository = "https://github.com/waynehamadi/marvin-datacircle"
|
|
24
|
+
|
|
25
|
+
[dependency-groups]
|
|
26
|
+
test = ["pytest>=8", "marvin>=3.2"]
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/marvin_datacircle"]
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.sdist]
|
|
32
|
+
include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Tools for Marvin 3 on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
|
|
2
|
+
|
|
3
|
+
from marvin_datacircle._api import BASE_URL, DatacircleError
|
|
4
|
+
from marvin_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 = "marvin-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,169 @@
|
|
|
1
|
+
"""Tools for Marvin 3 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 Google docstring, which Marvin gives to Pydantic AI as it is: its name, the
|
|
4
|
+
description before "Args:", each argument's type from the signature and its description from the docstring, and what
|
|
5
|
+
it gives from "Returns:". Each runs the same way in marvin.run(..., tools=[...]), an Agent(tools=[...]) and a
|
|
6
|
+
Task(tools=[...]), sync or async, beside an app's own tools. A tool makes one HTTPS GET and returns the API's answer as
|
|
7
|
+
a dict, which the model reads as JSON. A refusal (an unknown slug, an argument out of range, the API out of reach) is
|
|
8
|
+
the dict {"error": the API's words}, never an exception: Marvin makes a tool's exception a retry, and a tool that fails
|
|
9
|
+
past its retries ends the whole run.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import urllib.parse
|
|
14
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from marvin_datacircle import _api
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _answer(function: Callable[..., Any], *args: Any) -> dict[str, Any]:
|
|
21
|
+
"""What a tool gives the model: its answer, or {"error": ...} when the API or its checks refused."""
|
|
22
|
+
try:
|
|
23
|
+
return function(*args)
|
|
24
|
+
except _api.DatacircleError as error:
|
|
25
|
+
return {"error": str(error)}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _best(plans: Any) -> dict[str, Any] | None:
|
|
29
|
+
"""A provider's best plan on an API: its lowest rank, a plan with no score having none."""
|
|
30
|
+
ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
|
|
31
|
+
return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _list_apis(query: Any, limit: Any) -> dict[str, Any]:
|
|
35
|
+
count = _api.whole("limit", limit, 1, 200) or 20
|
|
36
|
+
apis = _api.get("/apis")
|
|
37
|
+
words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
|
|
38
|
+
held = []
|
|
39
|
+
for index, api in enumerate(apis):
|
|
40
|
+
name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
|
|
41
|
+
matched = sum(word in name for word in words)
|
|
42
|
+
if matched or not words:
|
|
43
|
+
held.append((-matched, index, api))
|
|
44
|
+
found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
|
|
45
|
+
return {"total": len(found), "apis": found[:count]}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _best_plans(slug: Any, limit: Any) -> dict[str, Any]:
|
|
49
|
+
made = _api.slug(slug)
|
|
50
|
+
if not made:
|
|
51
|
+
raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
|
|
52
|
+
answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
|
|
53
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _search_plans(api: Any, query: Any, sort: Any, limit: Any, offset: Any) -> dict[str, Any]:
|
|
57
|
+
order = str(sort).strip().lower() if sort not in (None, "") else None
|
|
58
|
+
if order is not None and order not in ("score", "provider", "price"):
|
|
59
|
+
raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
|
|
60
|
+
params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
|
|
61
|
+
"offset": _api.whole("offset", offset, 0)}
|
|
62
|
+
answer = _api.get("/plans", params)
|
|
63
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _provider(slug: Any) -> dict[str, Any]:
|
|
67
|
+
made = _api.slug(slug)
|
|
68
|
+
if not made:
|
|
69
|
+
raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
|
|
70
|
+
answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
|
|
71
|
+
apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
|
|
72
|
+
"best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
|
|
73
|
+
return {**answer, "apis": apis}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# The tools. sort is a str, not a Literal: the tool's own check gives the model its words for a value out of the list,
|
|
77
|
+
# where a schema's refusal would cost a retry of Marvin's.
|
|
78
|
+
|
|
79
|
+
def datacircle_list_apis(query: str | None = None, limit: int | None = None) -> dict[str, Any]:
|
|
80
|
+
"""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.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
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.
|
|
84
|
+
limit: How many APIs to give, 1 to 200. 20 when left out, of about 170.
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
dict: total, the APIs found, and apis, a list of up to limit of them, each with api, slug, plans, providers and best. Or {"error": ...} in the API's words.
|
|
88
|
+
"""
|
|
89
|
+
return _answer(_list_apis, query, limit)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def datacircle_best_plans(slug: str, limit: int | None = None) -> dict[str, Any]:
|
|
93
|
+
"""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.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
slug: The API's slug, like 'email-finder' or 'linkedin-profile', as datacircle_list_apis gives it.
|
|
97
|
+
limit: How many plans to give, 1 to 50. 10 when left out.
|
|
98
|
+
|
|
99
|
+
Returns:
|
|
100
|
+
dict: api, slug, total and plans, a list best first, 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.
|
|
101
|
+
"""
|
|
102
|
+
return _answer(_best_plans, slug, limit)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def datacircle_search_plans(api: str | None = None, query: str | None = None, sort: str | None = None,
|
|
106
|
+
limit: int | None = None, offset: int | None = None) -> dict[str, Any]:
|
|
107
|
+
"""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.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
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.
|
|
111
|
+
query: Words that must all appear in the provider's or plan's name, like 'bright data'.
|
|
112
|
+
sort: score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first).
|
|
113
|
+
limit: How many plans to give, 1 to 50. 10 when left out.
|
|
114
|
+
offset: How many found plans to skip first. 0 when left out.
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
dict: total, the plans found, offset and plans, a list of up to limit of them, each with api, 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.
|
|
118
|
+
"""
|
|
119
|
+
return _answer(_search_plans, api, query, sort, limit, offset)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def datacircle_provider(slug: str) -> dict[str, Any]:
|
|
123
|
+
"""Gives each API one provider sells and its rank on each on Datacircle's benchmark (https://datacircle.dev), with its best plan there.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
slug: The provider's slug, like 'bright-data', or its name, like 'Bright Data', which is made a slug.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
dict: provider, slug, website and apis, a list, each with api, slug, rank, plans (how many it has there) and best, its best plan there. Or {"error": ...} in the API's words.
|
|
130
|
+
"""
|
|
131
|
+
return _answer(_provider, slug)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
FUNCTIONS: dict[str, Callable[..., dict[str, Any]]] = {function.__name__: function for function in (
|
|
135
|
+
datacircle_list_apis, datacircle_best_plans, datacircle_search_plans, datacircle_provider)}
|
|
136
|
+
TOOL_NAMES = list(FUNCTIONS)
|
|
137
|
+
_ARGUMENTS = {"datacircle_list_apis": ("query", "limit"), "datacircle_best_plans": ("slug", "limit"),
|
|
138
|
+
"datacircle_search_plans": ("api", "query", "sort", "limit", "offset"),
|
|
139
|
+
"datacircle_provider": ("slug",)}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def datacircle_tools(tool_names: Sequence[str] | None = None) -> list[Callable[..., dict[str, Any]]]:
|
|
143
|
+
"""The tools, for marvin.run(..., tools=datacircle_tools()), Agent(tools=...) or Task(tools=...), or beside one's
|
|
144
|
+
own: tools=[*datacircle_tools(), my_tool]. tool_names keeps some of them only, in their order here; all four when
|
|
145
|
+
left out."""
|
|
146
|
+
if isinstance(tool_names, str):
|
|
147
|
+
raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
|
|
148
|
+
for name in tool_names or []:
|
|
149
|
+
if name not in FUNCTIONS:
|
|
150
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
151
|
+
return [FUNCTIONS[name] for name in (TOOL_NAMES if tool_names is None else tool_names)]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def run(name: str, arguments: Any = None) -> dict[str, Any]:
|
|
155
|
+
"""What a tool gives the model for these arguments: the API's answer, or {"error": its words}. arguments is a
|
|
156
|
+
mapping or its JSON text; the ones the tool doesn't take are left out."""
|
|
157
|
+
if name not in FUNCTIONS:
|
|
158
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
159
|
+
if isinstance(arguments, (str, bytes)):
|
|
160
|
+
try:
|
|
161
|
+
arguments = json.loads(arguments or "{}")
|
|
162
|
+
except ValueError:
|
|
163
|
+
return {"error": f"the arguments are no JSON object: {arguments[:200]!r}"}
|
|
164
|
+
given = arguments if isinstance(arguments, Mapping) else {}
|
|
165
|
+
return FUNCTIONS[name](**{key: given.get(key) for key in _ARGUMENTS[name]})
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
__all__: list[str] = ["FUNCTIONS", "TOOL_NAMES", "datacircle_best_plans", "datacircle_list_apis", "datacircle_provider",
|
|
169
|
+
"datacircle_search_plans", "datacircle_tools", "run"]
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Stand-ins on 127.0.0.1: Datacircle's API, and a model that speaks OpenAI's Chat Completions, plain and streamed, as
|
|
2
|
+
Pydantic AI's OpenAIChatModel calls it for Marvin. The task's instructions hold `CALL <tool> <json arguments>` lines: the
|
|
3
|
+
model asks for one a turn (all at once when state.parallel), in their order, and once every result is in, it ends the
|
|
4
|
+
task with Marvin's MarkTaskSuccessful tool, its result "read: " and each tool result it was given."""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import tempfile
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
13
|
+
from urllib.parse import parse_qs, urlparse
|
|
14
|
+
|
|
15
|
+
import pytest
|
|
16
|
+
|
|
17
|
+
os.environ["NO_PROXY"] = os.environ["no_proxy"] = "127.0.0.1,localhost"
|
|
18
|
+
os.environ.setdefault("MARVIN_HOME_PATH", tempfile.mkdtemp(prefix="marvin-home-"))
|
|
19
|
+
os.environ.setdefault("MARVIN_DATABASE_URL", f"sqlite+aiosqlite:///{os.environ['MARVIN_HOME_PATH']}/marvin.db")
|
|
20
|
+
os.environ.setdefault("MARVIN_ENABLE_DEFAULT_PRINT_HANDLER", "false")
|
|
21
|
+
|
|
22
|
+
from marvin_datacircle import _api # noqa: E402
|
|
23
|
+
|
|
24
|
+
PLAN = {"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1, "perThousand": 4.9,
|
|
25
|
+
"page": "https://datacircle.dev/x", "terms": "long", "aggregators": ["a"]}
|
|
26
|
+
CALLS = ('CALL datacircle_list_apis {"query": "email"}\n'
|
|
27
|
+
'CALL datacircle_best_plans {"slug": "email-finder", "limit": 1}\n'
|
|
28
|
+
'CALL datacircle_search_plans {"api": "email-finder", "sort": "price", "limit": 2}\n'
|
|
29
|
+
'CALL datacircle_provider {"slug": "Bright Data"}\n'
|
|
30
|
+
'CALL add_two_numbers {"a": 1, "b": 2}')
|
|
31
|
+
ASKED = ["/v1/apis", "/v1/apis/email-finder/best", "/v1/plans", "/v1/providers/bright-data"]
|
|
32
|
+
READ = ['"slug":"email-finder"', '"provider":"Hunter"', '"total":1', '"plan":"Pro"', "| 3"]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def add_two_numbers(a: int, b: int) -> int:
|
|
36
|
+
"""Adds two numbers: the app's own tool, beside Datacircle's.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
a: The first number.
|
|
40
|
+
b: The second number.
|
|
41
|
+
"""
|
|
42
|
+
return a + b
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def text(content):
|
|
46
|
+
if isinstance(content, list):
|
|
47
|
+
return " ".join(part.get("text", "") for part in content if isinstance(part, dict))
|
|
48
|
+
return content or ""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class State:
|
|
52
|
+
def __init__(self):
|
|
53
|
+
self.seen, self.busy, self.bodies, self.parallel = [], [], [], False
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _send(handler, status, body, headers=None, content_type="application/json"):
|
|
57
|
+
data = body.encode() if isinstance(body, str) else json.dumps(body).encode()
|
|
58
|
+
handler.send_response(status)
|
|
59
|
+
for key, value in {"Content-Type": content_type, "Content-Length": str(len(data)), **(headers or {})}.items():
|
|
60
|
+
handler.send_header(key, value)
|
|
61
|
+
handler.end_headers()
|
|
62
|
+
handler.wfile.write(data)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _turn(body, state):
|
|
66
|
+
"""The tool calls of this turn: the next CALL lines of the last task, or its end with what the model read since:
|
|
67
|
+
a thread's earlier runs are in the messages too."""
|
|
68
|
+
messages = body.get("messages") or []
|
|
69
|
+
last = max(i for i, m in enumerate(messages) if m.get("role") == "user" and "CALL " in text(m.get("content")))
|
|
70
|
+
found = re.findall(r"CALL (\w+) (\{.*?\})\s*$", text(messages[last].get("content")), re.M)
|
|
71
|
+
calls = [(name, json.loads(arguments)) for name, arguments in found]
|
|
72
|
+
results = [text(m.get("content")) for m in messages[last:] if m.get("role") == "tool"]
|
|
73
|
+
if len(results) < len(calls):
|
|
74
|
+
return calls[len(results):] if state.parallel else [calls[len(results)]]
|
|
75
|
+
end = next(tool["function"]["name"] for tool in body["tools"] if tool["function"]["name"].startswith("MarkTaskSuccessful"))
|
|
76
|
+
return [(end, {"result": "read: " + " | ".join(results)})]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _chat(handler, body, state):
|
|
80
|
+
"""OpenAI's /v1/chat/completions: this turn's tool calls, whole or streamed in chunks as OpenAI streams them."""
|
|
81
|
+
rid, now = f"{len(state.bodies)}", int(time.time())
|
|
82
|
+
calls = [{"id": f"call_{rid}_{i}", "type": "function", "function": {"name": name, "arguments": json.dumps(arguments)}}
|
|
83
|
+
for i, (name, arguments) in enumerate(_turn(body, state))]
|
|
84
|
+
if not body.get("stream"):
|
|
85
|
+
return _send(handler, 200, {"id": "chatcmpl-" + rid, "object": "chat.completion", "created": now, "model": body["model"],
|
|
86
|
+
"choices": [{"index": 0, "message": {"role": "assistant", "content": None, "tool_calls": calls},
|
|
87
|
+
"finish_reason": "tool_calls"}],
|
|
88
|
+
"usage": {"prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10}})
|
|
89
|
+
|
|
90
|
+
def chunk(delta, finish=None):
|
|
91
|
+
return "data: " + json.dumps({"id": "chatcmpl-" + rid, "object": "chat.completion.chunk", "created": now, "model": body["model"],
|
|
92
|
+
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}) + "\n\n"
|
|
93
|
+
events = [chunk({"role": "assistant", "content": None})]
|
|
94
|
+
for i, call in enumerate(calls):
|
|
95
|
+
events.append(chunk({"tool_calls": [{"index": i, "id": call["id"], "type": "function",
|
|
96
|
+
"function": {"name": call["function"]["name"], "arguments": ""}}]}))
|
|
97
|
+
arguments = call["function"]["arguments"]
|
|
98
|
+
for piece in (arguments[:10], arguments[10:]):
|
|
99
|
+
events.append(chunk({"tool_calls": [{"index": i, "function": {"arguments": piece}}]}))
|
|
100
|
+
events.append(chunk({}, "tool_calls"))
|
|
101
|
+
_send(handler, 200, "".join(events) + "data: [DONE]\n\n", content_type="text/event-stream")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _handler(state):
|
|
105
|
+
class Handler(BaseHTTPRequestHandler):
|
|
106
|
+
def log_message(self, *args):
|
|
107
|
+
pass
|
|
108
|
+
|
|
109
|
+
def do_POST(self):
|
|
110
|
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
|
|
111
|
+
path = urlparse(self.path).path
|
|
112
|
+
state.bodies.append((path, body))
|
|
113
|
+
if path.endswith("/chat/completions"):
|
|
114
|
+
_chat(self, body, state)
|
|
115
|
+
else:
|
|
116
|
+
_send(self, 404, {"error": f"no {path}"})
|
|
117
|
+
|
|
118
|
+
def do_GET(self):
|
|
119
|
+
url = urlparse(self.path)
|
|
120
|
+
query = {key: values[0] for key, values in parse_qs(url.query).items()}
|
|
121
|
+
state.seen.append((url.path, query, self.headers.get("User-Agent")))
|
|
122
|
+
headers = {}
|
|
123
|
+
if url.path == "/v1/plans" and query.get("query") == "busy" and not state.busy:
|
|
124
|
+
state.busy.append(1)
|
|
125
|
+
status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
126
|
+
elif url.path == "/v1/plans" and query.get("query") == "always-busy":
|
|
127
|
+
status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
128
|
+
elif url.path == "/v1/apis":
|
|
129
|
+
status, body = 200, [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3, "extra": 1},
|
|
130
|
+
{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]
|
|
131
|
+
elif url.path == "/v1/apis/email-finder/best":
|
|
132
|
+
status, body = 200, {"api": "Employee email", "slug": "email-finder", "total": 1, "plans": [PLAN]}
|
|
133
|
+
elif url.path.startswith("/v1/apis/"):
|
|
134
|
+
status, body = 404, {"error": "no API has the slug nope", "slugs": ["email-finder", "linkedin-profile"]}
|
|
135
|
+
elif url.path == "/v1/plans" and query.get("query") == "down":
|
|
136
|
+
status, body = 503, {"error": "down for a minute"}
|
|
137
|
+
elif url.path == "/v1/plans":
|
|
138
|
+
status, body = 200, {"total": 1, "offset": 0, "plans": [PLAN]}
|
|
139
|
+
elif url.path == "/v1/providers/bright-data":
|
|
140
|
+
status, body = 200, {"provider": "Bright Data", "slug": "bright-data",
|
|
141
|
+
"apis": [{"api": "Employee email", "slug": "email-finder", "rank": 7, "bestPage": "b",
|
|
142
|
+
"plans": [{**PLAN, "rank": 9}, {**PLAN, "rank": 7, "plan": "Pro"}]}]}
|
|
143
|
+
else:
|
|
144
|
+
status, body = 404, {"error": "no provider has the slug nope"}
|
|
145
|
+
_send(self, status, body, headers)
|
|
146
|
+
return Handler
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@pytest.fixture()
|
|
150
|
+
def stub(monkeypatch):
|
|
151
|
+
state = State()
|
|
152
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), _handler(state))
|
|
153
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
154
|
+
state.url = f"http://127.0.0.1:{server.server_address[1]}"
|
|
155
|
+
monkeypatch.setattr(_api, "BASE_URL", state.url + "/v1")
|
|
156
|
+
yield state
|
|
157
|
+
server.shutdown()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@pytest.fixture()
|
|
161
|
+
def model(stub):
|
|
162
|
+
"""Pydantic AI's OpenAI Chat Completions model on the stand-in, Marvin's default model while a test runs."""
|
|
163
|
+
import marvin
|
|
164
|
+
from pydantic_ai.models.openai import OpenAIChatModel
|
|
165
|
+
from pydantic_ai.providers.openai import OpenAIProvider
|
|
166
|
+
|
|
167
|
+
made = OpenAIChatModel("scripted", provider=OpenAIProvider(base_url=stub.url + "/v1", api_key="none"))
|
|
168
|
+
was, marvin.defaults.model = marvin.defaults.model, made
|
|
169
|
+
yield made
|
|
170
|
+
marvin.defaults.model = was
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Each tool on the live API, https://api.datacircle.dev/v1, and through a Marvin run on the stand-in model: run with
|
|
2
|
+
DATACIRCLE_LIVE=1."""
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
import marvin
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from marvin_datacircle import _api, datacircle_tools, run
|
|
10
|
+
|
|
11
|
+
pytestmark = pytest.mark.skipif(os.environ.get("DATACIRCLE_LIVE") != "1", reason="DATACIRCLE_LIVE=1 calls the live API")
|
|
12
|
+
LIVE = "https://api.datacircle.dev/v1"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_live(monkeypatch):
|
|
16
|
+
monkeypatch.setattr(_api, "BASE_URL", LIVE)
|
|
17
|
+
apis = run("datacircle_list_apis", {"query": "email finder", "limit": 3})
|
|
18
|
+
assert apis["total"] >= 1 and apis["apis"][0]["slug"] and len(apis["apis"]) <= 3
|
|
19
|
+
assert run("datacircle_list_apis", {"limit": 200})["total"] >= 150
|
|
20
|
+
best = run("datacircle_best_plans", {"slug": "email-finder", "limit": 3})
|
|
21
|
+
assert 1 <= len(best["plans"]) <= 3 and all(plan["provider"] and plan.get("page") for plan in best["plans"])
|
|
22
|
+
plans = run("datacircle_search_plans", {"api": "email-finder", "sort": "price", "limit": 2})
|
|
23
|
+
assert plans["total"] >= 1 and len(plans["plans"]) <= 2
|
|
24
|
+
slug = _api.slug(best["plans"][0]["provider"])
|
|
25
|
+
provider = run("datacircle_provider", {"slug": best["plans"][0]["provider"]})
|
|
26
|
+
assert provider["slug"] == slug and provider["apis"] and "plans" in provider["apis"][0]
|
|
27
|
+
refused = run("datacircle_best_plans", {"slug": "no-such-api"})
|
|
28
|
+
assert "answered 404" in refused["error"] and "email-finder" in refused["error"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_live_through_marvin(stub, model, monkeypatch):
|
|
32
|
+
"""The stand-in model asks for each tool; the tools call the live API."""
|
|
33
|
+
monkeypatch.setattr(_api, "BASE_URL", LIVE)
|
|
34
|
+
answer = marvin.run('Who is best for email-finder?\n'
|
|
35
|
+
'CALL datacircle_list_apis {"query": "email finder", "limit": 2}\n'
|
|
36
|
+
'CALL datacircle_best_plans {"slug": "email-finder", "limit": 2}\n'
|
|
37
|
+
'CALL datacircle_search_plans {"api": "email-finder", "sort": "price", "limit": 2}\n'
|
|
38
|
+
'CALL datacircle_provider {"slug": "hunter"}', tools=datacircle_tools())
|
|
39
|
+
assert '"slug":"email-finder"' in answer and '"rank":1' in answer and '"slug":"hunter"' in answer
|
|
40
|
+
assert "error" not in answer
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Offline tests through Marvin itself, on the stand-in model and API (conftest.py): marvin.run and run_async, an Agent's
|
|
2
|
+
own tools, a Task's tools, a thread of two runs, run_stream's events, each beside an app's own tool, the tool calls one a
|
|
3
|
+
turn and all at once, and refusals the run goes on after."""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
|
|
8
|
+
import marvin
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from conftest import ASKED, CALLS, READ, add_two_numbers
|
|
12
|
+
from marvin_datacircle import TOOL_NAMES, datacircle_tools
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def asked(stub):
|
|
16
|
+
return [path for path, _, _ in stub.seen]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def sent_tools(stub):
|
|
20
|
+
return [tool["function"]["name"] for tool in stub.bodies[0][1]["tools"]]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def read_all(answer):
|
|
24
|
+
for words in READ:
|
|
25
|
+
assert words in answer, (words, answer)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@pytest.mark.parametrize("parallel", [False, True])
|
|
29
|
+
def test_run(stub, model, parallel):
|
|
30
|
+
stub.parallel = parallel
|
|
31
|
+
answer = marvin.run(f"Who are the 3 best providers for the email-finder API?\n{CALLS}",
|
|
32
|
+
tools=[*datacircle_tools(), add_two_numbers])
|
|
33
|
+
read_all(answer)
|
|
34
|
+
assert (sorted(asked(stub)) == sorted(ASKED)) if parallel else asked(stub) == ASKED # all at once run at once
|
|
35
|
+
assert set(TOOL_NAMES) | {"add_two_numbers"} <= set(sent_tools(stub))
|
|
36
|
+
assert len(stub.bodies) == (2 if parallel else 6)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_run_async(stub, model):
|
|
40
|
+
answer = asyncio.run(marvin.run_async(f"Who is best for email-finder?\n{CALLS}", tools=[*datacircle_tools(), add_two_numbers]))
|
|
41
|
+
read_all(answer)
|
|
42
|
+
assert asked(stub) == ASKED
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_agent_tools(stub, model):
|
|
46
|
+
agent = marvin.Agent(name="GTM", model=model, tools=[*datacircle_tools(), add_two_numbers],
|
|
47
|
+
instructions="Use the Datacircle tools for GTM APIs.")
|
|
48
|
+
read_all(agent.run(f"Who is best for email-finder?\n{CALLS}"))
|
|
49
|
+
assert asked(stub) == ASKED
|
|
50
|
+
assert "Use the Datacircle tools" in json.dumps(stub.bodies[0][1]["messages"])
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_task_tools(stub, model):
|
|
54
|
+
task = marvin.Task(f"Who is best for email-finder?\n{CALLS}", result_type=str, tools=[*datacircle_tools(), add_two_numbers])
|
|
55
|
+
read_all(task.run())
|
|
56
|
+
assert task.is_successful() and asked(stub) == ASKED
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_some_tools_and_a_thread(stub, model):
|
|
60
|
+
with marvin.Thread() as thread:
|
|
61
|
+
first = marvin.run('Best for email-finder?\nCALL datacircle_best_plans {"slug": "email-finder", "limit": 1}',
|
|
62
|
+
tools=datacircle_tools(["datacircle_best_plans"]), thread=thread)
|
|
63
|
+
second = marvin.run('And Bright Data?\nCALL datacircle_provider {"slug": "Bright Data"}',
|
|
64
|
+
tools=datacircle_tools(["datacircle_provider"]), thread=thread)
|
|
65
|
+
assert '"provider":"Hunter"' in first and '"plan":"Pro"' in second
|
|
66
|
+
assert "datacircle_list_apis" not in sent_tools(stub)
|
|
67
|
+
assert asked(stub) == ["/v1/apis/email-finder/best", "/v1/providers/bright-data"]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_run_stream(stub, model):
|
|
71
|
+
async def events():
|
|
72
|
+
return [event async for event in marvin.run_stream(f"Who is best for email-finder?\n{CALLS}",
|
|
73
|
+
tools=[*datacircle_tools(), add_two_numbers])]
|
|
74
|
+
kinds = [type(event).__name__ for event in asyncio.run(events())]
|
|
75
|
+
assert "ToolCallEvent" in kinds or "ToolResultEvent" in kinds, kinds
|
|
76
|
+
assert asked(stub) == ASKED
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_refusals_and_the_run_goes_on(stub, model):
|
|
80
|
+
answer = marvin.run('Who is best for nope?\n'
|
|
81
|
+
'CALL datacircle_best_plans {"slug": "nope"}\n'
|
|
82
|
+
'CALL datacircle_search_plans {"limit": 99}\n'
|
|
83
|
+
'CALL datacircle_provider {"slug": "Bright Data"}',
|
|
84
|
+
tools=datacircle_tools())
|
|
85
|
+
assert "the slugs: email-finder, linkedin-profile" in answer and "limit must be from 1 to 50" in answer
|
|
86
|
+
assert '"plan":"Pro"' in answer # the run went on after both
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Offline tests of the tools alone, on the stand-in API (conftest.py): the tool definitions Pydantic AI makes of them
|
|
2
|
+
through Marvin's own wrapping, every call, its cut, every refusal."""
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
import marvin
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
import marvin_datacircle
|
|
11
|
+
from marvin_datacircle import TOOL_NAMES, datacircle_tools, run
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def definitions(tools):
|
|
15
|
+
"""Each tool's definition as Marvin hands it to Pydantic AI: Agent.get_agentlet, as a run builds it."""
|
|
16
|
+
agentlet = asyncio.run(marvin.Agent(model="test").get_agentlet(tools=tools, end_turn_tools=[]))
|
|
17
|
+
found = {}
|
|
18
|
+
for toolset in agentlet.toolsets:
|
|
19
|
+
found.update({name: tool.tool_def for name, tool in getattr(toolset, "tools", {}).items()})
|
|
20
|
+
return found
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_tools_as_marvin_makes_them():
|
|
24
|
+
tools = definitions(datacircle_tools())
|
|
25
|
+
assert set(TOOL_NAMES) <= set(tools)
|
|
26
|
+
for name in TOOL_NAMES:
|
|
27
|
+
tool = tools[name]
|
|
28
|
+
assert "https://datacircle.dev" in tool.description and "{\"error\": ...}" in tool.description
|
|
29
|
+
assert "Args:" not in tool.description and "Returns:" not in tool.description
|
|
30
|
+
assert all(spec.get("description") for spec in tool.parameters_json_schema["properties"].values())
|
|
31
|
+
best = tools["datacircle_best_plans"].parameters_json_schema
|
|
32
|
+
assert list(best["properties"]) == ["slug", "limit"] and best["required"] == ["slug"]
|
|
33
|
+
assert best["properties"]["slug"]["type"] == "string"
|
|
34
|
+
search = tools["datacircle_search_plans"].parameters_json_schema
|
|
35
|
+
assert list(search["properties"]) == ["api", "query", "sort", "limit", "offset"] and not search.get("required")
|
|
36
|
+
assert [f.__name__ for f in datacircle_tools(["datacircle_provider"])] == ["datacircle_provider"]
|
|
37
|
+
with pytest.raises(ValueError, match="no tool 'nope'"):
|
|
38
|
+
datacircle_tools(["nope"])
|
|
39
|
+
with pytest.raises(TypeError):
|
|
40
|
+
datacircle_tools("datacircle_provider")
|
|
41
|
+
assert marvin_datacircle.__version__ == "0.1.0"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_each_tool(stub):
|
|
45
|
+
apis = run("datacircle_list_apis", {"query": "email"})
|
|
46
|
+
assert apis == {"total": 1, "apis": [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3}]}
|
|
47
|
+
assert run("datacircle_list_apis", "{}")["total"] == 2
|
|
48
|
+
best = run("datacircle_best_plans", '{"slug": "Email Finder", "limit": "1"}')
|
|
49
|
+
assert best["plans"] == [{"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1,
|
|
50
|
+
"perThousand": 4.9, "page": "https://datacircle.dev/x"}]
|
|
51
|
+
assert stub.seen[-1] == ("/v1/apis/email-finder/best", {"limit": "1"}, "marvin-datacircle/0.1.0")
|
|
52
|
+
plans = run("datacircle_search_plans", {"api": "email-finder", "sort": "Price", "limit": 5, "offset": 0})
|
|
53
|
+
assert plans["total"] == 1
|
|
54
|
+
assert stub.seen[-1][1] == {"api": "email-finder", "sort": "price", "limit": "5", "offset": "0"}
|
|
55
|
+
provider = run("datacircle_provider", {"slug": "Bright Data", "unknown": 1})
|
|
56
|
+
assert provider["apis"][0]["best"]["plan"] == "Pro" and provider["apis"][0]["plans"] == 2
|
|
57
|
+
json.dumps(provider)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_refusals(stub):
|
|
61
|
+
assert "the slugs: email-finder, linkedin-profile" in run("datacircle_best_plans", {"slug": "nope"})["error"]
|
|
62
|
+
assert "Give an API's slug" in run("datacircle_best_plans", {})["error"]
|
|
63
|
+
assert "limit must be from 1 to 50" in run("datacircle_best_plans", {"slug": "x", "limit": 99})["error"]
|
|
64
|
+
assert "whole number" in run("datacircle_search_plans", {"limit": 2.5})["error"]
|
|
65
|
+
assert "sort must be" in run("datacircle_search_plans", {"sort": "cheap"})["error"]
|
|
66
|
+
assert "answered 503: down for a minute" in run("datacircle_search_plans", {"query": "down"})["error"]
|
|
67
|
+
assert "no JSON object" in run("datacircle_provider", "{not json")["error"]
|
|
68
|
+
assert "Give a provider's slug" in run("datacircle_provider", "[1]")["error"]
|
|
69
|
+
assert "no provider" in run("datacircle_provider", {"slug": "nope"})["error"]
|
|
70
|
+
with pytest.raises(ValueError):
|
|
71
|
+
run("nope", {})
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_one_wait_on_429(stub):
|
|
75
|
+
assert run("datacircle_search_plans", {"query": "busy"})["total"] == 1
|
|
76
|
+
assert "429 twice" in run("datacircle_search_plans", {"query": "always-busy"})["error"]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_out_of_reach(monkeypatch):
|
|
80
|
+
monkeypatch.setattr(marvin_datacircle._api, "BASE_URL", "http://127.0.0.1:9/v1")
|
|
81
|
+
assert "could not be reached" in run("datacircle_list_apis")["error"]
|