txtai-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.
- txtai_datacircle-0.1.0/.gitignore +4 -0
- txtai_datacircle-0.1.0/LICENSE +9 -0
- txtai_datacircle-0.1.0/PKG-INFO +119 -0
- txtai_datacircle-0.1.0/README.md +103 -0
- txtai_datacircle-0.1.0/pyproject.toml +32 -0
- txtai_datacircle-0.1.0/src/txtai_datacircle/__init__.py +17 -0
- txtai_datacircle-0.1.0/src/txtai_datacircle/_api.py +101 -0
- txtai_datacircle-0.1.0/src/txtai_datacircle/py.typed +0 -0
- txtai_datacircle-0.1.0/src/txtai_datacircle/tools.py +185 -0
- txtai_datacircle-0.1.0/tests/conftest.py +158 -0
- txtai_datacircle-0.1.0/tests/test_live.py +28 -0
- txtai_datacircle-0.1.0/tests/test_tools.py +70 -0
- txtai_datacircle-0.1.0/tests/test_txtai.py +126 -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,119 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: txtai-datacircle
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: txtai agent 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/txtai-datacircle
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agents,api,api-pricing,b2b-data,datacircle,gtm,smolagents,tool-calling,tools,txtai
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# txtai-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 [txtai](https://github.com/neuml/txtai) agents 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. txtai 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 txtai-datacircle "txtai[agent]" litellm
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
txtai-datacircle works with txtai 9.2 and later, on Python 3.10 and later. txtai-datacircle does not import `txtai`. You need `litellm` only for LiteLLM models, such as `anthropic/claude-haiku-5-5`.
|
|
39
|
+
|
|
40
|
+
## Use the tools in an agent
|
|
41
|
+
|
|
42
|
+
Give the tools to an `Agent`:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from txtai import Agent
|
|
46
|
+
from txtai_datacircle import datacircle_tools
|
|
47
|
+
|
|
48
|
+
agent = Agent(model="anthropic/claude-haiku-5-5", tools=datacircle_tools(), max_steps=8)
|
|
49
|
+
print(agent("Who are the 3 best providers for the email-finder API?"))
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The agent calls the tools with each step's arguments as JSON. Set `method="code"` and the agent writes Python that calls the tools as functions. Each tool returns a dict. The agent's code can read the dict's keys:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from txtai import Agent
|
|
56
|
+
from txtai_datacircle import datacircle_tools
|
|
57
|
+
|
|
58
|
+
agent = Agent(model="anthropic/claude-haiku-5-5", tools=datacircle_tools(), method="code", max_steps=8)
|
|
59
|
+
print(agent("Which provider is first for the email-finder API, and on which other APIs does it rank?"))
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Use the Datacircle tools beside your own tools
|
|
63
|
+
|
|
64
|
+
Put the Datacircle tools in one list with your own tools and txtai's tools: `tools=[*datacircle_tools(), my_tool, "websearch"]`.
|
|
65
|
+
|
|
66
|
+
To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
67
|
+
|
|
68
|
+
## Use the tools in a txtai app
|
|
69
|
+
|
|
70
|
+
In a txtai app's YAML file, name each tool by the tool's import path:
|
|
71
|
+
|
|
72
|
+
```yaml
|
|
73
|
+
llm:
|
|
74
|
+
path: anthropic/claude-haiku-5-5
|
|
75
|
+
|
|
76
|
+
agent:
|
|
77
|
+
gtm:
|
|
78
|
+
max_steps: 8
|
|
79
|
+
tools:
|
|
80
|
+
- target: txtai_datacircle.datacircle_list_apis
|
|
81
|
+
- target: txtai_datacircle.datacircle_best_plans
|
|
82
|
+
- target: txtai_datacircle.datacircle_search_plans
|
|
83
|
+
- target: txtai_datacircle.datacircle_provider
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Then run the agent with `Application("app.yml").agent("gtm", "Who is best for the email-finder API?")`. Or serve the app with txtai's API: `CONFIG=app.yml uvicorn "txtai.api:app"`. Then post to `/agent`:
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
curl -X POST http://localhost:8000/agent -H "Content-Type: application/json" \
|
|
90
|
+
-d '{"name": "gtm", "text": "Who is best for the email-finder API?"}'
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Call a tool yourself
|
|
94
|
+
|
|
95
|
+
You can call each tool without a model. You get the tool's answer as a dict:
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
from txtai_datacircle import datacircle_best_plans, run
|
|
99
|
+
|
|
100
|
+
print(datacircle_best_plans("email-finder", limit=3)["plans"])
|
|
101
|
+
print(run("datacircle_provider", {"slug": "Bright Data"}))
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## What the model reads
|
|
105
|
+
|
|
106
|
+
Each tool returns a dict. 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.
|
|
107
|
+
|
|
108
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
109
|
+
|
|
110
|
+
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. The agent keeps running. The model can call the tool again.
|
|
111
|
+
|
|
112
|
+
## Network
|
|
113
|
+
|
|
114
|
+
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.
|
|
115
|
+
|
|
116
|
+
## Links
|
|
117
|
+
|
|
118
|
+
- Datacircle: https://datacircle.dev
|
|
119
|
+
- The API's spec: https://api.datacircle.dev/v1/openapi.json
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# txtai-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 [txtai](https://github.com/neuml/txtai) agents 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. txtai 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 txtai-datacircle "txtai[agent]" litellm
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
txtai-datacircle works with txtai 9.2 and later, on Python 3.10 and later. txtai-datacircle does not import `txtai`. You need `litellm` only for LiteLLM models, such as `anthropic/claude-haiku-5-5`.
|
|
23
|
+
|
|
24
|
+
## Use the tools in an agent
|
|
25
|
+
|
|
26
|
+
Give the tools to an `Agent`:
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from txtai import Agent
|
|
30
|
+
from txtai_datacircle import datacircle_tools
|
|
31
|
+
|
|
32
|
+
agent = Agent(model="anthropic/claude-haiku-5-5", tools=datacircle_tools(), max_steps=8)
|
|
33
|
+
print(agent("Who are the 3 best providers for the email-finder API?"))
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The agent calls the tools with each step's arguments as JSON. Set `method="code"` and the agent writes Python that calls the tools as functions. Each tool returns a dict. The agent's code can read the dict's keys:
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from txtai import Agent
|
|
40
|
+
from txtai_datacircle import datacircle_tools
|
|
41
|
+
|
|
42
|
+
agent = Agent(model="anthropic/claude-haiku-5-5", tools=datacircle_tools(), method="code", max_steps=8)
|
|
43
|
+
print(agent("Which provider is first for the email-finder API, and on which other APIs does it rank?"))
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Use the Datacircle tools beside your own tools
|
|
47
|
+
|
|
48
|
+
Put the Datacircle tools in one list with your own tools and txtai's tools: `tools=[*datacircle_tools(), my_tool, "websearch"]`.
|
|
49
|
+
|
|
50
|
+
To give the model only some of the tools, list their names: `datacircle_tools(["datacircle_best_plans"])`.
|
|
51
|
+
|
|
52
|
+
## Use the tools in a txtai app
|
|
53
|
+
|
|
54
|
+
In a txtai app's YAML file, name each tool by the tool's import path:
|
|
55
|
+
|
|
56
|
+
```yaml
|
|
57
|
+
llm:
|
|
58
|
+
path: anthropic/claude-haiku-5-5
|
|
59
|
+
|
|
60
|
+
agent:
|
|
61
|
+
gtm:
|
|
62
|
+
max_steps: 8
|
|
63
|
+
tools:
|
|
64
|
+
- target: txtai_datacircle.datacircle_list_apis
|
|
65
|
+
- target: txtai_datacircle.datacircle_best_plans
|
|
66
|
+
- target: txtai_datacircle.datacircle_search_plans
|
|
67
|
+
- target: txtai_datacircle.datacircle_provider
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Then run the agent with `Application("app.yml").agent("gtm", "Who is best for the email-finder API?")`. Or serve the app with txtai's API: `CONFIG=app.yml uvicorn "txtai.api:app"`. Then post to `/agent`:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
curl -X POST http://localhost:8000/agent -H "Content-Type: application/json" \
|
|
74
|
+
-d '{"name": "gtm", "text": "Who is best for the email-finder API?"}'
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Call a tool yourself
|
|
78
|
+
|
|
79
|
+
You can call each tool without a model. You get the tool's answer as a dict:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from txtai_datacircle import datacircle_best_plans, run
|
|
83
|
+
|
|
84
|
+
print(datacircle_best_plans("email-finder", limit=3)["plans"])
|
|
85
|
+
print(run("datacircle_provider", {"slug": "Bright Data"}))
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## What the model reads
|
|
89
|
+
|
|
90
|
+
Each tool returns a dict. 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.
|
|
91
|
+
|
|
92
|
+
You can give a provider's name in place of a slug. The tool turns `Bright Data` into `bright-data`.
|
|
93
|
+
|
|
94
|
+
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. The agent keeps running. The model can call the tool again.
|
|
95
|
+
|
|
96
|
+
## Network
|
|
97
|
+
|
|
98
|
+
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.
|
|
99
|
+
|
|
100
|
+
## Links
|
|
101
|
+
|
|
102
|
+
- Datacircle: https://datacircle.dev
|
|
103
|
+
- 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 = "txtai-datacircle"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "txtai agent tools for the Datacircle API: find the best GTM APIs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = ["txtai", "smolagents", "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/txtai-datacircle"
|
|
24
|
+
|
|
25
|
+
[dependency-groups]
|
|
26
|
+
test = ["pytest>=8", "txtai[agent,api]>=9.0", "litellm", "openai"]
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/txtai_datacircle"]
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.sdist]
|
|
32
|
+
include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Tools for txtai's Agent on Datacircle's open API (https://api.datacircle.dev/v1): find the best GTM APIs, no key."""
|
|
2
|
+
|
|
3
|
+
from txtai_datacircle._api import BASE_URL, DatacircleError
|
|
4
|
+
from txtai_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 = "txtai-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
|
+
"""Tools for txtai's Agent on Datacircle's open API, https://api.datacircle.dev/v1: no key, no account.
|
|
2
|
+
|
|
3
|
+
Each tool is a plain typed function with a docstring. txtai turns each function in Agent(tools=[...]) into a smolagents
|
|
4
|
+
tool (smolagents.tool): its name, the description before "Args:", each argument's type from the signature and its
|
|
5
|
+
description from the docstring. Each runs the same way in a tool-calling agent (the default, the model's JSON action),
|
|
6
|
+
a code agent (method="code", the model's Python calling it in smolagents' interpreter) and an agent of a txtai app's
|
|
7
|
+
YAML config, each tool there a {target: txtai_datacircle.datacircle_best_plans}. A tool makes one HTTPS GET and returns
|
|
8
|
+
the API's answer as a dict: a code agent reads its keys, a tool-calling agent gives the model its text. A refusal (an
|
|
9
|
+
unknown slug, an argument out of range, the API out of reach) is the dict {"error": the API's words}, never an
|
|
10
|
+
exception: the model can call again and the agent goes on.
|
|
11
|
+
|
|
12
|
+
No `from __future__ import annotations` here: smolagents reads each argument's type from the signature's own types,
|
|
13
|
+
and an optional argument is Optional[...] = None, which it makes nullable.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import urllib.parse
|
|
18
|
+
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence
|
|
19
|
+
|
|
20
|
+
from txtai_datacircle import _api
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _answer(function: Callable[..., Any], *args: Any) -> Dict[str, Any]:
|
|
24
|
+
"""What a tool gives the model: its answer, or {"error": ...} when the API or its checks refused."""
|
|
25
|
+
try:
|
|
26
|
+
return function(*args)
|
|
27
|
+
except _api.DatacircleError as error:
|
|
28
|
+
return {"error": str(error)}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _best(plans: Any) -> Optional[Dict[str, Any]]:
|
|
32
|
+
"""A provider's best plan on an API: its lowest rank, a plan with no score having none."""
|
|
33
|
+
ranked = sorted(plans, key=lambda plan: plan.get("rank") if isinstance(plan.get("rank"), (int, float)) else float("inf"))
|
|
34
|
+
return _api.brief(ranked[0], ["plan", "score", "perThousand", "page"]) if ranked else None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _list_apis(query: Any, limit: Any) -> Dict[str, Any]:
|
|
38
|
+
count = _api.whole("limit", limit, 1, 200) or 20
|
|
39
|
+
apis = _api.get("/apis")
|
|
40
|
+
words = [word for word in str(query or "").lower().replace("-", " ").split() if word]
|
|
41
|
+
held = []
|
|
42
|
+
for index, api in enumerate(apis):
|
|
43
|
+
name = f"{api.get('api', '')} {str(api.get('slug', '')).replace('-', ' ')}".lower()
|
|
44
|
+
matched = sum(word in name for word in words)
|
|
45
|
+
if matched or not words:
|
|
46
|
+
held.append((-matched, index, api))
|
|
47
|
+
found = [_api.brief(api, _api.API_KEYS) for _, _, api in sorted(held, key=lambda h: h[:2])]
|
|
48
|
+
return {"total": len(found), "apis": found[:count]}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _best_plans(slug: Any, limit: Any) -> Dict[str, Any]:
|
|
52
|
+
made = _api.slug(slug)
|
|
53
|
+
if not made:
|
|
54
|
+
raise _api.DatacircleError("Give an API's slug, like 'email-finder': datacircle_list_apis gives every slug")
|
|
55
|
+
answer = _api.get(f"/apis/{urllib.parse.quote(made)}/best", {"limit": _api.whole("limit", limit, 1, 50)})
|
|
56
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _search_plans(api: Any, query: Any, sort: Any, limit: Any, offset: Any) -> Dict[str, Any]:
|
|
60
|
+
order = str(sort).strip().lower() if sort not in (None, "") else None
|
|
61
|
+
if order is not None and order not in ("score", "provider", "price"):
|
|
62
|
+
raise _api.DatacircleError(f"sort must be score, provider or price, not {sort!r}")
|
|
63
|
+
params = {"api": api, "query": query, "sort": order, "limit": _api.whole("limit", limit, 1, 50),
|
|
64
|
+
"offset": _api.whole("offset", offset, 0)}
|
|
65
|
+
answer = _api.get("/plans", params)
|
|
66
|
+
return {**answer, "plans": [_api.brief(plan) for plan in answer.get("plans") or []]}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _provider(slug: Any) -> Dict[str, Any]:
|
|
70
|
+
made = _api.slug(slug)
|
|
71
|
+
if not made:
|
|
72
|
+
raise _api.DatacircleError("Give a provider's slug or name, like 'bright-data' or 'Bright Data'")
|
|
73
|
+
answer = _api.get(f"/providers/{urllib.parse.quote(made)}")
|
|
74
|
+
apis = [{**_api.brief(entry, ["api", "slug", "rank", "bestPage"]), "plans": len(entry.get("plans") or []),
|
|
75
|
+
"best": _best(entry.get("plans") or [])} for entry in answer.get("apis") or []]
|
|
76
|
+
return {**answer, "apis": apis}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# The tools. smolagents takes a docstring's text before "Args:" as the description and leaves out its "Returns:". sort
|
|
80
|
+
# is a str, not a Literal: the tool's own check gives the model its words for a value out of the list.
|
|
81
|
+
|
|
82
|
+
def datacircle_list_apis(query: Optional[str] = None, limit: Optional[int] = None) -> Dict[str, Any]:
|
|
83
|
+
"""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.
|
|
84
|
+
|
|
85
|
+
Gives a dict: total, the APIs found, and apis, a list of up to limit of them, each with api, slug, plans, providers
|
|
86
|
+
and best.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
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.
|
|
90
|
+
limit: How many APIs to give, 1 to 200. 20 when left out, of about 170.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
The API's answer, or {"error": ...} in its words.
|
|
94
|
+
"""
|
|
95
|
+
return _answer(_list_apis, query, limit)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def datacircle_best_plans(slug: str, limit: Optional[int] = None) -> Dict[str, Any]:
|
|
99
|
+
"""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.
|
|
100
|
+
|
|
101
|
+
Gives a dict: api, slug, total and plans, a list best first, each with rank, provider, plan, score, perThousand (a
|
|
102
|
+
plan's price of 1,000 items in dollars), pay (the plan's whole price in its currency) and page.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
slug: The API's slug, like 'email-finder' or 'linkedin-profile', as datacircle_list_apis gives it.
|
|
106
|
+
limit: How many plans to give, 1 to 50. 10 when left out.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
The API's answer, or {"error": ...} in its words.
|
|
110
|
+
"""
|
|
111
|
+
return _answer(_best_plans, slug, limit)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def datacircle_search_plans(api: Optional[str] = None, query: Optional[str] = None, sort: Optional[str] = None,
|
|
115
|
+
limit: Optional[int] = None, offset: Optional[int] = None) -> Dict[str, Any]:
|
|
116
|
+
"""Searches every plan on Datacircle's sheet (https://datacircle.dev), or one API's, by provider or plan name, sorted by score, provider or price.
|
|
117
|
+
|
|
118
|
+
Gives a dict: total, the plans found, offset and plans, a list of up to limit of them, each with api, rank, provider,
|
|
119
|
+
plan, score, perThousand (a plan's price of 1,000 items in dollars), pay (the plan's whole price in its currency) and
|
|
120
|
+
page.
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
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.
|
|
124
|
+
query: Words that must all appear in the provider's or plan's name, like 'bright data'.
|
|
125
|
+
sort: score (best first, the default), provider (A to Z) or price ($ per 1,000, lowest first).
|
|
126
|
+
limit: How many plans to give, 1 to 50. 10 when left out.
|
|
127
|
+
offset: How many found plans to skip first. 0 when left out.
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
The API's answer, or {"error": ...} in its words.
|
|
131
|
+
"""
|
|
132
|
+
return _answer(_search_plans, api, query, sort, limit, offset)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def datacircle_provider(slug: str) -> Dict[str, Any]:
|
|
136
|
+
"""Gives each API one provider sells and its rank on each on Datacircle's benchmark (https://datacircle.dev), with its best plan there.
|
|
137
|
+
|
|
138
|
+
Gives a dict: provider, slug, website and apis, a list, each with api, slug, rank, plans (how many it has there) and
|
|
139
|
+
best, its best plan there.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
slug: The provider's slug, like 'bright-data', or its name, like 'Bright Data', which is made a slug.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
The API's answer, or {"error": ...} in its words.
|
|
146
|
+
"""
|
|
147
|
+
return _answer(_provider, slug)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
FUNCTIONS: Dict[str, Callable[..., Dict[str, Any]]] = {function.__name__: function for function in (
|
|
151
|
+
datacircle_list_apis, datacircle_best_plans, datacircle_search_plans, datacircle_provider)}
|
|
152
|
+
TOOL_NAMES = list(FUNCTIONS)
|
|
153
|
+
_ARGUMENTS = {"datacircle_list_apis": ("query", "limit"), "datacircle_best_plans": ("slug", "limit"),
|
|
154
|
+
"datacircle_search_plans": ("api", "query", "sort", "limit", "offset"),
|
|
155
|
+
"datacircle_provider": ("slug",)}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def datacircle_tools(tool_names: Optional[Sequence[str]] = None) -> List[Callable[..., Dict[str, Any]]]:
|
|
159
|
+
"""The tools, for Agent(llm=..., tools=datacircle_tools()) or beside one's own and txtai's:
|
|
160
|
+
tools=[*datacircle_tools(), my_tool, "websearch"]. tool_names keeps some of them only, in their order here; all
|
|
161
|
+
four when left out."""
|
|
162
|
+
if isinstance(tool_names, str):
|
|
163
|
+
raise TypeError("tool_names is a list of names, like ['datacircle_best_plans']")
|
|
164
|
+
for name in tool_names or []:
|
|
165
|
+
if name not in FUNCTIONS:
|
|
166
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
167
|
+
return [FUNCTIONS[name] for name in (TOOL_NAMES if tool_names is None else tool_names)]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def run(name: str, arguments: Any = None) -> Dict[str, Any]:
|
|
171
|
+
"""What a tool gives the model for these arguments: the API's answer, or {"error": its words}. arguments is a
|
|
172
|
+
mapping or its JSON text; the ones the tool doesn't take are left out."""
|
|
173
|
+
if name not in FUNCTIONS:
|
|
174
|
+
raise ValueError(f"Datacircle has no tool {name!r}: its tools are {', '.join(TOOL_NAMES)}")
|
|
175
|
+
if isinstance(arguments, (str, bytes)):
|
|
176
|
+
try:
|
|
177
|
+
arguments = json.loads(arguments or "{}")
|
|
178
|
+
except ValueError:
|
|
179
|
+
return {"error": f"the arguments are no JSON object: {arguments[:200]!r}"}
|
|
180
|
+
given = arguments if isinstance(arguments, Mapping) else {}
|
|
181
|
+
return FUNCTIONS[name](**{key: given.get(key) for key in _ARGUMENTS[name]})
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
__all__: List[str] = ["FUNCTIONS", "TOOL_NAMES", "datacircle_best_plans", "datacircle_list_apis", "datacircle_provider",
|
|
185
|
+
"datacircle_search_plans", "datacircle_tools", "run"]
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Stand-ins on 127.0.0.1: Datacircle's API, and a model that speaks OpenAI's Chat Completions, as txtai's LLM calls
|
|
2
|
+
it (its openai method, or litellm's openai/ on api_base) and gives an Agent its text. In a tool-calling agent the model
|
|
3
|
+
writes one action a turn, smolagents' JSON after "Action:", for each of state.calls (the four tools and the app's own
|
|
4
|
+
add_two_numbers), then final_answer with each observation it read. In a code agent (state.code) it writes the code of
|
|
5
|
+
state.code, one turn a block, then final_answer with the code's printed logs."""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
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("LITELLM_LOCAL_MODEL_COST_MAP", "True")
|
|
19
|
+
os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
|
20
|
+
|
|
21
|
+
from txtai_datacircle import _api # noqa: E402
|
|
22
|
+
|
|
23
|
+
PLAN = {"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1, "perThousand": 4.9,
|
|
24
|
+
"page": "https://datacircle.dev/x", "terms": "long", "aggregators": ["a"]}
|
|
25
|
+
CALLS = [{"name": "datacircle_list_apis", "arguments": {"query": "email"}},
|
|
26
|
+
{"name": "datacircle_best_plans", "arguments": {"slug": "email-finder", "limit": 1}},
|
|
27
|
+
{"name": "datacircle_search_plans", "arguments": {"api": "email-finder", "sort": "price", "limit": 2}},
|
|
28
|
+
{"name": "datacircle_provider", "arguments": {"slug": "Bright Data"}},
|
|
29
|
+
{"name": "add_two_numbers", "arguments": {"a": 1, "b": 2}}]
|
|
30
|
+
# What a code agent's model writes: each tool's answer read by its keys, as smolagents' interpreter runs it.
|
|
31
|
+
CODE = ["""apis = datacircle_list_apis(query="email")
|
|
32
|
+
best = datacircle_best_plans(slug=apis["apis"][0]["slug"], limit=1)
|
|
33
|
+
plans = datacircle_search_plans(api="email-finder", sort="price", limit=2)
|
|
34
|
+
provider = datacircle_provider("Bright Data")
|
|
35
|
+
print("found", best["plans"][0]["provider"], plans["total"], provider["apis"][0]["best"]["plan"], add_two_numbers(a=1, b=2))"""]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def add_two_numbers(a: int, b: int) -> int:
|
|
39
|
+
"""Adds two numbers: the app's own tool, beside Datacircle's.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
a: The first number.
|
|
43
|
+
b: The second number.
|
|
44
|
+
"""
|
|
45
|
+
return a + b
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def text(message):
|
|
49
|
+
content = message.get("content")
|
|
50
|
+
if isinstance(content, list):
|
|
51
|
+
return "".join(part.get("text", "") for part in content if isinstance(part, dict))
|
|
52
|
+
return content or ""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def observations(body):
|
|
56
|
+
"""What the agent told the model each tool or code gave: the text after "Observation:" or "Execution logs:"."""
|
|
57
|
+
found = []
|
|
58
|
+
for message in (body.get("messages") or [])[1:]:
|
|
59
|
+
if message.get("role") == "system":
|
|
60
|
+
continue
|
|
61
|
+
for part in re.findall(r"(?:Observation|Execution logs):\s*(.*?)(?=\n(?:Last output|Call id|Observation)|\Z)",
|
|
62
|
+
text(message), flags=re.S):
|
|
63
|
+
found.append(part.strip())
|
|
64
|
+
return found
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class State:
|
|
68
|
+
def __init__(self):
|
|
69
|
+
self.seen, self.busy, self.bodies, self.calls, self.code = [], [], [], CALLS, None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _send(handler, status, body, headers=None):
|
|
73
|
+
data = json.dumps(body).encode()
|
|
74
|
+
handler.send_response(status)
|
|
75
|
+
for key, value in {"Content-Type": "application/json", "Content-Length": str(len(data)), **(headers or {})}.items():
|
|
76
|
+
handler.send_header(key, value)
|
|
77
|
+
handler.end_headers()
|
|
78
|
+
handler.wfile.write(data)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _reply(body, state):
|
|
82
|
+
"""The model's text for this turn: its turn is how many of its own replies the messages hold."""
|
|
83
|
+
turn = sum(message.get("role") == "assistant" for message in body.get("messages") or [])
|
|
84
|
+
read = "read: " + " | ".join(observations(body))
|
|
85
|
+
if state.code is not None:
|
|
86
|
+
if turn < len(state.code):
|
|
87
|
+
return f"Thought: I call the tools.\n<code>\n{state.code[turn]}\n</code>"
|
|
88
|
+
return f"Thought: I have it.\n<code>\nfinal_answer({read!r})\n</code>"
|
|
89
|
+
made = state.calls[turn] if turn < len(state.calls) else {"name": "final_answer", "arguments": {"answer": read}}
|
|
90
|
+
return "Thought: I call a tool.\nAction:\n" + json.dumps(made, indent=2)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _chat(handler, body, state):
|
|
94
|
+
"""OpenAI's /v1/chat/completions, whole: the model's text, cut at the first of the request's stop sequences."""
|
|
95
|
+
content = _reply(body, state)
|
|
96
|
+
for stop in body.get("stop") or []:
|
|
97
|
+
if stop and stop in content:
|
|
98
|
+
content = content[:content.index(stop)]
|
|
99
|
+
_send(handler, 200, {"id": "chatcmpl-1", "object": "chat.completion", "created": int(time.time()), "model": body["model"],
|
|
100
|
+
"choices": [{"index": 0, "message": {"role": "assistant", "content": content},
|
|
101
|
+
"finish_reason": "stop"}],
|
|
102
|
+
"usage": {"prompt_tokens": 5, "completion_tokens": 5, "total_tokens": 10}})
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _handler(state):
|
|
106
|
+
class Handler(BaseHTTPRequestHandler):
|
|
107
|
+
def log_message(self, *args):
|
|
108
|
+
pass
|
|
109
|
+
|
|
110
|
+
def do_POST(self):
|
|
111
|
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
|
|
112
|
+
path = urlparse(self.path).path
|
|
113
|
+
state.bodies.append((path, body))
|
|
114
|
+
if path.endswith("/chat/completions"):
|
|
115
|
+
_chat(self, body, state)
|
|
116
|
+
else:
|
|
117
|
+
_send(self, 404, {"error": f"no {path}"})
|
|
118
|
+
|
|
119
|
+
def do_GET(self):
|
|
120
|
+
url = urlparse(self.path)
|
|
121
|
+
query = {key: values[0] for key, values in parse_qs(url.query).items()}
|
|
122
|
+
state.seen.append((url.path, query, self.headers.get("User-Agent")))
|
|
123
|
+
headers = {}
|
|
124
|
+
if url.path == "/v1/plans" and query.get("query") == "busy" and not state.busy:
|
|
125
|
+
state.busy.append(1)
|
|
126
|
+
status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
127
|
+
elif url.path == "/v1/plans" and query.get("query") == "always-busy":
|
|
128
|
+
status, body, headers = 429, {"error": "slow down"}, {"Retry-After": "1"}
|
|
129
|
+
elif url.path == "/v1/apis":
|
|
130
|
+
status, body = 200, [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3, "extra": 1},
|
|
131
|
+
{"api": "Employee profile", "slug": "linkedin-profile", "plans": 4, "providers": 2}]
|
|
132
|
+
elif url.path == "/v1/apis/email-finder/best":
|
|
133
|
+
status, body = 200, {"api": "Employee email", "slug": "email-finder", "total": 1, "plans": [PLAN]}
|
|
134
|
+
elif url.path.startswith("/v1/apis/"):
|
|
135
|
+
status, body = 404, {"error": "no API has the slug nope", "slugs": ["email-finder", "linkedin-profile"]}
|
|
136
|
+
elif url.path == "/v1/plans" and query.get("query") == "down":
|
|
137
|
+
status, body = 503, {"error": "down for a minute"}
|
|
138
|
+
elif url.path == "/v1/plans":
|
|
139
|
+
status, body = 200, {"total": 1, "offset": 0, "plans": [PLAN]}
|
|
140
|
+
elif url.path == "/v1/providers/bright-data":
|
|
141
|
+
status, body = 200, {"provider": "Bright Data", "slug": "bright-data",
|
|
142
|
+
"apis": [{"api": "Employee email", "slug": "email-finder", "rank": 7, "bestPage": "b",
|
|
143
|
+
"plans": [{**PLAN, "rank": 9}, {**PLAN, "rank": 7, "plan": "Pro"}]}]}
|
|
144
|
+
else:
|
|
145
|
+
status, body = 404, {"error": "no provider has the slug nope"}
|
|
146
|
+
_send(self, status, body, headers)
|
|
147
|
+
return Handler
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@pytest.fixture()
|
|
151
|
+
def stub(monkeypatch):
|
|
152
|
+
state = State()
|
|
153
|
+
server = ThreadingHTTPServer(("127.0.0.1", 0), _handler(state))
|
|
154
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
155
|
+
state.url = f"http://127.0.0.1:{server.server_address[1]}"
|
|
156
|
+
monkeypatch.setattr(_api, "BASE_URL", state.url + "/v1")
|
|
157
|
+
yield state
|
|
158
|
+
server.shutdown()
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Each tool on the live API, https://api.datacircle.dev/v1: run with DATACIRCLE_LIVE=1."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from txtai.agent.tool import ToolFactory
|
|
7
|
+
|
|
8
|
+
from txtai_datacircle import _api, datacircle_tools, run
|
|
9
|
+
|
|
10
|
+
pytestmark = pytest.mark.skipif(os.environ.get("DATACIRCLE_LIVE") != "1", reason="DATACIRCLE_LIVE=1 calls the live API")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_live(monkeypatch):
|
|
14
|
+
monkeypatch.setattr(_api, "BASE_URL", "https://api.datacircle.dev/v1")
|
|
15
|
+
apis = run("datacircle_list_apis", {"query": "email finder", "limit": 3})
|
|
16
|
+
assert apis["total"] >= 1 and apis["apis"][0]["slug"] and len(apis["apis"]) <= 3
|
|
17
|
+
best = run("datacircle_best_plans", {"slug": "email-finder", "limit": 3})
|
|
18
|
+
assert 1 <= len(best["plans"]) <= 3 and all(plan["provider"] and plan.get("page") for plan in best["plans"])
|
|
19
|
+
plans = run("datacircle_search_plans", {"api": "email-finder", "sort": "price", "limit": 2})
|
|
20
|
+
assert plans["total"] >= 1 and len(plans["plans"]) <= 2
|
|
21
|
+
slug = _api.slug(best["plans"][0]["provider"])
|
|
22
|
+
provider = run("datacircle_provider", {"slug": best["plans"][0]["provider"]})
|
|
23
|
+
assert provider["slug"] == slug and provider["apis"] and "plans" in provider["apis"][0]
|
|
24
|
+
refused = run("datacircle_best_plans", {"slug": "no-such-api"})
|
|
25
|
+
assert "answered 404" in refused["error"] and "email-finder" in refused["error"]
|
|
26
|
+
tools = {tool.name: tool for tool in ToolFactory.create({"tools": datacircle_tools()})} # as txtai's Agent runs them
|
|
27
|
+
assert tools["datacircle_list_apis"](sanitize_inputs_outputs=True)["total"] >= 150
|
|
28
|
+
assert tools["datacircle_best_plans"](slug="email-finder", limit=2, sanitize_inputs_outputs=True)["plans"][0]["rank"] == 1
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Offline tests of the tools alone, on the stand-in API (conftest.py): the tools txtai's Agent makes of them, every
|
|
2
|
+
call, its cut, every refusal."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from txtai.agent.tool import ToolFactory
|
|
8
|
+
|
|
9
|
+
import txtai_datacircle
|
|
10
|
+
from txtai_datacircle import TOOL_NAMES, datacircle_tools, run
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_tools_as_txtai_makes_them():
|
|
14
|
+
tools = ToolFactory.create({"tools": [*datacircle_tools(), "python"]})
|
|
15
|
+
assert [tool.name for tool in tools] == [*TOOL_NAMES, "python_interpreter"]
|
|
16
|
+
for tool in tools[:4]:
|
|
17
|
+
assert type(tool).__name__ == "SimpleTool" and tool.output_type == "object", tool # smolagents.tool, not txtai's "any" fallback
|
|
18
|
+
assert "https://datacircle.dev" in tool.description
|
|
19
|
+
assert "Args:" not in tool.description and "Returns:" not in tool.description
|
|
20
|
+
assert all(spec["description"] and spec["type"] in ("string", "integer") for spec in tool.inputs.values())
|
|
21
|
+
best, search = tools[1].inputs, tools[2].inputs
|
|
22
|
+
assert list(best) == ["slug", "limit"] and not best["slug"].get("nullable") and best["limit"]["nullable"]
|
|
23
|
+
assert list(search) == ["api", "query", "sort", "limit", "offset"] and all(spec["nullable"] for spec in search.values())
|
|
24
|
+
assert "def datacircle_best_plans(slug: string, limit: integer) -> object:" in tools[1].to_code_prompt()
|
|
25
|
+
assert [f.__name__ for f in datacircle_tools(["datacircle_provider"])] == ["datacircle_provider"]
|
|
26
|
+
with pytest.raises(ValueError, match="no tool 'nope'"):
|
|
27
|
+
datacircle_tools(["nope"])
|
|
28
|
+
with pytest.raises(TypeError):
|
|
29
|
+
datacircle_tools("datacircle_provider")
|
|
30
|
+
assert txtai_datacircle.__version__ == "0.1.0"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_each_tool(stub):
|
|
34
|
+
apis = run("datacircle_list_apis", {"query": "email"})
|
|
35
|
+
assert apis == {"total": 1, "apis": [{"api": "Employee email", "slug": "email-finder", "plans": 9, "providers": 3}]}
|
|
36
|
+
assert run("datacircle_list_apis", "{}")["total"] == 2
|
|
37
|
+
best = run("datacircle_best_plans", '{"slug": "Email Finder", "limit": "1"}')
|
|
38
|
+
assert best["plans"] == [{"api": "Employee email", "rank": 1, "provider": "Hunter", "plan": "Starter", "score": 80.1,
|
|
39
|
+
"perThousand": 4.9, "page": "https://datacircle.dev/x"}]
|
|
40
|
+
assert stub.seen[-1] == ("/v1/apis/email-finder/best", {"limit": "1"}, "txtai-datacircle/0.1.0")
|
|
41
|
+
plans = run("datacircle_search_plans", {"api": "email-finder", "sort": "Price", "limit": 5, "offset": 0})
|
|
42
|
+
assert plans["total"] == 1
|
|
43
|
+
assert stub.seen[-1][1] == {"api": "email-finder", "sort": "price", "limit": "5", "offset": "0"}
|
|
44
|
+
provider = run("datacircle_provider", {"slug": "Bright Data", "unknown": 1})
|
|
45
|
+
assert provider["apis"][0]["best"]["plan"] == "Pro" and provider["apis"][0]["plans"] == 2
|
|
46
|
+
json.dumps(provider)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_refusals(stub):
|
|
50
|
+
assert "the slugs: email-finder, linkedin-profile" in run("datacircle_best_plans", {"slug": "nope"})["error"]
|
|
51
|
+
assert "Give an API's slug" in run("datacircle_best_plans", {})["error"]
|
|
52
|
+
assert "limit must be from 1 to 50" in run("datacircle_best_plans", {"slug": "x", "limit": 99})["error"]
|
|
53
|
+
assert "whole number" in run("datacircle_search_plans", {"limit": 2.5})["error"]
|
|
54
|
+
assert "sort must be" in run("datacircle_search_plans", {"sort": "cheap"})["error"]
|
|
55
|
+
assert "answered 503: down for a minute" in run("datacircle_search_plans", {"query": "down"})["error"]
|
|
56
|
+
assert "no JSON object" in run("datacircle_provider", "{not json")["error"]
|
|
57
|
+
assert "Give a provider's slug" in run("datacircle_provider", "[1]")["error"]
|
|
58
|
+
assert "no provider" in run("datacircle_provider", {"slug": "nope"})["error"]
|
|
59
|
+
with pytest.raises(ValueError):
|
|
60
|
+
run("nope", {})
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_one_wait_on_429(stub):
|
|
64
|
+
assert run("datacircle_search_plans", {"query": "busy"})["total"] == 1
|
|
65
|
+
assert "429 twice" in run("datacircle_search_plans", {"query": "always-busy"})["error"]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_out_of_reach(monkeypatch):
|
|
69
|
+
monkeypatch.setattr(txtai_datacircle._api, "BASE_URL", "http://127.0.0.1:9/v1")
|
|
70
|
+
assert "could not be reached" in run("datacircle_list_apis")["error"]
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Offline tests through txtai itself, on the stand-in model and API (conftest.py): an Agent on txtai's openai method and
|
|
2
|
+
on litellm, its tool-calling and its code agent, each beside an app's own tool, an agent of a YAML app, and txtai's API
|
|
3
|
+
on uvicorn serving that app."""
|
|
4
|
+
|
|
5
|
+
import importlib.util
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import socket
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
|
|
15
|
+
import pytest
|
|
16
|
+
from txtai import Agent
|
|
17
|
+
from txtai.app import Application
|
|
18
|
+
|
|
19
|
+
from conftest import CALLS, CODE, add_two_numbers
|
|
20
|
+
from txtai_datacircle import TOOL_NAMES, datacircle_tools
|
|
21
|
+
|
|
22
|
+
READ = ["'slug': 'email-finder'", "'provider': 'Hunter'", "'total': 1", "'plan': 'Pro'", "3"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# txtai's openai method came in 9.x: before it, the agent's model is litellm's on api_base.
|
|
26
|
+
OPENAI = importlib.util.find_spec("txtai.pipeline.llm.openai") is not None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def llm(stub, method="openai" if OPENAI else "litellm"):
|
|
30
|
+
if method == "litellm":
|
|
31
|
+
return {"path": "openai/scripted", "method": "litellm", "api_base": stub.url + "/v1", "api_key": "none"}
|
|
32
|
+
return {"path": "openai/scripted", "method": "openai", "base_url": stub.url + "/v1", "api_key": "none"}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def asked(stub):
|
|
36
|
+
return [path for path, _, _ in stub.seen]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@pytest.mark.parametrize("method", ["openai", "litellm"] if OPENAI else ["litellm"])
|
|
40
|
+
def test_tool_calling_agent(stub, method):
|
|
41
|
+
agent = Agent(llm=llm(stub, method), tools=[*datacircle_tools(), add_two_numbers], max_steps=8)
|
|
42
|
+
assert list(agent.tools)[:4] == TOOL_NAMES
|
|
43
|
+
answer = agent("Who are the 3 best providers for the email-finder API?")
|
|
44
|
+
for words in READ:
|
|
45
|
+
assert words in answer, (words, answer)
|
|
46
|
+
assert asked(stub) == ["/v1/apis", "/v1/apis/email-finder/best", "/v1/plans", "/v1/providers/bright-data"]
|
|
47
|
+
prompt = json.dumps(stub.bodies[0][1]["messages"][0])
|
|
48
|
+
assert all(name in prompt for name in TOOL_NAMES) and "add_two_numbers" in prompt
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_tool_calling_agent_refusals(stub):
|
|
52
|
+
stub.calls = [{"name": "datacircle_best_plans", "arguments": {"slug": "nope"}},
|
|
53
|
+
{"name": "datacircle_search_plans", "arguments": {"limit": 99}},
|
|
54
|
+
{"name": "datacircle_provider", "arguments": {"slug": "Bright Data"}}]
|
|
55
|
+
answer = Agent(llm=llm(stub), tools=datacircle_tools(), max_steps=6)("Who is best for nope?")
|
|
56
|
+
assert "the slugs: email-finder, linkedin-profile" in answer and "limit must be from 1 to 50" in answer
|
|
57
|
+
assert "'plan': 'Pro'" in answer # the agent went on after both
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_code_agent(stub):
|
|
61
|
+
stub.code = CODE
|
|
62
|
+
agent = Agent(llm=llm(stub), tools=[*datacircle_tools(), add_two_numbers], method="code", max_steps=4)
|
|
63
|
+
answer = agent("Who is the best provider for the email-finder API?")
|
|
64
|
+
assert "found Hunter 1 Pro 3" in answer, answer
|
|
65
|
+
assert asked(stub) == ["/v1/apis", "/v1/apis/email-finder/best", "/v1/plans", "/v1/providers/bright-data"]
|
|
66
|
+
assert "def datacircle_best_plans(slug: string, limit: integer) -> object:" in stub.bodies[0][1]["messages"][0]["content"]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_some_tools(stub):
|
|
70
|
+
stub.calls = CALLS[1:2]
|
|
71
|
+
agent = Agent(llm=llm(stub), tools=datacircle_tools(["datacircle_best_plans"]), max_steps=4)
|
|
72
|
+
assert list(agent.tools) == ["datacircle_best_plans", "final_answer"]
|
|
73
|
+
assert "'provider': 'Hunter'" in agent("Who is best for email-finder?")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def config(stub):
|
|
77
|
+
return {"llm": llm(stub), "agent": {"gtm": {"max_steps": 8, "tools": [
|
|
78
|
+
{"target": f"txtai_datacircle.{name}"} for name in TOOL_NAMES] + [{"target": "conftest.add_two_numbers"}]}}}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_yaml_app_agent(stub):
|
|
82
|
+
app = Application(config(stub))
|
|
83
|
+
answer = app.agent("gtm", "Who are the 3 best providers for the email-finder API?")
|
|
84
|
+
for words in READ:
|
|
85
|
+
assert words in answer, (words, answer)
|
|
86
|
+
assert len(asked(stub)) == 4
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_api(stub, tmp_path):
|
|
90
|
+
"""txtai's API as its docs start it, CONFIG=app.yml uvicorn "txtai.api:app", its POST /agent: the tools there point at
|
|
91
|
+
the stand-in API through a sitecustomize, as the server is another process."""
|
|
92
|
+
(tmp_path / "app.yml").write_text(json.dumps(config(stub))) # JSON is YAML
|
|
93
|
+
(tmp_path / "sitecustomize.py").write_text(
|
|
94
|
+
f"import txtai_datacircle._api as api\napi.BASE_URL = {stub.url + '/v1'!r}\n")
|
|
95
|
+
with socket.socket() as free:
|
|
96
|
+
free.bind(("127.0.0.1", 0))
|
|
97
|
+
port = free.getsockname()[1]
|
|
98
|
+
tests = os.path.dirname(__file__)
|
|
99
|
+
env = {**os.environ, "CONFIG": str(tmp_path / "app.yml"), "PYTHONPATH": os.pathsep.join([str(tmp_path), tests])}
|
|
100
|
+
log = open(tmp_path / "server.log", "wb") # a file, never a pipe: a pipe no one reads stops the server once full
|
|
101
|
+
server = subprocess.Popen([sys.executable, "-m", "uvicorn", "txtai.api:app", "--host", "127.0.0.1", "--port", str(port)],
|
|
102
|
+
env=env, stdout=log, stderr=subprocess.STDOUT)
|
|
103
|
+
try:
|
|
104
|
+
url = f"http://127.0.0.1:{port}/agent"
|
|
105
|
+
request = urllib.request.Request(url, json.dumps({"name": "gtm", "text": "Who is best for email-finder?"}).encode(),
|
|
106
|
+
{"Content-Type": "application/json"})
|
|
107
|
+
for _ in range(240):
|
|
108
|
+
try:
|
|
109
|
+
with urllib.request.urlopen(request, timeout=120) as answer:
|
|
110
|
+
text = json.loads(answer.read())
|
|
111
|
+
break
|
|
112
|
+
except urllib.error.HTTPError as error:
|
|
113
|
+
raise AssertionError((tmp_path / "server.log").read_text()[-3000:]) from error
|
|
114
|
+
except urllib.error.URLError as error: # retried only while the port is still closed
|
|
115
|
+
assert isinstance(error.reason, ConnectionRefusedError), error
|
|
116
|
+
assert server.poll() is None, (tmp_path / "server.log").read_text()
|
|
117
|
+
time.sleep(0.5)
|
|
118
|
+
else:
|
|
119
|
+
raise AssertionError("txtai's API did not start")
|
|
120
|
+
finally:
|
|
121
|
+
server.terminate()
|
|
122
|
+
server.wait(10)
|
|
123
|
+
log.close()
|
|
124
|
+
for words in READ:
|
|
125
|
+
assert words in text, (words, text)
|
|
126
|
+
assert len(asked(stub)) == 4
|